text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: react-router indexroute doesn't work I have a routes like this:
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Login} />
<Route path="dashboard" component={Dashboard} />
</Route>
</Router>
In the render method of component App I have this:
return (
<div>
<Header loggedIn={ this.props.data.loggedIn}/>
{this.props.children}
</div>
);
When I visit my home / the Header component is rendered but the Login component is not.
The same if I visit /dashboard. The property {this.props.children} is always null.
What is wrong ?
EDIT:
<Router> is wrapper with <Provider>
<Provider store{store}>
<div>
{this.renderRoutes()}
</div>
</Provider>
The App component right now have no more than the return() showed above:
I have this propTypes and defaultTypes:
App.propTypes = {
children: PropTypes.object
};
App.defaultTypes = {
children: null
};
Maybe this defaultTypes set to null on children is the problem? However, the Route i've show before, is correct ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37799024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Magento Tag Url Rewrite and Generate I added lots of rewrite rules for tags in Magento. For example,
Request Path: tag/abc
Target Path: tag/product/list/tagId/7/
Type: Custom
Everything is going well in the request and response. But I am wondering how to change the tag URL in the front? Although the rewrite rules run perfectly it will not change the URL which has been rewritten.
I found the getTaggedProductsUrl() method in tag module and eventually, like others, it calls getUrl() method in core/url Model. I tried to add, '_use_rewrite' => true to the route params. But it does not generate the right URL.
I really would like to know what's wrong about this!
A: If you rewrite the tag/tag model and override the getTaggedProductsUrl() with the following it will work:
public function getTaggedProductsUrl()
{
$fullTargetPath = Mage::getUrl('tag/product/list', array(
'tagId' => $this->getTagId(),
'_nosid' => true
));
$targetPath = substr($fullTargetPath, strlen(Mage::getBaseUrl()));
$rewriteUrl = Mage::getModel('core/url_rewrite')->loadByIdPath($targetPath);
if ($rewriteUrl->getId()) {
return $rewriteUrl->getRequestPath();
}
return $fullTargetPath;
}
This is assuming you are using the target path without the base url as the "ID path" and the "Target Path" property, e.g tag/product/list/tagId/30/.
If you don't want to duplicate that setting then you will need to use the tag resource model and manually adjust the SQL to match the target_path column instead the id_path, because the resource model doesn't come with a method predefined for you.
Still, you can use the Mage_Tag_Model_Resource_Tag::loadByRequestPath()method as a reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8320857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to optimise Percona MongoDB LDAP for more concurrent connections? Percona MongoDB with LDAP is not working for more than 2 concurrent threads even if the connection pool configured for more than 2.
MongoDB Configuration,
setParameter:
saslauthdPath: /app/mongo/mongoldap/var/run/saslauthd/mux
authenticationMechanisms: PLAIN,SCRAM-SHA-1
ldapConnectionPoolSizePerHost: 10
ldapUseConnectionPool: true
ldapDebug: true
SASL Configuration,
ldap_servers: ldap://ldap.forumsys.com
ldap_mech: PLAIN
ldap_search_base: dc=example,dc=com
ldap_filter: (cn=%u)
ldap_bind_dn: cn=read-only-admin,dc=example,dc=com
ldap_password: password
Test Script (PHP),
<?php
use MongoDB\Driver\Manager as MongoDB;
use MongoDB\Driver\Query as Query;
use MongoDB\Driver\BulkWrite as BulkWrite;
try{
for($i=0;$i<3;$i++){
$handlerName = "handle".$i;
$$handlerName = new MongoDB("mongodb://xx.xx.xx.xx",array("authSource"=>"$external","authMechanism"=>"PLAIN","username"=>"cn=read-only-admin,dc=example,dc=com","password"=>"password","tls"=>true,"tlsCertificateKeyFile"=>"/xyzabc/dbs/mongoclient.pem","tlsCAFile"=>"/xyzabc/dbs/mongoca.pem","tlsAllowInvalidCertificates"=>true));
$filters=array();
$options=array();
$command = new Query($filters,$options);
$query="xyzabc.customerdetails";
$result = $$handlerName->executeQuery($query,$command);
$resultAsJson = $result->toArray();
$resultAsArray = json_decode(json_encode($resultAsJson), True);
print_r(count($resultAsArray));
echo "\n";
sleep(5);
}
for($i=0;$i<3;$i++){
$handlerName = "handle".$i;
$query="xyzabc.client";
$result = $$handlerName->executeQuery($query,$command);
$resultAsJson = $result->toArray();
$resultAsArray = json_decode(json_encode($resultAsJson), True);
print_r(count($resultAsArray));
echo "\n";
}
echo "Success";
}catch(Exception $e){
print_r($e);
echo "Failed";
}
?>
Test Script (Shell script for nohup),
nohup php test.php > output1.log 2>&1 &
nohup php test.php > output2.log 2>&1 &
nohup php test.php > output3.log 2>&1 &
nohup php test.php > output4.log 2>&1 &
nohup php test.php > output5.log 2>&1 &
Test Results,
Script executed in a single thread (same process ID) - there is no error it works for any number of connections
If the same script is executed on nohup (multi-thread or multiple process IDs) - only works for the first two threads, fails for 3rd and above
Error Message (MongoDB log),
LDAPLibraryError: Failed to authenticate 'cn=read-only-admin,dc=example,dc=com' using simple bind; LDAP error: Can't contact LDAP server
Percona MongoDB Version: 4.4.2-4
When the test PHP script is executed synchronously there is no error with the number of connections. I assume this is because the process ID is the same for all the DB connections so it uses the same connection pool.
On the other hand, if it is executed concurrently (with nohup), only the first 2 connections are working, by this, I assume only the first 2 connection pools are working and from 3rd connection pool, the requests are failing.
Since I have ldapConnectionPoolSizePerHost is set to 10, I don't understand why this is not working as expected.
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65186958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Icon for Representing Elevation I am in need of an icon for representing an elevation display, i.e. I have a label containing an elevation in metres, and I need a small (22x22 pixel) icon next to it to indicate thats what it is.
I have tried some things, like a vertical arrow, but none quite look right.
Anyone got any ideas?
I know this isn't strictly a programming question, but it is about a user interface, and therefore software related (i think).
Cheers
Edit:
In the end I went for this icon:
It represents it pretty well.
A: Something like this : (http://www.waymarking.com/images/cat_icons/elevationSigns.gif)
actually 24x24
A: look at this
alt text http://www.vectorportal.com/symbols/img/opengutter.gif
alt text http://t1.gstatic.com/images?q=tbn:7DqRw9FL5c9IfM%3Ahttp://media.peeron.com/ldraw/images/19/3044b.png
alt text http://t3.gstatic.com/images?q=tbn:jfs_Abjx3BnXEM:http://media.peeron.com/ldraw/images/272/50746.pngalt text http://t3.gstatic.com/images?q=tbn:L8injTgVVHLlIM%3Ahttp://media.peeron.com/ldraw/images/27/61409.png
alt text http://t1.gstatic.com/images?q=tbn:WXHlgHgon09alM:http://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Japanese_Road_sign_(Descent).svg/470px-Japanese_Road_sign_(Descent).svg.png
See also http://mutcd.fhwa.dot.gov/services/publications/fhwaop02084/index.htm
Don't forget about copyrighted © images
A: Create an icon form templates using axialis icon workshop. It is really convenient to use. As I remember there was a template. If no you can ealily import a image and edit or draw a one.
A: I don't think that's a sensible use of an icon; they're OK as visual cues to find something quickly once you've learned to recognize one, but as you have noticed, they suck at conveying actual information. Abbreviated text ("El.") would be more useful if you really lack the space for a full-length text label.
A: If it's for a plane:
alt text http://www.pekkagaiser.de/stuff/Plane.gif
Would need some re-working to look good on 22x22, though.
Plane stolen from here.
A: bullet_arrow_top from here any good:
http://www.famfamfam.com/lab/icons/silk/previews/index_abc.png
Download the set here:
http://www.famfamfam.com/lab/icons/silk/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2019502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to unit test Flowable.interval? I have the following code inside the presenter.
public class SignUpPresenter implements Presenter {
private CompositeDisposable disposables;
private View view;
@Inject public SignUpPresenter() {
}
public void setView(View view) {
this.view = view;
}
public void redirectToLogInScreenAfterOneSecond() {
disposables = RxUtil.initDisposables(disposables);
view.displaySuccessMessage();
Disposable disposable = Flowable.interval(1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> view.onRegistrationSuccessful(), view::handleError);
disposables.add(disposable);
}
@Override public void dispose() {
RxUtil.dispose(disposables);
}
public interface View extends Presenter.View {
void onRegistrationSuccessful();
void displaySuccessMessage();
}
}
Now, I want to write unit test for that method.
@RunWith(PowerMockRunner.class)
public class SignUpPresenterTest {
@Rule TrampolineSchedulerRule trampolineSchedulerRule = new TrampolineSchedulerRule();
@Mock SignUpPresenter.View view;
private SignUpPresenter presenter;
private TestScheduler testScheduler;
@Before public void setUp() {
testScheduler = new TestScheduler();
RxJavaPlugins.setComputationSchedulerHandler(scheduler -> testScheduler);
presenter = new SignUpPresenter();
presenter.setView(view);
}
@Test public void shouldDisplaySuccessMessage() {
testScheduler.advanceTimeTo(1, TimeUnit.SECONDS);
presenter.redirectToLogInScreenAfterOneSecond();
Mockito.verify(view).displaySuccessMessage();
Mockito.verify(view).onRegistrationSuccessful();
}
}
Here is the error that I get:
Wanted but not invoked:
view.onRegistrationSuccessful();
-> at com.test.presentation.signup.SignUpPresenterTest.shouldDisplaySuccessMessage(SignUpPresenterTest.java:36)
However, there were other interactions with this mock:
view.displaySuccessMessage();
-> at com.test.presentation.signup.SignUpPresenter.redirectToLogInScreenAfterOneSecond(SignUpPresenter.java:28)
Wanted but not invoked:
view.onRegistrationSuccessful();
-> at com.test.presentation.signup.SignUpPresenterTest.shouldDisplaySuccessMessage(SignUpPresenterTest.java:36)
However, there were other interactions with this mock:
view.displaySuccessMessage();
-> at com.test.presentation.signup.SignUpPresenter.redirectToLogInScreenAfterOneSecond(SignUpPresenter.java:28)
How I can solve this?
A: You have to move the time after the flow setup:
@Test public void shouldDisplaySuccessMessage() {
presenter.redirectToLogInScreenAfterOneSecond();
testScheduler.advanceTimeTo(1, TimeUnit.SECONDS);
Mockito.verify(view).displaySuccessMessage();
Mockito.verify(view).onRegistrationSuccessful();
}
Also you don't need that many operators after interval but use the mainThread scheduler directly:
Disposable disposable = Flowable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe(aLong -> view.onRegistrationSuccessful(), view::handleError);
and replace the mainThread scheduler:
@Before public void setUp() {
testScheduler = new TestScheduler();
RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler -> testScheduler);
presenter = new SignUpPresenter();
presenter.setView(view);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59608753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my If statement not working when I compare three numbers? I have this Code but it is not working :
double N1 = int.Parse(TB_S1.Text);
double N2 = int.Parse(TB_S2.Text);
double N3 = int.Parse(TB_S3.Text);
double N4 = int.Parse(TB_P1Y.Text);
double N5 = int.Parse(TB_P2X.Text);
double N11 = N1 + N2;
double N6 = N2 + N3;
double N7 = N3 + N4;
double R;
if ((N11 = N6 = N7))
{
messageBox.Show("Corect");
}
Edit:
solution: th eproblem was using single = instead of ==
A: The problem is most likely this line
if ((N11 = N6 = N7))
= in C# is assignment; you're most likely looking for equality, which is ==
Changing the above to this should fix it for you.
if (N11 == N6 && N11 == N7)
A: To handle your comparison, you need:
if ((N11 == N6) && (N11 == N7))
Or, simplified:
if (N11 == N6 && N11 == N7)
Note the == (comparison) instead of = (assignment). Also, you need to do two separate comparisons to check to see if the three values are equal.
In addition, right now you're using int.Parse, but assigning to a double. You should likely use double.Parse instead:
double N1 = double.Parse(TB_S1.Text);
You may also want to consider using double.TryParse, as this will better handle errors in user input:
double N1;
if(!double.TryParse(TB_S1.Text, out N1))
{
MessageBox.Show("Please enter a valid value in TB_S1");
return;
}
A: Try this:-
if ((N11 == N6) && (N11 == N7))
instead of
if ((N11 = N6 = N7))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13979106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: using to_tsvector and to_tsquery to filter non roman characters I want to allow multilingual search support for my app.
Postgresql 9.6 Search Controls says I need tsvector and tsquery to properly parse/normalize text. This works fine with roman-based languages, but not non-roman characters.
Considering this search snippet
where to_tsvector(title) @@ to_tsquery('hola')
I am looking for a title with "hola mi amiga", and it is found. However, given:
where to_tsvector(title) @@ to_tsquery('你') //language = Chinese, Code = zh-CN
I am looking for a title with 你好嗎 and it is not found.
What considerations should I take to allow string normalization to work with non roman characters?
A: Make sure you set the configuration right
default_text_search_config (string)
Selects the text search configuration that is used by those variants of the text search functions that do not have an explicit argument specifying the configuration. See Chapter 12 for further information. The built-in default is pg_catalog.simple, but initdb will initialize the configuration file with a setting that corresponds to the chosen lc_ctype locale, if a configuration matching that locale can be identified.
You can see the current value with
SHOW default_text_search_config;
or SELECT get_current_ts_config();
You can change it for the session with SET default_text_search_config = newconfiguration; Or, you can use ALTER DATABASE <db> SET default_text_search_config = newconfiguration
From Chapter 12. Full Text Search
During installation an appropriate configuration is selected and default_text_search_config is set accordingly in postgresql.conf. If you are using the same text search configuration for the entire cluster you can use the value in postgresql.conf. To use different configurations throughout the cluster but the same configuration within any one database, use ALTER DATABASE ... SET. Otherwise, you can set default_text_search_config in each session.
Each text search function that depends on a configuration has an optional regconfig argument, so that the configuration to use can be specified explicitly. default_text_search_config is used only when this argument is omitted.
You can use \dF to see the text search configurations you have installed.
So what you want, is something like this
where to_tsvector('newconfig', title) @@ to_tsquery('newconfig', '你')
No idea what language the query is in to answer this question, or what configuration will properly stem that language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41601379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RabbitMQ management In the console pane rabbitmq one day I had accumulated 8000 posts, but I am embarrassed that their status is idle at the counter ready and total equal to 1. What status should be completed at the job, idle? In what format is registered x-pires? It seems to me that I had something wrong =(
A: While it's difficult to fully understand what you are asking, it seems that you simply don't have anything pulling messages off of the queue in question.
In general, RabbitMQ will hold on to a message in a queue until a listener pulls it off and successfully ACKs, indicating that the message was successfully processed. You can configure queues to behave differently by setting a Time-To-Live (TTL) on messages or having different queue durabilities (eg. destroyed when there are no more listeners), but the default is to play it safe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8253371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SPNEGO troubles for users with many groups (memberOf) We install tomcat 7.0.56+spnego_r7 (+nginx proxy) on linux (RHEL), jdk 8_20. Its works fine in servlet - request.getUserPrincipal().
All work good only for users (AD) with few groups (2-3 memberOf).
For users with many groups we received in browser (IE, Chrome, Firefox) “ERR::UNEXPECTED”: provisional headers are shown.
Logs is empty, but we activate:
-Dsun.security.krb5.debug=true -Dsun.security.spnego.debug=all
And
<init-param>
<param-name>spnego.logger.level</param-name>
<param-value>1</param-value>
</init-param>
But logs show only successful auths. No errors.
We increase buffers, headers in nginx and tomcat to 64k (and to 1m for experiment, but go back), MaxTokenSize in Windows registry…. And don’t work.
Try another version of tomcat, jdk and its not help.
How we can get successful through pass auth for users with many groups (memberOf)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31318133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: a bug in my react native flatlist keeps bouncing to top without ability to continue scrolling I'm trying to build a flatlist of svg item, where I control position of each item (position='absolute')
However, my flatlist is not giving option to scroll down, it always keep bouncing to the top the moment I untouch the screen
This is how my screen looks like, every hexagon is an item in the flatlist
screen code:
return (
<View style={styles.container}>
<ImageBackground source={require('../../assets/edu_bg.png')} style={styles.image}>
<View style={{width: '100%', height: '25%'}}>
<ImageBackground source={require('../../assets/edu_top_bg.png')} style={{height:'100%', width: '100%'}}>
<Text style={styles.welcome_txt}>screen 3</Text>
<FlatList
style={{marginBottom: 10, height: 40}}
horizontal
data={Categories}
renderItem={(item, index) => renderCategory(item, index)}
keyExtractor={item => generate()}
showsHorizontalScrollIndicator={false}
></FlatList>
</ImageBackground>
</View>
<FlatList
style={{marginBottom: 45}}
data={Data}
renderItem={(item, index) => renderEvent(item, index)}
keyExtractor={item => generate()}
>
</FlatList>
<StatusBar style="auto" />
</ImageBackground>
</View>
);
don't mind the first flatlist, only the second one. (width="210" height="190")
Rendering item code:
const renderEvent = ({ item, index }) => {
// console.log('rendering', item, 'index ', index)
const i = index % 2;
const flex_p = i === 0 ? 'flex-start' : 'flex-end'
const top_p = index * 95;
const c = index%3;
console.log(i, flex_p, top_p, i_2_color[c])
return (
<View style={{marginHorizontal: 10}}>
<TouchableOpacity style={{flex:1, alignSelf:flex_p, position:'absolute', top:top_p}} onPress={() => console.log(item, index)}>
<CustomEvent color_map={i_2_color[c]} >
</CustomEvent>
</TouchableOpacity>
</View>
)};
where CustomEvent is the hexagn svg one
Please don't mind the bad code written above (style in the view part, calculating that variables and their names..., im just trying stuff out)
styles:
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
welcome_txt: {
fontWeight:"bold",
fontSize:50,
color:"#3589d4",
marginTop: 50,
textAlign: 'center',
},
image: {
flex: 1,
width: '100%',
height: '100%',
justifyContent: "center"
},
top_image: {
flex: 1,
width: '100%',
height: '20%',
}
});
I have checked and all solutions where to remove flex=1 from the flatlist itself, however, my flatlist style only is margin, nothing else.
Any help is appreciated, I have spent a lot of time trying to figure our what caused the issue but with no success
Thanks in advance!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65226474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using an Array to get the average of a selection of numbers I have 12 different numbers on a row in an excel sheet (repeated few times on different row) and I would like to get the average of the 8 bigger numbers (4 numbers won't be used). I thought to use an array, but how to select the 8 bigger numbers in this array?
I would like to do it in VBA. Do you have any ideas/directions how to proceed, because I am not really sure how to start.
Example: 12,3,5,6,8,11,9,7,5,8,10,1 (Results=8.875), if I didn't make a mistake!
Thanks.
A: I know you asked for VBA, but here's a formula. If this works, you can quickly throw in VBA (use the macro recorder to see how if you're unsure).
If that's in row 1, you can use:
=AVERAGE(LARGE(A1:L1,{1,2,3,4,5,6,7,8}))
You should be able to change A1:l1 to be the range where your numbers are, i.e.
=AVERAGE(LARGE(A1:F2,{1,2,3,4,5,6,7,8}))
Edit: Per your comment, also no need for VBA. Just use conditional highlighting. Highlight your range of numbers, then go to Conditional Highlighting --> Top/Bottom Rules --> Top 10 Items. Then just change the 10 to 8, and choose a color/format. Then Apply!
(each row in the above is treated as it's own range).
Edt2: bah, my image has duplicate numbers which is why the top 8 rule is highlighting 9 numbers sometimes. If you request I'll try to edit and tweak
A: You can use a simple Excel function to compute the answer
=AVERAGE(LARGE(A1:L1, {1,2,3,4,5,6,7,8}))
It is a bit more complex in VBA, but here is a function that does the same computation (explicit typing per Mat's Mug):
Public Function AvgTop8(r As Range) As Double
Dim Sum As Double, j1 As Integer
For j1 = 1 To 12
If WorksheetFunction.Rank(r(1, j1), r) <= 8 Then
Sum = Sum + r(1, j1)
End If
Next j1
AvgTop8 = Sum / 8#
End Function
The Excel RANK function returns the rank of a number in a list of numbers, with the largest rank 1 and so on. So you can search through the 12 numbers for the 8 largest, sum them and divide by 8.
A: You don't need VBA for this. You can use:
=AVERAGE(LARGE(A1:L1,{1;2;3;4;5;6;7;8}))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48713270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to Capitalize first 2 words of Navigation bar I have a horizontal NAV section and need to capitalize the first 2 words (of 5). I need to capitalize the words Developers and Designers. I know its a class or span but I'm just learning CSS and can't figure it out.
thanks!
Here is the HTML
<header>
<h1>Title</h1>
<nav>
<ul>
<li><a href="#">Developers</a></li>
<li><a href="#">Designers</a></li>
<li><a href="#">How it Works</a></li>
<li><a href="#">Our Team</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
</header>
CSS
header nav ul li {
float: right;
width: 8%;
}
header nav a {
float: right;
display: block;
color: white;
text-decoration: none;
width: 110px;
}
A: You are looking for text-transform: uppercase and nth-child selector.
Something like this:
header nav ul li:nth-child(-n+2) {
text-transform: uppercase;
}
<header>
<h1>Title</h1>
<nav>
<ul>
<li><a href="#">Developers</a></li>
<li><a href="#">Designers</a></li>
<li><a href="#">How it Works</a></li>
<li><a href="#">Our Team</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
</header>
A: You can use nth-of-type().
For your example you will want to use nth-of-type on the <li>.
header nav li:nth-of-type(-n+2) {
text-transform: capitalize;
}
https://jsfiddle.net/qfLrsdwr/1
My JSFiddle has slightly different selectors and markup for demonstration purposes.
<header>
<h1>Title</h1>
<nav class="primary-nav">
<ul>
<li><a href="#">Developers</a></li>
<li><a href="#">Designers</a></li>
<li><a href="#">How it Works</a></li>
<li><a href="#">Our Team</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
</header>
.primary-nav li {
text-transform: lowercase;
}
.primary-nav li:nth-of-type(-n+2) {
text-transform: capitalize;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33482535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hudson plugin for trend of timings of all jobs in a view Is there a Hudson plugin which would allow me to create a "trend" graph for build times for all jobs/projects in a view?
A: It is supported for one job.
But for all jobs, the Global Build Stats Plugin will be able to do that. However, it is not there yet.
Meaning you need to develop your own plugin, based on the Plot Plugin, to vizualise that kind of trend (build times)
alt text http://wiki.hudson-ci.org/download/attachments/2752526/examplePlot.png?version=1&modificationDate=1184536762000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3477235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Visual Studio taking long time to load solution I know that this is a trivial problem but Visual Studio 2008 has suddenly started taking a really long time to load one particular solution that I have. While watching the status bar it appears to get stuck on one project. That project is, however, the most trivial of all projects and is a simple library with a few DTO classes in it.
Any ideas on how to solve this?
A: Have you added a Setup project to the solution? It seems to me that those take much longer to load than other types of projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1608016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: React Native Navigation : Deep link events not being fired when Tabs and Side Drawer are reloaded Issue Description
I created a simple app where you login, and then a couple of tabs are loaded with a side drawer.
The side drawer has buttons that allow you to navigate to other pages by using deep links.
The first time I log into the app, the buttons and deep links work fine. But when I logout and login again (logging in reloads the tabs and side drawer) none of the side drawer buttons work. In my deep link handlers, I outputted a console message, and I realized that the deep link events weren't being fired the second time, which is clearly the issue.
I don't know why this is happening, and I suspect that it is a bug. But in case it isn't, I'd like to be pointed out where I'm going wrong with my code and what I should be doing instead.
I'm attaching code snippets below.
Code Snippets
sidedrawer.js
import React, {Component} from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import {Navigation} from 'react-native-navigation';
import Icon from 'react-native-vector-icons/FontAwesome';
export default class SidedrawerComponent extends Component {
constructor(props){
super(props);
}
render(){
return(
<View style={styles.sideMenuStyle}>
<View style={{height: '20%', borderColor: 'black', borderWidth : 1, backgroundColor : 'white'}}>
</View>
<TouchableOpacity onPress={this.goToScreen.bind(this, 'consumerSettings')}>
<View style={{borderColor : 'black', borderWidth : 1, flexDirection : 'row'}}>
<Icon name="home" size={30} color="black" />
<Text style={{color : 'black', fontWeight : 'bold', fontSize : 20, marginLeft : 10}}>Settings</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.goToScreen.bind(this, 'aboutUs')}>
<View style={{borderColor : 'black', borderWidth : 1, flexDirection : 'row'}}>
<Icon name="home" size={30} color="black" />
<Text style={{color : 'black', fontWeight : 'bold', fontSize : 20, marginLeft : 10}}>About Us</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.goToScreen.bind(this, 'termsAndConditions')}>
<View style={{borderColor : 'black', borderWidth : 1, flexDirection : 'row'}}>
<Icon name="home" size={30} color="black" />
<Text style={{color : 'black', fontWeight : 'bold', fontSize : 20, marginLeft : 10}}>Terms and Conditions</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.goToScreen.bind(this, 'inbox')}>
<View style={{borderColor : 'black', borderWidth : 1, flexDirection : 'row'}}>
<Icon name="home" size={30} color="black" />
<Text style={{color : 'black', fontWeight : 'bold', fontSize : 20, marginLeft : 10}}>Inbox</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.goToScreen.bind(this, 'logout')}>
<View style={{borderColor : 'black', borderWidth : 1, flexDirection : 'row'}}>
<Icon name="home" size={30} color="black" />
<Text style={{color : 'black', fontWeight : 'bold', fontSize : 20, marginLeft : 10}}>Logout</Text>
</View>
</TouchableOpacity>
</View>
)
}
goToScreen = (screen) => {
const visibleScreenInstanceId = Navigation.getCurrentlyVisibleScreenId();
visibleScreenInstanceId.then((result)=>{
this.props.navigator.handleDeepLink({
link: screen,
payload: result.screenId // (optional) Extra payload with deep link
});
})
}
}
const styles = StyleSheet.create({
sideMenuStyle : {
backgroundColor : 'white',
height : '100%'
}
})
deep link handlers in one of the tabs :
navigatorEvent = event => {
if(event.type==="NavBarButtonPress" && event.id === "DrawerButton"){
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
if(event.type == 'DeepLink') {
if(event.link=="aboutUs" && event.payload=='screenInstanceID5'){
this.props.navigator.push({
screen : 'ServiceTracker.AboutUsScreenComponent',
title : 'About Us'
})
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
if(event.link=="termsAndConditions" && event.payload=='screenInstanceID5'){
this.props.navigator.push({
screen : 'ServiceTracker.TermsAndConditionsScreenComponent',
title : 'Terms and Conditions'
})
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
if(event.link=="profile" && event.payload=='screenInstanceID5'){
this.props.navigator.push({
screen : 'ServiceTracker.ServiceProviderProfileScreenComponent',
title : 'Profile'
})
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
if(event.link=="serviceProviderSettings" && event.payload=='screenInstanceID5'){
this.props.navigator.push({
screen : 'ServiceTracker.ServiceProviderSettingsScreenComponent',
title : 'Settings'
})
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
/*if(event.link=="dashboard" && event.payload=='screenInstanceID5'){
LoadTabs();
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}*/
if(event.link=="inbox" && event.payload=='screenInstanceID5'){
this.props.navigator.push({
screen : 'ServiceTracker.InboxScreenComponent',
title : 'Inbox'
})
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
}
if(event.link=="logout" && event.payload=='screenInstanceID5'){
this.props.navigator.toggleDrawer({
side : 'left',
animated : true
})
Navigation.startSingleScreenApp({
screen : {
screen : "ServiceTracker.LandingScreenComponent",
title : "Landing Screen",
navigatorStyle : {
navBarHidden : true
}
}
})
}
}
}
Environment
React Native Navigation version: 1.1.476
React Native version: 0.55.2
Platform(s) : Android
Device info : Galaxy Nexus Simulator, Oreo (API 27), Debug
A: I figured out the issue - the deep link events were getting fired, but the problem was the value of result.screenId changes for each screen every time the tabs are reloaded.
So, in my deeplink handlers, instead of checking statically for a particular ID, I checked if the event.payload was == this.props.navigator.screenInstanceID, both variables which will of course match even if the ID's change, which is all that matters.
Hope this is useful for others trying to use React Native Navigation to create a side-drawer tab based app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51455188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sql sum of count field with different product name once Is there any good method to get the count of different product once.
for example
/* the table like */
id count product
1 5 a
2 2 b
3 6 c
4 2 a
......
I want to get the sum of product use one sql command. because the product number is very large.
the value like
a b c
7 2 6
Thank you very much!
A: It's a simple sum and group by
select product, sum(count)
from mytable
group by product
A: Select product, sum(count)
from table_name
group by product
You might want to go through tutorial of group_by clause
http://www.techonthenet.com/sql/group_by.php
A: i dont know if you looking for pivote result as you done in your question , if yes use this
SELECT Sum(CASE
WHEN ( product = 'a' ) THEN ` count `
ELSE 0
END)AS a,
Sum(CASE
WHEN ( product = 'b' ) THEN ` count `
ELSE 0
END)AS b,
Sum(CASE
WHEN ( product = 'c' ) THEN ` count `
ELSE 0
END)AS c
FROM table1
DEMO HERE
result:
A B C
7 2 6
note this query is only if you have 3 limited values on product.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20263863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: creating multiple src directories in eclipse I am doing this tutorial, which asks me to create multiple source directories in eclipse. Can someone explain how to do that? I am describing the steps I have taken so far as follows:
The image below shows the tutorial's directory structure on left, and my current directory structure on right:
As you can see, I need to create the following folders under Java Resources:
src/test/java
src/test/resources
src/main/resources
However, when I right click on the Java Resources folder and select new source folder, I get the following dialog box, for which I have clicked on the Browse... Folder Name button to open the subdialog which is also shown:
At this point, none of the choices seem to be what I want. So how do I create the three new src subdirectories that are specified by the tutorial?
A: Right-click your project, select Build Path and Configure Build Path.... In the Source tab, if src/main/resources or src/test/java appear, remove them. This might be a bug with the Maven plugin, I don't know. They appear like they are there, but aren't really.
Then use Add Folder... to add the folders you need. Do this by selecting a folder (to add folders to), like src/main, clicking Create New Folder... and using the folder name resources (or as appropriate).
A: You close the "Existing Folder Selection" dialog (since you don't want an existing folder, but a new one), and you enter src/test/java in "Folder Name". Then you click Finish. You repeat this operation for every new folder you want.
Of course, you could also use your file manager to create the folders, and select them in Eclipse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20081910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Chrome - why is it sending if-modified-since requests? I have a page with lots of small images (icons). When used with chrome, each time the page is reloaded, chrome requests each icon from the server with if-modified-since header.
All icons are served with expires and max-age headers. Firefox loads images from its cache.
Why is chrome doing that and how can I prevent it?
Thanks
A: A quick experiment with Chrome’s inspector shows that this only happens when the page is reloaded, not when it is loaded normally. Chrome is just trying to refresh its cache. Think about it — if you set Expires and Max-Age to several decades, are you asking the browser to cache that resource and never check to see if it gets updated? It’s caching the resource when it can, but when the page needs to be refreshed it wants to make sure that the entire page is refreshed. Other browsers surely do it too (although some have an option for the number of hours to wait before refreshing).
Thanks to modern browsers and servers, refreshing a large number of icons won’t be as slow as you think — requests are pipelined to eliminate multiple round-trip delays, and the entire purpose of the If-Modified-Since header is to allow the server to compare timestamps and return a "Not Modified" status code. This will happen for every resource the page needs, but the browser will be able to make all the requests at once and verify that none of them have changed.
That said, there are a few things you can do to make this easier:
*
*In Chrome’s inspector, use the resources tab to see how they are being loaded. If there are no request headers, the resource was loaded directly from the cache. If you see 304 Not Modified, the resource was refreshed but did not need to be downloaded again. If you see 200 OK, it was downloaded again.
*In Chrome’s inspector, use the audits tab to see what it thinks about the cacheability of your resources, just in case some of the cache headers aren’t optimal.
*All of those If-Modified-Since requests and 304 responses can add up, even though they only consist of headers. Combine your images into sprites to reduce the number of requests.
A: Modern browsers are getting more complex and intelligent with their caching behaviour. Have a read through http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx for some examples and more detail.
As Florian says, don't fight it :-)
A: Have you checked the request headers?
"‘Cache-Control’ is always set to ‘max-age=0′, no matter if you press enter, f5 or ctrl+f5. Except if you start Chrome and enter the url and press enter."
http://techblog.tilllate.com/2008/11/14/clientside-cache-control/
A: With chrome it matters whether you're refreshing a page or simply visiting it.
When you refresh, chrome will ping the server for each file regardless of whether or not they are already cached. If the file hasn't been modified you should see a 304 Not Modified response. If the file has been modified you'll see a 200 OK response instead.
When not refreshing, cached files will have a 200 OK status but if you look in the size/content column of the network panel you'll see (from cache).
A: Google Chrome will ignore the Expires header if it's not a valid date by the RFC. For instance, it always requires days to be specified as double-digits. 1st of May should be set as "01 May" (not "1 May") and so on. Firefox accepts them, this misleads the user that the problem is at the browser (this case, Chrome) and not the header values themselves.
So, if you are setting the expire date manually (not using mod_expires or something similar to calculate the actual date) I recommend you to check your static file headers using REDbot.
A: That sounds like it's trying to avoid an outdated cache by asking the server whether the images have changed since it last requested them. Sounds like a good thing, not something you would like to prevent.
A: Assuming you are running Apache, you can try explicitly setting up cache lifetimes for certain files types and/or locations in the filesystem.
<FilesMatch ".(jpg|jpeg|png|gif)$">
Header set Cache-Control "max-age=604800, public" # 7 days
</FilesMatch>
or something like
ExpiresByType image/jpeg "access plus 7 days"
ExpiresByType image/gif "access plus 7 days"
ExpiresByType image/png "access plus 7 days"
Typically, I will group types of files by use in a single directory and set lifetimes accordingly.
Browsers should not request files at all until this ages have expired, but may not always honor it. You may want/need to futz with Last-Modified and ETag headers. There is lots of good info on the web about this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3934413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How to find the median month between two dates? I need to find the median month value between two dates in a date frame. I am simplifying the case by showing four examples.
import pandas as pd
import numpy as np
import datetime
df=pd.DataFrame([["1/31/2016","3/1/2016"],
["6/15/2016","7/14/2016"],
["7/14/2016","8/15/2016"],
["8/7/2016","9/6/2016"]], columns=['FromDate','ToDate'])
df['Month'] = df.ToDate.dt.month-df.FromDate.dt.month
I am trying to append a column but I am not getting the desired result.
I need to see these values: [2,6,7,8].
A: You can calculate the average date explicitly by adding half the timedelta between 2 dates to the earlier date. Then just extract the month:
# convert to datetime if necessary
df[df.columns] = df[df.columns].apply(pd.to_datetime)
# calculate mean date, then extract month
df['Month'] = (df['FromDate'] + (df['ToDate'] - df['FromDate']) / 2).dt.month
print(df)
FromDate ToDate Month
0 2016-01-31 2016-03-01 2
1 2016-06-15 2016-07-14 6
2 2016-07-14 2016-08-15 7
3 2016-08-07 2016-09-06 8
A: You need to convert the string to datetime before using dt.month.
This line calculates the average month number :
df['Month'] = (pd.to_datetime(df['ToDate']).dt.month +
pd.to_datetime(df['FromDate']).dt.month)//2
print(df)
FromDate ToDate Month
0 1/31/2016 3/1/2016 2
1 6/15/2016 7/14/2016 6
2 7/14/2016 8/15/2016 7
3 8/7/2016 9/6/2016 8
This only works with both dates in the same year.
jpp's solution is fine but will in some cases give the wrong answer:
["1/1/2016","3/1/2016"] one would expect 2 because February is between January and March, but jpp's will give 1 corresponding to January.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54426767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: creating a network from a list in python3 So, I'm stuck with this problem.
I am given a list of users who are friends
For example: the list appears so that
0 1,
1 2,
1 8,
2 3
and should return
[(0,[1]), (1,[0,2,8]), (2,[1,3]), (3,[2]), (8,[1])]
This is what I have so far:
network = []
for i in lines[1: (len(lines))]:
network.append(i.split(" "))
network.sort()
secondary = [[]] * (len(lines)//2) #empty lists
for j in network:
for k in secondary:
#to make a new list for each user
secondary[k].append(network[j][0])
But it says:
TypeError: list indices must be integers or slices, not list
I've tried experimenting and I'm still not sure why
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70052804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is an efficient way to do this in R? In R,
I am trying to filter out all cases from x whose $a is in y$b or y$d (when y$c is true).
x[(x$a %in% y$b | x$a %in% y[y$c == TRUE, ]$d), ]
Is this right? Is there a better way to do this?
Thanks
A: If it is a logical column, no need to == TRUE. Also, when subsetting a single column, directly subset instead of subsetting it from the data.frame which is inefficient
x[(x$a %in% y$b | x$a %in% y$d[y$c]), ]
Or make it a bit more compact
x[(x$a %in% c(y$b, y$d[y$c])),]
A: It might be worth to give subset a try.
subset(x, a %in% b | a %in% y[y$c, 'd'])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68331418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ read a Registry entry in SOFTWARE\WOW6432 from a 64-bit app I've got some 32-bit C++ code to read a Key/Value pair from the Registry as follows:
// Get a handle to the required key
HKEY hKey;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\MyKey", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
// Look up the value for the key
bOK = (RegQueryValueEx(hKey, szKey, NULL, NULL, (PBYTE)szValue, &dwMax) == ERROR_SUCCESS);
// Release the handle
RegCloseKey(hKey);
}
As it's a 32-bit app it reads from SOFTWARE\WOW6432Node\MyKey
This was working fine until I ported the app to 64-bit, so it now reads from SOFTWARE\MyKey.
My installer won't let me put entries into both the 32-bit and 64-bit parts of the Registry, so I need the 64-bit app to go on getting its data from WOW6432Node.
Does anyone know how to do this?
Many thanks
Tony Reynolds
A: As documented under 32-bit and 64-bit Application Data in the Registry:
The KEY_WOW64_64KEY and KEY_WOW64_32KEY flags enable explicit access to the 64-bit registry view and the 32-bit view, respectively. For more information, see Accessing an Alternate Registry View.
The latter link explains that
These flags can be specified in the samDesired parameter of the following registry functions:
*
*RegCreateKeyEx
*RegDeleteKeyEx
*RegOpenKeyEx
The following code accomplishes what you are asking for:
// Get a handle to the required key
HKEY hKey;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\MyKey", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS)
{
// ...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66283273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RGB Color, wrong color I am currently working on an iOS Application in Swift 3 and wanted to change the color of my NavigationBar
with the following code:
self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 53.0/255.0, green: 70.0/255.0, blue: 90.0/255.0, alpha: 1.0)
This code works quite fine but there's one problem. The color I entered in RGB format is displayed wrong.
Should be like this color:
But looks like this (left: is current Color () right: as already said should look like):
A: Set navigationController?.navigationBar.isTranslucent = false.
You can also achieve this by unchecking Translucent from storyboard.
A: Change navigation bar to Opaque instead of Translucent.
Swift
self.navigationController?.navigationBar.isTranslucent = true
Objective-C
[[UINavigationBar appearance] setTranslucent:YES];
Please find in image.
And if you are setting navigations background color then change
navigation background color instead of tint color.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45817455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xamarin forms WebAuthenticator usage I'm trying to implement Facebook Auth for Xamarin Forms App.
I'm doing everything like in this tutorial https://learn.microsoft.com/en-us/xamarin/essentials/web-authenticator?tabs=android so I'm using server side auth. Here is my mobile app code:
public class WebAuthViewModel:ObservableObject
{
private const string AuthenticationUrl = "https://myapp.com/mobileauth/";
private string _accessToken = "";
private bool _isAuthenticated = false;
public string AuthToken
{
get => _accessToken;
set => SetProperty(ref _accessToken, value);
}
public ICommand FacebookCommand { get; }
public WebAuthViewModel()
{
FacebookCommand = new Command(async()=>await OnAuthenticate("Facebook"));
}
async Task OnAuthenticate(string scheme)
{
try
{
WebAuthenticatorResult result = null;
var authUrl = new Uri(AuthenticationUrl + scheme);
var callbackUrl = new Uri("myapp://");
result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);
AuthToken = string.Empty;
if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
{
AuthToken += $"Name: {name}{Environment.NewLine}";
}
if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
{
AuthToken += $"Email: {email}{Environment.NewLine}";
}
AuthToken += result?.AccessToken ?? result?.IdToken;
IsAuthenticated = true;
}
catch (Exception ex)
{
AuthToken = string.Empty;
}
}
}
Also I have some back-end code. All this works fine, I'm getting access token, UserId and so on.
But I still have some questions.
What is the right way to validate if login is still valid?
How should I authorize app actions?
And how could I implement Logout?
I will be grateful for advices or links.
A: As a user, you don’t want to have to sign in every time you use the app. Luckily, MSAL already caches your authorization and can log you in silently if it’s still valid.When properly authenticated we receive an access token that we can subsequently use to query other APIs that are secured by MSAL.
Signing out is pretty straight forward. We go through all the available accounts that MSAL has locally cached for us and sign them out. We also clear the access token that we stored in secure storage when we signed in.
public async Task<bool> SignOutAsync()
{
try
{
var accounts = await _pca.GetAccountsAsync();
// Go through all accounts and remove them.
while (accounts.Any())
{
await _pca.RemoveAsync(accounts.FirstOrDefault());
accounts = await _pca.GetAccountsAsync();
}
// Clear our access token from secure storage.
SecureStorage.Remove("AccessToken");
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65886362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTTP header weird field explanation If you look on the response header of the http://www.yale.edu, there is a field such as
Expires: Sun, 19 Nov 1978 05:00:00 GMT.
What does it stand for?
If you want to look at it yourself, just type in terminal
curl -I http://www.yale.edu
A:
A couple of years back, this was the main way of specifying when assets expires. Expires is simply a basic date-time stamp. It’s fairly useful for old user agents which still roam unchartered territories. It is however important to note that cache-control headers, max-age and s-maxage still take precedence on most modern systems. It’s however good practice to set matching values here for the sake of compatibility. It’s also important to ensure you format the date properly or it might be considered as expired.
taken from here
After that the response is no longer cached. See here
Also worth to look at
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40687376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using VBScript how can I check if the Spooler service is started and if not start it? I'd like to use VBScript to check if the Spooler service is started and if not start it, the code below checks the service status but I need some help modifying this so I can check if it is started.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
("Select * from Win32_Service")
For Each objService in colRunningServices
Wscript.Echo objService.DisplayName & VbTab & objService.State
Next
Many thanks
Steven
A: How about something like this. This command will start it if it isn't already running. No need to check in advance.
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run "NET START spooler", 1, false
A: strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
("select State from Win32_Service where Name = 'Spooler'")
For Each objService in colRunningServices
If objService.State <> "Running" Then
errReturn = objService.StartService()
End If
Next
Note you can also use objService.started to check if its started.
A: Just for the completeless, here's an alternative variant using the Shell.Application object:
Const strServiceName = "Spooler"
Set oShell = CreateObject("Shell.Application")
If Not oShell.IsServiceRunning(strServiceName) Then
oShell.ServiceStart strServiceName, False
End If
Or simply:
Set oShell = CreateObject("Shell.Application")
oShell.ServiceStart "Spooler", False ''# This returns False if the service is already running
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3887040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Validating a password with c++ and giving specific errors I am trying to write a c++ program that validates a password that requires one uppercase letter, one lowercase letter, and a digit using functions.
The issue is that I'm trying to display the specific errors that are occurring, not just "Invalid, try again.", but I'm having a hard time figuring out how to do that. It should keep asking until they enter a valid password.
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int validate(string);
string find(int);
int main()
{
string pw;
int val;
string result;
do{
cout << "Enter password: " << endl;
cin >> pw;
val = validate(pw);
cout << find(val) << endl;
} while (val != 0);
}
//VALIDATES PASSWORD
int validate(string pw)
{
int valid = 0;
char c;
int length = pw.length();
bool digit = false;
bool upper = false;
bool lower = false;
int i = 0;
if (pw.length() < 6)
valid = 1;
while (i < pw.length())
{
c = pw[i];
i++;
if (isdigit(c))
{
digit = true;
valid++;
}
if (isupper(c))
{
upper = true;
valid++;
}
if (islower(c))
{
lower = true;
valid++;
}
//Valid input
if (length >= 6 && upper && lower && digit)
valid = 0;
}
return valid;
}
//RETURNS STRING WITH PROBLEM
string find(int valid)
{
string result;
if (valid == 0)
{
result = "Valid Password ";
}
else
{
result = "Invalid Password: ";
if (valid == 1)
result = result + " Too short ";
else if (valid == 2)
result = result + " too short, needs a digit, and an uppercase letter";
else if (valid == 3)
result = result + " too short, needs a digit, and a lowercase letter";
else if (valid == 4)
result = result + " too short, and needs an uppercase letter";
else if (valid == 5)
result = result + " too short, and needs a lowercase letter";
else if (valid == 6)
result = result + " too short, needs a digit";
else if (valid == 7)
result = result + " Needs a didgit ";
else if (valid == 8)
result = result + " Needs digit and uppercase letter ";
else if (valid == 9)
result = result + " Needs digit and lowercase letter";
else if (valid == 10)
result = result + " Needs an uppercase letter ";
else if (valid == 11)
result = result + " Needs uppercase and lowercase letter";
else if (valid == 12)
result = result + " Needs a lowercase letter";
}
return result;
}
A: I think you are confusing the number of characters (valid) and the type of error -
else if (valid == 9)
result = result + " Needs digit and lowercase letter";
could be produced from 123456abc
As valid == 9 really only counts the characters in the set. Separate counting and whether character classes are used.
A: It's better to use some flags (bool variables) instead of one number.
If you want to use one number, you must create 2^(things to check) situations
using that number. Here 2^4 = 16 situations is required.
One of the easiest way to mix flags in one number is this:
nth digit = nth flag
for example use this order (length, lower, upper, digit).
So,
to set length validity, add 1000 to number;
to set lower validity, add 100 to number;
to set upper validity, add 10 to number;
to set digit validity, add 1 to number;
Now,
((number)%10 == 1) means digit validity
((number/10)%10 == 1) means upper validity
((number/100)%10 == 1) means lower validity
((number/1000)%10 == 1) means length validity
Following code uses separate flags:
#include<iostream>
#include<string>
using namespace std;
class PasswordStatus
{
bool len, low, up, dig;
//============
public:
PasswordStatus()
{
len = low = up = dig = false;
}
//-----------
void ShowStatus()
{
cout << endl << "Password Status:" << endl;
cout << "Length : " << (len ? "OK" : "Too Short") << endl;
cout << "Contains Lower Case : " << (low ? "Yes" : "No") << endl;
cout << "Contains Upper Case : " << (up ? "Yes" : "No") << endl;
cout << "Contains Digit : " << (dig ? "Yes" : "No") << endl;
}
//-----------
void checkValidity(string pass)
{
int sLen = pass.length();
len = (sLen >= 6);
for(int i = 0; i<sLen; i++)
{
char c = pass[i];
if(!low && islower(c)) {low = true; continue;}
if(!up && isupper(c)) {up = true; continue;}
if(!dig && isdigit(c)) {dig = true; continue;}
}
}
//-----------
bool IsTotalyValid()
{
return low && up && dig && len;
}
};
//====================================================================
int main()
{
PasswordStatus ps;
string pw;
do
{
cout << endl << "Enter password: " << endl;
cin >> pw;
ps.checkValidity(pw);
ps.ShowStatus();
} while (!ps.IsTotalyValid());
cout << "Valid Password : " << pw;
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33378961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to generate breadcrumbs when I have a following category structure I have a following nested categories structure array and now I need to generate breadcrumbs for each category. Suppose I am currently viewing the Adidas category page which is in Brands->Apparel->Adidas so I need breadcrumbs like this Brands/Apparel/Adidas.
Categories array structure follows:
[1] => Array
(
[name] => 01e3f447-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
[category] => Brands
[slug] => brands
[description] =>
[image] =>
[parentCategory] =>
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 14:58:31
)
[children] => Array
(
[0] => Array
(
[name] => 0ded5b28-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
[category] => Apparel
[slug] => apparel
[description] =>
[image] =>
[parentCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 14:58:51
)
[children] => Array
(
[0] => Array
(
[name] => 3681265e-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 3681265e-4b81-11e7-a858-b8763f541038
[category] => Adidas
[slug] => adidas
[description] =>
[image] =>
[parentCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 14:59:59
)
[children] =>
)
[1] => Array
(
[name] => 3f211015-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 3f211015-4b81-11e7-a858-b8763f541038
[category] => Columbia
[slug] => columbia
[description] =>
[image] =>
[parentCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 15:00:14
)
[children] =>
)
)
)
[1] => Array
(
[name] => 1988d10a-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
[category] => Footwear
[slug] => footwear
[description] =>
[image] =>
[parentCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 14:59:11
)
[children] => Array
(
[0] => Array
(
[name] => 49becbc8-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 49becbc8-4b81-11e7-a858-b8763f541038
[category] => Polo
[slug] => polo
[description] =>
[image] =>
[parentCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 15:00:31
)
[children] =>
)
[1] => Array
(
[name] => 4e647bee-4b81-11e7-a858-b8763f541038
[nodeInfo] => stdClass Object
(
[idCategory] => 4e647bee-4b81-11e7-a858-b8763f541038
[category] => Nike
[slug] => nike
[description] =>
[image] =>
[parentCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
[idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
[date] => 2017-06-07 15:00:39
)
[children] =>
)
)
)
)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45764771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I avoid having the database password stored in plaintext in sourcecode? In the web-application I'm developing I currently use a naive solution when connecting to the database:
Connection c = DriverManager.getConnection("url", "username", "password");
This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?
A: In .NET, the convention is to store connectionstrings in a separate config file.
Thereon, the config file can be encrypted.
If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.
A: You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html
A: I can recommend these techniques for .NET programmers:
*
*Encrypt password\connection string in config file
*Setup trusted connection between client and server (i.e. use windows auth, etc)
Here is useful articles from CodeProject:
*
*Encrypt and Decrypt of ConnectionString in app.config and/or web.config
A: Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.
Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.
Also, never give priviliges to the db account over or above what is essentially needed.
An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.
A: Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.
A: *
*Create an O/S user
*Put the password in an O/S environment variable for that user
*Run the program as that user
Advantages:
*
*Only root or that user can view that user's O/S environment variables
*Survives reboot
*You never accidentally check password in to source control
*You don't need to worry about screwing up file permissions
*You don't need to worry about where you store an encryption key
*Works x-platform
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Oracle Apex instance setting on Oracle Cloud I have this error while trying to upload file in my oracle apex application on oracle cloud:
The instance does not allow unauthenticated users to upload files.
I login into the admin console to allow users to upload files but I don't see the security tab?
environmment:
Host: oracle cloud
DB : 18c
APEX : Application Express 19.1.0.00.15
A: This document addresses issues on what you can, or rather, cannot do as Instance Administrators. You are permitted to change what you have access to the web UI and SMTP parameters using the APEX_INSTANCE_ADMIN package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58433543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loading page content and its CSS dynamically - how to prevent jump because CSS is not loaded yet? On my website, I catch clicks on links to load the content of that page dynamically using AJAX. This new content may require some CSS file that isn't loaded yet. Setting the content of the target element to the response HTML will automatically load the required CSS (the <link> tags are there), but the content will look messed up for a brief period until the CSS gets loaded.
Other than loading all CSS files in advance, what can I do to prevent this? For completeness sake, here is my code:
$(document).ready(function() {
$('a').live('click', function(event) {
if (this.target || this.rel == 'ignore' || this.rel == 'fancybox') {
return true;
}
if (/^javascript:/.test(this.href)) {
return true;
}
if (this.href.indexOf('#') >= 0) {
return false;
}
if (!this.href) {
return true;
}
loadDynamicPage(this.href);
event.preventDefault();
return false;
});
});
var currentLoader = null;
function loadDynamicPage(url) {
if (currentLoader) {
currentLoader.abort();
currentLoader = null;
}
$('#backButton').addClass('loaderBG');
currentLoader = $.ajax({
context: $('#army_content'),
dataType: 'text',
url: url + '&format=raw',
success: function(data) {
currentLoader = null;
$('#backButton').removeClass('loaderBG');
clearRoomIntervals();
$(this).html(data).find('[title]').tooltip({
showURL: false,
track: false,
delay: 300
});
$(document).trigger('dynamicLoad');
}
});
}
A: *
*Click on the link, show "Loading.."
*Load CSS file by ajax, in callback function, create <style> tag, and then insert CSS code to <style> tag, and then start load content by ajax.
*you can optimize the flow by load CSS and content individually, but content only take place in a hidden container, once CSS file finish load, then change hidden container to be shown.
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5232160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenCV, can't release CAP_OPENCV_MJPEG VideoWriter for long records Hi stackoverflow community,
I recently had a problem with the performance of the opencv VideoWriter (see here), and I am now using cv::CAP_OPENCV_MJPEG as a backend instead of cv::CAP_FFMPEG.
Now I am running in another issue, so my code looks like this:
cv::VideoWriter videoWriter(path, cv::CAP_OPENCV_MJPEG, fourcc, fps, *size);
videoWriter.set(cv::VIDEOWRITER_PROP_QUALITY, 100);
int id = metaDataWriter.insertNow(path);
while (this->isRunning) {
while (!this->stackFrames.empty()) {
cv:Mat m = this->stackFrames.pop();
videoWriter << m;
}
}
videoWriter.release();
This loop runs in a separate thread and "isRunning" will be switched from outside. There is a stack with cv::Mat (stackFrames) which is filled by another thread that captures the images by a video capture card. This works fine, but if the file size is too big, several GB, I get the following error when the videoWriter.release() is called:
terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.4.0) /home/michael-gary/opencv/opencv/modules/videoio/src/container_avi.cpp:27: error: (-211:One of the arguments' values is out of range) Failed to write AVI file: chunk size is out of bounds in function 'safe_int_cast'
I tried to change the video container from .avi to .mkv, .mp4, .mpg but none of them is working, it does not even create the file. Only .avi is working, but fails by the release.
For now I will try to write multiple files, so I don't run in this problem, but I would like to face the problem itself.
Open for any suggestions
BR Michael
A: AVI files are practically limited in size.
when you force it to use OPENCV_MJPEG, it will only use OpenCV's own writing methods, which can only do AVI and MJPEG.
if you need a different container, you have to use a different backend, such as FFMPEG. you can still have MJPG for a codec (fourcc).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65358568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Correct status code to send for an HTTP POST request where the given ID does not match an object in the database Lets say I have an endpoint in my API with the following URL:
www.example.com/api/create-order-for-restaurant/
Now, in my POST request, I send the following data:
{
"restaurant_id": 43,
"order": {...}
}
Lets say a restaurant with the id 43 does not exist in my database. What should be the appropriate HTTP status code that should be sent back to the client?
Im confused if I should be sending back 404 or 500.
A: This is a client error because the client specified a restaurant_id that didn't exist.
The default code for any client error is 400, and it would be fitting here too.
There are slightly more specific client error codes that might work well for this case, but it's not terribly important unless there is something a client can do with this information.
*
*422 - could be considered correct. The JSON is parsable, it just contains invalid information.
*409 - could be considered correct, if the client can create the restaurant with that specific id first. I assume that the server controls id's, so for that reason it's probably not right here.
So 400, 422 is fine. 500 is not. 500 implies that there's a server-side problem, but as far as I can tell you are describing a situation where the client used an incorrect restaurant_id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56157615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Line height in textarea (IE7) I have a textarea (fixed size), which is getting populated by some text which is then resized to fit (font changed).
The code below runs fine in Chrome, Firefox, etc, but not IE (versions 7/8/9, which it also has to).
In non-IE, the text gets resized and fits in the textares nicely, but in IE there is huge gaps between each line of the textarea.
I have tried setting line-height but it doesn't seem to work. I have read that it is todo with the height of the font, which would mean wrapping each line in a span and setting a negative top margin.
Any ideas greatly appreciated.
Code sample;
html
<span id="inner-text">
<textarea readonly="readonly"
cols="10"
rows="5"
class="messagetext"
style="width:400px; border:none;height:100px;overflow-y:hidden; resize:none;color: #D31245;"
>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>
</span><span id="temp" style="visibility:hidden"></span>
JS
$(function() {
var while_counter = 1;
var txt = $('textarea.messagetext');
var font_size = txt.css('font-size').replace(/\D/g,'');
var scHeight = txt.get(0).scrollHeight;
var txtHeight = txt.height();
while ( scHeight > (txtHeight+10) ) {
font_size = (font_size - 1);
txtHeight = (txtHeight + 15);
while_counter = while_counter + 1;
}
var lines = txt.val().split('\n');
var total_lines = lines.length;
var span_width = $('#inner-text').width() - 5;
var temp_span = $('#temp');
// now calculate line wraps
$.each(lines, function(){
// temp write to hidden span
temp_span.html(String(this));
// check width
if (temp_span.width() > 400) {
total_lines = total_lines + 1;
}
});
txt.css('font-size', font_size+'px');
txt.height( (total_lines * font_size) + (total_lines * 1.14) + 10);
});
A: Copy below code in one html file and check in IE
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('hi');
var while_counter = 1;
var txt = $('textarea.messagetext');
var font_size = txt.css('font-size').replace(/\D/g,'');
var scHeight = txt.get(0).scrollHeight;
var txtHeight = $(txt).height();
while ( scHeight > (txtHeight+10) ) {
font_size = (font_size - 1);
txtHeight = (txtHeight + 15);
while_counter = while_counter + 1;
}
var lines = txt.val().split('\n');
var total_lines = lines.length;
var span_width = $('#inner-text').width() - 5;
var temp_span = $('#temp');
// now calculate line wraps
$.each(lines, function(){
// temp write to hidden span
temp_span.html(String(this));
// check width
if (temp_span.width() > 400) {
total_lines = total_lines + 1;
}
});
$(txt).css('font-size', font_size+'px');
$(txt).innerHeight( (total_lines * font_size) + (total_lines * 1.14) + 10);
});
</script>
</head>
<body>
<span id="inner-text">
<textarea readonly="readonly"
cols="10"
rows="5"
class="messagetext"
style="width:400px; border:none;height:100px;overflow:hidden;resize:none;color: #D31245;"
>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>
</span><span id="temp" style="visibility:hidden"></span>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13286286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular Firestore - Get document ID as a property to use it again in an other function - Typescript So here is my code :
getOutfitsCollectionData(): Promise<any> {
let outfitsRef = this.afStore.collection('outfits');
let allOutfits = outfitsRef.snapshotChanges().pipe(
map(actions=>{
return actions.map(a=>{
const id = a.payload.doc.id;
return id
})
})
)
let outfitsID = allOutfits.forEach(outID=>{
console.log(outID)
return outID
})
return outfitsID
}
}
When I do this part
let outfitsID = allOutfits.forEach(outID=>{
console.log(outID)
return outID
})
The console is giving me this :
console perfect
It's exactly what I want, I just want to rename the array and set it as the result of my function but every console.log I put under these lines doesn't do anything so it seems that every line under isn't doing anything.
If I'm not clear, tell me guys !
What I'm trying to do is get each documents id of my collection to use it in an other function on the same tab.
I think that it might be easier to create a service but I don't really know how to do it.
Please don't make me ban one more time, I'm just trying to learn ... It won't be really smart to send me to a really general subject.
I'm not just trying to have pro that give a code that works, I want to understand and get better.
Thanks for your help guys !
( BTW sorry for my bad English, I'm French :) )
So just a little edit :
I tried this code, I don't really understand why when I console.log allOutfits, I'm not getting the good value :
async getOutfitsCollectionData(){
let outfitsRef = this.afStore.collection('outfits');
let allOutfits = await outfitsRef.get().toPromise().then((step)=>{
return step.forEach(doc=>{
if (!doc.exists){
console.log('Zut !')
}else{
console.log(doc.id)
return doc.id
}
})
})
.catch(err=>{
console.log('Error getting outfits', err)
})
console.log(allOutfits)
return allOutfits
}
A: Problem lies in this code:
return step.forEach(doc=>{
if (!doc.exists){
console.log('Zut !')
}else{
console.log(doc.id)
return doc.id
}
step is a QuerySnapshot so you should access the documents using step.docs. The function forEach does not return you the the array, but returns undefined instead.
use map which actually returns the transformed data:
return steps.docs.map(doc => doc.id);
A: I've finished my app long time ago, but I think that might interest.
I finally decided to learn typescript lol.
You can't get a value of a promise since it's not return, that was what I was trying to do.
Just call your function and .then do what you want ^^.
By the way, I needed to map my data as said by Lim Shang Yi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62027646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: performance advantages of using bottle for routing? I started developing a web application based on the bottle web framework a couple of years ago. I chose Bottle at that time because it was the easiest solution to get up and running fast, and I was just working on building a prototype of an idea I had. Now, I have several thousand lines of code, and I'm looking to move into production-level solution.
At first I thought that I should move to a full stack framework such as django or web2py. As I was moving that direction, I started just using various parts of other frameworks as I needed them. For example, I implemented web2py's data access layer (DAL) so that I could run my application on google-app-engine, and now I'm looking to into using web2py's scheduler to manage jobs. Then, I began to use cherrypy as a production-level webserver. I tried the rocket server, but I was getting more errors with it, so I preferred cherrypy over rocket.
I started looking into rewrite my code to fully use web2py's full stack solution; however, the amount of time to rewrite my routing functions to fully move into web2py seems to be significant, and I really wasn't happy with the rocket server.
I really like the simplicity of Bottle, the way that Bottle uses decorator functions to map the routes to the functions, and also the philosophy of extensibility.
I want to know if there are any specific advantages in terms of performance in using Bottle to do routing, versus any of the full stack frameworks.
I appreciate anyone's advice on this!
A: According to this benchmark and others, Bottle performs significantly faster than some of its peers, which is worth taking into account when comparing web frameworks' performance:
1. wheezy.web........52,245 req/sec or 19 μs/req (48x)
2. Falcon............30,195 req/sec or 33 μs/req (28x)
3. Bottle............11,977 req/sec or 83 μs/req (11x)
4. webpy..............6,950 req/sec or 144 μs/req (6x)
5. Werkzeug...........6,837 req/sec or 146 μs/req (6x)
6. pyramid............4,035 req/sec or 248 μs/req (4x)
7. Flask..............3,300 req/sec or 303 μs/req (3x)
8. Pecan..............2,881 req/sec or 347 μs/req (3x)
9. django.............1,882 req/sec or 531 μs/req (2x)
10. CherryPy..........1,090 req/sec or 917 μs/req (1x)
But bear in mind that your web framework may not be your bottleneck.
A: From the creator of web2py, Massimo Di Pierro:
If you have simple app with lots of models, bottle+gluino may be
faster than web2py because models are executed only once and not at
every request.
Reference:
groups.google.com/forum/#!topic/web2py/4gB9mVPKmho
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28473908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual Studio package cannot be debugged in VS 2017 RC I have a VSIX package (extension) that works and can be debugged in VS 2013 and 2015. I have now adjusted the manifest to allow the package to be installed in VS 2017. However, it doesn't work there properly and I want to debug it.
I open the package project in VS 2015 and tell it to debug the package in VS 2017 RC with the usual command line switch /rootsuffix Exp. A clean VS 2017 instance starts, but the package is not installed in it so it cannot be debugged. How to fix this?
A: The only practical way to add support for VS 2017 is to open and build your extension in VS 2017: How to: Migrate Extensibility Projects to Visual Studio 2017. After the migration it should be easy to debug in VS 2017.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41035089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: open62541 Visual Studio 2017 error, OPCUA I am trying to build open62541, generate files for VS 2017, using Cmake.
I am having problem,
"MSB6006 'cmd.exe' exited with code 1 error " for open62541 files.
When I build the generated file from Cmake, using VS2017.
I am trying to connect my 4Diac control system to UA expert, which will be used to read and write data to JS simulator.
I am looking for answers but have not found any satisfactory answers.
I will really appreciate some solution.
Thank you.
BR,
Ahsan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51651989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you control the size of a blank character in a TextBox or a MessageBox? Picture (1) is the content of my string (This is an output of an ML.NET routine. I don't have control of it). Picture (2) is how the string looks like in a TextBox or a MessageBox.
The blank character size in a TextBox is slightly smaller than in a string. How can we fix that?
(1)
(2)
A: To ensure text alignment in vb.net textbox/Messagebox string, use-
*
*MonoSpace font
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.fontfamily.genericmonospace?view=dotnet-plat-ext-6.0
C# .NET multiline TextBox with same-width characters
*Add padding to each text piece to position it in desired location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72997642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python password strength checker How you would change the code below so that a new password is asked until the password is strong?
I know that you have to use a while loop but I keep making a mess of it every time I try.
digits = False
upcase = False
lowcase = False
alnum = False
password = input("Enter a password between 6 and 12 characters: ")
while len(password) < 6 or len(password)>12:
if len(password)<6:
print("your password is too short")
elif len(password) > 12:
print("your password is too long")
password = input("Please enter a password between 6 and 12 characters.")
for i in range(0,len(password)):
if password[i].isupper():
upcase = True
if password[i].islower():
lowcase = True
if password[i].isalnum():
alnum = True
if password[i].isdigit():
digits = True
if digits and alnum and lowcase and upcase and digits:
print("Your password is strong")
elif (digits and alnum) or (digits and lowcase) or (digits and upcase) or (alnum and lowcase) or (alnum and upcase) or (lowcase and upcase):
print("Your password is medium strength")
else:
print("Your password is weak")
A: Try this:
notStrong = True
while notStrong:
digits = False
upcase = False
lowcase = False
alnum = False
password = input("Enter a password between 6 and 12 characters: ")
while len(password) < 6 or len(password)>12:
if len(password)<6:
print("your password is too short")
elif len(password) > 12:
print("your password is too long")
password = input("Please enter a password between 6 and 12 characters.")
for i in range(0,len(password)):
if password[i].isupper():
upcase = True
if password[i].islower():
lowcase = True
if password[i].isalnum():
alnum = True
if password[i].isdigit():
digits = True
if digits and alnum and lowcase and upcase and digits:
print("Your password is strong")
notStrong = False
elif (digits and alnum) or (digits and lowcase) or (digits and upcase) or (alnum and lowcase) or (alnum and upcase) or (lowcase and upcase):
print("Your password is medium strength")
else:
print("Your password is weak")
A: You don't have to make use of a loop, you can simply call the function within itself if the password is weak or medium, like so:
def Password():
digits = False
upcase = False
lowcase = False
alnum = False
password = input("Enter a password between 6 and 12 characters: ")
while len(password) < 6 or len(password)>12:
if len(password)<6:
print("your password is too short")
elif len(password) > 12:
print("your password is too long")
password = input("Please enter a password between 6 and 12 characters.")
for i in range(0,len(password)):
if password[i].isupper():
upcase = True
if password[i].islower():
lowcase = True
if password[i].isalnum():
alnum = True
if password[i].isdigit():
digits = True
if digits and alnum and lowcase and upcase and digits:
print("Your password is strong")
elif (digits and alnum) or (digits and lowcase) or (digits and upcase) or (alnum and lowcase) or (alnum and upcase) or (lowcase and upcase):
print("Your password is medium strength")
Password()
else:
print("Your password is weak")
Password()
Password()
This is a very useful technique and can be used to simplify many problems without the need for a loop.
Additionally, you can put in another check so that you can adjust the required strength of the password as needed in the future - this is not as easy to do (or rather, cannot be done as elegantly) if you use a while loop.
EDIT - To add to the advice given in the comments:
How does a "stack overflow" occur and how do you prevent it?
Not deleting the answer because I now realize that it serves as an example of how one shouldn't approach this question, and this may dissuade people from making the same mistake that I did.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64957627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Kernel Error in Jupyter notebook - failed to start I am facing a Kernel Error in Jupyter Notebook.
I am on Windows 10, created a new environment for tensorflow in Anaconda using Python 3.5
Initially, Jupyter Notebook did not start. I was told to downgrade “tornado” to 5.1.1
After downgrading tornado to 5.1.1 (current version), Jupyter Notebook starts but i have the following Kernel error.
Any kind souls can help to advise on the issue. Thank you in advance.
Traceback (most recent call last):
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 528, in get
value = obj._trait_values[self.name]
KeyError: 'loop'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\notebook\base\handlers.py", line 457, in wrapper
result = yield gen.maybe_future(method(self, *args, **kwargs))
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1133, in run
value = future.result()
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1141, in run
yielded = self.gen.throw(*exc_info)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\notebook\services\sessions\handlers.py", line 62, in post
kernel_id=kernel_id))
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1133, in run
value = future.result()
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1141, in run
yielded = self.gen.throw(*exc_info)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 79, in create_session
kernel_name)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1133, in run
value = future.result()
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1141, in run
yielded = self.gen.throw(*exc_info)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 92, in start_kernel_for_session
self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 1133, in run
value = future.result()
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\tornado\gen.py", line 326, in wrapper
yielded = next(result)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 87, in start_kernel
super(MappingKernelManager, self).start_kernel(**kwargs)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
km.start_kernel(**kwargs)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\jupyter_client\manager.py", line 258, in start_kernel
self.start_restarter()
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\jupyter_client\ioloop\manager.py", line 49, in start_restarter
kernel_manager=self, loop=self.loop,
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 556, in __get__
return self.get(obj, cls)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 535, in get
value = self._validate(obj, dynamic_default())
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 591, in _validate
value = self.validate(obj, value)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 1677, in validate
self.error(obj, value)
File "C:\Users\fayas\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\traitlets.py", line 1524, in error
raise TraitError(e)
traitlets.traitlets.TraitError: The 'loop' trait of an IOLoopKernelManager instance must be a ZMQIOLoop, but a value of class 'tornado.platform.asyncio.AsyncIOMainLoop' (i.e. <tornado.platform.asyncio.AsyncIOMainLoop object at 0x000002AED01F69E8>) was specified.
[E 15:41:57.102 NotebookApp] {
"Host": "localhost:8888",
"Connection": "keep-alive",
"Content-Length": "158",
"Accept": "application/json, text/javascript, */*; q=0.01",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
"Content-Type": "application/json",
"Origin": "http://localhost:8888",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "http://localhost:8888/notebooks/Desktop/cellstrat/DL%20Course/CellStrat%20DL%20course%20Mod%201/demo2/Module2_graphs.ipynb",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Cookie": "_xsrf=2|1213e26b|cf2abf81e87bb35c13497822b64d0315|1607083322; username-localhost-8888=\"2|1:0|10:1607083520|23:username-localhost-8888|44:OTRlNTYwMGNlZTg0NDlhZTk3Y2NlNDIzNDBiMmIyMzc=|8fb6e08950a5fc84a46daa6b8798530ca0071664e3001824679396a616bbe4fb\""
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65197270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get ajax POST form values in Nodejs? Am trying to get ajax POST values it backend via nodejs but keep getting undefined values.
Form request: com_type: undefined value: undefined
what am doing?
frontend js code
const formData = new FormData();
formData.append('com_type', "AAAA");
formData.append('com_value', "123456");
let origin = window.location.origin;
let url = origin + "/api";
fetch(url, {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
backend nodejs side
// my app express settings
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
/ API route
app.post('/api', function(request, response) {
// Capture the input fields
let com_type = request.body.com_type;
let com_value = request.body.com_value;
console.log(request.body);
response.json(request.body);
console.log('Form request: com_type: '+com_type+' value: '+com_value);
//response.sendStatus(200)
});
so any idea what am doing wrong as am getting
Form request: com_type: undefined value: undefined
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73232060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Determine application framework version in library C# I have a library which is .NET standard version. This library will be used both .NET app and .NET Core apps. I want to use IConfiguration for .NET Core apps in my library but .NET apps throw an exception.
I need to check version or determine the application if .NET Core or .NET framework? I have tried get appsettings.json file to determine app type but getting root path different both .NET and .NET Core apps.
When I tried to get framework version of app it gives me library's version.
How can I distinguish which type of application it is? How can I achieve this?
A: There are several ways to solve your problem:
*
*try to use more common parameters for your methods that requires string's, int's or custom classes instead. Is it really necessary to add a framework specific class or function or is there a better option?
*You can use a multi-target configuration for your library which then requires #if NET45 and #elif NETSTANDARD2_0 code everywhere you have to use different logic for different frameworks. This could lead to not very well readable code.
*Use two libraries, one for .NET Core apps (e.g. based on .NET Standard 2.1) and the other for .NET Framework (e.g. .NET FW 4.8). The .cs files from the .NET Standard library can then also be used in the .NET 4.8 library (if compatible features have been used). The .cs files can be selected e.g. in VS via "context menu > add existing element". When confirming the selected file(s), expand the dropdown option under "Add" and select "Add as Link". This way the file only needs to be maintained once (changes are applied in both libraries). Framework-specific files can then be added individually in the respective library, not as a link. Here's a good article about it.
These are just some examples, there might be of course other or better solutions to it.
Personally I would try to use independent arguments for my methods, if this is not possible I prefer the custom library solution for each framework version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70037595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having issues removing UIViews from a UIScrollView I'm trying to make code that will add players to a view based on objects but, I'm having some issues.
Right now currently if I run the initView method with 4 confirmed working Player objects in playerList, only 3 UIViews will appear in my scrollview, then when I click the clear players button, only the last (3rd) UIView will be removed.
A side note, none of my custom buttons appear in the UIViews either, I have an image that they should load with, but its not working.
Thanks in advance for any help.
- (void)clearPlayers {
for (Player* i in self.playerList) {
[i.viewPane removeFromSuperview];
}
[self.playerList removeAllObjects];
}
- (void)initView {
int Loc = 0;
int Count = 1;
int margin = 5;
int height = 100;
for (Player *p in playerList) {
UIView *playerView = [[UIView alloc] initWithFrame:CGRectMake(0, Loc, 320.0, height)];
p.viewPane = playerView;
[playerView setBackgroundColor:[UIColor redColor]];
[scrollView addSubview:playerView];
UIButton *plus = [[UIButton alloc] initWithFrame:CGRectMake(200, 10, (height - 5), (height - 5))];
UIImage *buttonImage =[[UIImage alloc] initWithContentsOfFile:@"Metal_Plus_Up_2.png"];
[plus setBackgroundImage:buttonImage forState:UIControlStateNormal];
[p.viewPane addSubview:plus];
[plus release];
[playerView release];
Loc = Loc + (height + margin);
Count = Count + 1;
}
[scrollView setContentSize:CGSizeMake(320.0, (height * Count) + (margin * Count))];
}
A: Question: have you verified that the UIImage returned from initWithContentsOfFile is not nil? You might need the full path instead of just the filename
As far as the wackiness with the UIViews not getting removed goes, everything you've posted looks fine as far as I can see. The only thing I can think of is that maybe you don't have retain specified as an attribute for your viewPane property...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6178136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: With Rust Regular Expressions, how can I use named capture groups preceding a string? I'm using the sd tool which uses rust regular expressions, and I am trying to use it with a named capture group, however if in the replacement the named capture group precedes a string, then the string is included as the potential the for named capture group, causing unexpected behaviour.
Here is a contrived example to illustrate the issue:
echo 'abc' | sd -p '(?P<cg>b)' '$cgB'
# outputs: ac
# desired output: abBc
echo 'abc' | sd -p '(?P<cg>b)' '$cg B'
# outputs as expected: ab Bc
# however, places a space there
I've tried $<cg>B, $cg(B), $cg\0B, all don't give abBc.
I've also checked the rust regex docs however the x flag, and other techniques seem only applicable to the search pattern, not the replace pattern.
A: We don't need the sd tool to reproduce this behavior. Here it is in pure Rust:
let re = regex::Regex::new(r"(?P<n>b)").unwrap();
let before = "abc";
assert_eq!(re.replace_all(before, "$nB"), "ac");
assert_eq!(re.replace_all(before, "${n}B"), "abBc");
The brace replacement syntax isn't described in the front documentation but on the documentation of the replace method:
The longest possible name is used. e.g., $1a looks up the capture
group named 1a and not the capture group at index 1. To exert more
precise control over the name, use braces, e.g., ${1}a.
In short, unless there's a character that can't be part of a name just after in the replacement pattern, you should always put the group name between braces.
A: For the rust regexes via sd via bash use case in the question:
echo 'abc' | sd -p '(?P<cg>b)' '${cg}B'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70196449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Julia char array to string This seems like a really obvious thing to do, but I couldn't find a solution. I tried:
convert(String, array)
# -> MethodError: Cannot `convert` an object of type Array{Char,1} to an object of type String
and
string(array)
# -> "['U']"
Obviously none achieve what I want to achieve.
My whole code looks like this:
function to_rna(dna)
assignments = Dict('G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U')
res = Char[length(dna)]
for i in 1:length(dna)
res[i] = assignments[dna[i]]
end
return string(res)
end
A: You want the actual String constructor:
julia> String(['a', 'b', 'c'])
"abc"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68582375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ggplot2 displaying unlabeled tick marks between labeled tick marks I've been having issues displaying minor tick marks on my histogram plot. I've tried the idea of plotting unlabeled major tick marks, but the tick marks wouldn't display. My code is pretty cumbersome and probably has some redundant lines. Any help would be appreciated.
ggplot(data=Shrimp1, aes(Shrimp1$Carapace.Length))+
geom_histogram(breaks=seq(3.5, 25, by=0.1),
col="black",
fill="gray",
alpha=1)+
labs(title="Total Female Carapace Length")+
labs(x="Carapace Length (mm)", y="# of Shrimp")+
xlim(c(3.5, 25))+
theme_bw()+
scale_y_continuous(expand = c(0,0),
limits = c(0,200))+
scale_x_continuous(breaks=seq(2.5,25,2.5))+
theme(axis.text.x=element_text(size=30,angle=45,hjust=1))+
theme(plot.title=element_text(size=30, hjust=0.5))+
theme(axis.text=element_text(size=30, color = "black"),
axis.title=element_text(size=30,face="bold"))+
theme(panel.grid.major=element_line(colour="white"),
panel.grid.minor = element_line(colour = "white"))+
theme(panel.border=element_blank())+
theme(axis.ticks.x = (element_line(size=2)),
axis.ticks.y=(element_line(size=2)))+
theme(axis.ticks.length=unit(.55, "cm"))+
theme(panel.border=element_blank(), axis.line.x=element_line(colour="black"),
axis.line.y=element_line(colour="black"))
Major ticks are present but I need minor ticks between them at intervals of 0.1
A: I don't think you can add ticks to minor breaks, but you can have unlabeled major ticks, as you were thinking, by labeling them explicitly in scale_x_continuous. You can set the "minor" tick labels to blank using boolean indexing with mod (%%).
Similarly, you can set the tick sizes explicitly in theme if you want the "minor" ticks to be a different size.
set.seed(5)
df <- data.frame(x = rnorm(500, mean = 12.5, sd = 3))
breaks <- seq(2.5, 25, .1)
labels <- as.character(breaks)
labels[!(breaks %% 2.5 == 0)] <- ''
tick.sizes <- rep(.5, length(breaks))
tick.sizes[(breaks %% 2.5 == 0)] <- 1
df %>%
ggplot(aes(x)) +
geom_histogram(binwidth = .1, color = 'black', fill = 'gray35') +
scale_x_continuous(breaks = breaks, labels = labels, limits = c(2.5,25)) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.ticks.x = element_line(size = tick.sizes))
Also as you might notice from my code, you can just call theme() once and put all the theme modifications into that one call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46412250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UINavigationController navigationBarHidden set to true only for a single view controller Assuming, I have a view hierarchy of type:
A [rootviewcontroller of a UINavigationController] --> B --> C
I want to disable the navigationBar for A but enable it for B & C.
*
*Is it possible to do so?
*Currently I am achieving this by enabling it in viewWillAppear for B & C but disabling when viewWillAppear for A. It kind of does the job but it feels unnatural and forced. Is there a right way of doing this?
A: You better hide the navigationBar inside viewDidAppear method.
-(void)viewDidAppear:(BOOL)animated{
[yourNavigationController setNavigationBarHidden:YES animated:YES];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27612081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sinatra & Rails 3 routes issue I have just setup Sinatra v1.1.0 inside my rails (v3.0.1) app. But I can't invoke any routes that are more than 1 level deep, meaning this works - http://localhost/customer/3,
but this one does not work - http://localhost/customer/3/edit and I get a "Routing Error"
Here's the Sinatra object
class CustomerApp < Sinatra::Base
# this works
get "/customer/:id" do
"Hello Customer"
end
# this does NOT work
get "/customer/:id/edit" do
"Hello Customer"
end
end
This is what I have in my rails routes.rb file -
match '/customer/(:string)' => CustomerApp
I am guessing I need some magic in the routes file? What could be the problem?
A: In your routes file, you can specify the mapping this way:
mount CustomerApp, :at => '/customer'
Now, inside your sinatra application, you can specify your routes without the /customer part.
Dont't forget to require your sinatra application somewhere (you can do it directly in the route file)
A: You need to add an additional route to match the different URL:
match '/customer/(:string)/edit' => CustomerApp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4191698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conditionally Apply Class with Advanced Custom Fields I'm using Advanced Custom Fields (ACF PRO) to build out a CMS for a client. Currently, ACF allows you to give a particular field a class. In addition, you can make this field appear under certain conditions.
I'm looking for a way to combine the these two concepts.
Simply put, let's say I want to have a text editor's background color turn blue if a certain condition is met. With the current set up, I'd have to create two completely different fields, a default field and a field that has its own class that I can target and make blue. This would mean that, if I started typing out my content and decided halfway through that I would rather a blue background, the content would appear to disappear because a completely new field would have to load based on the new condition.
I'd much rather be able to conditionally apply a class to a single field.
Can anyone point me in the right direction?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44524692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Image Normalization in Java I have been working on finger image processing and I am currently want to do Normalization.
I have studied this link on Griuale Biometric website.
The idea of normalization consist in changing the intensity of each pixel so that mean and variance of the whole image are changed to some predefined values.
Could any suggest me any example code or algorithm in java that can help me.
EDIT:
I am taking image pixel's MEAN and VARIANCE into account for the image normalization:
Here is my code:
public class NormalizeHistMeanVariance {
private static BufferedImage original, normalize;
public static void main(String[] args) throws IOException {
final int N = 256; // Number of graylevels
final int M = 250; // Max value in histogram for displaying purposes
int nrows, ncols, size, in_img[][], out_img[][];
int i, j, max, maxgray;
double hist[] = new double[N], norm, mean, var, tmp;
String f1 = "E:/single.jpg";
String f2 = "E:/normImg";
File original_f = new File(f1);
original = ImageIO.read(original_f);
Histogram histogram = new Histogram(original);
in_img = histogram.getPixels(original);
nrows = in_img.length;
ncols = in_img[0].length;
size = in_img.length * in_img[0].length;
// Compute average gray and histogram
for (i = 0; i < N; i++)
hist[i] = 0;
mean = 0;
for (i = 0; i < nrows; i++) {
for (j = 0; j < ncols; j++) {
hist[in_img[i][j]]++;
mean += in_img[i][j];
}
}
mean /= size;
System.out.println("Mean graylevel = " + mean);
// Compute variance
var = 0;
for (i = 0; i < nrows; i++) {
for (j = 0; j < ncols; j++) {
tmp = in_img[i][j] - mean;
var += tmp * tmp;
}
}
var = Math.sqrt(var / (size));
System.out.println("Variance = " + var);
max = maxgray = 0;
for (i = 0; i < N; i++) {
if (max < hist[i]) {
max = (int) hist[i];
maxgray = i;
}
}
System.out.println("Max count " + max + " (graylevel = " + maxgray
+ " )");
// Normalize to M for better display effect
norm = (double) M / maxgray;
System.out.println("Norm = " + norm);
out_img = new int[nrows][ncols];
for (int x = 0; x < in_img.length; x++) {
for (int y = 0; y < in_img[0].length; y++) {
out_img[x][y] = (int) (in_img[x][y] * norm);
}
}
normalize = ImageUtils.CreateImagefromIntArray(out_img);
writeImage(f2);
}
private static void writeImage(String output) throws IOException {
File file = new File(output + ".jpg");
ImageIO.write(normalize, "jpg", file);
}
}
What i want is smooth image after normalization like in this link. But I am not getting desired result. Could anyone help me?
A: Here is a Java project that does image normalization, includes code:
http://www.developer.com/java/other/article.php/3441391/Processing-Image-Pixels-Using-Java-Controlling-Contrast-and-Brightness.htm
When working with images, terms that are used are (root mean square) contrast and brightness instead of variance and average.
(Be sure to specify what kind of contrast definition you use.)
Information in this page seems to hint that it is about histogram equalization.
http://answers.opencv.org/question/6364/fingerprint-matching-in-mobile-devices-android/
Information on wikipedia: http://en.wikipedia.org/wiki/Histogram_equalization#Implementationhint
A: I can help you implementing Image Normalization used in this article Fingerprint Recognition Using Zernike Moments
Try to use Catalano Framework, in next version (1.2), I'll code Image Normalization in the framework.
Zernike Moments is ready like Hu Moments too, if you want to do like this article.
A: So, you dont need to use Histogram to perform this filter.
// Parameters to ImageNormalization
float mean = 160;
float variance = 150;
int width = fastBitmap.getWidth();
int height = fastBitmap.getHeight();
float globalMean = Mean(fastBitmap);
float globalVariance = Variance(fastBitmap, globalMean);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int g = fastBitmap.getGray(i, j);
float common = (float)Math.sqrt((variance * (float)Math.pow(g - globalMean, 2)) / globalVariance);
int n = 0;
if (g > globalMean){
n = (int)(mean + common);
}
else{
n = (int)(mean - common);
}
n = n > 255 ? 255 : n;
n = n < 0 ? 0 : n;
fastBitmap.setGray(i, j, n);
}
}
private float Mean(FastBitmap fb){
int height = fb.getHeight();
int width = fb.getWidth();
float mean = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mean += fastBitmap.getGray(i, j);
}
}
return mean / (width * height);
}
private float Variance(FastBitmap fb, float mean){
int height = fb.getHeight();
int width = fb.getWidth();
float sum = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
sum += Math.pow(fastBitmap.getGray(i, j) - mean, 2);
}
}
return sum / (float)((width * height) - 1);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18576538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to untar all tar files in current directory using Putty How can I untar all tar files in one command using Putty.
I Tried the following but its not un-tarring (all files start with alcatelS*)
tar -xfv alcatelS*.tar
It is not working i don't get no errors and it is not un-tarring.
Thank you,
A: You can use following command for extract all tar.gz files in directory in unix
find . -name 'alcatelS*.tar.gz' -exec tar -xvf {} \;
A: -xfv is wrong since v is being referred as the file instead. Also, tar can't accept multiple files to extract at once. Perhaps -M can be used but it's a little stubborn when I tried it. Also, it would be difficult to pass multiple arguments that were extracted from pathname expansion i.e. you have to do tar -xvM -f file1.tar -f file2.tar.
Do this instead:
for F in alcatelS*.tar; do
tar -xvf "$F"
done
Or one-line: (EDIT: Sorry that -is- a "one"-liner but I find that not technically a real one-liner, just a condensed one so I should haven't referred to that as a one-liner. Avoid the wrong convention.)
for F in alcatelS*.tar; do tar -xvf "$F"; done
A: Following is my favorite way to untar multiple tar files:
ls *tar.gz | xargs -n1 tar xvf
A: Can be done in one line:
cat *.tar | tar -xvf - -i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25123651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem Fetching JSON Result with jQuery in Firefox and Chrome (IE8 Works) I'm attempting to parse JSON using jQuery and I'm running into issues. Using the code below, the data keeps coming back null:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url: 'http://datawarehouse.hrsa.gov/ReleaseTest/HGDWDataWebService/HGDWDataService.aspx?service=HC&zip=20002&radius=10&filter=8357&format=JSON',
type: 'GET',
dataType: 'json',
success: function(data) {
$('#msg').html(data[0].title); // Always null in Firefox/Chrome. Works in IE8.
},
error: function(data) {
alert(data);
}
});
</script>
</body>
</html>
The JSON results look like the following:
{"title":"HEALTHPOINT TYEE CAMPUS","link":"http://www.healthpointchc.org","id":"tag:datawarehouse.hrsa.gov,2010-04-29:/8357","org":"HEALTHPOINT TYEE CAMPUS","address":{"street-address":"4424 S. 188TH St.","locality":"Seatac","region":"Washington","postal-code":"98188-5028"},"tel":"206-444-7746","category":"Service Delivery Site","location":"47.4344818181818 -122.277672727273","update":"2010-04-28T00:00:00-05:00"}
If I replace my URL with the Flickr API URL (http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?), I get back a valid JSON result that I am able to make use of.
I have successfully validated my JSON at JSONLint, so I've run out of ideas as to what I might be doing wrong.
Any thoughts?
Update: I had the client switch the content type to application/json. Unfortunately, I'm still experiencing the exact same problem. I also updated my HTML and included the live URL I've been working with.
Update 2: I just gave this a try in IE8 and it works fine. For some reason, it doesn't work in either Firefox 3.6.3 or Chrome 4.1.249.1064 (45376). I did notice a mistake with the data being returned (the developer is returning a collection of data, even for queries that will always return a single record), but it still baffles me why it doesn't work in other browsers.
It might be important to note that I am working from an HTML file on my local file system. I thought it might be a XSS issue, but that doesn't explain why Flickr works.
A: Flickr's API supports JSONP, whereas the one you're connecting to does not.
jQuery sees that =? and understands there's a request for a JSONP callback and creates one. You can see it on line 5003 of the jQuery library your sample page uses.
So, you need to change two things
*
*Add a callback parameter to your request. Whatever you (or your developer) wants to call it. Let's say you choose cb - so add this to the AJAX request: &cb=? (this way we let jQuery handle the creation of a callback for us)
*Have your developer that made the service accept this new parameter, and "pad" the result with it before returning it.
A: Have you considered using the more flexible $.ajax? I would break it down there and see if the default $.getJSON is not providing you with exactly what you need.
$.ajax({
url: 'results.json',
type: 'GET',
dataType: 'json',
success: function(data, status)
{
alert(data);
}
});
Would be the equivalent ajax 'parent' implementation. Try mucking around and see if there is a specific property you need to set.
A: Is the content served as "application/json"?
A: if one url (the flickr url) works, while another doesnt (your own), i would say the problem is with your url.
It looks like you are using a relative path, is that your intention? have you used firebug's net panel to see what the request looks like?
A: This is a case of Crossdomain request error. Flickr Works , because it is JSONP , while the other url does not work because it is not JSONP enabled.
1. Check if the url supports JsonP
2. if not, create a proxy web service in your local domain (the same domain as the web page is)
3. Call that proxy webservice which in turn calls the external url from the server side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2737852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fix program and NOT receive "Command Execution Failed" error message in Java? This is my first class and first time using Java. I also need to display 'Employee Name, Rate of Pay, Hours Worked, Overtime Worked, Gross Pay, Total amount of deductions, & Net Pay in the program as well.
package calculatepayprogram;
import java.util.Scanner;
/**
* Calculate Pay Program
* CPT 307: Data Structures & Algorithms
* 7/5/2022
*/
public class CalculatePayProgram{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double RateOfPay;
int HoursWorked;
double GrossPay;
double OvertimeHours;
double OvertimePay;
double NetPay;
double TotalDeductions;
String name;
System.out.println("Enter Your Name: ");
name = reader.nextLine();
System.out.print("Enter Your Pay Per Hour: ");
RateOfPay = reader.nextDouble();
System.out.print("Enter Your Hours Worked: ");
HoursWorked = reader.nextInt();
System.out.print("Enter Your Overtime Hours Worked: ");
OvertimeHours = reader.nextDouble();
GrossPay = RateOfPay * HoursWorked;
OvertimePay = OvertimeHours * 1.5 * RateOfPay;
double Pay = OvertimePay + GrossPay;
System.out.println("Your Gross Pay For This Week Will Be $" + Pay);
double FederalTax = .15 * Pay;
double StateTax = .0307 * Pay;
double Medicare = .0145 * Pay;
double SocialSecurity = .062 * Pay;
double Unemployment = .0007 * Pay;
double TotalDeduct = FederalTax + StateTax + Medicare + SocialSecurity + Unemployment;
System.out.println("Your Total Deductions For This Week Will Be $" + TotalDeduct);
NetPay = Pay - TotalDeduct;
System.out.println("Your Net Pay For This Week Will Be $" + NetPay);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72878069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File size error code not working I have written below lines of code
<?php
$uniqId = uniqid('file_');
$root = $_REQUEST['root'];
$target_file = "uploads/".basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if ( 0 < $_FILES['file']['error'] )
{
echo 'Error';
}
else if ($_FILES["file"]["size"] > 2097152)
{
echo "SizeError";
}
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "docx" && $imageFileType != "pdf")
{
echo "ExtensionError";
}
else
{
if( move_uploaded_file($_FILES['file']['tmp_name'], $root.$uniqId.".".$imageFileType))
{
echo $uniqId.".".$imageFileType;
}
}
?>
If I upload 5 mb file, the code is jumped to simple "Error" condition. I want that it should display SizeError. Please help!!!
A: This is an alternative way to get size
if (filesize($target_file) > 2097152)
{
echo "SizeError";
}
But firstly I think there is an error UPLOAD_ERR_INI_SIZE at $_FILES['file']['error']. UPLOAD_ERR_INI_SIZE=1 You can increase it in php.ini. Add or modify this in your php.ini for example yo increase max_file_size = 25mb:
upload_max_filesize = 25M
After modifying php.ini your code should work too:
if ( 0 < $_FILES['file']['error'] )
{
echo 'Error';
}
else if ($_FILES["file"]["size"] > 2097152)
{
echo "SizeError";
}
To check your php.ini settings call:
echo phpinfo();
You will see your settings, find upload_max_filesize it's 2mb as default value. Looks like this:
A: check this condition first if ($_FILES["file"]["size"] > 2097152) then check others.
You probably get the UPLOAD_ERR_INI_SIZE at $_FILES['file']['error'] which is qual to 1. You can increase it in php.ini. Change this in your php.ini:
upload_max_filesize = 25M
A: The reason you're getting "error" is because of this line:
if ( 0 < $_FILES['file']['error'] )
If you read the documentation here: PHP: Upload Error Messages Explained, then you'll notice that there are several values that can be returned with $_FILES['file']['error']. It returns 0 when there are no errors. But it returns 1 if
The uploaded file exceeds the upload_max_filesize directive in
php.ini.
And it returns 2 if:
The uploaded file exceeds the MAX_FILE_SIZE directive that was
specified in the HTML form.
In both cases 0 is smaller than 1 or 2. So your script is returning you "Error". Because the condition evaluates to true.
You need to either change the condition, or check for the file size first.
A: I was facing the same issue,and got the solution.
Codeigniter allows you to upload the image of size less than 2mb.but if you want to upload the image of 5 mb than you should add this line in your .htaccess file.
php_value upload_max_filesize 20M
After adding this line in your .htaccess file,your code will work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49999288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Disabling Internet Explorer thru Powershell Trying to disable Internet Explorer but is receiving a prompt whether to complete the operation now? [Y/N]?
Tried this command:
Disable-WindowsOptionalFeature -FeatureName Internet-Explorer-Optional-amd64 -Online -Confirm:$false
Tried this command:
Disable-WindowsOptionalFeature -FeatureName Internet-Explorer-Optional-amd64 -Online -Confirm:$false
But received an error message:
A: I agree with the suggestion given by Santiago.
The correct command to disable the Internet Explorer using the Powershell is as below.
Disable-WindowsOptionalFeature -online -FeatureName internet-explorer-optional-amd64
When you run the command, it will ask you whether you would like to restart the machine or later. You could enter the desired choice.
Note: Make sure you are running the Powershell as Administrator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74608663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I overwrite lines from text file to specific lines in another file instead of appending them public class AddSingleInstance {
public void addinstances(String txtpath,String arffpath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\src\\text.txt"));
FileWriter fw = new FileWriter("C:\\src\\" + test.txt,true);
StringBuilder sb = new StringBuilder();
//String toWrite = "";
String line = null;
while ((line = reader.readLine())!= null){
// toWrite += line;
sb.append(line);
sb.append("\n");
}
reader.close();
fw.write(sb.toString());
fw.flush();
fw.close();
}
}
my code is working on append lines from text file(A) to specific lines in another file(B), like
*
*I
*AM
*......
*(above lines are fixed, cannot be overwriting)
*student(New string was added from text file)
*now(New string...)
How can I overwrite those lines into file(B) instead of appending them on B?
A: You can use java.io.RandomAccessFile to access file(B) and write to it at the desired location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23113375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make Helm install to use 'kubectl apply' instead of 'kubectl create' When we run helm install ./ --name release1 --namespace namespace1, it creates the chart only if none of the deployments exist then it fails saying that the deployment or secret or any other objects already exist.
I want the functionality to create Kubernetes deployment or objects as part of helm install only those objects or deployments already not exists if exists helm should apply the templates instead of creating.
I have already tried 'helm install' by having a secret and the same secret is also there in the helm templates, so helm installs fail.
A: Short answer, I would try helm upgrade.
A: In recent helm versions you can run helm upgrade --install which does an upgrade-or-install.
Another alternative is you can use helm template to generate a template and pipe it to kubectl apply -f -. This way you can install or upgrade with the same command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54138762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to install a package that contains only one component of Material-UI? Material-UI is a very big package and I only want to use one component of it.
Is there a way to install a package that only contains the component I want to use?
e.g.
use
import Button from '@material-ui/core/Button';
But only have in your package.json something like @material-ui/core/Button.
The reason I want this is to have a small node_modules.
A: you can install each component of Material-UI via bit.dev collection:
https://bit.dev/mui-org/material-ui
Here is the Button component for example:
https://bit.dev/mui-org/material-ui/button
I exported the project to bit.dev and I'm trying to keep it up to date as much as possible.
A: You can install and use the isolated material components here:
bit.dev
A: Unfortunately, you can't install the separate components from the Material UI. The only way is to install the @material-ui/core directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59468962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Is there a way i can get applicationContext in cordova using javascript? I use angular build to generate a cordova android application. I need to get applicationContext in order for me to integrate with third party. Is there a way i can get using JavaScript?
A: If i understand correctly, you want to get something similar to from native android project:
public class MyApp extends android.app.Application {
private static MyApp instance;
public MyApp() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
Is that the context you need? If yes, then no - you cant get and access it directly. But, you can write a plugin, that will pass required parameters from and to it that will manipulate the context in the native code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68178901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I use an interface as a DTO in NHibernate? I was reducing the bytes transferred over the wire via my query and as I was writing... I realized that I should be able to pass an interface to the QueryOver object and get the specified columns for that interface's properties.
Is it possible to pass an interface to a select or similar command for the QueryOver object? Would it return just the columns that are "mapped" to the interface?
Example:
Repository
.QueryOver<MyTable>()
.Select(table => table as IJustWantTheseColumnsInterface)
.Execute(Parameters);
//or
Repository
.QueryOver<MyTable>()
.Select<IJustWantTheseColumnsInterface>()
.Execute(Parameters);
//...
public class Table : IJustWantTheseColumnsInterface
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public Phone Phone { get; set; }
public DateTime BirthDate { get; set; }
public Occupation Occupation { get; set; }
public Employer Employer { get; set; }
//etc...
}
public interface IJustWantTheseColumnsInterface
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Phone Phone { get; set; }
}
A: Why can't you just create a second implementation which you map to only those columns?
public class Table : IJustWantTheseColumnsInterface
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string MiddleName { get; set; }
public virtual string LastName { get; set; }
public virtual Address Address { get; set; }
public virtual Phone Phone { get; set; }
public virtual DateTime BirthDate { get; set; }
public virtual Occupation Occupation { get; set; }
public virtual Employer Employer { get; set; }
}
public class SameTable : IJustWantTheseColumnsInterface
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Phone Phone { get; set; }
}
public interface IJustWantTheseColumnsInterface
{
int Id { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
Phone Phone { get; set; }
}
public class SameTableMap : ClassMap<SameTable>
{
public SameTableMap()
{
Table("Table");
Id(x => x.Id, "ID");
Map(x => x.FirstName, "FIRST_NAME");
Map(x => x.LastName, "LAST_NAME");
Reference(x => x.Phone, "PHONE_ID");
}
}
You can also use an Interface as T for ClassMap.
Also in case the Phone property was of type interface IPhone in your Table class. You could specify which implementation to return like this.
public interface IJustWantTheseColumnsInterface
{
...
IPhone Phone { get; set; }
...
}
public class SameTableMap : ClassMap<SameTable>
{
public SameTableMap()
{
...
Reference(x => x.Phone, "PHONE_ID").Class(typeof(Phone));
...
}
}
Now if you want to get your partial entity
IJustWantTheseColumnsInterface someVariable = session.Get<SameTable>();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20154445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Key value observation on discrete data derived from a continuous data So I have two properties defined
@property (nonatomic) float continous;
@property (nonatomic, readonly) NSInteger discrete;
continous is an actual property that varies continously, while the getter for discrete looks like this:
- (NSInteger)discrete {
return floor(continuous);
}
So, now I want to KVO on discrete, of course, I need to implement the following in my class:
+ (NSSet *)keyPathsForValuesAffectingDiscrete {
return [NSSet setWithObject:NSStringFromSelector(continuous)];
}
Now, the problem is that since continuous is constantly changing, KVO would constantly send out updates, even though discrete has not actually changed! For example, KVO would keep updating me as continous varies from 0 to 0.9, but during this process, discrete is always 0. Now I don't really want that, is there anyway to only make KVO fire up changes when discrete has actually changed?
A: Rather than making a derived property for discrete, you could make it a stored property which is publicly readonly but privately readwrite. Implement the setter for continuous yourself, like so:
- (void) setContinuous:(float)newValue
{
_continuous = newValue;
NSInteger newDiscrete = floor(_continuous);
if (newDiscrete != _discrete)
self.discrete = newDiscrete;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24298623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails filtering records in many to many relationship I have many to many relationship for books and authors like:
class Book < ApplicationRecord
has_many :books_authors, inverse_of: :author, dependent: :destroy
has_many :authors, through: :books_authors
end
class Author < ApplicationRecord
has_many :books_authors, dependent: :destroy
has_many :books, through: :books_authors
end
class AuthorsBook < ApplicationRecord
belongs_to :author
belongs_to :book
end
Now to get all the Books with Authors of ids: 1 and 3
The query is like :
Book.joins(:authors).where(authors: {id: [1, 3]}).uniq
Book.joins(:books_authors).where(books_authors: {author_id: [1,3]}).uniq
Book.joins(:authors).where('authors.id IN (?)', [1,3]).uniq
But I get a book whose authors' ids are 2,3,5, which should not be the case, as it does not have author with id 1.
So , how could I only get the books with given authors ids?
A: You need a having clause in there combined with your where clause:
ids = [1,3]
Book
.select('books.*') # not sure if this is necessary
.where(authors_books: { author_id: ids })
.joins(:authors_books)
.group('books.id')
.having('count(authors_books) >= ?', ids.size)
The SQL: https://www.db-fiddle.com/f/i7TXPJgavLwQCHb4GhgH3b/0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54260550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Referring to a variable in a list of data frames in an lapply I would like to produce frequency tables for various subgroups of my data. The data looks as follows:
school <- c(rep(1, 20), rep(2,20))
class <- c(rep(1,10), rep(2,10), rep(1,10), rep(2,10))
female <- sample(0:1, 40, replace=TRUE)
age <- sample(12:13, 40, replace=TRUE)
data <- data.frame(school, class, female, age)
There are 2 schools, and each school has 2 classes. My goal is to get a function that allows me to produce a frequency table for a specified variable for each school. The table within each school should include the frequencies of a given variable for the entire school, as well as for each class within the school. It should look like this (example variable female):
Female 0 1
school 10 10
Class1 8 12
Class2 11 9
I have tried to first program a function, and then use lapply to get a separate table for each school. Specifically, what I have tried is
dist <- function(data, var) {
f_all <- table(data$var)
f_class <- table(data$class, data$var)
freq <- rbind(f_all, f_class)
return(freq)
}
data_test <- split(data, school)
a <- lapply(data_test, dist, var="age")
When I apply this code I get an error message
"Error in table(data$class, data$var)) :
all arguments must have the same length"
My guess is that I fail to properly use the variable name as a function argument. I have tried without quotation marks, but with the same result. Any help will be much appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26365322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing a Function from HTML inside of a JS Module So I can currently enqueing the script as so.
wp_enqueue_script( 'myScripts', WPEX_JS_DIR_URI .'/myScripts.js', array( 'jquery' ), '1.7.5', true );
And I am currently attempting to use the function as seen below.
(function($) {
function vote_up () {
$(".voteButton").html("Hello jQuery");
}
})(jQuery);
And I am just for the sake of getting it work attempting to call it with an onclick method,
<div class="button voteButton" onclick="vote_up()">Vote Up !</div>
I understand that I may need to assign the function like this,
var foo = (function ($) {
Although when I do this and attempt to call it with
foo.vote_up()
I still cannot get it to work.
Am I missing something simple?
Thank you.
A: If you want to invoke the method as object method (foo.vote_up()) then return an object from you immediate function instead of only create a function, and then invoke the method. I think that you're looking for something like:
var foo = (function($) {
return {
vote_up : function () {
$(".voteButton").html("Hello jQuery");
}
}
})(jQuery);
foo.vote_up();
Hope this helps,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28420766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What it means that associated with Class synchronization sentence in java specification In Java language spec, there is below sentence
A class method that is declared synchronized synchronizes on the monitor associated with the Class object of the class.
I don't understand this sentence totally even I don't know what I don't know.
Could you let me know this sentence with some examples?
I appreciate you
A: synchronized (YourClass.class)
static synchronized
Are equivalent, this is what it means.
Or in other words:
public static synchronized void go(){
}
will acquire the monitor that is associated with a class, not with an instance, as opposed to :
public synchronized void go() {
}
that will acquire the monitor from an instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52079817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Message box formatting I need my totals to be in currency format. my code is not letting me output a long sting into a message box. below is what i am trying to output into a message box. how can i format my totals to come out as currency.
MessageBox.Show(cmboCrust.GetItemText(cmboCrust.SelectedItem) + " - " + cmboSize.GetItemText(cmboSize.SelectedItem)
+ "\nSauce: " + cmboSauce.GetItemText(cmboSauce.SelectedItem) +
"\nToppings ($1.50 each): " + topings +
"\n\nPizza total: {0:C}" + pizzaTotal +
"\n\nDrink selection: " +
"\n\t" + sodaTotal + " soda(s)" +
"\n\t{0:C}" + waterTotal + " water(s)" +
"\nDrink Total: {0:C}" + drinksTotal +
"\n\nSpecialty Items: " + specialtyMessage +
"\nAmount Due: {0:C}" + billTotal +
"\n\n Deliver to: " + txtBxName.Text + ", " + txtBxAddress.Text
, "D & G Pizza Express Order");
string output = string.Format(cmboCrust.GetItemText(cmboCrust.SelectedItem), " - ", cmboSize.GetItemText(cmboSize.SelectedItem),
"\nSauce: ", cmboSauce.GetItemText(cmboSauce.SelectedItem),
"\nToppings ($1.50 each): ", topings,
"\n\nPizza total: {0:C}", pizzaTotal,
"\n\nDrink selection: ",
"\n\t", sodaTotal, " soda(s)",
"\n\t{0:C}", waterTotal, " water(s)",
"\nDrink Total: {0:C}", drinksTotal,
"\n\nSpecialty Items: ", specialtyMessage,
"\nAmount Due: {0:C}", billTotal,
"\n\n Deliver to: ", txtBxName.Text, ", ", txtBxAddress.Text);
A: hmm you can do it this way..
MessageBox.Show(
String.Format(
"\r\nSauce: {0} \r\nToppings ($1.50 each): {1} \r\nPizza total: {2:C} \r\nDrinkSection", 1, 2, 3));
you get the idea.. just replace 1,2,3 with your variables
EDIT.
String.Format adds readability.
A: The following example displays currency symbol with two decimal points.
billTotal.ToString("C");
A: billTotal.ToString("C", CultureInfo.CurrentCulture);
billTotal.ToString("C", new CultureInfo("en-US");
You can format according to current culture or in a required culture by using overloaded ToString() method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40601776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery/AJAX automatic population of values I have a problem with jQuery and AJAX.
I have 3 select tags with values which are populated through AJAX.
Here is the case I need.
When I select option on first select tag I get specific values in the second select tag.
Then when I select option on second tag I get specific values in the third select tag.
After I select option in third select tag - submit happens.
This part works.
Of course after submit everything resets. I didn't want that so I've put selected in select tag. Now I don't know how to "live" read from first and second select tag so that after submit options stays populated.
Here is my code PHP/HTML code:
<form action="<?php echo $PHP_SELF; ?>" method="POST" name="userVideos" id="userVideos" style="width: 580px; margin-left: 5px; margin-bottom: 2px;">
<select name="brand_select" id="brand_select" style="width: 140px; margin-right: 20px;">
<option value="">Select Brand</option>
<?php
$query_brands = mysql_query("SELECT DISTINCT brand FROM users_video WHERE location = '2' ORDER BY brand");
while ($row = mysql_fetch_object($query_brands))
{
$name = $row->brand;
$sel = ($_POST['brand_name'] == $name) ? "selected='selected'" : "";
echo "<option value='{$row->brand}' $sel>{$row->brand}</option>";
}
?>
</select>
<input type="hidden" value="<?php echo htmlspecialchars($_POST['brand_select']); ?>" name="brand_name" id="brand_name"/>
<select name="series_select" id="series_select" style="width: 140px; margin-right: 20px;" disabled>
<option value="">Select Series</option>
<?php
//TODO: finish code tidification
$sel = ($_POST['series_name'] != "") ? "selected='selected'" : "";
echo "<option value='" . htmlspecialchars($_POST['series_name']) . "' $sel>" . htmlspecialchars($_POST['series_name']) . "</option>";
?>
</select>
<input type="hidden" value="" name="series_name" id="series_name"/>
<select name="model_select" id="model_select" style="width: 140px; margin-right: 20px;" disabled>
<option value="">Select Model</option>
<?php
$sel = ($_POST['model_name'] != "") ? "selected='selected'" : "";
echo "<option value='" . htmlspecialchars($_POST['model_name'] != "") . "' $sel>" . htmlspecialchars($_POST['model_name']) . "</option>";
?>
</select>
<input type="hidden" value="" name="model_name" id="model_name"/>
</form>
And here is my jQuery code:
jQuery(document).ready(function(){
var brand = "";
var series = "";
var model = "";
var _brand = "";
_brand = $('#brand_name').val();
$("#brand_select").live("change", function(){
brand = $('select#brand_select').val();
if (brand == "" && _brand == "")
{
$('select#series_select').attr('disabled','disabled');
$('#model_select').attr('disabled','disabled');
}
else
{
$('select#series_select').removeAttr('disabled');
$('#brand_name').val(brand);
var grbData = $.ajax({
type: "GET",
url: "series.php",
data: "brand=" + brand,
success: function(html){
$("#series_select").html(html);
}
});
}
});
$("#series_select").change(function(){
series = $('select#series_select').val();
if (series != ""){
$('#model_select').removeAttr('disabled');
$('#series_name').val(series);
var newData = $.ajax({
type: "GET",
url: "model.php",
data: "brand=" + brand + "&series=" + series,
success: function(html){
$("#model_select").html(html);
}
});
}else{
$('#model_select').attr('disabled','disabled');
}
});
$("#model_select").change(function(){
model = $('select#model_select').val();
if (model != ""){
$('#model_name').val(model);
$('#userVideos').submit();
}
});
A: Try something like this for simplicity. Give them all the same class but use id for Brand or Series. I'm writing this without testing sorry but you can move all you functions into 1. Basic Idea you will need to tweak. Also I may have even over complicated it with static variables. But at least you can keep track of the values.
$(".series_select").change(function(){
var value = $(this).val(),
type = $(this).attr('id'),
data,
self = $(this);
if(type == "brand"){
data = "brand=" + value;
$(".series_select").change.brand = value;
} else if (type == "series"){
data = "brand=" + $(".series_select").change.brand + "&series=" + value;
$(".series_select").change.series = value;
} else if( type == "submit"){
if($(".series_select").change.brand != '' && $(".series_select").change.series != ''){
$('#userVideos').submit();
return;
}
}
$.ajax({
type: "GET",
url: "model.php",
data: data,
success: function(html){
self.html(html);
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11640948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIImagePickerController Edited Image - cropping some extra image on top I'm using UIImagePickerController for profile image and the original image was
Now, I'm editing the image in UIImagePickerController as
But, the editedImage frame from the UIImagePickerController is slightly different from the image frame what I cropped
If you can compare the the images, during cropping and after cropping, there I cropped the image upto text "GIVE", but in the final image it has text "NEVER". Is there any properties I need to change in UIImagePickerController to get correct image as cropped or it is default from the OS itself?
A: It is a known issue that has been there for a number of years now.
We dedicated a lot of time to investigating the issue in work but found even with a MVCE the issue occurs.
We also found a Radar link from iOS 8: https://openradar.appspot.com/18957593
We replicated the issue in iOS 9, 10, 11 and 12.
A: I came across this issue and the only solution I found is to make your own crop functionality. Nothing else works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57489961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Navigation Bar Not Populated - iOS7 A single view in my application refuses to populate the navigation bar in iOS7. I can see the bar is there, enabled, visible and transparent, because my scrollable controls float underneath it when I drag them up. The issue is simply that when I add controls to self.navigationItem.leftBarButtonItem / self.navigationItem.rightBarButtonItem, and denote the title of the view (in the ViewController) with self.title = @"Title"; they do not show in the navigation area.
The strange thing is if I set self.navigationController.navigationBar.topItem.title = @"Title", this renders a title on the view in the navigation bar (but is not a solution as it causes problems when navigating elsewhere in the app). The expression "(self.navigationController.navigationBar.topItem != self.navigationItem)" evaluates true, and I do not understand how this can be the case.
There are other views in the application which render navigation controls properly with the statements shown above.
I should mention that this application performs as expected under iOS6.1. I am pretty new to iPhone dev, so could easily have missed something. Any suggestions for what I could check will be appreciated.
A: Solved. I was using an incorrect method of pushing the view controller into the navigation controller.
Instead of
self.navigationController.viewControllers = [NSArray arrayWithObject:self.myViewController];
Use the following
[self.navigationController pushViewController:self.vehicleListViewController animated:YES];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19250497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .NET MS Interop Word not saving document in UTF8 web page Note: A sample document I used for test can be foud in: http://ftp.3gpp.org//Specs/archive/38_series/38.413/38413-100.zip
Problem
I am trying to convert an MS Word 97-2003 document (.doc) into a UTF-8 web page with the following code:
var wordApp = new Word.Application();
var doc = wordApp.Documents.Open("input.doc");
Console.WriteLine(doc.TextEncoding); // msoEncodingWestern
doc.SaveEncoding = MsoEncoding.msoEncodingUTF8;
doc.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8;
doc.SaveAs2("output.htm", WdSaveFormat.wdFormatFilteredHTML, Encoding: MsoEncoding.msoEncodingUTF8);
doc.Close();
wordApp.Quit();
The problem is the document contains a certain character which is rendered incorrectly in a web page:
In document
In web page
(Information) Manual Way
For information, if I do the above in a manual way as below, the arrow character is rendered correctly in web page.
A: I think you have cited the encoding in too many different ways. You should only need to set it once.
Try this:
var wordApp = new Word.Application();
var doc = wordApp.Documents.Open("input.doc");
doc.Fields.Update(); // ** this is the new line of code.
Console.WriteLine(doc.TextEncoding); // msoEncodingWestern
doc.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8;
doc.SaveAs2("output.htm", WdSaveFormat.wdFormatFilteredHTML);
doc.Close();
wordApp.Quit();
A: I solved the problem with the following:
var from = ((char)0xF0AE).ToString();
var to = ((char)0x2192).ToString();
doc.Content.Find.Execute(from, ReplaceWith: to, Replace: WdReplace.wdReplaceAll);
It's not a generalized solution, i.e. this method only handles a right arrow case and another method needs to be defined if a left arrow is an issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60931142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cannot make my status bar color to match my UINavigationBar color in SiwftUI My problem appears to be a simple one. But I just spent hours looking for a solution!
I just have to make the status bar's background color conform to my UINavigationBar background's color (red in this sample).
I wrote a minimal code sample to reproduce my problem and help you for giving me a solution...
TestApp.swift
import SwiftUI
@main
struct TestApp: App {
@Environment(\.scenePhase) private var phase
var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: phase) { newPhase in
switch newPhase {
case .active:
UINavigationBar.appearance().backgroundColor = UIColor.red
break
default:
break
}
}
}
}
ContentView.swift
struct DetailView1: View {
var body: some View {
Text("Detail view 1")
}
}
struct ContentView: View {
@State private var isDisplayDetailView1 = true
var body: some View {
NavigationView {
List {
Section {
NavigationLink(destination: DetailView1(), isActive: $isDisplayDetailView1) {
Text("Go to detail view 1")
}
}
}
.navigationBarTitle("Menu")
.listStyle(GroupedListStyle())
DetailView1()
}
}
}
Obviously, I tried to add edgesIgnoringSafeArea(.top) to my NavigationView view (and to the List one, and to the DetailView1 one,...), but it doesn't change anything... Please help me, I don't understand where is the problem!
A: Is there a reason you are using ScenePhase
You can just add this code at file scope
extension UINavigationController {
override open func viewDidLoad() {
super.viewDidLoad()
let standard = UINavigationBarAppearance()
standard.backgroundColor = .blue
let compact = UINavigationBarAppearance()
compact.backgroundColor = .green
let scrollEdge = UINavigationBarAppearance()
scrollEdge.backgroundColor = .red
navigationBar.standardAppearance = standard
navigationBar.compactAppearance = compact
navigationBar.scrollEdgeAppearance = scrollEdge
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64351536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to extract geometry from source file in the form of XYZ coordinate I use the link reference:
https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/xtract-geometry-from-source-file/
but at the end of task when I send request
curl -X GET \
'https://developer.api.autodesk.com/modelderivative/v2/designdata/URL_SAFE_URN_OF_SOURCE_FILE/manifest' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
it shows only .png URN not .obj UNR like below
"urn": "urn:adsk.viewing:fs.file:URL_SAFE_URN_OF_SOURCE_FILE/output/geometry/b576231b-9684-3609-8fa0-1221a424a77c.obj"
how I get .obj file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66902911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Failed to map SQL query to topology on data node I have 3 Ignite servers running in Kubernetes. I set up them last night. and the following query was working fine.
select distinct u.userId,u.attempts,u.passwordCreatedOn,u.password from users u inner join users_roles ur on ur.userId = u.userId inner join roles r on r.roleId = ur.roleId
where lower(u.email) = '[email protected]' and r.organizationId = 23 and r.isActive = 1 and ur.isActive = 1 and u.isActive = 1;
But the next morning I was getting the following error upon running the above query :
SQL Error [50000]: Failed to map SQL query to topology on data node [dataNodeId=6c26a6d5-1ba1-432f-9e72-05a23da76275, msg=Failed to execute non-collocated query (will retry) [localNodeId=6c26a6d5-1ba1-432f-9e72-05a23da76275, rmtNodeId=6c26a6d5-1ba1-432f-9e72-05a23da76275, reqId=34201, errMsg=Timeout reached.]]
I am using Ignite 2.8.1 version
Please suggest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62928464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: checking a view's background I have 3 buttons, all of them have the same background drawable by default (subject_button)
What I want to do:
When I click one button his background changes ( to clicked_subject), all the others remain with the default background, if I click one button after clicking another, the button I just clicked changes his background while the previous one gets back to the initial background, allowing only one button to have the clicked_subject background, if the diffrent button gets clicked again his background goes back to the initial one, leting all the buttons with the initial background.
The problem:
If I click the diffrent button, his background remains the same instead of changing back to the initial one.
My logic:
theButton1.setBackgroundResource(R.drawable.subject_button);
theButton1.setOnClickListener(this);
//same for other 2
@Override
public void onClick(View v) {
if (v.getBackground() == ContextCompat.getDrawable(this, R.drawable.subject_button)) {
theButton1.setBackgroundResource(R.drawable.subject_button);
theButton2.setBackgroundResource(R.drawable.subject_button);
theButton3.setBackgroundResource(R.drawable.subject_button);
v.setBackgroundResource(R.drawable.clicked_subject);
} else {
v.setBackgroundResource(R.drawable.subject_button);
}
Why is this happening?
A: You can do this:
private final List<Button> mButtons = new ArrayList<>();
// somewhere in your code
mButtons.add(mButton1);
mButtons.add(mButton2);
mButtons.add(mButton3);
mButton1.setOnClickListener(mClickListener);
mButton2.setOnClickListener(mClickListener);
mButton3.setOnClickListener(mClickListener);
private final View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
for (Button button : mButtons) {
if (button == v) {
// set selected background
} else {
// set not selected backround
}
}
}
};
If you define a stateful drawable for your buttons, then you can simply change the onclick to this:
private final View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
for (Button button : mButtons) {
button.setSelected(v == button);
}
}
};
A: For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button. For example button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/your_image1" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/your_image2" /> <!-- focused -->
android:drawable="@drawable/your_image3" <!-- default -->
</selector>
then just apply it as :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawable="@drawable/button_selector.xml" />
A: "Pressed", "selected", "disabled" and such are View states. As such they're supposed to be handled automatically by Android and not by your click listeners.
This is achieved using SateLists, which control the look your Views sould have depending on which state(s) they're in. So you can easily set subject_button as the unpressed state, clicked_subject as the pressed state, and let Android take care of actually switching between them.
Full explanation: https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
A: I solved it by instead of changing only the background color on clicking the button, I also change the textColor, then I can check the textColor with if (((Button) v).getCurrentTextColor() == Color.WHITE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36960313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python AttributeError: 'Page' object has no attribute '_getContents' I'am trying to remove the watermark from the PDF by using a python code and the code that i am running is
I am using PyMuPDF and have used fitz library.
def remove_img_on_pdf(idoc, page):
#image list
img_list = idoc.getPageImageList(page)
con_list = idoc[page]._getContents()
# xref 274 is the only /Contents object of the page (could be
for i in con_list:
c = idoc._getXrefStream(i) # read the stream source
#print(c)
if c != None:
for v in img_list:
arr = bytes(v[7], 'utf-8')
r = c.find(arr) # try find the image display command
if r != -1:
cnew = c.replace(arr, b"")
idoc._updateStream(i, cnew)
c = idoc._getXrefStream(i)
return idoc
doc=fitz.open('ELN_Mod3AzDOCUMENTS.PDF')
rdoc = remove_img_on_pdf(doc, 0) #first page
rdoc.save('no_img_example.PDF')
I get this error saying
Traceback (most recent call last):
File "watermark.py", line 27, in <module>
rdoc = remove_img_on_pdf(doc, 0) #first page
File "watermark.py", line 5, in remove_img_on_pdf
con_list = idoc[page]._getContents()
AttributeError: 'Page' object has no attribute '_getContents'
Please help me find out a solution out of this, thank you in advance.
A: Your function have some strange methods such as _getContents, _getXrefStream and _updateStream, maybe they are deprecated or somthing, but here is working code for solving your problem:
import fitz
def remove_img_on_pdf(idoc, page):
img_list = idoc.getPageImageList(page)
con_list = idoc[page].get_contents()
for i in con_list:
c = idoc.xref_stream(i)
if c != None:
for v in img_list:
arr = bytes(v[7], 'utf-8')
r = c.find(arr)
if r != -1:
cnew = c.replace(arr, b"")
idoc.update_stream(i, cnew)
c = idoc.xref_stream(i)
return idoc
doc = fitz.open('ELN_Mod3AzDOCUMENTS.PDF')
rdoc = remove_img_on_pdf(doc, 0)
rdoc.save('no_img_example.PDF')
As you can see, I've used another methods instead of non-working ones. Also, here is documentation for PyMuPDF.
A: Ïf you print dir(idoc[0]) , you see a list of attributes. you should use idoc[page].get_contents() instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68422506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regex \n doesn't work I'm trying to parse text out of two lines of HTML.
Dim PattStats As New Regex("class=""head"">(.+?)</td>"+
"\n<td>(.+?)</td>")
Dim makor As MatchCollection = PattStats.Matches(page)
For Each MatchMak As Match In makor
ListView3.Items.Add(MatchMak.Groups(1).Value)
Next
I added the \n to match the next line, but for some reason it won't work. Here's the source I'm running the regex against.
<table class="table table-striped table-bordered table-condensed">
<tbody>
<tr>
<td class="head">Health Points:</td>
<td>445 (+85 / per level)</td>
<td class="head">Health Regen:</td>
<td>7.25</td>
</tr>
<tr>
<td class="head">Energy:</td>
<td>200</td>
<td class="head">Energy Regen:</td>
<td>50</td>
</tr>
<tr>
<td class="head">Damage:</td>
<td>53 (+3.2 / per level)</td>
<td class="head">Attack Speed:</td>
<td>0.694 (+3.1 / per level)</td>
</tr>
<tr>
<td class="head">Attack Range:</td>
<td>125</td>
<td class="head">Movement Speed:</td>
<td>325</td>
</tr>
<tr>
<td class="head">Armor:</td>
<td>16.5 (+3.5 / per level)</td>
<td class="head">Magic Resistance:</td>
<td>30 (+1.25 / per level)</td>
</tr>
<tr>
<td class="head">Influence Points (IP):</td>
<td>3150</td>
<td class="head">Riot Points (RP):</td>
<td>975</td>
</tr>
</tbody>
</table>
I'd like to match the first <td class...> and the following line in one regex :/
A: Description
This regex will find td tags and return them in groups of two.
<td\b[^>]*>([^<]*)<\/td>[^<]*<td\b[^>]*>([^<]*)<\/td>
Summary
*
*<td\b[^>]*> find the first td tag and consume any attributes
*([^<]*) capture the first inner text, this can be greedy but we assume the cell has no nested tags
*<\/td> find the close tag
*[^<]* move past all the rest of the text until you, this assumes there are no additional tags between the first and second td tag
*<td\b[^>]*> find the second td tage and consume any attributes
*([^<]*) capture the second inner text, this can be greedy but we assume the cell has no nested tags
*<\/td> find the close tag
Groups
Group 0 will get the entire string
*
*will have the first td group
*will have the second td group
VB.NET Code Example:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim sourcestring as String = "replace with your source string"
Dim re As Regex = New Regex("<td\b[^>]*>([^<]*)<\/td>[^<]*<td\b[^>]*>([^<]*)<\/td>",RegexOptions.IgnoreCase OR RegexOptions.Singleline)
Dim mc as MatchCollection = re.Matches(sourcestring)
Dim mIdx as Integer = 0
For each m as Match in mc
For groupIdx As Integer = 0 To m.Groups.Count - 1
Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames(groupIdx), m.Groups(groupIdx).Value)
Next
mIdx=mIdx+1
Next
End Sub
End Module
$matches Array:
(
[0] => Array
(
[0] => <td class="head">Health Points:</td>
<td>445 (+85 / per level)</td>
[1] => <td class="head">Health Regen:</td>
<td>7.25</td>
[2] => <td class="head">Energy:</td>
<td>200</td>
[3] => <td class="head">Energy Regen:</td>
<td>50</td>
[4] => <td class="head">Damage:</td>
<td>53 (+3.2 / per level)</td>
[5] => <td class="head">Attack Speed:</td>
<td>0.694 (+3.1 / per level)</td>
[6] => <td class="head">Attack Range:</td>
<td>125</td>
[7] => <td class="head">Movement Speed:</td>
<td>325</td>
[8] => <td class="head">Armor:</td>
<td>16.5 (+3.5 / per level)</td>
[9] => <td class="head">Magic Resistance:</td>
<td>30 (+1.25 / per level)</td>
[10] => <td class="head">Influence Points (IP):</td>
<td>3150</td>
[11] => <td class="head">Riot Points (RP):</td>
<td>975</td>
)
[1] => Array
(
[0] => Health Points:
[1] => Health Regen:
[2] => Energy:
[3] => Energy Regen:
[4] => Damage:
[5] => Attack Speed:
[6] => Attack Range:
[7] => Movement Speed:
[8] => Armor:
[9] => Magic Resistance:
[10] => Influence Points (IP):
[11] => Riot Points (RP):
)
[2] => Array
(
[0] => 445 (+85 / per level)
[1] => 7.25
[2] => 200
[3] => 50
[4] => 53 (+3.2 / per level)
[5] => 0.694 (+3.1 / per level)
[6] => 125
[7] => 325
[8] => 16.5 (+3.5 / per level)
[9] => 30 (+1.25 / per level)
[10] => 3150
[11] => 975
)
)
Disclaimer
Parsing html with a regex is really not the best solution as there a ton of edge cases what we can't predict. However in this case if input string is always this basic, and you're willing to accept the risk of the regex not working 100% of the time, then this solution would probably work for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16812765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XQuery return doesn't calculate anything So, there is this exercise we need to do with XQuery. A calculator for operations stored in an XML. This is my first time using XQuery and i am very confused. Whatever I put in my return statements, Saxon returns not the results of functions included in the return segment but just returns it in plain text, so calling:
declare function m:evaluate($tree as element()) as element(fraction) {
if(local-name($tree)="fraction") then (
for $a in $tree
return
<fraction>
<numerator>$tree/numerator</numerator>
<denominator>$tree/denominator </denominator>
</fraction>
)
else(
typeswitch($tree)
case $tree as element(sum)
return element fraction{
<numerator>$tree/*[1]/numerator/$tree/*[1]/denominator*$ggT+$tree/*[2]/numerator/$tree/*[2]/denominator*$ggT)</numerator>,
<denominator>m:findggT($tree/*[1]/denominator,$tree/*[2]/denominator)</denominator>}
case $tree as element(product)
return element fraction{
<numerator>m:evaluate($tree/*[1]/numerator)*m:evaluate($tree/*[2]/numerator)</numerator>,
<denominator>m:evaluate($tree/*[1]/denominator)*m:evaluate($tree/*[2]/denominator)</denominator>
}
default return element fraction {
<numerator>$tree/numerator</numerator>,
<denominator>$tree/denominator </denominator>
}
)
returns
<fraction>
<numerator>m:evaluate($tree/*[1]/numerator)*m:evaluate($tree/*[2]/numerator)</numerator>
<denominator>m:evaluate($tree/*[1]/denominator)*m:evaluate($tree/*[2]/denominator)</denominator>
</fraction>%
Obviously, the root element of the called xml is a product.
It seems I missed something about how function calls in XQuery work but I don't know what.
The XML I used is:
<product>
<sum>
<fraction >
<numerator >1</numerator >
<denominator >2</denominator >
</fraction >
<fraction >
<numerator >1</numerator >
<denominator >3</denominator >
</fraction >
<fraction >
<numerator >1</numerator >
<denominator >4</denominator >
</fraction >
</sum>
<fraction >
<numerator >2</numerator >
<denominator >3</denominator >
</fraction >
</product >
A: Your expressions are treated as text because they are not inside curly braces ({}). Curly braces are already part of the computed element constructor syntax, but they need to be added when using a direct element constuctor to differentiate between plain text and expressions:
<numerator>{ m:evaluate($tree/*[1]/numerator) * m:evaluate($tree/*[2]/numerator)}</numerator>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51407077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Do strong-named assemblies in .NET ensure the code wasn't tampered with? I'm trying to understand the point of strong-naming assemblies in .NET. While googling about it I noticed that everywhere it is said that it ensures that the code comes from me and wasn't tampered with. So I tested it. I created a simple DLL, signed it with a newly created PFX key and referenced it by my WPF application. And ok, everything works. When I compile the DLL with another PFX file I get an error, so it's ok.
BUT when I decompile the DLL by ildasm, modify it and recompile it by ilasm the WPF application still works without any error. So I tampered the strongly-named DLL and changed it manually with the old one and the application still works with the tampered DLL. The PublicKeyToken is the same. So what is the point of strong-naming? It doesn't ensure the code hasn't been tampered with since I strong-named it.
A: It used to check for tampering, but the overhead of checking every strong-name-signed assembly at application startup was too high, so Microsoft disabled this behaviour by default a number of years ago (way back when ".NET Framework version 3.5 Service Pack 1" was released).
This is called the Strong-Name bypass feature.
You can disable the feature (i.e. make Windows check for tampering) for a particular application by adding the following to its ".config" file:
<configuration>
<runtime>
<bypassTrustedAppStrongNames enabled="false" />
</runtime>
</configuration>
You can enable strong-name checking for ALL applications by editing the registry (which is clearly not a feasible solution!).
For more details, see the following page:
https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-disable-the-strong-name-bypass-feature
The advice nowadays is to use a full code-signing certificate for your executable and DLLs if you want to prevent code tampering.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53116713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why get's Python with PyQt5 slow when creating a large amount of QPushButtons? I am building a larger program in PyQt5. I want to create a large number of clickable QPushButtons in a ScrollArea.
As far as I can see it, the program works so far, but gets very slow, when the number of buttons gets high (about 10,000 to 20,000 characters).
How can I ensure that this program builds these buttons responsive? I need to load textfiles separated by chars as QPushButtons which are usually about 15-20 kb large (sometimes up to 50 kb). I believe, this should not be a size limitation.
import sys
from PyQt5.QtWidgets import QApplication, QGridLayout, QScrollArea, QPushButton, QVBoxLayout, QWidget
class Widget(QWidget):
def __init__(self, parent= None):
super(Widget, self).__init__()
self.setFixedHeight(200)
self.setFixedWidth(1000)
self.setGeometry(50, 100, 600, 500)
widget = QWidget()
layout = QVBoxLayout(self)
grid = QGridLayout()
gridpos = [0, 0]
number = 15000
for i in range(number):
btn = QPushButton('x')
btn.setCheckable(True)
grid.addWidget(btn, *gridpos)
gridpos[1] += 1
if gridpos[1] == 10:
gridpos[0] += 1
gridpos[1] = 0
layout.addLayout(grid)
widget.setLayout(layout)
scroll = QScrollArea()
scroll.setWidgetResizable(False)
scroll.setWidget(widget)
vLayout = QVBoxLayout(self)
vLayout.addWidget(scroll)
self.setLayout(vLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Widget()
dialog.show()
app.exec_()
A: Apparently, a high amount of qpushbuttons are "expensive" and slow the program down. So, there seems no way to generate 10,000 to 20,000 qpushbuttons at once without delay.
What worked however, was to only show the visible pushbuttons and generate new buttons when they are visible in the window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34127398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JWT validation failure error in azure apim I am currently trying to implement Oauth2.0 to protect API using below documentation
https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad
And currently using the DEMO CONFERENCE API provide by azure apim to test the implementation.
And currently receiving error during test in developer portal as :
"message": "JWT Validation Failed: Claim value mismatch: aud=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxx.."
Compared the token passed with the claim value by decoding it and its matching.
I have the jwt token validation policy as below
<inbound>
<base />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid." require-expiration-time="false" require-signed-tokens="false">
<openid-config url="https://login.microsoftonline.com/xxxxxxxxx-07c8-xxxxx-xxxx-xxxxxxxxx/.well-known/openid-configuration" />
<required-claims>
<claim name="aud" match="all" separator="-">
<value>xxxxxxxx-xxxxx-489e-a26e-xxxxxxxx</value>
</claim>
</required-claims>
</validate-jwt>
</inbound>
A: First, you need to validate your JWT token. Then when we register an application its getting registered with version V1 and Access token issuer comes with sts url and if we try to pass Access Token with V2 its failed V2 issuer is login.microsoft.com.
So fix is to go in manifest file "accessTokenAcceptedVersion": 2 for registered applications in AD. Refer to this issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57703697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Sending user to nested view When a user shuts down my app, I'd like to send them back to where they left off. The app starts on a tableview, the user drills down to another tableview and then clicks a row for a detail view. When they startup the app again, I have two choices:
1.) Display options (alertview) for returning to the previous location or cancelling and remaining on the start view.
2.) Immediately jet them over to the detail view.
I don't like either option. (1) gets to be nagging if you must go through it on every startup. (2) could be confusing and I'm not sure technically how that works.
Any suggestions on the above or something different?
A: But 2) is the preferred way according to Apple's HIG:
Even though your application does not run in the background when the user switches to
another application, you are encouraged to make it appear as if that is the case. When your
application quits, you should save out information about your application’s current state in
addition to any unsaved data. At launch time, you should look for this state information and
use it to restore your application to the state it was in when it was last used. Doing so
provides a more consistent user experience by putting the user right back where they were
when they last used your application. Saving the user’s place in this way also saves time by
potentially eliminating the need to navigate back through multiple screens’ worth of
information each time an application is launched.
As far as the technical implementation, it's exactly the same: push your subviews onto the navigation controller. The only thing I'd do differently is not animate the 'drilling down.'
A: When your app starts up, it has an initial 'look', screen, view, whatever.
When it starts back up and has a previous context, add a link or button naming the previous context that allows returning there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1717921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find all the esp8266 connected to a router Hi all I want to connect multiple esp8266 devices to my router and create a mobile app that can find those devices and send messages to them using udp.
Currently my plan is to let esp devices listen to a port and then my app would send a message on that port, esp would respond and the app will store the IP.
Is there any better way to do that?
A friend of mine told me that this approach will fail if routers's gateway is changed. Is it true?
I am just calling WiFi.begin(Ssid, Password); to connect to wifi without doing any changes with wifi.conf().
I am using arduino SDK.
A: Give your ESP8266 devices a static IP addresses so the mobile app will know in advance where they could be 'found':
IPAddress ip(192,168,1,xx); // desired static IP address
IPAddress gateway(192,168,1,yy); // IP address of the router
IPAddress subnet(255,255,255,0);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
and use dynamic DNS service (unless you have a static IP address) with port forwarding to access each of the ESPs. You can choose ports 8266, 8267, 8268, 8269, ... or any other above 1024 and then set the port forwarding in your router settings so port 8266 will be forwarded to the IP address of your first ESP and port 80 (or any other), port 8267 will be forwarded to the IP address of your second ESP and port 80 etc.
Afterwards you can access your ESPs from mobile app (or internet) using URLs looking like http://xx.xx.xx.xx:8266, http://xx.xx.xx.xx:8267, http://xx.xx.xx.xx:8268, http://xx.xx.xx.xx:8269, ... or by using dynamic DNS service with: http://myhome.something.com:8266, http://myhome.something.com:8267 etc. Or you can access them from your local network by known static IP addresses. That is - your mobile app will have to determine if it is inside local network or not. Or you can always access ESPs using proxy - in that case the URLs will not depend upon being inside or outside the local network.
A: Your friend may have more of the details of your solution, but IMO the gateway has nothing to do with it. If all clients and the server are on the same subnet inside the router's local network then the gateway doesn't come into play.
I would do a UDP multicast. Your mobile app would just need to send one request and then listen for replies from the ESPs for a few seconds.
A: One way is to check all the Mac addresses on the network. The first 6 digits is the unique code for the company that made the wifi dongle.
This is assuming you do not have any other devices on the network using the same dongle and aren't what you're trying to search for.
You can find all the Mac addresses on a network by performing an ARP request on each IP.
But all the devices would have to be on the same subnet.
If you devices are remote, then I would go with your original plan, however your friend is correct if the gateway changes this would require something a little more robust. Use a Dynamic DNS service along with a domain name. The Dynamic DNS will update your DNS records in almost real time if your gateway address changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38402642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Without joins on Google App Engine, does your data have to exist in one big table? Since Google App Engine doesn't permit joins, does this mean that I have to take all of the tables in my web app and figure out a way of combining them into a single huge table?
A: Just because you don't have joins implemented by the DBMS doesn't mean you can't have multiple tables. In App Engine, these are called 'entity types', and you can have as many of them as you want.
Generally, you need to denormalize your data in order to avoid the need for frequent joins. In the few situations where they're inevitable, you can use other techniques, like doing the join in user code.
A: Combining it to one big table is always an option, but it results unnecessarily large and redundant tables most of the time, thus it will make your app slow and hard to maintain.
You can also emulate a join, by iterating through the results of a query, and running a second query for each result found for the first query. If you have the SQL query
SELECT a.x FROM b INNER JOIN a ON a.y=b.y;
you can emulate this with something like this:
for b in db.GqlQuery("SELECT * FROM b"):
for a in db.GqlQuery("SELECT * FROM a WHERE y=:1", b.y):
print a.x
A: If you are looking for way's to design the datatable. I'd recommend you do a bit of research before you start the work. There are pretty magical properties for Google App Engine like :
*
*Self-merge
*Multi-valued list property
That would be very helpful in your design. I've shared my experience here.
To learn about scale-ability there is an exclusive free course in Udacity here just on the topic. It's taught by the founder of reddit.com and he clearly explains the whole scaling things happening in reddit, one of the sites with the highest number of visitors. He shows the entire course demo implementation in gae (and that was a jackpot for me!). They offer the entire course videos free to download here . I've been toiling hard with app engine before I got these resources. So I thought sharing this might help other who are stepping the foot in waters.
A: Switching from a relational database to the App Engine Datastore requires a paradigm shift for developers when modeling their data. Take a look here to get a better idea. This will require you to think more up front about how to fit your problem into the constraints the datastore imposes, but if you can then you are guaranteed that it will run quickly and scale.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/810303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: p:dataTable: How to sort only the data on the current page like Struts ? I am given the task to port an old Struts 1.3 application on Jetty 9.3 to JSF/Primefaces.
The well-know Struts <display:table>-component has a sort-attribute which can have either "list" or "page" as values, meaning either to sort the entire underlying data or just the visible part of it on the current page, respectively.
How can this be emulated with JSF <h:dataTable> or preferably Primefaces <p:dataTable>?
I have consulted the Primefaces 5.3 user guide, the showcase and many internet resources and of course stackoverflow search.
The lazy loading features of Primefaces could be a key I figured but no complete example was to be found.
Is there a complete example with say in-memory dummy data?,
A: PrimeFaces supports lazyloading for the datatable. The feature that you can do lazy loading (no need to fully load all data upfront), is actually provided by actually giving you full control of any aspect of sorting, paging and filtering.
Normally you would filter, sort and then page, but that could be done in any order.
So it is very simple to just sort after you e.g. loaded the data for the right page with the right filter instead of doing the sorting before the paging.
That way you achieve the behaviour you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40104711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GCC finding errors in MinGW's stdio.h I'm trying to compile some example C code with GCC/MinGW on Windows 7. The example code includes some local header files which ultimately include stdio.h, and I get this error when I try to compile:
c:\mingw\include\stdio.h:345:12: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__mingw__snprintf'
extern int __mingw_stdio_redirect__(snprintf)(char*, size_t, const char*, ...);
This is a weird one to me. How could there possibly be errors in stdio.h?
A: regarding:
if (i == 0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return 0;
}
pcap_freealldevs(alldevs);
since the variable i is initialized to 0 and never modified, this if() statement will always be true. One result is the call to: pcap_freealldev() will never be called.
the scope of variables should be limited as much as reasonable.
Code should never depend on the OS to clean up after itself. suggest
#include <stdio.h>
#include <stdlib.h>
#include "pcap.h"
int main( void )
{
pcap_if_t *alldevs = NULL;
char errbuf[PCAP_ERRBUF_SIZE];
/* Retrieve the device list from the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
exit(1);
}
/* Print the list */
for( pcap_if_t *d = alldevs; d != NULL; d= d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if ( ! alldevs )
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
}
/* We don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52993896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does !! mean in ruby? Just wondering what !! is in Ruby.
A: Note that this idiom exists in other programming languages as well. C didn't have an intrinsic bool type, so all booleans were typed as int instead, with canonical values of 0 or 1. Takes this example (parentheses added for clarity):
!(1234) == 0
!(0) == 1
!(!(1234)) == 1
The "not-not" syntax converts any non-zero integer to 1, the canonical boolean true value.
In general, though, I find it much better to put in a reasonable comparison than to use this uncommon idiom:
int x = 1234;
if (!!x); // wtf mate
if (x != 0); // obvious
A: It returns true if the object on the right is not nil and not false, false if it is nil or false
def logged_in?
!!@current_user
end
A: It's useful if you need to do an exclusive or. Copying from Matt Van Horn's answer with slight modifications:
1 ^ true
TypeError: can't convert true into Integer
!!1 ^ !!true
=> false
I used it to ensure two variables were either both nil, or both not nil.
raise "Inconsistency" if !!a ^ !!b
A: It is "double-negative", but the practice is being discouraged. If you're using rubocop, you'll see it complain on such code with a Style/DoubleNegation violation.
The rationale states:
As this is both cryptic and usually redundant, it should be avoided
[then paraphrasing:] Change !!something to !something.nil?
A: Not not.
It's used to convert a value to a boolean:
!!nil #=> false
!!"abc" #=> true
!!false #=> false
It's usually not necessary to use though since the only false values to Ruby are nil and false, so it's usually best to let that convention stand.
Think of it as
!(!some_val)
One thing that is it used for legitimately is preventing a huge chunk of data from being returned. For example you probably don't want to return 3MB of image data in your has_image? method, or you may not want to return your entire user object in the logged_in? method. Using !! converts these objects to a simple true/false.
A: ! means negate boolean state, two !s is nothing special, other than a double negation.
!true == false
# => true
It is commonly used to force a method to return a boolean. It will detect any kind of truthiness, such as string, integers and what not, and turn it into a boolean.
!"wtf"
# => false
!!"wtf"
# => true
A more real use case:
def title
"I return a string."
end
def title_exists?
!!title
end
This is useful when you want to make sure that a boolean is returned. IMHO it's kind of pointless, though, seeing that both if 'some string' and if true is the exact same flow, but some people find it useful to explicitly return a boolean.
A: Understanding how it works can be useful if you need to convert, say, an enumeration into a boolean. I have code that does exactly that, using the classy_enum gem:
class LinkStatus < ClassyEnum::Base
def !
return true
end
end
class LinkStatus::No < LinkStatus
end
class LinkStatus::Claimed < LinkStatus
def !
return false
end
end
class LinkStatus::Confirmed < LinkStatus
def !
return false
end
end
class LinkStatus::Denied < LinkStatus
end
Then in service code I have, for example:
raise Application::Error unless !!object.link_status # => raises exception for "No" and "Denied" states.
Effectively the bangbang operator has become what I might otherwise have written as a method called to_bool.
A: Other answers have discussed what !! does and whether it is good practice or not.
However, none of the answers give the "standard Ruby way" of casting a value into a boolean.
true & variable
TrueClass, the class of the Ruby value true, implements a method &, which is documented as follows:
Returns false if obj is nil or false, true otherwise.
Why use a dirty double-negation when the standard library has you covered?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/524658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "139"
} |
Q: Setting up a Sensu-Go cluster - cluster is not synchronizing I'm having an issue setting up my cluster according to the documents, as seen here: https://docs.sensu.io/sensu-go/5.5/guides/clustering/
This is a non-https setup to get my feet wet, I'm not concerned with that at the moment. I just want a running cluster to begin with.
I've set up sensu-backend on my three nodes, and have configured the backend configuration (backend.yml) accordingly on all three nodes through an ansible playbook. However, my cluster does not discover the other two nodes. It simply shows the following:
For backend1:
=== Etcd Cluster ID: 3b0efc7b379f89be
ID Name Peer URLs Client URLs
────────────────── ─────────────────── ─────────────────────── ───────────────────────
8927110dc66458af backend1 http://127.0.0.1:2380 http://localhost:2379
For backend2 and backend3, it's the same, except it shows those individual nodes as the only nodes in their cluster.
I've tried both the configuration in the docs, as well as the configuration in this git issue: https://github.com/sensu/sensu-go/issues/1890
None of these have panned out for me. I've ensured all the ports are open, so that's not an issue.
When I do a manual sensuctl cluster member-add X X, I get an error message and it results in the sensu-backend process failing. I can't remove the member, either, because it causes the entire process to not be able to start. I have to revert to an earlier snapshot to fix it.
The configs on all machines are the same, except the IP's and names are appropriated for each machine
etcd-advertise-client-urls: "http://XX.XX.XX.20:2379"
etcd-listen-client-urls: "http://XX.XX.XX.20:2379"
etcd-listen-peer-urls: "http://0.0.0.0:2380"
etcd-initial-cluster: "backend1=http://XX.XX.XX.20:2380,backend2=http://XX.XX.XX.31:2380,backend3=http://XX.XX.XX.32:2380"
etcd-initial-advertise-peer-urls: "http://XX.XX.XX.20:2380"
etcd-initial-cluster-state: "new" # have also tried existing
etcd-initial-cluster-token: ""
etcd-name: "backend1"
A: Did you find the answer to your question? I saw that you posted over on the Sensu forums as well.
In any case, the easiest thing to do in this case would be to stop the cluster, blow out /var/lib/sensu/sensu-backend/etcd/ and reconfigure the cluster. As it stands, the behavior you're seeing seems like the cluster members were started individually first, which is what is potentially causing the issue and would be the reason for blowing the etcd dir away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57621384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get Spring MVC Controller to load lazily? I am not able to get Spring MVC Controllers to lazy load.
I have tried the solution mentioned in Does Spring MVC initialize all controllers on start up??
Here is my code:
app-servlet.xml
<context:component-scan base-package="com.mvc.controller">
AssetController.java
@Lazy(value=true)
@Controller
@RequestMapping("/api/asset")
public class AssetController{
@Autowired
private AssetService assetService;
What am I missing here?
Spring v3.0.7
A: @RequestMapping annotation makes controller to be initialized eagerly despite the fact that it is also annotated with @Lazy(value=true).
In your case, removing @RequestMapping annotation should make the controller initialize lazily. Though I do not know if it is possible to use @RequestMapping annotation and have that controller load lazily, I did not manage to achieve it (solved my issue without making the controller load lazily, but that is out of scope of this question).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27438314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AngularJS: format element text with a function I have an element
<td colspan="3" class="linkCol"><a ng-href="{{ad.url}}" target="_blank" title="{{ad.url}}">Link</a></td>
And a function getDomain(url) that returns domain.
I want the '.linkCol' element to have text returned by getDomain(ad.url).
It's all inside an ng-repeat.
How do I do this?
A: getDomain() needs to be added to the scope in the controller...
$scope.getDomain = function(url) {
// ...
return domain;
};
Then you can use it in your view...
<td colspan="3" class="linkCol">
<a ng-href="{{ad.url}}" target="_blank" title="{{ad.url}}">{{ getDomain(ad.url) }}</a>
</td>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23358065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to retrieve only current date data from SQLite database? I'm storing the date and time in SQLite Db. I want to retrieve only data of current data. I have search internet for a solution but I couldn't find any answers.
My code:
Creating Table
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String query = "CREATE TABLE " + Db_Contract.Db_Fieds.TABLE_NAME +" ("
+ Db_Contract.Db_Fieds._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Db_Contract.Db_Fieds.MONEY+ " REAL NOT NULL,"
+ Db_Contract.Db_Fieds.CAT+" TEXT NOT NULL,"
+ Db_Contract.Db_Fieds.TIMESTAMP+" TIMESTAMP DEFAULT CURRENT_TIMESTAMP"+"); " ;
sqLiteDatabase.execSQL(query);
}
Retrieving all data :
private Cursor getAllData()
{
return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
null,
null,
null,
null,
null,
Db_Contract.Db_Fieds.TIMESTAMP);
}
Here I want to retrieve only the data of current date
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50315621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Narrowing conversions and initializer lists, which compiler is right? Considering the following piece of code:
#include <iostream>
auto main() -> int {
double x(7.0);
int i{x};
std::cout << "i = " << x << std::endl;
return 0;
}
*
*When compiled in GCC4.9 it compiles fine with only a warning:
warning: narrowing conversion of ‘x’ from ‘double’ to ‘int’ inside { }
*
*Compiling with either Clang3.3 or VC++2013 gives a compile error:
error: type 'double' cannot be narrowed to 'int' in initializer list
error C2397: conversion from 'double' to 'int' requires a narrowing
Questions:
*
*Which of the compilers is right according to the standard?
*Is there any reason why the compilers mentioned above should exhibit such diverse behaviour?
A: The answer
Both compilers are correct!
Explanation
The Standard doesn't distinguish between an error and a warning, both go under the category of Diagnostics.
1.3.6 diagnostic message [defns.diagnostic]
message belonging to an implementation-defined subset of the implementation's output messages
Since the Standard says that a diagnostic is required in case a program is ill-formed, such as when a narrowing-conversion takes place inside a braced-initializer, both compilers are confirming.
Even if the program is ill-formed from the Standards point of view, it doesn't mandate that a compiler halts compilation because of that; an implementation is free to do whatever it wants, as long as it issues a diagnostic.
The reason for gcc's behavior?
Helpful information was provided by @Jonathan Wakely through comments on this post, below are a merge of the two comments;
he exact reason is that GCC made it an error at one point and it broke ALL THE PROGRAMS so it got turned into a warning instead. Several people who turned on the -std=c++0x option for large C++03 codebases found harmless narrowing conversions to cause most of the porting work to go to C++11See e.g. PR 50810 where Alisdair reports narrowing errors were >95% of the problems in Bloomberg's code base.In that same PR you can see that unfortunately it wasn't a case of "let's just issue a warning and be done with it" because it took a lot of fiddling to get the right behaviour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24032430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: banshee: How would I set the rating for a specific track on Banshee through DBus? I'd like to set the 'rating' of a specific track (i.e. not only the one currently playing) on Banshee through the DBus interface?
A: Banshee does not expose rating functions via DBus.
You can quickly view all functions that it exposes, using applications like d-feet[1]. Make sure that an instance of the application you are interested in (like Banshee in this case) is running.
There is a bug report already requesting to add rating functionality[2] to DBus interface. You might want to subscribe to it.
*
*https://fedorahosted.org/d-feet/
*https://bugzilla.gnome.org/show_bug.cgi?id=579754
A: Banshee does support rating via commandline since last year.
banshee --set-rating={1;2;3;4;5}
See the bug report for more options:
Add item rating to DBus interface
A: Sadly the developer have not implemented a GET method, so there is no common way to execute "rate current track 1 star up/down"-command, much less than a specific track.
Does anyone has written a script which provide this feature?
Yet, I haven't found any solution to modify the D-Bus Property via command line.
Finally here is my Workaround for rate the current played Track.
#!/bin/bash
#read current TrackRating
R=$(qdbus org.mpris.MediaPlayer2.banshee /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadata | grep 'userRating' | tr -d '/xesam:userRating: ')
case $R in
'' ) R=0 ;;
'0.2' ) R=1 ;;
'0.4' ) R=2 ;;
'0.6' ) R=3 ;;
'0.8' ) R=4 ;;
'1' ) R=5 ;;
esac
case $1 in
'inc' ) [ $R -lt 5 ]
banshee --set-rating=$(($R+1)) ;;
'dec' ) [ $R -gt 0 ]
banshee --set-rating=$(($R-1)) ;;
'res' ) banshee --set-rating=3 ;;
'min' ) banshee --set-rating=0 ;;
'max' ) banshee --set-rating=5 ;;
esac
Options:
*
*inc -> increase rating by one if possible
*dec -> decrease rating by one if possible
*res -> reset rating to three stars
*min -> set rating to zero stars
*max -> set rating to five stars
As far Banshee will not provide manipulating data of a specific Track this is my best bet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1517984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python : recognising if a list has no duplicate numbers Im currently working on a game which uses lists and gives users choices depending on if there is/isnt duplicates in a list (really basic text based game), however i cant seem to code something that recognises if there is no duplicates without looping through and checking if the count for each number is greater than 1. I really just need something that would check if the list contains no duplicates so that i can then write the rest of the program.
so the psuedocode would look something like this
numbers = [1, 3, 5, 6]
check list for duplicates
if no duplicates:
do x
A: Use set function with sorted:
if sorted(set(y)) == sorted(y):
pass
Set remove duplicates from given list so its easy to check if your list has duplicates. Sorted its optional but if you give user option to input numbers in other order this will be helpful then.
set()
sorted()
Simpler solution if you don't need sorted use:
len(y) != len(set(y))
Its faster because u dont need use sort on both lists. Its return True of False.
Check for duplicates in a flat list
A: You can check the length of the set of the list and compare with its regular length:
l = [1, 3, 32, 4]
if len(set(l)) == len(l):
pass
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46119502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Less number of levels for a categorical variable in decision tree output I am presently fitting a model using decision tree and the data set contains both numeric and categorical variables. One of the variable is a categorical variable A having 3 levels: Good, Bad and Medium. Now, when I fit the model using 'tree' package, it gave the tree output with A as my root node but with only 2 levels and the significant level, Good is not included in the tree. To experiment, I have increased the Good values in the input dataset to more than 200 in a dataset of 400 but still it did not included it in the tree output. Why is that so?. And what to do force it to include Good in the tree?.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45113819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a rollback in functions with transactions annotation in case if save operation returns null? I use Spring Boot 5 and MongoDB in my project. When I save a user in users collection I also need to save authority of the user in another collection. In case if an error has happened and one of the items did not saved I have to rollback the operation to prevent the saving
of the another item in case if it saved.
For this purpose I use Transaction annotation above my create method:
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService{
@Autowired
public AutoMapper autoMapper;
private final UserRepository userRepository;
private final AdminUserRepository adminUserRepository;
@Override
@Transactional
public SaveBuilderResponse create(UserDto newUser){
AdminUser adminUser = autoMapper.map(newUser, AdminUser.class);
User userToSave = autoMapper.map(newUser, User.class);
AdminUser savedAdminUser = adminUserRepository.save(adminUser);
User savedUser = userRepository.save(builderToSave);
return new SaveUserResponse(savedUser);
}
}
As you can see in function above I have two rows that saves items:
AdminUser savedAdminUser = adminUserRepository.save(adminUser);
User savedBuilder = userRepository.save(userToSave);
After the the row above executed I need to check that returned value not null and proceed. In case if savedAdminUser or savedBuilder variables is null I need to do a rollabck to prevent the saving operation of the another item in case if it saved.
My question is how can I do rollback in case if savedAdminUser or savedUser variables is null?
A: you used, @Transactional annotation can rollback in case if savedAdminUser or savedUser variables is null. Also you Should throw an exception like below.
@Override
@Transactional
public SaveBuilderResponse create(UserDto newUser) throws Exception {
try {
AdminUser adminUser = autoMapper.map(newUser, AdminUser.class);
User userToSave = autoMapper.map(newUser, User.class);
AdminUser savedAdminUser = adminUserRepository.save(adminUser);
User savedUser = userRepository.save(builderToSave);
return new SaveUserResponse(savedUser);
} catch (Exception ex) {
throw ex;
}
}
A: If you don't want to engage with custom exception you can simply do (before the last return statement) :
if (adminUser == null || savedBuilder == null) {
//do whatever you want
return null;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68433582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling @CacheEvict and @Cacheable annotation on a single method? I'm trying to call @CacheEvict and @Cacheable annotation on a single method.
@CacheEvict(value = "tripDetailsDashboardCache", key = "#userId")
@Cacheable(value ="tripDetailsDashboardCache", key="#userId")
public List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
return dashBoardObject;
}
On call of @CacheEvict, I want to delete the cached data for the particular key and again i want to cache the fresh data of the method response. But it is not caching the fresh data ?. And also it is not giving any error ?.
A: I think you want to update the cache, so try to use @CachePut, method will be executed in all cases, if the key is new, new record will be added in the cache, if the record is old, old value will be updated by new value (refresh the value).
@CachePut(value = "tripDetailsDashboardCache", key = "#userId")
public List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
return dashBoardObject;
}
A: @CacheEvict runs by default after the method invocation. So the method above does the caching the list with key #userId and then clear the cache completely .
it makes the code unclear I’d recommend creating separate cacheable and cache-evict methods
A: Look at docs. There are @Caching annotation where you can define your @Cacheable, @CachePut and @CacheEvict
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36860870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: show line in screen (read file j2me)? i want to read a file in j2me and show it in screen i try very a lot , exactly i try all code exist in web but no one worked. this is just one of them :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import java.io.*;
/**
* @author ZARA-T
*/
public class ReadMidlet extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command read, exit;
StringBuffer buff;
public void startApp(){
display = Display.getDisplay(this);
read = new Command("Read", Command.EXIT, 1);
exit = new Command("Exit", Command.EXIT, 1);
form = new Form("Read File");
form.addCommand(exit);
form.addCommand(read);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable s){
if (c==read) {
try {
String SS;
SS=ReadFile("file:///root1//hello.txt");
TextBox input = new TextBox("Enter Some Text:", "", 5, TextField.ANY);
input.setString(SS);
display.setCurrent(input);
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (c==exit) destroyApp(false);
}
private String ReadFile(String url) throws IOException {
FileConnection fc = (FileConnection) Connector.open(url,Connector.READ);
AlertType.ERROR.playSound(display);
StringBuffer sb = new StringBuffer();
try {
InputStream in = fc.openInputStream();
try {
int i;
while ((i = in.read()) != -1) {
sb.append((char) i);
}
} finally {
in.close();
}
} finally {
fc.close();
}
form.append(sb.toString());
return sb.toString();
}
}
I put this CODE line to test which line cause error.
AlertType.ERROR.playSound(display);
it seems this line can't be run.also i read the POSTS here (stackOverflow) but i could not solve my problem. tnx for ur helping.
A: Here is my version of an OpenFileDialog for Java ME.
public class OpenFileDialog extends List
implements CommandListener
{
public static final String PREFIX = "file:///";
private static final String UP = "[ .. ]";
private static final String DIR = " + ";
private Stack stack = new Stack();
private OpenFileListener listener;
private CommandListener commandListener;
private String extension;
public OpenFileDialog (OpenFileListener listener,
String title, String extension)
{
super(title, List.IMPLICIT);
super.setCommandListener(this);
this.listener = listener;
this.extension = extension;
addRoots();
}
public void setCommandListener(CommandListener l) {
this.commandListener = l;
}
public void commandAction(Command c, Displayable d) {
if (c == List.SELECT_COMMAND) {
this.changeSelection();
} else {
if (this.commandListener != null) {
this.commandListener.commandAction(c, d);
}
}
}
private String getSelectedText () {
int index = getSelectedIndex();
if (index < 0 || index >= this.size()) {
return "";
}
return this.getString(index);
}
private void changeSelection () {
String target = this.getSelectedText();
String parent = null;
boolean goingUp = false;
if (UP.equals(target)) {
goingUp = true;
stack.pop();
if (stack.isEmpty() == false) {
target = (String) stack.peek();
} else {
super.deleteAll();
addRoots();
this.setTicker(null);
return;
}
} else {
if (stack.isEmpty() == false) {
parent = stack.peek().toString();
}
}
try {
if (target.startsWith(DIR)) {
target = target.substring(3);
}
if (parent != null) {
target = parent + target;
}
this.setTicker(new Ticker(target));
FileConnection fc = (FileConnection)
Connector.open(PREFIX + target, Connector.READ);
if (fc.isDirectory()) {
super.deleteAll();
if (goingUp == false) {
stack.push(target);
}
super.append(UP, null);
Enumeration entries = fc.list();
while (entries.hasMoreElements()) {
String entry = (String) entries.nextElement();
FileConnection fc2 = (FileConnection)
Connector.open(PREFIX + target + entry,
Connector.READ);
if (fc2.isDirectory()) {
super.append(DIR + entry, null);
} else if (entry.toLowerCase().endsWith(extension)) {
super.append(entry, null);
}
fc2.close();
}
fc.close();
} else {
this.listener.fileSelected(fc);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void addRoots() {
Enumeration roots = FileSystemRegistry.listRoots();
while (roots.hasMoreElements()) {
super.append(DIR + roots.nextElement().toString(), null);
}
}
}
interface OpenFileListener {
void fileSelected(FileConnection fc);
}
It was first presented at http://smallandadaptive.blogspot.com.br/2009/08/open-file-dialog.html
A: i find my problem, maybe this is your problem too, i just Use thread in commandAction function and it works. here is the code that changed:
if (c==read) {
new Thread(new Runnable() {
public void run() {
try {
ReadFile(path);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}).start();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17633687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to distinguish cookies with the same name by domain?
*
*User gets cookie named X from site a.com.
*User gets cookie named X from sub.a.com (a subdomain of a.com).
*Both of the cookies X use their respective domains.
Given the assumptions above, can JavaScript identify one cookie X out of the two by using domain info, then update it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68457607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WatchKit see if crown is pressed or screen flipped/tilted I have made an app that uses the AppleWatch.
I want to call NSObject cancelPreviousPerformRequestsWithTarget when the user goes to the home screen, but continue if they put down their wrist
Is there any way I can see the difference in -(void)didDeactivate?
Kim
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41018558",
"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.