text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Avoid permanent redirect to login page http://127.0.0.1:3000/login I have a problem using nuxt/auth v4.9.1.
when I logged in and I enter a URL for example http://127.0.0.1:3000/configuration/locations it redirects me to the login page http://127.0.0.1:3000/login while I I'm already logged in and my token hasn't expired yet.
Please how to avoid this redirect?
Nuxt.config.js
router: {
middleware: ['auth']
},
// Auth Strategies
auth: {
redirect: {
login: '/login',
logout: false,
callback: false,
home: '/'
},
token: {
property: 'accessToken',
global: true,
maxAge: 1800
},
refreshToken: {
property: 'refreshToken',
data: 'refreshToken',
maxAge: 60 * 30
},
strategies: {
local: {
endpoints: {
login: { headers: { 'Content-Type': 'application/x-www-form-urlencoded'}, url:'oauth/v2/token', method: 'post', propertyName: "accessToken" },
refresh: { headers: { 'Content-Type': 'application/x-www-form-urlencoded'}, url: '/oauth/v2/token/refresh', method: 'post', propertyName: 'refreshToken'},
user: { url: 'security/users/me', method: 'get', propertyName: false}
},
/* user: {
property: 'data'
}, */
tokenType: 'Bearer'
}
}
}
Someone to help me please?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71110873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image used for wordpress posts on Facebook I've seen it several times on my facebook timeline where the image of a shared link is not in the post itself. Example:
https://www.facebook.com/BarakaBits/posts/1065758210116791 - Image has text on it.
screenshot
Here's the post itself: http://www.barakabits.com/2015/01/beauty-moroccos-diversity-captured-stunning-photo-series
Is this a hidden image? I'm using a wordpress blog, how can I do this? Do I need a special plugin?
Thank you in advance!
Wil
A: I don't know exactly what this site is doing, but you can suggest that Facebook use a specific image (not necessarily one found on the page) by using the og:image Open Graph tag. For example, something like this would go in the <head> portion of your site:
<meta property="og:image" content="http://www.barakabits.com/wp-content/uploads/2015/01/Moroccos-faces-featured-6.jpg">
As you can see from the site you referenced, you can have multiple og:image tags, and the user will be able to choose which one is displayed in the post.
Here's Facebook's guide to Open Graph tags: https://developers.facebook.com/docs/sharing/best-practices
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28254174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't call async method synchronously from MeasureOverride I need to call an async method from MeasureOverride. This call should be synchronous because I need to return the value of the async method.
I tried about a dozen different calls from these threads:
Synchronously waiting for an async operation, and why does Wait() freeze the program here
How would I run an async Task<T> method synchronously?
They all failed, some wouldn't compile in Universal Windows Applications, some weren't synchronous, some provoked a deadlock etc..
I feel strongly against async/await because of how it contaminates the call hierarchy prototypes. At the override level I'm stuck with no async keyword and I need to call await synchronously from the blackbox. Concretely how should I go about it?
A: The first thing you should do is take a step back. There should be no need to call asynchronous code from within a MeasureOverride in the first place.
Asynchronous code generally implies I/O-bound operations. And a XAML UI element that needs to send a request to a remote web server, query a database, or read a file, just to know what its size is, is doing it wrong. That's a fast track to app certification rejection.
The best solution is almost certainly to move the asynchronous code out of the element itself. Only create/modify the UI elements after the necessary asynchronous work completes.
That said, if you feel you must block the UI thread while asynchronous operations complete, I've compiled a list of every hack I know of, published in my MSDN article on brownfield asynchronous development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34485996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Bootstrap carousel news slides timing wrong I've been developing a wordpress template with a bootstrap (3.3.6.) carousel news slider. But the slides timing is all wrong after a few seconds. I already set a timer in custom.js, but it only worked on the news button (replacement of indicator), while the slides are moving way too fast after a few seconds.The weirdest thing is, if I change the bootstrap link to the cdn, the slides move properly but the news button are not moving at all. Any ideas on how to fix this?
This is the website for you to review: http://tfcakalimantan.org
The front-page.php
<?php
$args = array(
'post_type' => 'post',
'tag' => 'featured',
'posts_per_page' => 5
);
$the_query = new WP_Query( $args );
?>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<ol class="list-group col-sm-4" style="padding-right: 0px;"> <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li data-target="#myCarousel" data-slide-to="<?php echo $the_query->current_post; ?>" class="list-group-item <?php if( $the_query->current_post == 0) echo 'active'; ?>"><h5><?php the_title(); ?></h5></li><?php endwhile; endif; ?>
</ol>
<?php rewind_posts(); ?>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
$thumbnail_id = get_post_thumbnail_id();
$thumbnail_url = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail-size', true );
$thumbnail_meta = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true);
?>
<div class="item <?php if( $the_query->current_post == 0) echo 'active'; ?>">
<img src="<?php echo $thumbnail_url[0]; ?>" class="img-responsive" alt="<?php echo $thumbnail_meta; ?>">
<div class="carousel-caption">
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
</div></div>
<?php endwhile; endif; ?>
</div><!-- End Item -->
</div><!-- End Carousel Inner -->
</div>
<!-- Controls -->
<div class="row">
<div class="carousel-controls">
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<i class="fa fa-arrow-circle-left fa-2x"></i>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<i class="fa fa-arrow-circle-right fa-2x"></i>
</a>
</div>
</div>
</div><!-- End Carousel -->
The custom.js
// Carousel
$(document).ready(function(){
var clickEvent = false;
$('#myCarousel').carousel({
interval: 2000
}).on('click', '.list-group li', function() {
clickEvent = true;
$('.list-group li').removeClass('active');
$(this).addClass('active');
}).on('slid.bs.carousel', function(e) {
if(!clickEvent) {
var count = $('.list-group').children().length -1;
var current = $('.list-group li.active');
current.removeClass('active').next().addClass('active');
var id = parseInt(current.data('slide-to'));
if(count == id) {
$('.list-group li').first().addClass('active');
}
}
clickEvent = false;
});
});
$(window).load(function() {
var boxheight = $('#myCarousel .carousel-inner').innerHeight();
var itemlength = $('#myCarousel .item').length;
var triggerheight = Math.round(boxheight/itemlength+1);
$('#myCarousel .list-group-item').outerHeight(triggerheight);
});
The style.css
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
#myCarousel .carousel-caption {
left:0;
right:0;
bottom:0;
text-align:left;
padding:10px;
background:rgba(0,0,0,0.6);
text-shadow:none;
font-family: 'Droid Sans', sans-serif;
color: #FFFFFF;
}
#myCarousel .list-group {
position:absolute;
top:0;
right:0;
font-family: 'Pontano Sans', sans-serif;
}
#myCarousel .list-group-item {
border-radius:0px;
cursor:pointer;
}
#myCarousel .list-group .active {
background-color:#6D9755;
}
#myCarousel .item {
height: 300px;
}
.carousel-controls {display:none;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34176195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dispatch controller zf2 event manager I have a base controller named MyController
I extend my Controller from MyController instead of AbstractActionController
What's wrong with this code ?
It doesn't work :
$sharedEventManager->attach('MyController', 'dispatch', function ($e) {
$controller = $e->getTarget();
},100) ;
but this does :
$sharedEventManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function ($e) {
$controller = $e->getTarget();
},100) ;
A: The first parameter of the SharedEventManager::attach() is the identity of the event manager to target. This identity is dynamically assigned for any class that is event capable (implements Zend\EventManager\EventManagerAwareInterface) or has otherwise had it's identity set via $eventManager->setIdentity().
The question refers to the \Zend\Mvc\Controller\AbstractActionController; this itself is an identity given to any controller that extends \Zend\Mvc\AbstractActionController (among others), allowing for just one id to attach() to target all controllers.
To target just one controller (which is perfectly valid, there are many use cases), you can do so in two ways:
*
*via the SharedEventManager, external to the controller class (as you have been doing)
*directly fetching said controller's event manager and handling the events within the controller class.
via SharedEventManager
Use the fully qualified class name as this is is added as an identity to the event manager
$sharedEventManager->attach(
'MyModule\Controller\FooController', 'dispatch', function($e){
// do some work
});
Within controller
I modify the normal attachDefaultListeners() method (which is called automatically), this is where you can attach events directly.
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\EventManager\EventInterface;
class FooController extends AbstractActionController
{
protected function attachDefaultListeners()
{
// make sure you attach the defaults!
parent::attachDefaultListeners();
// Now add your own listeners
$this->getEventManager()->attach('dispatch', array($this, 'doSomeWork'));
}
public function doSomeWork(EventInterface $event) {
// do some work
}
}
A: Why do you use your own base controller? there is no real benefit of doing that, unless you have rare edge case scenario.
Your base controller class is missing this part from AbstractController:
/**
* Set the event manager instance used by this context
*
* @param EventManagerInterface $events
* @return AbstractController
*/
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
'Zend\Stdlib\DispatchableInterface',
__CLASS__,
get_class($this),
$this->eventIdentifier,
substr(get_class($this), 0, strpos(get_class($this), '\\'))
));
$this->events = $events;
$this->attachDefaultListeners();
return $this;
}
See setIdentifiers call there? That is why second example works.
Also i suspect you might not actually trigger dispatch event in dispatch() method of your controller
As side note: you should never create classes without top level namespace. Eg all my classes use Xrks\ vendor namespace
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24469400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NodeJS writes to MongoDB only once I have a NodeJS app that is supposed to generate a lot of data sets in a synchronous manner (multiple nested for-loops). Those data sets are supposed to be saved to my MongoDB database to look them up more effectively later on.
I use the mongodb - driver for NodeJS and have a daemon running. The connection to the DB is working fine and according to the daemon window the first group of datasets is being successfully stored. Every ~400-600ms there is another group to store but after the first dataset there is no output in the MongoDB console anymore (not even an error), and as the file sizes doesn't increase i assume those write operations don't work (i cant wait for it to finish as it'd take multiple days to fully run).
If i restart the NodeJS script it wont even save the first key anymore, possibly because of duplicates? If i delete the db folder content the first one will be saved again.
This is the essential part of my script and i wasn't able to find anything that i did wrong. I assume the problem is more in the inner logic (weird duplicate checks/not running concurrent etc).
var MongoClient = require('mongodb').MongoClient, dbBuffer = [];
MongoClient.connect('mongodb://127.0.0.1/loremipsum', function(err, db) {
if(err) return console.log("Cant connect to MongoDB");
var collection = db.collection('ipsum');
console.log("Connected to DB");
for(var q=startI;q<endI;q++) {
for(var w=0;w<words.length;w++) {
dbBuffer.push({a:a, b:b});
}
if(dbBuffer.length) {
console.log("saving "+dbBuffer.length+" items");
collection.insert(dbBuffer, {w:1}, function(err, result) {
if(err) {
console.log("Error on db write", err);
db.close();
process.exit();
}
});
}
dbBuffer = [];
}
db.close();
});
Update
*
*db.close is never called and the connection doesn't drop
*Changing to bulk insert doesn't change anything
*The callback for the insert is never called - this could be the problem! The MongoDB console does tell me that the insert process was successful but it looks like the communication between driver and MongoDB isn't working properly for insertion.
A: I "solved" it myself. One misconception that i had was that every insert transaction is confirmed in the MongoDB console while it actually only confirms the first one or if there is some time between the commands. To check if the insert process really works one needs to run the script for some time and wait for MongoDB to dump it in the local file (approx. 30-60s).
In addition, the insert processes were too quick after each other and MongoDB appears to not handle this correctly under Win10 x64. I changed from the Array-Buffer to the internal buffer (see comments) and only continued with the process after the previous data was inserted.
This is the simplified resulting code
db.collection('seedlist', function(err, collection) {
syncLoop(0,0, collection);
//...
});
function syncLoop(q, w, collection) {
batch = collection.initializeUnorderedBulkOp({useLegacyOps: true});
for(var e=0;e<words.length;e++) {
batch.insert({a:a, b:b});
}
batch.execute(function(err, result) {
if(err) throw err;
//...
return setTimeout(function() {
syncLoop(qNew,wNew,collection);
}, 0); // Timer to prevent Memory leak
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39966845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to test akismet in a Rails app? I'm using the rakismet gem to submit user content to Akismet for spam testing.
So far every test I have done has classified the content as spam.
I'm starting to think I'm doing something wrong.
Does anyone know why I might be getting all false positives on my test data?
A: ... Because they're test data ?
You can't rely on real rakismet data in your test. Because any test can be detected as spam one day or an other.
Or just because using rakismet requires that you have an internet connection, which can sometimes not be the case.
You should mock the rakismet methods and force them to return what you expect them to.
For example you can use mocha. And do something like the following :
Object.stubs(:spam?).returns(false)
So your objects will never be spams.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1725857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show and hide div on the basis of radio button selection I have two radio button on the selection of radio button it's should display div and hide div. Below is my script I don't understand why it's not working.
JavaScript
$(document).ready(function() {
$(".text").show();
$(".text1").hide();
$("#r1").click(function() {
$(".text").show();
$(".text1").hide();
});
$("#r2").click(function() {
$(".text1").show();
$(".text").hide();
});
});
HTML
<p>Show textboxes
<input type="radio" name="radio1" id="r1" checked value="Show" onClick="getResults()">Do nothing
<input type="radio" name="radio1" id="r2" onClick="getResults()" value="Show">
</p> Wonderful textboxes:
<div class="text">
<p>Textbox #1
<input type="text" name="text" id="text" maxlength="30">
</p>
<p>Textbox #2
<input type="text" name="text" id="text" maxlength="30">
</p>
</div>
<div class="text1">
<p>Textbox #3
<input type="text" name="text1" id="text1" maxlength="30">
</p>
<p>Textbox #4
<input type="text" name="text2" id="text1" maxlength="30">
</p>
</div>
here is jsfiddle link
A: Use change() event handler to handle the change event and toggle the element state using toggle() method with a boolean argument.
$(document).ready(function() {
// attach change event handler
$("#r1,#r2").change(function() {
// toggle based on the id
$(".text").toggle(this.id == 'r1');
$(".text1").toggle(this.id == 'r2');
// trigger change event to hide initially
}).first().change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Show textboxes
<input type="radio" name="radio1" id="r1" checked value="Show">Do nothing
<input type="radio" name="radio1" id="r2" value="Show">
</p> Wonderful textboxes:
<div class="text">
<p>Textbox #1
<input type="text" name="text" maxlength="30">
</p>
<p>Textbox #2
<input type="text" name="text" maxlength="30">
</p>
</div>
<div class="text1">
<p>Textbox #3
<input type="text" name="text1" maxlength="30">
</p>
<p>Textbox #4
<input type="text" name="text2" maxlength="30">
</p>
</div>
FYI : The attribute should be unique on the page, for a group of elements use class attribute otherwise only the first element with the id get selected while using id selector.
A: Your Code is looking fine. make it sure that you add JQuery Properly
like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".text").show();
$(".text1").hide();
$("#r1").click(function() {
$(".text").show();
$(".text1").hide();
});
$("#r2").click(function() {
$(".text1").show();
$(".text").hide();
});
});
</script>
A: your code is working fine after added the jquery reference.
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
A: use toggle method for hide and show go to following link
https://www.w3schools.com/jquery/eff_toggle.asp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42827454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you merge dataframes in pandas with different shapes? I am trying to merge two dataframes in pandas with large sets of data, however it is causing me some problems. I will try to illustrate with a smaller example.
df1 has a list of equipment and several columns relating to the equipment:
Item ID Equipment Owner Status Location
1 Jackhammer James Active London
2 Cement Mixer Tim Active New York
3 Drill Sarah Active Paris
4 Ladder Luke Inactive Hong Kong
5 Winch Kojo Inactive Sydney
6 Circular Saw Alex Active Moscow
df2 has a list of instances where equipment has been used. This has some similar columns to df1, however some of the fields are NaN values and also instances of equipment not in df1 have also been recorded:
Item ID Equipment Owner Date Location
1 Jackhammer James 08/09/2020 London
1 Jackhammer James 08/10/2020 London
2 Cement Mixer NaN 29/02/2020 New York
3 Drill Sarah 11/02/2020 NaN
3 Drill Sarah 30/11/2020 NaN
3 Drill Sarah 21/12/2020 NaN
6 Circular Saw Alex 19/06/2020 Moscow
7 Hammer Ken 21/12/2020 Toronto
8 Sander Ezra 19/06/2020 Frankfurt
The resulting dataframe I was hoping to end up with was this:
Item ID Equipment Owner Status Date Location
1 Jackhammer James Active 08/09/2020 London
1 Jackhammer James Active 08/10/2020 London
2 Cement Mixer Tim Active 29/02/2020 New York
3 Drill Sarah Active 11/02/2020 Paris
3 Drill Sarah Active 30/11/2020 Paris
3 Drill Sarah Active 21/12/2020 Paris
4 Ladder Luke Inactive NaN Hong Kong
5 Winch Kojo Inactive NaN Sydney
6 Circular Saw Alex Active 19/06/2020 Moscow
7 Hammer Ken NaN 21/12/2020 Toronto
8 Sander Ezra NaN 19/06/2020 Frankfurt
Instead, with the following code I'm getting duplicate rows, I think because of the NaN values:
data = pd.merge(df1, df2, how='outer', on=['Item ID'])
Item ID Equipment_x Equipment_y Owner_x Owner_y Status Date Location_x Location_y
1 Jackhammer NaN James James Active 08/09/2020 London London
1 Jackhammer NaN James James Active 08/10/2020 London London
2 Cement Mixer NaN Tim NaN Active 29/02/2020 New York New York
3 Drill NaN Sarah Sarah Active 11/02/2020 Paris NaN
3 Drill NaN Sarah Sarah Active 30/11/2020 Paris NaN
3 Drill NaN Sarah Sarah Active 21/12/2020 Paris NaN
4 Ladder NaN Luke NaN Inactive NaN Hong Kong Hong Kong
5 Winch NaN Kojo NaN Inactive NaN Sydney Sydney
6 Circular Saw NaN Alex NaN Active 19/06/2020 Moscow Moscow
7 NaN Hammer NaN Ken NaN 21/12/2020 NaN Toronto
8 NaN Sander NaN Ezra NaN 19/06/2020 NaN Frankfurt
Ideally I could just drop the _y columns however the data in the bottom rows means I would be losing important information. Instead the only thing I can think of merging the columns and force pandas to compare the values in each column and always favour the non-NaN value. I'm not sure if this is possible or not though?
A:
merging the columns and force pandas to compare the values in each column and always favour the non-NaN value.
Is this what you mean?
In [45]: data = pd.merge(df1, df2, how='outer', on=['Item ID', 'Equipment'])
In [46]: data['Location'] = data['Location_y'].fillna(data['Location_x'])
In [47]: data['Owner'] = data['Owner_y'].fillna(data['Owner_x'])
In [48]: data = data.drop(['Location_x', 'Location_y', 'Owner_x', 'Owner_y'], axis=1)
In [49]: data
Out[49]:
Item ID Equipment Status Date Location Owner
0 1 Jackhammer Active 08/09/2020 London James
1 1 Jackhammer Active 08/10/2020 London James
2 2 Cement Mixer Active 29/02/2020 New York Tim
3 3 Drill Active 11/02/2020 Paris Sarah
4 3 Drill Active 30/11/2020 Paris Sarah
5 3 Drill Active 21/12/2020 Paris Sarah
6 4 Ladder Inactive NaN Hong Kong Luke
7 5 Winch Inactive NaN Sydney Kojo
8 6 Circular Saw Active 19/06/2020 Moscow Alex
9 7 Hammer NaN 21/12/2020 Toronto Ken
10 8 Sander NaN 19/06/2020 Frankfurt Ezra
(To my knowledge) you cannot really merge on null column. However you can use fillna to take the value and replace it by something else if it is NaN. Not a very elegant solution, but it seems to solve your example at least.
Also see pandas combine two columns with null values
A: Generically you can do that as follows:
# merge the two dataframes using a suffix that ideally does
# not appear in your data
suffix_string='_DF2'
data = pd.merge(df1, df2, how='outer', on=['Item_ID'], suffixes=('', suffix_string))
# now remove the duplicate columns by mergeing the content
# use the value of column + suffix_string if column is empty
columns_to_remove= list()
for col in df1.columns:
second_col= f'{col}{suffix_string}'
if second_col in data.columns:
data[col]= data[second_col].where(data[col].isna(), data[col])
columns_to_remove.append(second_col)
if columns_to_remove:
data.drop(columns=columns_to_remove, inplace=True)
data
The result is:
Item_ID Equipment Owner Status Location Date
0 1 Jackhammer James Active London 08/09/2020
1 1 Jackhammer James Active London 08/10/2020
2 2 Cement_Mixer Tim Active New_York 29/02/2020
3 3 Drill Sarah Active Paris 11/02/2020
4 3 Drill Sarah Active Paris 30/11/2020
5 3 Drill Sarah Active Paris 21/12/2020
6 4 Ladder Luke Inactive Hong_Kong NaN
7 5 Winch Kojo Inactive Sydney NaN
8 6 Circular_Saw Alex Active Moscow 19/06/2020
9 7 Hammer Ken NaN Toronto 21/12/2020
10 8 Sander Ezra NaN Frankfurt 19/06/2020
On the following test data:
df1= pd.read_csv(io.StringIO("""Item_ID Equipment Owner Status Location
1 Jackhammer James Active London
2 Cement_Mixer Tim Active New_York
3 Drill Sarah Active Paris
4 Ladder Luke Inactive Hong_Kong
5 Winch Kojo Inactive Sydney
6 Circular_Saw Alex Active Moscow"""), sep='\s+')
df2= pd.read_csv(io.StringIO("""Item_ID Equipment Owner Date Location
1 Jackhammer James 08/09/2020 London
1 Jackhammer James 08/10/2020 London
2 Cement_Mixer NaN 29/02/2020 New_York
3 Drill Sarah 11/02/2020 NaN
3 Drill Sarah 30/11/2020 NaN
3 Drill Sarah 21/12/2020 NaN
6 Circular_Saw Alex 19/06/2020 Moscow
7 Hammer Ken 21/12/2020 Toronto
8 Sander Ezra 19/06/2020 Frankfurt"""), sep='\s+')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64976628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update streamProvider stream based on other providers value I want to update StreamProvider stream, based on the value of the Provider. I arrived at this solution.
return Provider<SelectedDay>.value(
value: selectedDay,
child: ProviderToStream<SelectedDay>(
builder: (_, dayStream, Widget child) {
return StreamProvider<DailyHomeData>(
initialData: DailyHomeData.defaultValues(DateTime.now()),
create: (_) async* {
await for (final selectedDay in dayStream) {
yield await db
.dailyHomeDataStream(
dateTime: selectedDay.selectedDateTime)
.first;
}
},
child: MainPage(),
);
},
),
);
This is the providerToStream class, which i copied from here Trouble rebuilding a StreamProvider to update its current data
class ProviderToStream<T> extends StatefulWidget {
const ProviderToStream({Key key, this.builder, this.child}) : super(key: key);
final ValueWidgetBuilder<Stream<T>> builder;
final Widget child;
@override
_ProviderToStreamState<T> createState() => _ProviderToStreamState<T>();
}
class _ProviderToStreamState<T> extends State<ProviderToStream> {
final StreamController<T> controller = StreamController<T>();
@override
void dispose() {
controller.close();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
controller.add(Provider.of<T>(context));
}
@override
Widget build(BuildContext context) {
return widget.builder(context, controller.stream, widget.child);
}
}
And this is the error i get when i try to use it
type '(BuildContext, Stream<SelectedDay>, Widget) => StreamProvider<DailyHomeData>' is not a subtype of type '(BuildContext, Stream<dynamic>, Widget) => Widget'
Note: The code doesnt even work when i place a dummy widget inside the ProviderToStream widget.
child: ProviderToStream<SelectedDay>(
builder: (_, ___, Widget child) {
return child;
},
),
I also tried to force somehow the type in the builder, so that it is not dynamic, with no luck
child: ProviderToStream<SelectedDay>(
builder: (_, Stream<SelectedDay> dayStream, Widget child) {
return child;
},
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68642086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Locate stack/heap variables in memory I am currently trying to hot patch programs (update code and data in the program memory, according to a released patch).
Assume that we can stop a running program, and do the patch. If the patch changes some data initialization or assignment values, how could we know where the variables are, like those in stack or heap?
Example:
Before patch:
void func() {
int a = 1;
}
After patch:
void func() {
int a = 2;
}
When patching, how could we know the location of a in the stack (or maybe not in the stack)?
A: Unless you have a lot of knowledge of how the compiler works, you cannot know a priori where these variables are stored, or even how they are represented. Each compiler designer makes his own rules for how/where variables are stored.
You might be able to figure out for a specific compiled program, by inspecting the generated code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35144001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert ndarray to string array Lets say there is array
values = [[ 116.17265886, 39.92265886, 116.1761427 , 39.92536232],
[ 116.20749721, 39.90373467, 116.21098105, 39.90643813],
[ 116.21794872, 39.90373467, 116.22143255, 39.90643813]]
now I want to convert this to
values = [[ '116.17265886', '39.92265886', '116.1761427' , '39.92536232'],
[ '116.20749721', '39.90373467', '116.21098105', '39.90643813'],
[ '116.21794872', '39.90373467', '116.22143255', '39.90643813']]
A: Assuming you really have a numpy array (not a list of list), you can use astype(str):
values = np.array([[ 116.17265886, 39.92265886, 116.1761427 , 39.92536232],
[ 116.20749721, 39.90373467, 116.21098105, 39.90643813],
[ 116.21794872, 39.90373467, 116.22143255, 39.90643813]])
out = values.astype(str)
output:
array([['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
['116.21794872', '39.90373467', '116.22143255', '39.90643813']],
dtype='<U32')
A: If it's not a numpy array and it is a list of a list of values the following code should work:
for index in range(len(values)):
values[index] = [str(num) for num in values[index]]
print(values)
For each list it returns a list of each of the values changed to a string, this returns the following.
[['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
['116.21794872', '39.90373467', '116.22143255', '39.90643813']]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72466665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails_Admin - how to export specific rows My Table contains rows, each row has an account field containing the email of the current_user so that users have access only to rows containing their own data. Rails_Admin exports successfully ALL rows. How could I export ONLY the rows that belongs to the user email account.
I am new in .haml
A: You can select which fields to export by defining the export block
RailsAdmin.config do |config|
config.model 'Highway' do
export do
field :number_of_lanes
end
end
end
Also you can configure the value of each field
RailsAdmin.config do |config|
config.model 'Lesson' do
export do
field :teacher, :string do
export_value do
value.name if value #value is an instance of Teacher
end
end
end
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47997157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: flutter post request with header and body anyone could help me to write flutter request post for the following header and body with the corresponding response below;
Example Post Request
Header Request:
Content-Type:application/x-www-form-urlencoded
Body Request:
grant_type: client_credentials
scope: accounts
client_assertion_type: code**
client_assertion: code**
A: Try the following,
String hostname = "myhostname";// example
String port = "1234"; //example
String url = "https://$hostname:$port/as/token.oauth2";
String body = "{'grant_type' : '$client_credentials' }" +
"'scope' : '$accounts'" +
//... etc etc
"'Corresponding Response': { 'access_token': 'JWt CODE', 'expires_in': '86400', 'token_type': 'bearer', 'scope': 'payments' }"+
"}";
var res = await http.post(Uri.encodeFull(url),
headers: {
"Accept": "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
},
body: body);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57448858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Get relative links from html page I want to extract only relative urls from html page; somebody has suggest this :
find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)
but it return :
1/all absolute and relative urls from the page.
2/the url may be quated by "" or '' randomly .
A: Use the tool for the job: an HTML parser, like BeautifulSoup.
You can pass a function as an attribute value to find_all() and check whether href starts with http:
from bs4 import BeautifulSoup
data = """
<div>
<a href="http://google.com">test1</a>
<a href="test2">test2</a>
<a href="http://amazon.com">test3</a>
<a href="here/we/go">test4</a>
</div>
"""
soup = BeautifulSoup(data)
print soup.find_all('a', href=lambda x: not x.startswith('http'))
Or, using urlparse and checking for network location part:
def is_relative(url):
return not bool(urlparse.urlparse(url).netloc)
print soup.find_all('a', href=is_relative)
Both solutions print:
[<a href="test2">test2</a>,
<a href="here/we/go">test4</a>]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24472957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to avoid content from overlapping div border Here I have this markup:
<div class="cabinet">
<ul>
<li>This is short</li>
<li>This one is longer</li>
<li>Yet this one is a lot more longer</li>
</ul>
</div>
And here's the CSS:
div.cabinet{
width:120px;
border-right:5px solid #e7e8e1;
white-space:nowrap;
}
I need the content not to overlap the right border of the div but instead be padded some 5px away. Here's the jsfiddle. I tried to play with z-index but it didn't help. What should I do?
A: Demo Fiddle
How about the following:
div.cabinet{
border-right:5px solid #e7e8e1;
white-space:nowrap;
display:inline-block;
padding-right:5px;
}
Use inline-block to make the div fit the content, then add padding. If you only wish the child ul to do this, simply apply those properties to div.cabinet ul instead (as well as the border).
A: Add a Padding to your UL or LI tag,
ul{padding:5px;} /** Will be applicable to all li's or you can also give it seperately **/
you can change that 5px value, but it will be enough !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25057701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Find column value Excel I have a data that looks like this in Excel:
A 17 8,5 5,666666667 4,25 3,4 2,833333333 2,428571429
B 5 2,5 1,666666667 1,25 1 0,833333333 0,714285714
C 5 2,5 1,666666667 1,25 1 0,833333333 0,714285714
G 4 2 1,333333333 1 0,8 0,666666667 0,571428571
I want to find a the letter representing a specific value. For instance, if I search for "17" I want to get the output "A" and if I am looking for 0,8 I want to get "G". Can anyone help me?
(In reality I want to find sort all the values in the data from the largest to the lowest and find the corresponding letter for the value)
A: =INDEX($A$1:$A$4,AGGREGATE(14,6,ROW($B$1:$H$4)/(L3=$B$1:$H$4),1))
assuming your example data is in the A1:H4 Range
When you have duplicate value that can be found this formula will return the one in the largest row number. If you want the value in the first row number you can change the 14 to 15.
EDIT
Option 1
=INDEX($A$1:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1))
Option 2
=INDEX($A$18:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)-ROW($A$18)+1)
The problem you had when you moved it was most likely because of your range reference changes. The row number that is returned from the aggregate check has to be a row within the index range. So option one keep the index range large but matches all possible rows from the aggregate results. Option two reduces the range to just your data and adjust the results to subtract the number of rows before your data so its really referring to which row within the index range you want to look at.
Option 3
Thanks to Scott Craner indicating the full column reference is perfectly acceptable outside the aggregate function, you could also use:
=INDEX($A:$A,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46019348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In OpenTest, how does one run tests across multiple actors using a single template that contains a dozen tests? As it stands currently, we have a single template with a dozen tests underneath it. We have two actors, but the second actor never picks up any tests under the session using the template that was launched.
How should I structure my distributed testing to allow for the tests to be executed in parallel against the two actors?
A: As of version 1.1.4, test sessions execute sequentially, within one test session. The reason for that is to be deterministic about what happens when, so testers can make reliable assumptions about the execution flow. This is important because tests can have dependencies between them and must execute in a specific order for them to succeed. To be sure, this is a bad practice, but it's sometimes necessary for practical reasons.
To execute tests in parallel, you must create two (or more) separate test sessions, so you must split your current session template in two. In the future, OpenTest will introduce an option that will allow one single test session to execute against multiple actors, but the default will still be executing the tests sequentially.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58756223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access in folder images in node.js? So in my project I have folder /Pictures and everything else is all over the project folder. My problem is that I can access all the CSS , JS, HTML, but it doesn't let me get this image folder as a source of the web app.
I tried this(doesn't work):
app.get('/water.jpeg', function (req, res) {
res.sendFile(__dirname + '/' + "Pictures" + '/' + "water.jpeg");
});
I want all my images from the /Pictures folder to be a source for my web app.
A: if image uploads to '/uploads' folder then try like
app.use('/uploads', express.static(process.cwd() + '/uploads'))
A: __dirname gives you the directory name of entry point file. I don't know where is your entry point file in your application, but that's where you have to start.
By the way, I advise you to use the "join" function of the "path" module to concatenate the path so as it works on linux or window filesystem.
A: I found a solution by Quora here, thanks to everyone who helped :) :
link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53936760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot infer type for `U` I am using Rust and Diesel:
fn create_asset_from_object(assets: &HashMap<String, Assets_Json>) {
let connection: PgConnection = establish_connection();
println!("==========================================================");
insert_Asset(&connection, &assets);
}
pub fn insert_Asset(conn: &PgConnection, assests: &HashMap<String, Assets_Json>){
use self::schema::assets;
for (currency, assetInfo) in assests {
let new_asset = self::models::NewAssets {
asset_name: ¤cy,
aclass: &assetInfo.aclass,
altname: &assetInfo.altname,
decimals: assetInfo.decimals,
display_decimals: assetInfo.display_decimals,
};
//let result = diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post");
println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
}
}
Compiler error:
error[E0282]: type annotations needed
--> src/persistence_service.rs:107:81
|
107 | println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
| ^^^^^^^^^^ cannot infer type for `U`
A: I strongly recommend that you go back and re-read The Rust Programming Language, specifically the chapter on generics.
LoadDsl::get_result is defined as:
fn get_result<U>(self, conn: &Conn) -> QueryResult<U>
where
Self: LoadQuery<Conn, U>,
In words, that means that the result of calling get_result will be a QueryResult parameterized by a type of the callers choice; the generic parameter U.
Your call of get_result in no way specifies the concrete type of U. In many cases, type inference is used to know what the type should be, but you are just printing the value. This means it could be any type that implements the trait and is printable, which isn't enough to conclusively decide.
You can use the turbofish operator:
foo.get_result::<SomeType>(conn)
// ^^^^^^^^^^^^
Or you can save the result to a variable with a specified type:
let bar: QueryResult<SomeType> = foo.get_result(conn);
If you review the Diesel tutorial, you will see a function like this (which I've edited to remove non-relevant detail):
pub fn create_post() -> Post {
diesel::insert(&new_post).into(posts::table)
.get_result(conn)
.expect("Error saving new post")
}
Here, type inference kicks in because expect removes the QueryResult wrapper and the return value of the function must be a Post. Working backwards, the compiler knows that U must equal Post.
If you check out the documentation for insert you can see that you can call execute if you don't care to get the inserted value back:
diesel::insert(&new_user)
.into(users)
.execute(&connection)
.unwrap();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46255634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Threejs: Disable frustum culling for some objects In order to solve the problem of z-fighting, I limited the near and far of camera to a small range.But when I want to add a larger object,it was culled by view frustum.
I tried object3d.frustumCulled property,not working as expected,the reason is as follows:
https://github.com/mrdoob/three.js/issues/12170
So,is there a way to ensure that some specific objects are not frustum culled without changing the camera near and far? THX.
A: Culling doesn't mean that an object is drawn or not. It can be either drawn or not drawn depending on where it is. It is an optimization that tries to say something like this:
Hey, i have a really cheap check (plane/sphere intersection) that i can do and tell you if you need to attempt to draw this at all.
So you do a cheap check, and if the object is guaranteed to be entirely out of the frustum, you never issue the draw call. If it intersects, you have to issue a draw call, but you may still see nothing if none of the triangles are actually in the frustum.
If you download something like specter.js and inspect your draw calls, you will infact see that with frustumCulled = false you get a draw call for every object in your scene. Your screen may be empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59727192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to detect the screen DPI using VB.NET? I need the screen DPI so i can adjust my program accordingly.
So my question is How to detect the screen DPI using VB.NET?
A: try this:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim g As Graphics = Me.CreateGraphics()
MessageBox.Show("ScreenWidth:" & Screen.PrimaryScreen.Bounds.Width & " ScreenHeight:" & Screen.PrimaryScreen.Bounds.Height & vbCrLf & " DpiX:" & g.DpiX & " DpiY:" & g.DpiY)
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50818466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to continue at particular step - spookyjs? I am using spookyjs to test my application.
Question
Is there anyway to enforce the spookyJs to start at particular step?
How to force start at particular step spookyJs?
Example
SpookyJs will run step by step, Suppose some connection error happened at particular step and server got stopped, Now how can I continue the test from particular step instead of running from beginning.
Any suggestion will be grateful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30974458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Helper not available in the view I am migrating from 1.3 to 2.0.6 and have the following problem:
Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp on line 2
Why is there a problem accessing the session helper?
A: That's not how to use helpers
Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp
Whilst it's not in the question your login.ctp template looks something like this:
<?php
echo $session>flash(); # line 2
That's not how helpers are expected to be used in CakePHP 2.x:
you can use [the helper] in your views by accessing an object named after the
helper:
<!-- make a link using the new helper -->
<?php echo $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5'); ?>
The code you're looking for is:
# echo $session->flash(); # wrong
echo $this->Session->flash(); # right
Note also that Session needs to be in the controller $helpers array.
In 1.2 and earlier versions of CakePHP helpers were expected to be variables, this changed but was still supported in 1.3. If your 1.3 CakePHP application has been using helpers in this way, it has been relying on backwards-compatibility with earlier versions. In 2.0 helpers are not variables, and only possible to access as a view class property. Be sure to read the migration guides - for more information on what has changed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32952043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show count for messages which are hidden below the scroll using jQuery? I need to show counter for loaded but scroll down messages in conversation screen. Suppose there are 15 messages in total but showing only 6 on browser right now. It means 9 messages are hidden in below so counter should display 9. But when I scroll up or down counter should change the value accordingly visible and hidden messages.
function isScrolledIntoView(elem) {
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
var message = $('#messages');
$(window).scroll(function() {
if (isScrolledIntoView('#hiddenElem')) {
message.text("Visible");
} else {
message.text("Invisible");
}
});
Check code in this JS Fiddle. Also JavaScript code written for show hidden or visible element.
A: You have to compare the position of each messages with the scrolled value.
So you need to loop throught them.
Here is something working:
var messages=$(".msg");
$(window).scroll(function(){
var counter=0;
for(i=0;i<messages.length;i++){
if( messages.eq(i).offset().top < $(window).scrollTop() ){
counter++;
}
}
// Display result.
$("#messages").html(counter);
});
Updated Fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44701595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: addTextChangedListener Null Pointer Exception Been looking at other questions but none of them solved my problem.
I have an editText and I need to implement an addTextChangedListener to this field so i can update values of other text views in real time.
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText billText = (EditText)findViewById(R.id.billValue);
billText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
Anything wrong in my code that I may be missing?
A: As far as I can guess, following line causing NullPointerException because your editText is null
billText.addTextChangedListener(new TextWatcher() {
May be the EditText you are trying to access here isn't in the activity_main.xml layout. So at first, make sure that the EditText with id billValue exists in the activity_main.xml.
A: You are creating a new instance of an interface not a class. Instead, you may write your activity class as
public class MainActivity extends ActionBarActivity implements TextWatcher
and add some methods to your class:
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
Try it, you will not have an exception I guess.
A: Do like the following -
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
billText.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
EditText billText = (EditText) view.findViewById(R.id.billText);
billText_val = billText.getText().toString().toLowerCase();
//do anything with this value
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void afterTextChanged(Editable s)
{
}
});
}
A: You are doing that fine There Might be an Issue with the Reference of your EditText
Anyhow here is my sample code attached for this purpose.
et_email = (EditText) findViewById(R.id.et_regstepone_email);
et_email.addTextChangedListener(this);
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if(count==0&&et_email.length()==0){
et_email.setCompoundDrawables(null, null, null, null);
}else if(count>0){
}
}
A: I had exactly the same problem.
Check the ID of your EditText in other layout xml files of the same activity. In my case it was the xml in layout-v21. I was overriding the ID of the EditText element in it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23083150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to compare two column values incrementally and copy entire row if the cells in those columns meet a condition I am trying to compare two columns in one workbook and based on a certain condition copy the row where that condition is met to another workbook.
This is for a "database" I am working on. I have a Master sheet and then several versions of sub-masters that are catered specifically to certain individuals.
I have tried to some success by creating two different With statements and using a delete function on the sub-sheet but it is clunky and I'm not a fan of it. Please see the example code below.
Public Sub Workbook_Open()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant
Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")
Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")
'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear
'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial
With ws1
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("L1:L" & lRow)
.AutoFilter Field:=1, Criteria1:=strSearch
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
.AutoFilterMode = False
End With
'~~> Destination File
With ws2
If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row + 1
Else
lRow = .Range("A" & Rows.Count).End(xlUp).Row
End If
copyFrom.Copy .Rows(lRow)
End With
With ws2
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("AD1:AD" & lRow)
.AutoFilter Field:=1, Criteria1:=strSearch
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
.AutoFilterMode = False
End With
With ws1
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("AD1:AD" & lRow)
.AutoFilter Field:=1, Criteria1:=strSearch
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
.AutoFilterMode = False
End With
'~~> Destination File
With ws2
If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row + 1
Else
lRow = .Range("A" & Rows.Count).End(xlUp).Row
End If
copyFrom.Copy .Rows(lRow)
End With
With ws2.Sort
.SetRange Range("A2:A12000")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
wb1.Save
wb1.Close
wb2.Save
End Sub
This is the code that I am trying to get work. I keep getting a Type Mismatch error on my cell comparison lines. '' If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then ''
Public Sub Workbook_Open()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant
Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")
Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")
'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear
'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial
With ws1
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then
With .Range("AD1:AD" & lRow)
.AutoFilter Field:=1, Criteria1:=strSearch
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
.AutoFilterMode = False
End If
End With
'~~> Destination File
With ws2
If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row + 1
Else
lRow = .Range("A" & Rows.Count).End(xlUp).Row
End If
copyFrom.Copy .Rows(lRow)
End With
With ws1
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
If ws1.Range("AD1:AD" & lRow) = ws1.Range("L1:L" & lRow) Then
With .Range("L1:L" & lRow)
.AutoFilter Field:=1, Criteria1:=strSearch
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
.AutoFilterMode = False
End If
End With
'~~> Destination File
With ws2
If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row + 1
Else
lRow = .Range("A" & Rows.Count).End(xlUp).Row
End If
copyFrom.Copy .Rows(lRow)
End With
With ws2.Sort
.SetRange Range("A2:A12000")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
wb1.Save
wb1.Close
' wb2.Save
End Sub
A: I just wanted to thank everyone who helped. I am going to just stick with my initial solution of filter, copy, paste, filter, delete, filter, copy, paste, sort.
See my first code block for what I am talking about. Cheers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54295269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: would a css grid framework be a good fit for creating application like layouts? I have a webapp that I am making and it has some particular layout needs that are closer to an application than a website.
The layout has:
*
*a left sidebar that is fixed to the left side of the browser window and has a static width until it stacks, this sidebar will have tabs in it
*a content area that will expand to a certain max-width and then stop
*a right side bar that is fixed the the right edge of the content
I've been struggling to really determine if using a grid system, like bootstrap, would be an appropriate fit for something like this. Having some rows/columns and a collapsible grid in the content area seems like it would make sense, but in the sidebars it seems like its best to not use a grid system at all. I don't particularly like the idea doing some layout in the html with bootstrap3 and some in css.
Basically my app has the same layout as http://qz.com/ and I want similar responsive design breaks, and with that I would like to know if there is one or more css frameworks that support that type of layout with little overriding.
A: if you have some experience with resposive design and media queries, i would code it myself to avoid the thousands of lines of unnecessary code that comes with frameworks/libraries. bootstrap is great, but it also requires a bit of effort to master, and it would be a bit overkill for this one layout (if i understand you correctly).
if you just need this one layout, i would really recommend you do code it from scratch (personally i'd use something like jQuery and LESS). i hope i understood your question correctly, and sorry if this was not very hands-on.
to sum it up: in my opinion you're probably better off coding it yourself, but bootstrap and other frameworks will provide valuable insight and inspiration for how to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18651474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Spring Transaction not working I'm having a problem with transactions, when execution reaches
taskExecutor.execute();
I get an Exception:
Caused by: org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
I know this error is self-explanatory, but I can't get it to work properly.
This is how I get the controller and make the call:
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml");
BeanFactory beanFactory = context;
FacadeControler f = beanFactory.getBean("facadeController");
f.method(reservation);
This is my FacadeController:
package xxx;
import ...
@Service
public class FacadeControllerImpl implements FacadeController {
static Logger logger = Logger.getLogger(FacadeControllerImpl.class);
@Qualifier("executor")
@Autowired
private TaskExecutor taskExecutor;
@Transactional(propagation=Propagation.REQUIRED)
public Reservation method(Reservation reservationFromEndpoint){
...
taskExecutor.execute();
...
}
Here is the Executor:
@Component("executor")
public class QueueTaskExecutor implements TaskExecutor {
final static Logger logger = LoggerFactory.getLogger(QueueTaskExecutor.class);
@Autowired
protected QueuedTaskHolderDao queuedTaskDao;
@Autowired
protected Serializer serializer;
@Override
@Transactional(propagation=Propagation.MANDATORY)
public void execute(Runnable task) {
logger.debug("Trying to enqueue: {}", task);
AbstractBaseTask abt;
try {
abt = AbstractBaseTask.class.cast(task);
} catch (ClassCastException e) {
logger.error("Only runnables that extends AbstractBaseTask are accepted.");
throw new IllegalArgumentException("Invalid task: " + task);
}
// Serialize the task
QueuedTaskHolder newTask = new QueuedTaskHolder();
byte[] serializedTask = this.serializer.serializeObject(abt);
newTask.setTriggerStamp(abt.getTriggerStamp());
logger.debug("New serialized task takes {} bytes", serializedTask.length);
newTask.setSerializedTask(serializedTask);
// Store it in the db
this.queuedTaskDao.persist(newTask);
// POST: Task has been enqueued
}
}
Here is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Where to look for Spring components -->
<context:annotation-config />
<context:component-scan base-package="com.xxx"/>
<!-- @Configurable with AspectJ -->
<context:spring-configured/>
<!-- A task scheduler that will call @Scheduled methods -->
<!-- <task:scheduler id="myScheduler" pool-size="10"/> -->
<!-- <task:annotation-driven scheduler="myScheduler"/> -->
<!-- DataSource -->
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/bbdd"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<!-- JPA Entity Manager -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="myEntityManagerFactory">
<property name="dataSource" ref="myDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"></bean>
</property>
<property name="persistenceUnitName" value="comm_layer" />
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false"/>
<entry key="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<entry key="eclipselink.logging.level" value="INFO"/>
</map>
</property>
</bean>
<!-- Transaction management -->
<tx:annotation-driven mode="aspectj" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
<property name="entityManagerFactory" ref="myEntityManagerFactory"/>
</bean>
<bean id="facadeController" class="xxx.FacadeControllerImpl">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17474257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to ask a context in EF how big its tracking set is? I'm running into what appears to be a fairly typical problem in EF. As I continue accessing my context, the number of items it tracks and enumerates over in detect changes increases. Eventually, everything slows to a crawl. Here's what I'm currently doing to address the problem:
public class ContextGenerator
{
private IContext _context;
private string _connString;
private int accessCount;
public ContextGenerator(string conn)
{
_connString = conn;
}
public IContext Instance
{
get
{
if (accessCount > 100)
{
Dispose();
}
if (_context == null)
{
var conn = EntityConfigurationContext.EntityConnection(_connString);
_context = new MyDbContext(conn);
accessCount = 0;
}
++accessCount;
return _context;
}
}
public void Dispose()
{
_context.Dispose();
_context = null;
}
}
This mostly works to prevent my context from getting too unwieldy, as it disposes and creates a new one every 100 accesses, but it seems very clunky and messy. Furthermore, 100 was chosen arbitrarily and there's no guarantee that somebody won't insert a million things with only one access. Is there a way to instead ask the context itself if it's gotten "too big"?
Or if anyone has a better idea for tackling this problem, I'm open to suggestions.
A: Each context should be a single Unit of Work, therefore I would highly recommend you have 1 context per operation (unless you relly have to).
For more info on what EF is currently tracking checkout Context.ChangeTracker
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38906108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XML xquery retrieve the descendent nodes value from a xml string I'm reading a XML document using XQuery in SQL Server. This is my XML:
declare @xml as xml='
<contactdata>
<contacts>
<groupkey>24</groupkey>
<groupname>Test Group One</groupname>
<contact>
<contactkey>100</contactkey>
<contactname>Test Contact One</contactname>
</contact>
<contact>
<contactkey>111</contactkey>
<contactname>Test Contact Two</contactname>
</contact>
</contacts>
<contacts>
<groupkey>26</groupkey>
<groupname>Test Group Two</groupname>
<contact>
<contactkey>101</contactkey>
<contactname>Test Contact Six</contactname>
</contact>
</contacts>
</contactdata>';
In order to retrieve the each contact details under every group, I'm using this XQuery syntax
select
c.value('(groupkey)[1]','int'),
c.value('(groupname)[1]','nvarchar(max)'),
c.value('(contact/contactkey)[1]','int'),
c.value('(contact/contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts') as Contacts(c)
But this will return only the first contact under each group.
But I need this output
Please help.
A: Just change your query to this:
select
c.value('(../groupkey)[1]','int'),
c.value('(../groupname)[1]','nvarchar(max)'),
c.value('(contactkey)[1]','int'),
c.value('(contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts/contact') as Contacts(c)
You need to get a list of all <contact> elements - and then extract that necessary data from those XML fragments. To get the groupkey and groupname, you can use the ../ to navigate "up the tree" one level to the parent node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20881146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GCM Notification not register for token and not receiving notifications This is my appdelegate where is my notification implementations goes on. Sometimes I register with token and token is received. But not receiving notifications. But some time there is no registration with token at all. This is my code below.
import UIKit
import UserNotifications
import RxSwift
//import Firebase
//import Messages
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let gcmMessageIDKey = "gcm.message.shopflow.key"
var window: UIWindow?
let userdefaults = Foundation.UserDefaults.standard
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// FirebaseApp.configure()
// [START set_messaging_delegate]
// Messaging.messaging().delegate = self
// [END set_messaging_delegate]
UNUserNotificationCenter.current().delegate = self
registerForPushNotifications()
checkReachability()
checkRegisterdUser()
// Check whether the app has opened from a notification or a normal launch
//crashing code
// let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
// if remoteNotif != nil {
// let notifName = remoteNotif?["aps"] as! String
// print("Notification: \(notifName )")
// }else{
// print("Not remote")
// }
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
checkReachability()
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
checkReachability()
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
checkReachability()
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// check connectivity
func checkReachability(){
if ReachabilityHelper.shared.checkNetworkReachability(){
}else{
showNetworkAlert()
}
}
// show network alert
func showNetworkAlert(){
let alertController = UIAlertController(title: "Connection Error", message:"An active internet connection is needed to use this app.Please make sure you are connected and try again.", preferredStyle: .alert)
let okAction = UIAlertAction(title: NSLocalizedString("Retry", comment: ""), style: UIAlertActionStyle.default) {
UIAlertAction in
if ReachabilityHelper.shared.checkNetworkReachability(){
//print("Connected")
}else{
// print("Not connected")
self.showNetworkAlert()
}
}
alertController.addAction(okAction)
window!.rootViewController?.present(alertController, animated: true, completion: nil)
}
func checkRegisterdUser(){
// let storyBoard = UIStoryboard(name: storyboardIdentifier., bundle: <#T##Bundle?#>)
if UserDefaults.standard.bool(forKey: Key.loginStatus){
let vc = UIStoryboard(name: storyboardIdentifier.home.rawValue, bundle: nil).instantiateViewController(withIdentifier: viewControllerIdentifiers.tabBar.rawValue) as! UITabBarController
Constants.AppObjects.appDelegate.window?.rootViewController = vc
// self.present(vc, animated: true, completion: nil)
}
}
func registerForPushNotifications() {
// if #available(iOS 10.0, *) {
// // For iOS 10 display notification (sent via APNS)
// UNUserNotificationCenter.current().delegate = self
//
// let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
// UNUserNotificationCenter.current().requestAuthorization(
// options: authOptions,
// completionHandler: {_, _ in })
// } else {
// let settings: UIUserNotificationSettings =
// UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
// UIApplication.shared.registerUserNotificationSettings(settings)
// }
//
// UIApplication.shared.registerForRemoteNotifications()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
// private func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
//// if notificationSettings. != UIUserNotificationType() {
// application.registerForRemoteNotifications()
//// }
// }
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
userdefaults.set("NA", forKey: "DEVICE_TOKEN")
userdefaults.synchronize()
print("Registration failed!")
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
userdefaults.set(token, forKey:"DEVICE_TOKEN")
userdefaults.synchronize()
_ = HomeViewModel().deviceToken().subscribe(onNext:{ message in
if message == response.success.rawValue{
//print("Signup done")
print("new Device Token device registation")
}else if message != ""{
print("shopErrors:fail Device Token device registation")
//print(alertMessage)
}
}).disposed(by: DisposeBag())
}
// func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
// if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as! [NSObject : AnyObject]? {
//
// }
// }
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Let FCM know about the message for analytics etc.
// Messaging.messaging().appDidReceiveMessage(userInfo)
// handle your message
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
func registerForPushNitfication(){
registerForPushNotifications()
}
}
//extension AppDelegate: MessagingDelegate{
// func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
// let dataDic: [String: String] = ["token": fcmToken]
// NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDic)
//
// userdefaults.set(dataDic["token"], forKey:"DEVICE_TOKEN")
// userdefaults.synchronize()
//
// _ = HomeViewModel().deviceToken().subscribe(onNext:{ message in
//
// if message == response.success.rawValue{
// //print("Signup done")
// print("shopErrors:new Device Token device registation")
// }else if message != ""{
// print("shopErrors:fail Device Token device registation")
// //print(alertMessage)
// }
//
// }).disposed(by: DisposeBag())
// }
//
//}
I register for APNs and enable push notifications and also background notification fetch capability. But I couldn't resolve this. Anyone can find an answer?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60629328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to configure Swagger in Spring project, getting File not found exception I am trying to configure swagger for my spring application. Below is the configuration. However, getting an error
[springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
Spring version - 4.0.4
Springfox version - 2.9.2
It's NOT a maven project, I have all the required jar files added to the classpath.
Spring-context.xml
<bean id="Swagger" class="skt.test.SwaggerConfig" />
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
Swagger config class
package skt.test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Jar files included
https://i.imgur.com/sYaYnrY.png
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: skt.test.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:160)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:299)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4682)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5143)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:82)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:77)
at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:551)
at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getRelated(ConfigurationClassParser.java:760)
at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getAnnotationAttributes(ConfigurationClassParser.java:741)
at org.springframework.context.annotation.ConfigurationClassParser.collectImports(ConfigurationClassParser.java:366)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:340)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:426)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:174)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:156)
... 39 more
A: You need below library ,
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
If you are not using pom just download it from
https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui/2.5.0
https://mvnrepository.com/artifact/io.springfox/springfox-swagger2/2.5.0
To get more insight you can follow here
https://github.com/mayurbavisiya/Spring4Swagger
In your spring file you need to write
<mvc:resources mapping="/swagger-ui.html" location="classpath:/META-INF/resources/swagger-ui.html"/>
Hope this will help you out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56929655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: ResourceReferenceKeyNotFoundException on NotifyIcon I'm using WPF NotifyIcon, and actually I'm trying to learn how to display a simple NotifyIcon in the system tray. Actually In the MainWindow I put this code:
private TaskbarIcon tb;
public MainWindow()
{
InitializeComponent();
}
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)FindResource("TestNotifyIcon");
}
}
essentially when the main window is minimized the tb should show the Icon declared in a Dictionary like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PrimoCalendarExport.Utils.Resources.UIDictionary"
xmlns:tb="http://www.hardcodet.net/taskbar">
<tb:TaskbarIcon x:Key="TestNotifyIcon"
IconSource="/Utils/Images/Test.ico"
ToolTipText="hello world" />
</ResourceDictionary>
this dictionary of resource is located inside a folder, in particular:
Project name
\Utils
\Resources
\Dictionary
\InlineToolTip.xaml
Now the problem's that when I minimize the main window I get this error:
ResourceReferenceKeyNotFoundException
so seems that the TestNotifyIcon can't be located in the project. I don't know what am I doing wrong, I followed all the steps of the tutorial, someone maybe know my mistake? Thanks.
A: It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
}
}
or
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37160474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to post values of each item in model from view to controller as a List or Array? example of view priority list of orders
i have a orders model, i need the user to arrange orders in order of priority by numbers.
for each order a different number of priority and post to the controller the id of the order and the priority number that he selected for the order.
post it to the controller as a list/array of pairs (id, position).
and also how to receive in the actionResult a list/array of value pairs.
this is my PackerController:
public ActionResult SetByCity(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var supplier = db.Suppliers.Where(s => s.Id == id).FirstOrDefault();
var mySupplierOrders = db.Orders.Where(o => o.SupplierId == supplier.Id && o.SupplierApproval == 1).Include(o => o.Clients).Include(o => o.Suppliers);
return View(mySupplierOrders.OrderBy(o => o.Clients.BusinessAddress).ToList());
}
and this is the view for "SetByCity":
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Clients.BusinessName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Clients.BusinessAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.PayDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
@Html.DisplayFor(modelItem => item.TotalPrice)
</td>
<td>
<form method="post" action="@Url.Action("SetOrdersPosition", "Packer")" id="editform">
<input type="hidden" name="Id" value="@item.Id">
<input type="number" name="Position" min="1" max="@Model.Count()">@*i need to put all the positions and id's of all the items in a pairs list and send it to the controller*@
</form>
</td>
</tr>
}
</table>
<input type="submit" value="send" form="editform" />
and this is the receiving actionResult "SetOrdersPosition" in the PackerController:
[HttpPost]
public ActionResult SetOrdersPosition(List<id,position>)
{
//does something...
}
i don't know what to put in the parameters that the SetOrdersPosition gets...
A: Hope you are using the Model name called "Suppliers".
So in get method pass that into view.
You needs to do come little changes accordingly to use Begin Form in your view, so that you can directly post your model data to controller.
Use this item inside body.
Don't forget to declare the model which you are using in the view page like below.
@model MVC.Models.Suppliers
@using (Html.BeginForm("SetOrdersPosition", "Packer", FormMethod.Post))
{
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Clients.BusinessName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Clients.BusinessAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.PayDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
@Html.DisplayFor(modelItem => item.TotalPrice)
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
}
</table>
}
Controller Code [HttpPost]
public ActionResult SetOrdersPosition(Suppliers _suppliers)
{
//does something...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50451972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expanding to consumer to cater for each producer? I have the following socket connection codes. Where for every connection is one new thread. After receiving the data which is done via the producer then I put into a queue for next database processor which is the consumer. This works fine but the moment the queue gets build up it can hang or even take even hours to clear cause is like so many producers and just one single consumer. I am thinking is it possible for me to have one consumer handles one producer meaning each message goes into its own queue gets process and that it. What changes can I do to handle it or must I build a thread pooling ?
public class cServer {
private LinkedBlockingQueue<String> databaseQueue = new LinkedBlockingQueue<String>();
class ConnectionHandler implements Runnable {
private Socket receivedSocketConn1;
ConnectionHandler(Socket receivedSocketConn1) {
this.receivedSocketConn1=receivedSocketConn1;
}
// gets data from an inbound connection and queues it for databse update
public void run() { // etc
// you already have most of this in your existing code.
// it uses the shared databaseQueue variable to queue message Strings
BufferedWriter w = null;
BufferedReader r = null;
String message="";
try {
PrintStream out = System.out;
BufferedWriter fout = null;
w = new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
int m = 0, count=0;
int nextChar=0;
while ((nextChar=r.read()) != -1)
{
message += (char) nextChar;
if (nextChar == '*')
{
databaseQueue.add(message);
message="";
}
}
}
catch (IOException ex)
{
System.out.println("MyError:IOException has been caught in in the main first try");
ex.printStackTrace(System.out);
}
finally
{
try
{
if ( w != null )
{
w.close();
}
else
{
System.out.println("MyError:w is null in finally close");
}
}
catch(IOException ex){
System.out.println("MyError:IOException has been caught in w in finally close");
ex.printStackTrace(System.out);
}
}
}
}
class DatabaseProcessor implements Runnable {
// updates databaase with data queued by ConnectionHandler
Connection dbconn = null;
Statement stmt = null;
Statement stmt1 = null;
Statement stmt2 = null;
Date connCreated = null;
public void run()
{ // this is just like the QueueProcessor example I gave you
// open database connection
//createConnection();
while (true)
{
try
{
int count=0;
String message = "";
message = databaseQueue.take();
if (message.equals(null)) {
System.out.println("QueueProcessor is shutting down");
break; // exit while loop, ends run() method
}
System.out.println("Message taken from queue is :"+message);
}
catch (Exception e)
{
e.printStackTrace();
}
}//while true
//closeConnection();
}//run
}
public static void main(String[] args) {
new cServer();
}
cServer() { // default constructor
new Thread(new DatabaseProcessor()).start();
try
{
final ServerSocket serverSocketConn = new ServerSocket(5000);
while (true)
{
try
{
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
}
catch(Exception e)
{
System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
}
}
}
catch (Exception e)
{
System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
//System.exit(0);
}
databaseQueue.add(null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40311266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In DynamoDb, is there a way to atomically check a secondary index for an item before writing it? I've got an object like this:
{
"id": (UUID generated at call time)
"referenceId": (Foreign key for another system)
"referenceType": (enum)
}
The primary index is just
*
*Primary key: id
And I've got a secondary index like
*
*Primary key: referenceId
*Secondary key: referenceType
So what I want to do, is query the secondary index with the referenceId and referenceType, and then if that's empty, write the record to the table.
The problem is, Conditional Expressions can only check same index you're querying. And I've looked into DynamoDb Transactions, but they say you can't have two transactions target the same item.
Is there a way to make this work?
A: If I understand your question correctly, your item has three attributes: id,
referenceId and referenceType. You've also defined a global secondary index with a composite primary key of referenceId and referenceType.
Assuming all these attributes are part of the same item, you shouldn't need to read the secondary index before deciding to write to the table. Rather, you could perform a PUT operation on the condition that referenceId and reference type don't yet exist on that item.
ddbClient.putItem({
"TableName": "YOUR TABLE NAME",
"Item": { "PK": "id" },
"ConditionExpression": "attribute_exists(referenceId) AND attribute_exists(referenceType)"
})
You may also want to check out this fantastic article on DynamoDB condition expressions.
A: As I understand the question, your table PK is generated "at call time" so it would be different for two different requests with the same reference ID and reference type.
That being the case, your answer is no.
If you've got a requirement for uniqueness of a key set by a foreign system, you should consider using the same key or some mashup of it for your DDB table.
Alternately, modify the foreign system to set the UUID for a given reference ID & type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66002469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does mapping over a DataFrame using a case class fail with "Unable to find encoder for type stored in a Dataset"? I have already imported spark.implicits._ But still I get error
Error:(27, 33) Unable to find encoder for type stored in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._ Support for serializing other types will be added in future releases.
I have a case class like:
case class User(name: String, dept: String)
and I am converting Dataframe to dataset using:
val ds = df.map { row=> User(row.getString(0), row.getString(1) }
or
val ds = df.as[User]
Also, when I am trying the same code in Spark-shell I get no error, only when I run it through IntelliJ or submit the job I get this error.
Any reasons why?
A: Moving declaration of case class out of scope did the trick!
Code structure will then be like:
package main.scala.UserAnalytics
// case class *outside* the main object
case class User(name: string, dept: String)
object UserAnalytics extends App {
...
ds = df.map { row => User(row.getString(0), row.getString(1)) }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47971162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make first post bigger in wordpress This is probably very easy to do, but unfortunately I'm not too good with coding. I am honestly trying to learn though.
I have a theme in wordpress that makes posts tagged with "spotlight" twice the size of the rest. I would like to change this so that it's automatically the first post that is this size. I hope that makes sense.
A snippet of the code I have:
// Get blog layout setting
$blog_layout = get_theme_mod( 'blog_layout_setting', 'three-columns' );
$portfolio_layout = get_theme_mod( 'portfolio_layout_setting', 'four-columns' );
if ( is_tax( 'ct_portfolio' ) || is_page_template( 'templates/template-portfolio.php' ) ) :
if ( 'four-columns' == $portfolio_layout ) {
if ( has_tag( 'spotlight' ) ) {
$classes[] = 'col-lg-6 col-md-8 col-sm-12';
} else {
$classes[] = 'col-lg-3 col-md-4 col-sm-6';
}
} else {
if ( has_tag( 'spotlight' ) ) {
$classes[] = 'col-md-8 col-sm-12';
} else {
$classes[] = 'col-md-4 col-sm-6';
}
}
I'm pretty sure it's just to change the "if ( has_tag( 'spotlight' )" to something i++ or i=1, or something like that. I might also be completely wrong. I feel like the answer is staring me in the face, but I just can't grasp it. I've tried searching around, but haven't found a good answer.
I would be really happy for any help, and I really do learn from this.
Thanks in advance.
A: Please refer this jsFiddle code. I hope this solves your problem.
You just needed to add the CSS to your style.css
.myspotlight{
background-color:red;
}
and
the javascript to the particular php file which runs the loop of all your articles and creates the list of articles.
$( "article" ).first().addClass("myspotlight");
The jquery code basically appends the necessary class to the first tag that it finds
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40627899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter: why can't I create a DateTime object with all 0 values? So I want to make a Stopwatch in Flutter.
static void startTrip() {
SharedPrefsHelper().setIsCurrentlyOnTrip(true);
_elapsedTime = DateTime(
0, //year
0, //month
0, //day
0, //hour
0, //minute
0, //second
0, //millisecond
0, //microsecond
);
_timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
_elapsedTime.add(Duration(seconds: 1));
print('new time: $_elapsedTime');
_controller.sink.add(_elapsedTime); //same object/reference, but this is for the StreamBuilder to update
});
//TODO
}
As you can see I first attempted to use a DateTime object to keep track of the time.
But DateTime(0, 0, 0, 0, 0, 0, 0, 0) initializes to -0001-11-30 00:00:00.000. And the value doesn't update after I try to add 1 second, it always prints out the same.
Go and try it out your self on dartpad by running this code:
DateTime elapsedTime = DateTime(0, 0, 0, 0, 0, 0, 0, 0);
print(elapsedTime);
elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
Does anyone know why this happens?
For now I will just use an int to keep track of the time instead and do the formatting myself.
P.S so this is how I did it, if anyone wants the code:
int hours = elapsedTime ~/ 3600;
int minutes = (elapsedTime % 3600) ~/ 60; //get rid of all additional hours, then divide by 60
int seconds = elapsedTime % 60; //get rid of all additional minutes
String h = hours > 9 ? hours.toString() : '0$hours';
String m = minutes > 9 ? minutes.toString() : '0$minutes';
String s = seconds > 9 ? seconds.toString() : '0$seconds';
A: You can try this:
DateTime elapsedTime = DateTime.utc(0);
print(elapsedTime);
elapsedTime = elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
Note: The lowest value for day and month is 1 and not 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71259139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading Clojure code in Eclipse plug-in I have this kind of problem. I have Clojure code contained in Eclipse plug-in (denoted A) in *.clj files. I don't want AOT compilation. However, I need to load the clojure code from another Clojure plug-in B. This is possible when B depends on A. Clojure can easily access the classpath and everything works. But I want the plug-in A to be plugged as extension to B. But there is a problem because I could not find a way how to load a Clojure file contained in A from *.clj file contained in B. I would like to use the Clojure 'load' function which can load *.clj files from classpath but this function just cannot see contents of plug-in A event when I explicitely start the plug-in like this
(org.eclipse.core.runtime.Platform/getBundle "A")
Reaction to Laurent's answer
Laurent, thank you very much! This is very interesting. However, I think this mayby solves a harder problem then my original one. You discribed how to call clojure code from java plug-in which is totaly awesome. I need to call clojure code from clojure plug-in which I think may be easier. I imagine that I would create extension point and provide clojure functions like this
<extension point="transforms">
<function namespace="my.nemaspace" fn="my-transform"/>
</extension>
So I do not need any magic with IExecutableExtensionFactory. I can read the extension registry from clojure code. What I cannot do is load the function specified in the extension. Is this doable or did I just misunderstood something? I noticed that you are using clojure.osgi. This looks cool, is there any documentation for that project?
A: The problem you're having with regards to classloaders is to be expected : if the dependencies of your Eclipse plugins/OSGi bundles are A -> B, with the Clojure jar bootstraped from B, then not being able to see resources of A from B is normal.
There can be no cycles among dependencies of Eclipse plugins, so there can be no cycles among classloader hierarchies.
This is the same problem that you would face if you were to write extensions to B from A with regular Eclipse machinery : plugin B would declare an interface, and an extension point. Then plugin A could implement the interface, and declare an extension to the extension point. This last part allows the Eclipse framework to do some tricks with the bundles: it sees that A declares an extension to B, thus instanciates a class from A implementing the interface declared in B (this works since A depends on B), and gives B the implementation instance from A which is also OK since it implements the interface in B !
(Not sure this is clear).
Anyway, back to plugins written in Clojure.
With Clojure, you don't have, out of the box, such separate environments provided by classloaders, because everything gets aggregated in one "Clojure environment" living in the classloader realm of the plugin embedding the clojure jar.
So one possibility would just be, when plugin A starts, to load the relevant namespaces from A. Then they would be loaded at the right time, and available to any other Clojure code.
Another possibility would be to use the Extension Point/Extension machinery. Eclipse provides a way to use "factories" to create instances of extension points. In Counterclockwise, we leverage this feature, and have a generic factory class (written in java, so no AOT) which takes care of loading the right namespace from the right bundle.
Here are more detail concerning how to extend extension points.
An example from Counterclockwise:
There is an existing Extension Point in the Eclipse framework for contributing hyperlink detectors for the Console contents. Counterclockwise extends this extension point to add nrepl hyperlinks.
In the java world, you would have to directly declare, in your extension, some class of yours which implements interface IPatternMatchListenerDelegate.
But with CCW, for probably the same reasons as you, I try to avoid AOT at all costs, so I can't give a java class name in the extension, or I would have either had to write it in java and compile it, or write a gen-class in Clojure and AOT-compile it.
Instead, CCW leverages a hidden gem of plugin.xml's possibilities: in almost every place, when you have to provide a class name, you can instead provide an instance of IExecutableExtensionFactory whose create() method will be called by the Eclipse framework to create an instance of the desired class.
This allowed me to write a generic class for calling into the Clojure world: I just use, in place of the class name I should have written, the class name ccw.util.GenericExecutableExtension
Extract from plugin.xml :
<extension point="org.eclipse.ui.console.consolePatternMatchListeners">
<consolePatternMatchListener
id="ccw.editors.clojure.nREPLHyperlink"
regex="nrepl://[^':',' ']+:\d+">
<class class="ccw.util.GenericExecutableExtension">
<parameter
name="factory"
value="ccw.editors.clojure.nrepl-hyperlink/factory">
</parameter>
</class>
</consolePatternMatchListener>
Note the class attribute, and how I can give parameters to the factory via the parameter element (the factory has to implement interface IExecutableExtension for being able to be initialized with the parameters).
Finally, you can see that in namespace ccw.editors.clojure.nrepl-hyperlink, the function factory is rather simple and just calls the make function:
(defn make []
(let [state (atom nil)]
(reify org.eclipse.ui.console.IPatternMatchListenerDelegate
(connect [this console] (dosync (reset! state console)))
(disconnect [this] (reset! state nil))
(matchFound [this event] (match-found event @state)))))
(defn factory "plugin.xml hook" [ _ ] (make))
Please note that I'm showing this as an example, and the relevant code in Counterclockwise is not ready to be released as an independant library "ready for consumption".
But you should nonetheless be able to roll your own solution (it's quite easy once you get all the pieces in place in your head).
Hope that helps,
--
Laurent
A: Another solution occured to me: it is possible, in Eclipse, despite what I said in my previous answer, to create cyclic dependencies between the classloaders!
Eclipse guys needed to introduce this so that certain types of libraries (log4j, etc.) could work in an OSGi environment (which is what Eclipse is based upon).
This requires to leverage the Eclipse-BuddyPolicy mechanism (Third Party libraries and classloading).
It's quite easy: if you want plugin B to see all classes and resources of plugin A, just add this to plugin B's META-INF/MANIFEST.MF file:
Eclipse-BuddyPolicy: dependent
The line above indicates that plugin B's classloader will be able to access what its dependents classloaders have access to.
I created a sample set of plugins named A and B where B has 2 commands (visible in the top menu) : the first applies a text transformation on the "hello" hard coded string by calling clojure code in B. The second dynamically loads an new text transformation from plugin A, so that when you invoke the first command again, you see the result of applying transformations from B and transformations from A.
In your case, it may not even be required to use Eclipse Extension Point / Extension mechanism at all, after all. It will all depend on how you intent plugin B to "discover" plugin A relevant information.
The github repository showing this in action: https://github.com/laurentpetit/stackoverflow-12689605
HTH,
--
Laurent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12689605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Implement fold with for-comprehension How can a fold be implemented as a for-comprehension in Scala? I see the only way is to use some recursive call? This is a try that is failing, not sure how to do this? What is the best way to implement fold as a for-comprehension
val nums = List(1,2,3)
nums.fold(0)(_+_)
def recFold(acc: Int = 0): Int = {
(for {
a <- nums
b = recFold(a + acc)
} yield b).head
}
recFold(0) //Stack overflow
A: If you really want to use for, you don't need recursion, but you would need a mutable variable:
val nums = List(1,2,3)
def recFold(zero: Int)(op: (Int, Int) => Int): Int = {
var result: Int = zero
for { a <- nums } result = op(result, a)
result
}
recFold(0)(_ + _) // 6
Which is pretty similar to how foldLeft is actually implemented in TraversableOnce:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this foreach (x => result = op(result, x))
result
}
A: Fold can be implemented both ways right to left or left to right. No need to use for plus recursion. Recursion is enough.
def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
as match {
case Nil => z
case x :: xs => f(x, foldRight(xs, z)(f))
}
}
@annotation.tailrec
def foldLeft[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
as match {
case Nil => z
case x :: xs => foldLeft(xs, f(x, z))(f)
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39618657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scala/Spark Apriori implementation extremely slow We are trying to implement the Apriori algorithm in Scala using Spark (you don't need to know the algorithm to answer this question).
The function computing the itemsets of the Apriori algorithm is freq(). The code is correct but it gets slower after each iteration in the while in the freq() function, up to the point of taking several seconds to perform a cross join on a table with 1 row with itself.
import System.{exit, nanoTime}
import scala.collection.mutable.WrappedArray
import org.apache.spark.sql.{Column, SparkSession, DataFrame}
import org.apache.spark.sql.functions._
import spark.implicits._
object Main extends Serializable {
val s = 0.03
def loadFakeData() : DataFrame = {
var data = Seq("1 ",
"1 2 ",
"1 2",
"3",
"1 2 3 ",
"1 2 ")
.toDF("baskets_str")
.withColumn("baskets", split('baskets_str, " ").cast("array<int>"))
data
}
def combo(a1: WrappedArray[Int], a2: WrappedArray[Int]): Array[Array[Int]] = {
var a = a1.toSet
var b = a2.toSet
var res = a.diff(b).map(b+_) ++ b.diff(a).map(a+_)
return res.map(_.toArray.sortWith(_ < _)).toArray
}
val comboUDF = udf[Array[Array[Int]], WrappedArray[Int], WrappedArray[Int]](combo)
def getCombinations(df: DataFrame): DataFrame = {
df.crossJoin(df.withColumnRenamed("itemsets", "itemsets_2"))
.withColumn("combinations", comboUDF(col("itemsets"), col("itemsets_2")))
.select("combinations")
.withColumnRenamed("combinations", "itemsets")
.withColumn("itemsets", explode(col("itemsets")))
.dropDuplicates()
}
def countCombinations(data : DataFrame, combinations: DataFrame) : DataFrame = {
data.crossJoin(combinations)
.where(size(array_intersect('baskets, 'itemsets)) === size('itemsets))
.groupBy("itemsets")
.count
}
def freq() {
val spark = SparkSession.builder.appName("FreqItemsets")
.master("local[*]")
.getOrCreate()
// data is a dataframe where each row contains an array of integer values
var data = loadFakeData()
val basket_count = data.count
// Itemset is a dataframe containing all possible sets of 1 element
var itemset : DataFrame = data
.select(explode('baskets))
.na.drop
.dropDuplicates()
.withColumnRenamed("col", "itemsets")
.withColumn("itemsets", array('itemsets))
var itemset_count : DataFrame = countCombinations(data, itemset).filter('count > s*basket_count)
var itemset_counts = List(itemset_count)
// We iterate creating each time itemsets of length k+1 from itemsets of length k
// pruning those that do not have enough support
var stop = (itemset_count.count == 0)
while(!stop) {
itemset = getCombinations(itemset_count.select("itemsets"))
itemset_count = countCombinations(data, itemset).filter('count > s*basket_count)
stop = (itemset_count.count == 0)
if (!stop) {
itemset_counts = itemset_counts :+ itemset_count
}
}
spark.stop()
}
}
A: Since Spark retains the right to regenerate datasets, at any time, that may be what's happening, in which case caching the results of expensive transformations can lead to dramatic improvements in performance.
In this case, it looks at first glance like itemset is the heavy hitter, so
itemset = getCombinations(itemset_count.select("itemsets")).cache
May pay dividends.
It should also be noted that building up a list by appending in a loop is generally a lot slower (O(n^2)) than building it by prepending. If correctness isn't affected by the order of itemset_counts, then:
itemset_counts = itemset_count :: itemset_counts
will produce at least a marginal speed-up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64835206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Enable :active state in IE7 with jQuery? I've searched for a simple jQuery plugin to enable the active state in IE7, but I've only been able to find IE7-js, which doesn't play well with my current javascript.
I think I could build this myself, but I figure someone else has already done a better job of it than I would. Is there a solid jQuery plugin that does this already?
Thanks in advance!
A: IE7 should work just fine with :active on anchors (<a>), as long as the anchor has the href attribute (source).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5794057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android launchin thridparty intent not working I 'm trying to launch the camera app on button click but I don't want to hav the fot
I want it to behave like it is launched by the lauc´ncher but when I call my code the application simply closes and the camera isn't starting.There isn't even an error code.
Code :
if(v == camera)
{
//Intent in=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// this.startActivity(in);
Intent startupIntent = new Intent();
ComponentName distantActivity = new ComponentName("com.android.camera","com.android.camera/.Camera");
startupIntent.setComponent(distantActivity);
startupIntent.setAction(Intent.ACTION_MAIN);
startActivity(startupIntent);
finish();
}
A: use android.intent.action.VIEW instead of Intent.ACTION_MAIN as:
Intent startupIntent = new Intent();
ComponentName distantActivity= new ComponentName("YOUR_CAMRA_APP_PACKAGE","YOUR_CAMRA_APP_PACKAGE.ACTIVTY_NAME");
// LIKE IN LG DEVICE WE HAVE AS
//ComponentName distantActivity= new //ComponentName("com.lge.camera","com.lge.camera.CameraApp");
startupIntent .setComponent(distantActivity);
startupIntent .setAction("android.intent.action.VIEW");
startActivity(startupIntent);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10837353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does Terminals.tokenizer() tokenize unregistered operators/keywords? I've just discovered the root cause of some very confusing behavior I was observing. Here is a test:
@Test
public void test2() {
Terminals terminals = Terminals.caseInsensitive(new String[] {}, new String[] { "true", "false" });
Object result = terminals.tokenizer().parse("d");
System.out.println("Result: " + result);
}
This outputs:
Result: d
I was expecting the parser returned by terminals.tokenizer() not to return anything because "d" is not a valid keyword or operator.
The reason I care is because I wanted my own parser at a lower priority than that returned by terminals.tokenizer():
public static final Parser<?> INSTANCE =
Parsers.or(
STRING_TOKENIZER,
NUMBER_TOKENIZER,
WHITESPACE_TOKENIZER,
(Parser<Token>)TERMINALS.tokenizer(),
IDENTIFIER_TOKENIZER);
The IDENTIFIER_TOKENIZER above is never used because TERMINALS.tokenizer() always matches.
Why does Terminals.tokenizer() tokenize unregistered operators/keywords? And how might I get around this?
A: In the upcoming jParsec 2.2 release, the API makes it more clear what Terminals does:
http://jparsec.github.io/jparsec/apidocs/org/codehaus/jparsec/Terminals.Builder.html
You cannot even define your keywords without first providing a scanner that defines "words".
The implementation first uses the provided word scanner to find all words, and then identifies the special keywords on the scanned words.
So, why does it do it this way?
*
*If you didn't need case insensitivity, you could have passed the keywords as "operators". Yes, you read it right. One can equally use Terminals.token(op) or Terminals.token(keyword) to get the token level parser of them. What distinguishes operators from keywords is just that keywords are "special" words. Whether they happen to be alphabet characters or other printable characters is just by convention.
*Another way to do it, is to define your word scanner precisely as Parsers.or(Scanners.string("keyword1"), Scanners.string("keyword2"), ...). Then Terminals won't try to tokenize anything else.
*The above assumes that you want to do the 2-phase parsing. But that's optional. Your test shows that you weren't feeding the tokenizer to a token-level parser using Parser.from(tokenizer, delim). If two-phase parsing isn't needed, it can be as simple as: or(stringCaseInsensitive("true"), stringCaseInsensitive("false"))
More on point 3. The 2-phase parsing creates a few extra caveats in jParsec that you don't find in other parser combinators like Haskell's Parsec. In Haskell, a string is no different from a list of character. So there really isn't anything to gain by special casing them. many(char 'x') parses a string just fine.
In Java, String isn't a List or array of char. It would be very inefficient if we take the same approach and box each character into a Character object so that the character level and token level parsers can be unified seamlessly.
Now that explains why we have character level parsers at all. But it's completely optional to use the token level parsers (By that, I mean Terminals, Parser.from(), Parser.lexer() etc).
You could create a fully functional parser with only character-level parsers, a.k.a scanners.
For example: Scanners.string("true").or(Scanners.string("false")).sepEndBy1(delim)
A: From the documentation of Tokenizer#caseInsensitive:
org.codehaus.jparsec.Terminals
public static Terminals caseInsensitive(String[] ops,
String[] keywords)
Returns a Terminals object for lexing and parsing the operators with names specified in
ops, and for lexing and parsing the keywords case insensitively. Keywords and operators
are lexed as Tokens.Fragment with Tokens.Tag.RESERVED tag. Words that are not among
keywords are lexed as Fragment with Tokens.Tag.IDENTIFIER tag. A word is defined as an
alphanumeric string that starts with [_a - zA - Z], with 0 or more [0 - 9_a - zA - Z]
following.
Actually, the result returned by your parser is a Fragment object which is tagged according to its type. In your case, d is tagged as IDENTIFIER which is expected.
It is not clear to me what you want to achieve though. Could you please provide a test case ?
A: http://blog.csdn.net/efijki/article/details/46975979
The above blog post explains how to define your own tag. I know it's in Chinese. You just need to see the code. Especially the withTag() and patchTag() part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24384203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Screenshot comes out black on Wayland I found this code to take a screenshot on Ted Mielczarek's website.
/*
* gdk-screenshot.cpp: Save a screenshot of the root window in .png format.
* If a filename is specified as the first argument on the commandline,
* then the image will be saved to that filename. Otherwise, the image will
* be saved as "screenshot.png" in the current working directory.
*
* Compile with:
* g++ -o gdk-screenshot gdk-screenshot.cpp `pkg-config --cflags --libs gdk-x11-2.0`
*/
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
int main(int argc, char** argv)
{
gdk_init(&argc, &argv);
GdkWindow* window = window = gdk_get_default_root_window ();
GdkPixbuf* screenshot = gdk_pixbuf_get_from_drawable (NULL, window, NULL,
0, 0, 0, 0,
gdk_screen_width(),
gdk_screen_height());
GError* error = NULL;
const char* filename = (argc > 1) ? argv[1] : "screenshot.png";
return TRUE == gdk_pixbuf_save (screenshot, filename, "png",
&error, NULL);
}
I compiled it as described and it appears to work, in that it produces an image with the correct dimensions, but the screenshot is entirely black.
This appears to be a common issue on systems running Wayland (I'm running Archlinux with Wayland), so my question is:
What modifications need to be made to this code to get it to produce a proper screenshot on Wayland (and X)?
A: I had a similar problem.
I use Xlib to take screenshots, but this method can't work on Wayland. Every time I run to xgetimage, I report an error. After looking up the data, I find Wayland doesn't allow such screenshots. However, in this way, I can still get the correct screen size.
Now I use DBUS to call the session bus of the system to take a screenshot, which I learned from reading the source code of Gnome screenshot.
This is a simple summary code:
method_name = "Screenshot";
method_params = g_variant_new ("(bbs)",
TRUE,
FALSE, /* flash */
filename);
connection = g_application_get_dbus_connection (g_application_get_default ());
g_dbus_connection_call_sync (connection,
"org.gnome.Shell.Screenshot",
"/org/gnome/Shell/Screenshot",
"org.gnome.Shell.Screenshot",
method_name,
method_params,
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
The document link is here:
https://developer.gnome.org/references
The GitHub of Gnome screenshot is here:
https://github.com/GNOME/gnome-screenshot
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41560368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to query a document with the highest value of a field Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below.
I want to get the document with the greatest value of "id". Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find me the max value of a certain field.
[
{
name: "name1",
id: 1
}
{
name: "name2",
id: 2
}
{
name: "name1",
id: 3
}
{
name: "name1",
id: 0
}
]
A:
let documents = [
{
name: "name1",
id: 1
},
{
name: "name2",
id: 2
},
{
name: "name1",
id: 3
},
{
name: "name1",
id: 0
}
];
let max = documents.sort( (a, b) => a.id > b.id ? -1 : 1)[0]
console.log( max );
How about
let maxIdDocument = documents.sort( (a, b) => a.id > b.id ? 1 : -1)[0]
A: First, sort in descending order, then get the first one:
const arr = [{
name: "name1",
id: 1
},
{
name: "name2",
id: 2
},
{
name: "name1",
id: 3
},
{
name: "name1",
id: 0
}
];
const [greatest] = arr.sort(({ id: a }, { id: b }) => b - a);
console.log(greatest);
A: You can sort that array and with the function pop get the object with the greatest id.
arr.slice() // This is to avoid a mutation on the original array.
let arr = [ { name: "name1", id: 1 }, { name: "name2", id: 2 }, { name: "name1", id: 3 } , { name: "name1", id: 0 } ],
greatest = arr.slice().sort(({id: a}, {id: b}) => a - b).pop();
console.log(greatest);
.as-console-wrapper { min-height: 100%; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55737093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ADB2C - How to change UI for password confirmation screen(In reset password flow) I have created sign-in user flow with reset password user flow.
I have updated UI with custom UI in both the flows. When user click on 'Forgot password' link then user is seeing new UI for 'Reset password' user flow, but after email verification when user click on continue then user is seeing default UI as below.
Any one know how can I change this UI as well with custom UI.
A: You have to add Custom page for Change password page also. I thin you have added Custom Page only for Forgot password page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71605173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Resolve @RegisteredOAuth2AuthorizedClient with the token obtained outside of spring server of Spring Security 5.2.x I have a controller method that has an argument OAuth2AuthorizedClient with annotation @RegisteredOAuth2AuthorizedClient.
ResponseEntity<String> getFoo(
@RegisteredOAuth2AuthorizedClient("custom") OAuth2AuthorizedClient client) {
OAuth2AccessToken token = client.getAccessToken();
....
}
In order to resolve this, spring look for OAuth token on OAuth2AuthorizedClientService which actually stores the previously authenticated tokens in memory.
Now, I have a scenario where I obtain JWT token from OAuth server outside of this spring resource server, and trying to authenticate this server by passing token using Authorization header.
But when spring trying to resolve OAuth2AuthorizedClient it is looking for token in-memory with the principle of JWT (which will obviously not found since token is not obtained on this server). Hence send new login redirection for new token.
Overall question would be, is it possible to resolve OAuth2AuthorizedClient with the JWT token (obtained ourside of the server) passed in Authorization header?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66623303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Importing python packages, nested packages... going up, traversing, etc... doesn't appear to work - what am I doing wrong? I'm having an issue. I'm porting a lot of code to Python from various other languages of things I've coded over the years and turning it into a large package.
Because not everything fits under a single package - I am nesting packages within. The main package is AcecoolLib, which has init, all of the nested packages have it too.
Because I want to be able to import AcecoolLib - and have everything imported beneath it, all of my init files import everything within their respective folder, and any packages beneath. I only nest 1 deep at the moment - I am not sure whether or not this will change. Probably not.
I have tried absolute imports, and I have tried relative. I have tried modifying sys.modules, and sys.path. I have tried adding paths and I don't know where I can map a name to the path. I end up with a lot of the package loading properly, and some areas I end up with errors where Acecool.X doesn't exist. I fix one, and another one pops up.
One I fixed was - I thought, because I had a few packages named list / tuple / dict that since these are referenced to data-types, that changing them may be beneficial. so I put them into a nested package called array and renamed all of them to include an s on the end. lists, tuples, dicts. not a fan of this - but the error went away.
I'm getting an error in my steam directory now but I don't know of steam being a protected name.
I am using the package, right now, in Sublime Text. I will be using it there for plugins I'm writing - to replace the current system I use which is a single file Acecool.py imported as AcecoolLib in another plugin... It's ugly, hard to maintain, etc.. so I moved some of the code into packages.
In short - I am running into a lot of issues.
This is the first main attempt: https://bitbucket.org/Acecool/acecoollib/src/master/
And this is where I'm at currently: https://www.dropbox.com/s/xvaubq78hlhym9o/AcecoolLib.7z?dl=0
I have tried a lot of variation....
I have looked over other packages which import through nested packages and I haven't found anything which shows me doing anything different ( before I started adding a bunch of crap to the start to find a solution )...
There must be something which lets me set up the paths for each package, and then define they all get added to the AcecoolLib namespace, with nested namespaces within...
I want to be able to go into AcecoolLib/tests/ dir and run tests throughout by running the scripts directly from tests. I also want to be able to import from external / internal sources to have access to everything if I need it.
I also want to be able to import just nested packages or the entire. ie: import AcecoolLib means I should be able to get to Acecool.util.accessors - and so on... or if I import Acecool.util then I don't see AcecoolLib.math - but I could import it.
Right now I'm testing importing everything as my current project uses almost every single function, etc... I added a few as tests..
I have read quite a lot on the subject of importing and I have come across countless 'this is the right way' 'no this' 'nope, this', and so on... none of which work. I have come across articles which say never use this type of import, or this... etc.. most of the articles aren't very useful and are plagued with personal opinions instead of covering the material of the title. Or they cover the basic 101 level variants, or show the directory tree ( which looks identical to mine ) and say that it just works as is...
Maybe that's right - maybe Sublime Text does something differently - ie: I do know that the package is being added to sys.modules, and All of the nested ones are too - so I'm just lost....
Any help is appreciated. Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59971816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "__NSAutoreleaseFreedObject(): release of previously deallocated object" out of the blue I'm not sure if this is an error or not. The code compiles fine (no warnings), but when I enter a method, a local's value (an NSMutableString) displays this content in the debugger:
__NSAutoreleaseFreedObject(): release of previously deallocated object
I'm not getting an exception, it looks like the contents of the string (which is not even allocated at that time) is that NSAutoReleaseFreedObject warning.
What's going on?
A: it (likely) means that your app has executed different from usual, and exposed a bug in your ref counting of the object. this type of issue can also be related to improper multithreading.
executing your app to trigger the problem with zombies enabled should help you locate it.
A: If you don't initialize a normal local variable to anything, its value is undefined — it could be anything. In practice, it will interpret the bit pattern that happens to lie on the stack where the variable is allocated as a value of the variable's type. In this case, the "anything" that the variable contains happens to be the address of that string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5344645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSV -> JSON -> PostgreSQL "Token invalid" I have a CSV file containing 1 column ("json_doc") with many rows of JSON data. I want to collect this json data and upload it to a Postgres database. The rows are in the format:
{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "description": "Agenti e rappresentanti di animali vivi"}], "founded": "1972-07-10", "legalName": "COBEM - S.R.L.", "legalForms": [{"name": "Società Di Capitale", "level": 1}, {"name": "Società A Responsabilità Limitata", "level": 2}]}, "name": "COBEM - S.R.L.", "people": {"items": [{"name": "45808b0b5b5affa871c8e91169bb10c6930fac56", "givenName": "64e4393f477394f11f6477ca76395ed469548865", "familyName": "68ee44f14dc54d664dffe63195d42a14988b69bb"}]}, "country": "it", "locations": {}}
There are millions of rows, and not all of the formatting is consistent i.e. some nested dictionaries are structurally different to others.
I've taken 5 of these rows, and applied the following Python:
import pandas as pd
df = pd.read_csv('samplecol.csv')
df = df.to_json('data.json')
I then use https://jsonlint.com to check the JSON and all is good.
I have a JSON file, data.json, and a PostgreSQL database, and want to get data.json into Postgres.
I run the following to create a table :
SN_ITA_test=# CREATE TABLE jsons(ID serial NOT NULL PRIMARY KEY, info jsonb NOT NULL);
When I try to upload the file to Postgres using :
SN_ITA_test=# \copy jsons (info) FROM 'data.json';
I get the error:
ERROR: invalid input syntax for type json
DETAIL: Token "id" is invalid.
CONTEXT: JSON data, line 1: {"json_doc":{"0":"{"id...
COPY jsons, line 1, column info: "{"json_doc":{"0":"{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "d..."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53648602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting Pending Request on HTTP Client Response while ataching multiple files I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
$response = Http::withHeaders([
'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
]);
foreach($files as $k => $file)
{
$response = $response->attach('images['.$k.']', $file);
}
$response->post($this->base_url.$url, $params);
return response()->json($response->collect());
}
The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70688117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Security: Sending email address in a url parameter Is it considered bad security practice to include somebody's email address in a url as a parameter over http? The email address belongs to a client, and they may not want anybody to see it. The url points to my own domain, I'm just creating unique urls with email addresses as a parameter so I can detect who visited the url. Can anybody sniff http traffic to extract that info?
A: Yes, it's bad practice to put any personal information in the URL. A URL can be cached and viewed in so many ways. Even if you use SSL, URLs are still saved in your browser's history, so it just makes me cringe to pass non-public data in the URL. Usually it's not any more work to pass information in the body of a POST request, so that's what I would do.
A: Not if you do it over https, as the URL path and querystring will be encrypted along with the body.
It's not a problem for the URL to be stored in the browser history, as that is private to the user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17303940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Code not working. Dropdown menu in Android This is the java file of the code followed by xml file.
The programs shows an error "Unexpectedly stopped working"
I cannot find the error through logCat also. Can someone suggest something ?
Java file:
package com.example.ui;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Tp extends ListActivity implements OnItemSelectedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tp);
String[] technology = {"PHP", "Ruby", "Java", "SQL"};
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
spinnertech.setAdapter(adp);
spinnertech.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = arg0.getSelectedItemPosition();
if(position == 0) {
Toast.makeText(getApplicationContext(), " 0 selected",
Toast.LENGTH_LONG).show();
} else if(position == 1) {
Toast.makeText(getApplicationContext(), " 1 selected",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), " extra selected",
Toast.LENGTH_LONG).show();}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView100"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="248dp"
android:layout_height="36dp"
android:prompt="@string/title" />
</LinearLayout>
Here's the LogCat
05-25 16:33:31.270: D/AndroidRuntime(566): Shutting down VM
05-25 16:33:31.270: W/dalvikvm(566): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-25 16:33:31.289: E/AndroidRuntime(566): FATAL EXCEPTION: main
05-25 16:33:31.289: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ui/com.example.ui.Tp}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.os.Looper.loop(Looper.java:123)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-25 16:33:31.289: E/AndroidRuntime(566): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 16:33:31.289: E/AndroidRuntime(566): at java.lang.reflect.Method.invoke(Method.java:521)
05-25 16:33:31.289: E/AndroidRuntime(566): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-25 16:33:31.289: E/AndroidRuntime(566): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-25 16:33:31.289: E/AndroidRuntime(566): at dalvik.system.NativeStart.main(Native Method)
05-25 16:33:31.289: E/AndroidRuntime(566): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ListActivity.onContentChanged(ListActivity.java:245)
05-25 16:33:31.289: E/AndroidRuntime(566): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.Activity.setContentView(Activity.java:1647)
05-25 16:33:31.289: E/AndroidRuntime(566): at com.example.ui.Tp.onCreate(Tp.java:18)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-25 16:33:31.289: E/AndroidRuntime(566): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-25 16:33:31.289: E/AndroidRuntime(566): ... 11 more
05-25 16:33:33.089: I/Process(566): Sending signal. PID: 566 SIG: 9
A: I guess problem in below statement
Toast.makeText(getApplicationContext(), " 0 selected",
Toast.LENGTH_LONG).show();
change to
Toast.makeText(this, " 0 selected",
Toast.LENGTH_LONG).show();
or
Toast.makeText(tp.this, " 0 selected",
Toast.LENGTH_LONG).show();
Edit:--------------------------------------------------------------------------
public class Tp extends Activity implements OnItemSelectedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tp);
String[] technology = {"PHP", "Ruby", "Java", "SQL"};
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
spinnertech.setAdapter(adp);
spinnertech.setOnItemSelectedListener(this);
}
if this is not working then include listview in xml file.
A: This is your problem
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
If you are using ListActivity, your layout file R.layout.activity_tp must have a ListView with android:id="@android:id/list" attribute. Look here: http://developer.android.com/reference/android/app/ListActivity.html for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23854538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse LDT doesn't run local Lua interpreter I have problem with Eclipse LDT. When I run my test Lua app, it executes just fine using JNLua inside JavaVM environment. But according to this tutorial, when I reference native lua.exe interpreter and set it in Run Configuration as Runtime Interpreter, Run Configuration disables Launch script: and nothing is executed. When I run a same script with a same native local Lua interpreter 5.1, everything works just fine.
So, what is the problem with LDT? Has anyone had the same experience?
EDIT
I've managed to run local lua.exe from Lua Development Tools stand-alone product, but still it doesn't work as Eclipse plug-in.
A: I'm not sure it's a bug.
I guess when you register your interpreter, you uncheck the checkbox : "Accept file as argument"
This mean LDT will not manage the file to launch (that's why the Launch script is disabled)
The standard lua interpreter support file as argument and -e option, so the two check box should be checked. (It's the default value)
A: It looks like a bug ... Would you mind filing it in the Koneki bug tracker?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18716699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I calculate subtotals using onblur and javascript? How do I calculate subtotals for each row of a product listing by using an input text field to enter one of the numbers?
example:
colA colB colC
100 - [text input] = [calculated result]
880 - [text input] = [calculated result]
720 - [text input] = [calculated result]
130 - [text input] = [calculated result]
...
I'm sure this is fairly easy to do with Javascript, but I've looked and can't find a simple answer. I'm not very familiar with Javascript so I need a simple solution. Thanks in advance for all the help! :)
A: Welcome to StackOverflow! In the future, you can probably get a good answer faster if you write your question more clearly.
You can use document.getElementById('id_of_text_input').value to get or set the value of any text input. Note that you are using id, not name.
You can use parseFloat to get a read a string as a floating number value.
In order to attach a function to the onblur event, you can use the setAttribute function.
So, for example, if you have a text input with id colA and you want to subtract 100 from the value the user enters and save the result in a text input with id colB.
You could write code like this:
<html>
<head runat="server">
<title></title>
</head>
<body>
<input type='text' id='colA' />
<input type="text" id='colB' />
</body>
<script type="text/javascript">
var colA = document.getElementById('colA');
var colB = document.getElementById('colB');
colA.setAttribute('onblur',
function () {
var value = colA.value;
var number = parseFloat(value)-100;
colB.value = number;
});
</script>
</html>
A: Very useful for me. Thanks, Daniel
If you want to calculate a percentage (5% for example) and use Jquery, you have to
$(function(){
$(".input-valorinicial").blur(function(){
var valorinicial = document.getElementById('valorinicial');
var fee = document.getElementById('fee');
var value = valorinicial.value;
var number = parseFloat(value)*5/100;
fee.value = number;
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8718114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Manually sanitize SQL parameters I would like to run a script like:
CREATE LOGIN [me] WITH PASSWORD = @0
and run it like:
var createUserCommand = conn.CreateCommand();
createUserCommand.CommandText = script;
createUserCommand.Parameters.AddWithValue("@0", passwordDecrypted);
However, this throws:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near '@0'.
From what I read online (nowhere official, just from SO answers/comments) it is not possible to use SQL parameters with DDL statements. Link to official docs for this are welcome!
OK. I do need this parametrized. As I see it, there are 2 options:
*
*I manually sanitize (.Replace("'", "''") => how can I do this best?
*I call into .NET to sanitize for me. However I assume this is not sanitized within ADO.NET, but just past to SQL Server, and sanitized there...
What would be the best approach?
A: All you need to escape is the single ' to 2 x '
commandText = string.Format("CREATE LOGIN [me] WITH PASSWORD = '{0}'", pass.Replace("'", "''"));
An alternative would be to create a stored procedure with a password parameter and use it to build a CREATE LOGIN string which you then sp_executeSQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26489820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenCV. detectMultiScale() function return error I'm new to OpenCV. Took an example from official documentation. When I try to run the code, an error pops up. When you try to run the code, an error pops up when you call the function detectMultiScale ()
Mat image;
image = imread("1.jpg", CV_LOAD_IMAGE_COLOR);
imshow("cam", image);
// Load Face cascade (.xml file)
CascadeClassifier face_cascade;
face_cascade.load("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml");
// Detect faces
std::vector<Rect> faces;
Mat frame_gray;
cvtColor(image, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));
Tell me how to solve this problem?
enter image description here
A: It is because of your xml file path, be sure about that your path directory is true. I checked your code in my pc and worked well. Search your "haarcascade_frontalface_alt2.xml" file in your pc and copy it to your code.
The same problem was also mentioned here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57108437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java. HSSF. Apache-poi. How to modificate code
My data is stored in a format(look down): [-] means a blank cell, on the right may
be only 10 columns, after the space. Something like this:
[string0] [-] [string1] [string2] [string3] .. [string10] [-]
How to change this code for:
1) obtain only [string0]
2) obtain only [string1] [string2] [string3] .. [string10] [-]
try {
FileInputStream file = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xls");
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
list1.add(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream("C:\\Users\\student3\\"+sfilename+".xls");
workbook.write(out);
out.close();
I don't know how to stop Iterator. He absorbs all..
A: If I am clear you just want to filter your first column string and rest seperately.
Why not you just use a simple counter for this:
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
String RowContent = null;
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
RowContent=RowContent+cell.toString();
}
//Code for saving RowContent or printing or whatever you want for text in complete row
}
RowContent will give concatenation of each cells of a single row in each iteration.
A: Like you did in the switch block with "break".
But what i think you want is this:
Iterator<Cell> cellIterator = row.cellIterator();
boolean stop = false;
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
list1.add(cell.getStringCellValue());
stop = true;
break;
}
if (stop) {
break;
}
}
This would stop the while loop when you found a string cell and will then operate on the next row.
Make any possible condition you need to break the while loop. For example collect string columns and when you found the desired set stop to true, to get to the next row.
A: External Link: Busy Developers' Guide to HSSF and XSSF Features
Here is an example that should work.
Maven Dependencies:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
Code:
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
public class StackOverflowQuestion18095443 {
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Please specify the file name as a parameter");
System.exit(-1);
}
String sfilename = args[0];
File file = new File("C:\\Users\\student3\\" + sfilename + ".xls");
read(file);
}
public static void read(File file) {
try (InputStream in = new FileInputStream(file)) {
HSSFDataFormatter formatter = new HSSFDataFormatter();
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
StringBuilder rowText = new StringBuilder();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellAsStringValue = formatter.formatCellValue(cell);
rowText.append(cellAsStringValue).append(" ");
}
System.out.println(rowText.toString().trim());
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
}
}
As for terminating the iteration you can conditionally break from the loop. Or, you could also just not use an iterator. Notice that you can obtain a Cell from a Row using a named reference (this allows you to refer to a cell by name, such as "A2", just like you would in Excel) or simply by the column index within the row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18082358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to populate additive field via JOIN with Doctrine Suppose i have an entity with a ManyToOne relation (with EXTRA_LAZY) and obviously a join column.
eg. Article (main entity) -> Author (external entity)
suppose i add a field author_name to the Article that NOT mapped to the ORM and that in certain contexts this field should contain the article->author->name value (usually it can stay null).
When i query a list of articles, i would like to populate automatically that article-author_name without implementing a getter that perform a select on each element of the query result. I would like Doctrine to fetch and hydrate that value in with a simple JOIN in the original query...
I don't want to set fetch mode to EAGER for performance as in my project Author is a really complex entity.
Is this possible?
Thanks
A: Probably i've found a solution. Don't know if it is the best way to do it but it works.
I've added to the main class a field getter
public getAuthorName() {
return $this->author->name
}
in my context this getter will only be called by a serializer in certain conditions.
In my repository code i have a special method (that i refactored so that any method could implicitly call it) to impose the population of the Article->author field when queried. The method simply use the querybuilder to add LEFT JOIN to the Author class and temporarily set FetchMode to EAGER on Article->author.
At the end a simple repository method could be this
public findAllWithCustomHydration() {
$qb = $this->createQueryBuilder('obj');
$qb->leftJoin("obj.author", "a")
-> addSelect("a"); //add a left join and a select so the query automatically retrive all needed values to populate Article and Author entities
//you can chain left join for nested entities like the following
//->leftJoin("a.address", "a_address")
//-> addSelect("a_address");
$q = $qb->getQuery()
->setFetchMode(Article::class, "author", ClassMetadata::FETCH_EAGER);
//setFetchMode + EAGER tells Doctrine to prepopulate the entites NOW and not when the getter of $article->author is called.
//I don't think that line is strictly required because Doctrine could populate it at later time from the same query result or maybe doctrine automatically set the field as EAGER fetch when a LEFT JOIN is included in the query, but i've not yet tested my code without this line.
return $q->getResult();
}
The con is that you have to customize each query or better use a DQL / SQL / QueryBuilder for each method of the repo but with a good refactoring, for simple inclusion cases, you can write a generic method that inject that join on a field_name array basis.
Hope this help and add your answer if you find a better way.
PS. i've wrote the above code on the fly because now i'm not on my notebook, hope it works at first execution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42551664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: class that extends AbstractGoogleJsonClient constructor expecting Builder, rather than 5 params from Android Developers Tic Tac Toe client (Android), https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-android
there is....
public class Tictactoe extends AbstractGoogleJsonClient { etc}
with the constructor:
public Tictactoe(HttpTransport transport, JsonFactory jsonFactory,
HttpRequestInitializer httpRequestInitializer) {
super(transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer
, false);
}
I get compile errors on the super(), and I'm told that super expects Builder, not the 6 params,
BUT the class Tictactoe extends has a constructor that takes the 6 arguments.
(see
https://code.google.com/p/google-api-java-client/source/browse/google-api-client/src/main/java/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java?r=32555da5a2e95a90154f278184f3be9e230486b3 )
for
protected AbstractGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory,
String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer,
boolean legacyDataWrapper) {
super(transport, httpRequestInitializer, rootUrl, servicePath, newObjectParser(
jsonFactory, legacyDataWrapper));
}
So...
What's happening here? Why does 'super' expect Builder rather than the 6 args?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21007597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android get unique firebase token and authenticate with cloud functions I'm building a multi-player Android game, and it uses Firebase Cloud Functions.
There are some tutorials that explains how to allow only users of my application to use my cloud function (link below), but I don't want to allow all the users to use all my functions, I want to give access based on Id. How to generate unique tokens for every user, from Android (Using Java not Kotlin) and how to get the Id from that token in node.js (Javascript not TypeScript)?
The tutorial link: https://firebase.google.com/docs/cloud-messaging/auth-server
A: Starting Firebase Functions 1.0+, there are 2 kinds of HTTP functions that you can use for your Android app.
*
*Call Functions directly. Via functions.https.onCall
*Call Functions through HTTP Request. Via functions.https.onRequest
I recommend you to use onCall as your functions endpoint, and call directly by using FirebaseFunctions. This way, you don't need to get FirebaseUser token, as it will be automatically included when you call using FirebaseFunctions.
And remember, TypeScript is just superset of Javascript. I will still give examples in Node.js, but it is recommended to type your Javascript code in TypeScript.
Example
index.js (CloudFunctions endpoint)
exports.importantfunc = functions.https.onCall((data, context) => {
// Authentication / user information is automatically added to the request.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('not-authorised',
'The function must be called while authenticated.');
}
const uid = context.auth.uid;
const email = context.auth.token.email;
//Do whatever you want
});
MyFragment.java
//Just some snippets of code examples
private void callFunction() {
FirebaseFunctions func = FirebaseFunctions.getInstance();
func.getHttpsCallable("importantfunc")
.call()
.addOnCompleteListener(new OnCompleteListener<HttpsCallableResult>() {
@Override
public void onComplete(@NonNull Task<HttpsCallableResult > task) {
if (task.isSuccessful()) {
//Success
} else {
//Failed
}
}
});
}
More information about callable function, read here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50924981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting smallest value from column that holds numbers as strings I'm saving numbers as strings because they are generally larger than the maximum limits MySQL allows for integers.
What I'm trying to get is the smallest and largest values from this column, but just comparing as strings returns very different results.
I've tried to add a CONVERT clause to my query like so:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CONVERT('end_timestamp', SIGNED INTEGER) DESC LIMIT 1"
But the result coming through is not correct. I think the CONVERT clause is not converting to integers in the way I was expecting it to.
So what is the best way to convert strings to integers and get the smallest value?
A: If you have a number as a string and it is an integer with no leading 0s, you can compare it by comparing the length first and then the value. For instance, the following will order by col1 correctly (assuming the above):
select t.*
from t
order by char_length(col1), col1;
So, one way to get the minimum is:
select col1
from t
order by char_length(col1), col1
limit 1;
You can also get both in a group by by doing:
select substring_index(group_concat(col1 order by char_length(col1), col1), ',', 1
) as mincol1,
substring_index(group_concat(col1 order by char_length(col1) desc, col1 desc), ',', 1
) as maxcol1
from t;
If you have zeros in front of the numbers and or decimal places, the ideas are the same, but the coding is a bit more complicated.
A: I don't have a MySQL instance to test on, but it looks like a workaround may solve your problem. I don't know that the issue here is the numbers are too large for conversion, but if they can't be integers in the database, why should it be possible to convert them to integers outside the database?
Try something like this:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CHAR_LENGTH(end_timestamp) DESC, end_timestamp DESC LIMIT 1"
That will sort by the number of characters first, which is where string sorts on numbers fall apart (as long as you don't have any leading zeros), followed by a numerical sort on numbers which are the same length. If that still doesn't work you may need to `SELECT CHAR_LENGTH(end_timestamp) AS ts_len' to calculate the value outside of the sort command. That is where I really don't know which will work because I don't have a MySQL instance available to test on.
You also may want to consider a data type more suited to timestamps, like TIMESTAMP or DATETIME, which could likely be converted to the format you need once they're outside the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18548306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Debugger Visualizer and "Type is not marked as serializable" I am trying to create a debugger visualizer that would show control hierarchy for any Control. It's done but I'm getting the exception "Type is not marked as serializable".
How do I overcome that? Control is a .NET Windows Forms framework type, I can't mark it as serializable.
A: You'll need to also implement a VisualizerObjectSource to perform custom serialization.
Example:
public class ControlVisualizerObjectSource : VisualizerObjectSource
{
public override void GetData(object target, Stream outgoingData)
{
var writer = new StreamWriter(outgoingData);
writer.WriteLine(((Control)target).Text);
writer.Flush();
}
}
public class ControlVisualizer : DialogDebuggerVisualizer
{
protected override void Show(
IDialogVisualizerService windowService,
IVisualizerObjectProvider objectProvider)
{
string text = new StreamReader(objectProvider.GetData()).ReadLine();
}
public static void TestShowVisualizer(object objectToVisualize)
{
var visualizerHost = new VisualizerDevelopmentHost(
objectToVisualize,
typeof(ControlVisualizer),
typeof(ControlVisualizerObjectSource));
visualizerHost.ShowVisualizer();
}
}
class Program
{
static void Main(string[] args)
{
ControlVisualizer.TestShowVisualizer(new Control("Hello World!"));
}
}
You'll also need to register the visualizer with the appropriated VisualizarObjectSource, which for this example could be something like this:
[assembly: DebuggerVisualizer(
typeof(ControlVisualizer),
typeof(ControlVisualizerObjectSource),
Target = typeof(System.Windows.Forms.Control),
Description = "Control Visualizer")]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2959048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Continue on exception I get a few exceptions when I run my code.
What I want to do is, I want to continue on FileNotFoundException and NullPointerException and break on any other exception.
How can I go about it?
Thanks
A: try {
stuff()
} catch( NullPointerException e ) {
// Do nothing... go on
} catch( FileNotFoundException e ) {
// Do nothing... go on
} catch( Exception e ) {
// Now.. handle it!
}
A: You can do this as @daniel suggested, but I have some additional thoughts.
*
*You never want to 'do nothing'. At least log the fact that there was an exception.
*catching NullPointerExceptions can be dangerous. They can come from anywhere, not just the code where you expect the exception from. If you catch and proceed, you might get unintended results if you don't tightly control the code between the try/catch block.
A: multiple catch block to caught exception arised in try block
<code>
try{<br/>
// Code that may exception arise.<br/>
}catch(<exception-class1> <parameter1>){<br/>
//User code<br/>
}catch(<exception-class2> <parameter2>){<br/>
//User code<br/>
}catch(<exception-class3> <parameter3>){<br/>
//User code<br/>
}
</code>
Source : Tutorial Data - Exception handling
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4752361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: import file into skype for business calender I created a patient schedule file outside of Skype for business. I want to associate a patient with a selected physician. How can I import the file to the Skype for business calendar? What format should the imported file be?
A: Skype for Business does not support its own calendar. Instead, it gets calendar data from the Exchange account of the signed in user. You can easily add a new event to the user's calendar by using the Microsoft Graph RESTful API: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_post_events
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36252048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replace a word in a sentence using preg_replace How can I replace a string like
style="color:red;width:90%;" class="textbox"
to
style="color:red;width:65%;" class="textbox"
using preg_replace?
I just want to replace "width:90%" with "width:65%" and the rest of the string should stay as it is. What regular expression should I use to accomplish this?
A: str_replace("width:90%", "width:65%", $string)
A: $string = preg_replace("/width:90%/", "width:65%", $string);
if you want to make sure only elements with the class="textbox" are affected:
$string = preg_replace("/(style=\".+)(width:90%)(.+class=\"textbox\")/", "$1width:65%$3", $string);
having it work with any value and unit:
$string = preg_replace("/width:(\d+)(%|px)/", "width:65($2)", $string);
A: Thanks a lot jairajs
this worked for me
preg_replace("/width:\d+(%|px)/", "width:65%", $string)
and thanks to Gerald Schneider for helping me out
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4284635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to multiply index values looped in a list I get this error when I run my code however I had converted the data in my list to an int
I have been working on this for weeks and cannot figure it out
ValueError: invalid literal for int() with base 10: '95.7'
How can I by pass this error to get the total ,
import csv
counter = 0
sum = 0
avg = 0
with open('sales_data_sample (3).csv','r') as csv_file: # opens the csv
csv_reader = csv.reader(csv_file)
next(csv_reader) # skips the header so we can work only with raw data
for ((lines)) in csv_reader: # loop through all data in the file
counter =+ 1 # counter
lines[1] = int(lines[1])
lines[2] = int(lines[2])
avg = avg + (lines[1]* lines[2])
total = avg/counter
A: I think the issue is in the data maybe somewhere in your data you have 95.7 and since you are converting it into int so that's why it is breaking your code. You should try
lines[1] = int(float(lines[1]))
lines[2] = int(float(lines[2]))
A: Your problem is you're using integers (whole numbers). Either your lines in the csv are not whole numbers, or when calculating total, you are dividing into decimals.
To solve this, you have to use a floating-point number. Replace your uses of integers with floats.
eg.
lines[1] = int(lines[1]) should become lines[1] = float(lines[1])
You will however find you start getting numbers with long decimal places, so you can round them with the round() function, like this:
lines[1] = round(float(lines[1]), '.2f') Which will set it to 2 decimal places. You can change that 2 to any number of decimal places you'd like.
lines[1] = round(float(lines[1]), '.2f')
lines[2] = round(float(lines[2]), '.2f')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70025347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use OrderBy to sort a custom object ascending by Date I have a collection of a custom object as follows:
public struct Record {
public string Caller { get; set; }
public DateTime Started { get; set; }
public string Dialed { get; set; }
public decimal Duration { get; set; }
public decimal Cost { get; set; }
public string Location { get; set; }
public Switch Switch { get; set; }
}
public static List<Record> Records { get; set; }
Using LINQ, how can I sort Records in ascending order using the value stored in Record.Started ?
A: Just use the OrderBy method:
Records.OrderBy(record => record.Started)
or:
from r in Records
order by r.Started
select r
A: Could it be this easy?
records.OrderBy(r=>r.Started)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31280433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Unable to extract key-value pairs from BigQuery table which has arrays and structs I have integrated Firebase analytics data with google BigQuery and everyday a new table gets created with the DATE stamp.
one sample table is "projectID.com_dev_sambhav_ANDROID.app_events_20170821"
One sample table is shown below
sample table
My requirement is to get result in the below desired format for event_dim.name="notification_received"
desired output
To get this desired output I execute the below query(standardSQL)
SELECT event.name
(SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="notification_title") as notification_title,
(SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"
But I got this error
Error: Each function argument is an expression, not a query. To use a
query as an expression, the query must be wrapped with additional
parentheses to make it a scalar subquery expression.
can anybody help me get out of this problem
A: The problem is a comma and an alias. This query works:
#standardSQL
WITH `projectID.com_dev_sambhav_ANDROID.app_events_2017` AS(
SELECT ARRAY< STRUCT<date STRING, name STRING, params ARRAY< STRUCT<key STRING, value STRUCT<string_value STRING> > > > > [STRUCT('20170814' AS date, 'notification_received' AS name, [STRUCT('notification_title' AS key, STRUCT('Amazing Offers two' AS string_value) AS value ),
STRUCT('firebase_screen_class' AS key, STRUCT('RetailerHomeActivity' AS string_value) AS value),
STRUCT('notification_id' AS key, STRUCT('12345' AS string_value) AS value),
STRUCT('firebase_screen_id' AS key, STRUCT('app' AS string_value) AS value),
STRUCT('item_id' AS key, STRUCT('DEMO-02' AS string_value) AS value),
STRUCT('firebase_screen' AS key, STRUCT('My Order' AS string_value) AS value)] AS params)] event_dim
)
SELECT
event.name,
(SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="notification_title") as notification_title,
(SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"
If you UNNEST the field event_dim and call it event, then you should use this alias as reference in your query.
As a complement, here's another way of solving your problem as well (it's just another possibility so you have more techniques in your belt when working with BigQuery):
#standardSQL
SELECT
(SELECT date FROM UNNEST(event_dim)) date,
(SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'notification_title') AS notification_title,
(SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'item_id') AS item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_2017`
WHERE EXISTS(SELECT 1 FROM UNNEST(event_dim) WHERE name = 'notification_received')
When processing up to terabytes you may find this query still perform quite well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45836216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: shortcut for creating an javascript object from an array of objects using lodash I often have an array of objects and want to make it into an object of objects by keying on a specific key of the contained objects.
Currently I'm doing something like:
_.zipObject(_.pluck(results, '_id'), results);
However, this is such a common thing I wondered if there's a shortcut to do this using Lodash / underscore.
Anyone?
A: You are looking for _.indexBy() http://lodash.com/docs#indexBy
Example from the docs:
var keys = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.indexBy(keys, 'dir');
// → { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23931758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting the name of cells inside a vba function While inside a VBA function I'm attempting to change the name of certain cells to flag them and use them later. I have a searching function that searches excel docs for keywords from a .txt file and need to know which cells don't include any of the search terms. To do this I was going to name each cell I query and include all unnamed cells in the results column for "Other". But whenever I try to name a cell the name doesn't get updated. I've tried the following:
ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange
and
foundRange.name = "QUERIED"
The function is here:
Function Single_word_occurrences(datatoFind As String, resultsCol As String) As Integer
'Initializations
Dim strFirstAddress As String
Dim foundRange As Range
Dim currentSheet As Integer, sheetCount As Integer, LastRow As Integer, loopedOnce As Integer, FoundCount As Integer
FoundCount = 0
currentSheet = ActiveSheet.Index
sheetCount = ActiveWorkbook.Sheets.Count
Sheets("Sheet1").Activate
Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=Cells(2, 6), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
Sheets("List Results").Cells(1, resultsCol).Value = datatoFind
'if datatoFind is found in search range
If Not foundRange Is Nothing Then
'save the address of the first occurrence of datatoFind, in the strFirstAddress variable
strFirstAddress = foundRange.Address
Do
'Find next occurrence of datatoFind
Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=foundRange.Cells, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
'Place the value of this occurrence in the next cell down in the column that holds found values (resultsCol column of List Results worksheet)
LastRow = Sheets("List Results").Range(resultsCol & Rows.Count).End(xlUp).Row + 1
Sheets("List Results").Range(resultsCol & LastRow).Value = foundRange.Address
ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange
If loopedOnce = 1 Then
FoundCount = FoundCount + 1
End If
If loopedOnce = 0 Then
loopedOnce = 1
End If
'The Loop ends on reaching the first occurrence of datatoFind
Loop While foundRange.Address <> strFirstAddress And Not foundRange Is Nothing
Msgbox(foundRange.Name)
End If
Single_word_occurrences = FoundCount
Application.ScreenUpdating = True
Sheets(currentSheet).Activate
End Function
A: You can't Define a Name in a UDF
you must use a sub
the following will fail:
Public Function qwerty(r As Range) As Variant
qwerty = 1
Range("B9").Name = "whatever"
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27382881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: httplib post call error I am trying to automate few http requests where, I have following POST call data which i captured from the web :
Method: POST
Request Header :
POST /cgi-bin/auto_dispatch.cgi HTTP/1.1
Host: 10.226.45.6
Connection: keep-alive
Content-Length: 244
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhwDXAifvLs48E95A
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Referer: http://10.226.45.6/auto_dispatch.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,kn;q=0.6
Cookie: TWIKISID=dce9a6aa10e33b708f5bbc2912f781ab
payload :
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="taskid"
123
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="Submit"
Submit Form
------WebKitFormBoundaryhwDXAifvLs48E95A--
MY script is as follows :
import httplib, urllib
def printText(txt):
lines = txt.split('\n')
for line in lines:
print line.strip()
params = urllib.urlencode({'@taskid': 12524, '@Submit': 'Submit Form'})
headers = {"Content-type": "multipart/form-data", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
conn = httplib.HTTPConnection("10.226.45.6", 80)
conn.request("POST", "auto_dispatch.html", params, headers)
response = conn.getresponse()
print response.status, response.reason
printText (response.read())
conn.close()
I am getting the following error :
400 Bad Request
400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.
Please help me to form a proper request .
A: I Tried with the curl commands which worked for me :
curl --request POST 'http://10.226.45.6/cgi-bin/auto_dispatch.cgi HTTP/1.1' --data 'taskid=111&submit=submit'
curl --request POST 'http://10.226.45.6/cgi-bin/auto_free.cgi HTTP/1.1' --data 'submit=submit'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40036814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Socket connection only when needed I have a web application that needs to refresh some values often because the changes have to be available almost in real time. To do this, I run via ajax a refresh.php routine every 15 seconds, which returns the updated information. Time that increases if there is no user activity.
I thought about the possibility of creating a service-worker in the browser (since I already use it for pwa too), and in it create a web-socket, and then only when there is an update on the server, create a socket for the ip's of the users that are logged in (and saved in a db), just to send to the user's browser that there is an update, then the web-socket triggers the javascript routine that connects to the server and does the update.
I do not know if it would be possible to create the socket just to inform that there is an update, because in this case, I do not want to leave the socket open, creating the connection only when there is an update of the information, which should happen to several users.
Has anyone ever needed or done anything like this, or would you have any other ideas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46288636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sorting in Linux I have a string "abc" and I am greping it in 15 files in my directory in shell.
When I grep "abc" in my 15 files than it returns me the whole line of the files in which its present like this:
abc 0.2 9.0
abc 0.01 8.0
abc 0.06 9.4
abc 0.02 8.7
Now I want this output to be sorted in ascending order according to the second column.
So I wrote the command like this:
grep "abc" *.txt | sort -nr -t_ -k2
but the above command is not working and I don't know why.
A: Your command is not working because you don't have underscores separating the columns; further, you wanted the data ascending but you told it to sort in reverse (descending) order. Use:
grep "abc" *.txt | sort -n -k 2
Or:
grep "abc" *.txt | sort -k 2n
Note that if there are multiple files, your grep output will be prefixed with a file name. You will have to decide whether that matters. It only screws things up if there are spaces in any of the file names. The -h option to grep suppresses the file names.
A: I suggest to delete -t_ parameter, because as I see you use spaces as separator, not underscore. After that it works for me:
$ cat t | sort -n -k2
abc 0.01 8.0
abc 0.02 8.7
abc 0.06 9.4
abc 0.2 9.0
Updated: and yes, as @jonathan-leffler said you also should omit -r option for sorting in ascending order.
A: You can replace your entire script, including the call to grep, with one call to awk
awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt
Example
$ ls *.txt
four.txt one.txt three.txt two.txt
$ cat *.txt
abc 0.02 8.3
foo
abc 0.06 9.4
bar
blah blah
abc 0.2 9.0
blah
abc 0.01 8.0
blah
abc 0.02 8.7
blah blah
$ awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt
abc 0.01 8.0
abc 0.02 8.3
abc 0.02 8.7
abc 0.06 9.4
abc 0.2 9.0
A: First problem: you've used -t_ to specify the field separator, but the output doesn't contain _ characters.
Next problem: the -k option has two arguments, start field and end field. By omitting the end field, you get end_of_line by default.
I'd suggest writing it like this:
grep "abc" *.txt | sort -nr -k2,2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9028972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to eliminate elements of a vector according to a pattern I have this vector:
a <- c("es1", "es2", "es3", "is1", "is2", "is3")
and i would like to eliminate all elements staring with "es", so it ends up looking like this:
b <- c("is1", "is2", "is3")
Thanks everyone!
A: If you want to remove all words that contain "es", try
b <- a[-grep("es", a)]
If you want to remove only the words that starts with "es", try
b <- a[-grep("\\bes\\w+", a)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22933492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Toast in not showing in asynctask I am trying to get message from the server to show in toast but it does not appear. The client receives the message from the server without any errors.I have tried opening UI thread in onpost but it didn't work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new test().execute();
}
public class test extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... params) {
try
{
socket = new Socket("ip", port);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
Log.i(debugString, "Connected_reg!");
out.writeUTF("3");
InputStream inFromServer = socket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
Log.i(debugString, in.readUTF());
string= in.readUTF();
}
catch (Exception e) {
Log.e(debugString, e.getMessage());
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
Context context = getApplicationContext();
CharSequence text = string;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
A: It might be to do with the context.
I've had issues in the past with getApplicationContext not working for certain things, although can't remember what form the top of my head.
Instead of using getApplicationContext, in the activity where you call your async task put this in the constructor call. For example, assuming you are going from MainActivity change the line new test().execute(); to new test(MainActivity.this).execute();
Then in the async class create the constructor as
public test(Context context) and set a global class variable to be the value of context, and then use this in your toast.makeText instead of what is returned from getApplicationContext.
Also take a look in the logcat, see if there are any errors or exceptions being thrown, it might also be worth adding a log line in the onpostexecute method just to double check you're definetely going in there.
A: Create a constructor in the test class which receive a context and use that context in the Toast.makeText. Pass the host activity context to that constructor.
getApplicationContext() is a Context class method, AsyncTask does not inherent from that class. I suppose you are in a scope where you can invoke that method but that scope context is not valid in the scope that you are invoking the Toast.makeText method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44549191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: best way to access a windows service via GUI I'm curious about the best way for a C# gui to access the functions of a Windows Service, be it WCF or ServiceController or some other option.
I'll explain what I'm doing: on a regulated time interval the service will be zipping one hours worth of datafiles from location A and sending the zipped file to location B, this will be done in the background 24/7 or until the service is stopped by the user and runs even when no one is logged in (hence the need for service) I would like the user to be able to pull up a GUI program that will allow them several options:
1) change the location to zip from
2) change the location to zip to
3) manually start the zipping process for a DateTime range specified
Now most of the functions for zipping and timers is all stored within the service. SO im wondering if a ServiceController in the GUI program would allow me to send variables to/from the service (ie folderpath names as strings, various other data) or if I'll need to spend the time making a WCF and treat the GUI as the Client and the Windows service as a source.
It should be noted the GUI will likely recieve data from the service, but only to signify if it is currently busy zipping.
A: One option is to tave a WCF service embedded on your windows service. With this WCF you can control the behaviour without restarting the service.
But the best option IMO is to have this in a config file. You can add some keys, but you would have to restart the service when you update the config.
In this case you can try a workaround, as in this thread.
The config is a good place for this kind of detail, because it can be easily modified and, unlike a database, it will be always avaiable.
A: I don't fully understand what you're trying to say, but you define what the interface to your service is when you make it. If the operations you define take in variables, then you can pass data from your application to the service.
From what you described, just make opertaions in the service to do those 3 things you listed then call those from a button click in your UI code.
WCF would be fine for this here's a basic introduction to it http://msdn.microsoft.com/en-us/library/bb332338.aspx.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18133474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sticky Table two header using CSS for all OS i have two table headers and i want to sticky it using CSS only. Here is my html, and also posted image of my table, i have all the dynamic data and columns.
<div class="fix-table-parent">
<table>
<thead>
<tr class="first_head">
<th>test11</th>
<th>test12</th>
<th>test13</th>
</tr>
<tr class="second_head">
<th>test21</th>
<th>test22</th>
<th>test23</th>
</tr>
</thead>
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
</tbody>
</table>
</div>
How can I make the headers sticky using only CSS?
A: Try below css. You have to change top: 20px; with height of .first_head.
.fix-table-paren thead .first_head th{ position: sticky; top: 0; }
.fix-table-paren thead .second_head th{ position: sticky; top: 20px; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59663249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i Tlit the layout from Left to Right? I want to know about the Layout which can be Tlit from Left to Right. please give me any suggestion for help out me.
A: You can create .xml layouts for when the phone is placed horizontal or vertical. To create a horizontal layout, simply create a new .xml file and check that you would like the layout to be horizontal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11083337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: URL gives 404 ..Angularjs I'm having issue with my url..i actually was trying to remove # tag from my url..which is done but the problem is now if i'm having url like this
http://localhost/xyz
it redirects me to
http://localhost/xyz/home
but the if i try and refersh the same page
http://localhost/xyz/home
it gives 404
any one knows how to solve it..
Thanks.
A: so actually now i'm able to open http://localhost/xyz/home directly with url rewrite which will point to my index.html.but now the bigger issue is whenever i'm trying to run my project it says unable to start debugging and none of my service is getting called it says 405(metod not allowed).i tried iisrest.but no luck.
so if you have any ideas,please share and thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39486575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are the differences between OLEDB/ODBC drivers when connecting to SQL Server? I have an SQL Server database, and I need to push data into it through vbscript, as well as pull data into Excel. I have found multiple connection strings, but no repository for the benefits of performance and functionality comparing them. The driver options (Provider=) I have found so far are:
*
*{SQL Server} (ODBC)
*SQLOLEDB (newer than ODBC, but being deprecated?)
*SQLOLEDB.1 (what Excel 2016 uses when clicking 'Get External Data', but not even mentioned on connectionstrings.com... I assume a newer version of the above, but still the deprecated technology?)
*SQLNCLI11 (native client, OLE DB)
*{SQL Server Native Client 11.0} (native client, ODBC)
Different things I read say that ODBC is better because it has been around longer. And that OLE DB has been around long enough to have the same advantages. And OLE DB was made to work with a certain company's applications. And ODBC was made by the same company. And OLE DB can connect to and from different kinds of applications better. And ODBC works better with databases. And Native is...Native, so must be better... because of the name?
I find multiple questions here on SO floating around with no or partial answers, or having multiple comments claiming the answers are out of date. So, as of now, what the specific differences between these different drivers? Do they have different performance in different circumstances? Do they have different features? Do I need to do profiling to determine the best performance and reliability for my particular use case, or is there a standard "best practice" recommended by Microsoft or some recognized expert? Or are they all basically doing the same thing and as long as it's installed on the target system it doesn't really matter?
A: ODBC-it is designed for connecting to relational databases.
However, OLE DB can access relational databases as well as nonrelational databases.
There is data in your mail servers, directory services, spreadsheets, and text files. OLE DB allows SQL Server to link to these nonrelational database systems. For instance, if you want to query, through SQL Server, the Active Directory on the domain controller, you couldn't do this with ODBC, because it's not a relational database. However, you could use an OLE DB provider to accomplish that.
http://www.sqlservercentral.com/Forums/Topic537592-338-1.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37894058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to initialize and set a 2D array in golang I am trying to simplay make a 2D array as a field on an object. I want a function that creates the object and returns it. But when trying to create the 2d array it returns a single array.
type Struct struct {
X int
Y int
Grid [][]bool
}
func NewLifeSimulator(sizeX, sizeY int) *Struct{
s := &Struct{
X: sizeX,
Y: sizeY,
Grid: make([][]bool, sizeX,sizeY), //Creates a regular array instead of 2D
}
return s
}
What do I need to change so that my function initializes a 2D array?
A: The expression:
make([][]bool, sizeX)
will create a slice of []bools of size sizeX. Then you have to go through each element and initialize those to slices of sizeY. If you want a fully initialized array:
s := &Struct{
X: sizeX,
Y: sizeY,
Grid: make([][]bool, sizeX),
}
// At this point, s.Grid[i] has sizeX elements, all nil
for i:=range s.Grid {
s.Grid[i]=make([]bool, sizeY)
}
The expression make([][]bool, sizeX, sizeY) creates a [][]bool slice with initial size sizeX and capacity sizeY.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63239776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: yarn workspaces monorepo with vite, react, tailwind - VS Code fails to resolve packages I have created a monorepo using yarn@3 workspaces.
My root package.json:
{
"name": "hello-yarn-workspaces",
"packageManager": "[email protected]",
"workspaces": [
"apps/*",
"packages/*"
],
"devDependencies": {
"@commitlint/cli": "^16.0.1",
"@commitlint/config-conventional": "^16.0.0",
"husky": "^7.0.4"
},
"scripts": {
"postinstall": "husky install",
"prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
}
}
The package.json in apps/ui:
{
"name": "ui",
"packageManager": "[email protected]",
"scripts": {
"dev": "vite"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@tailwindcss/forms": "^0.4.0",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"@vitejs/plugin-react": "^1.1.3",
"autoprefixer": "latest",
"postcss": "latest",
"tailwindcss": "latest",
"typescript": "^4.5.4",
"vite": "^2.7.10"
}
}
I have created a component inside my apps/ui/src folder and when I run yarn workspace ui run dev, the app can be started in the browser.
However, when opening my monorepo in VS Code, it fails to resolve npm packages in import statements:
// Cannot find module 'react' or its corresponding type declarations.ts(2307)
import React, { ReactElement, useState } from 'react'
The same happens for the vite.config.ts in apps/ui
// Cannot find module 'vite' or its corresponding type declarations.ts(2307)
import { defineConfig } from 'vite'
// Cannot find module '@vitejs/plugin-react' or its corresponding type declarations.ts(2307)
import react from '@vitejs/plugin-react'
When opening the monorepo in WebStorm, everything is ok.
The repro repository can be found here.
Update: It looks like it is related to the PnP mechanism. I came across this question and setting nodeLinker: node-modules in .yarnrc.yml followed by yarn install fixed it.
However, the ansers for this question didn't work for me.
I get this error in VS Code after running yarn dlx @yarnpkg/sdks vscode:
The path /Users/alexzeitler/src/hello-yarn-workspaces/.yarn/sdks/typescript/lib/tsserver.js doesn't point to a valid tsserver install. Falling back to bundled TypeScript version.
The files in .yarn/sdks/typescript/lib actually don't exist but I have a file integrations.yml in .yarn/sdks:
# This file is automatically generated by @yarnpkg/sdks.
# Manual changes might be lost!
integrations:
- vscode
A: Looks like the missing pieces have been due to the PnP configuration:
yarn add --dev typescript ts-node prettier
yarn dlx @yarnpkg/sdks vscode
Add a minimal tsconfig.json:
{
"compilerOptions": {
/* Basic Options */
"target": "es5",
"module": "commonjs",
"lib": ["ESNext"],
/* Strict Type-Checking Options */
"strict": true,
/* Module Resolution Options */
"moduleResolution": "node",
"esModuleInterop": true,
/* Advanced Options */
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
}
}
Then install this VS Code extension followed by these steps:
*
*Press ctrl+shift+p in a TypeScript file
*Choose "Select TypeScript Version"
*Pick "Use Workspace Version"
More details can be found in the docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70572380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Firebase indexOn issue Edit: I want to filter all the post liked by someone using their phone number
My app was working since 3 years earlier i got warning in console about indexOn issue and i have added security rules as per instructed, now when i have updated firebase sdk and also now I'm using addOnCompleteListener instead of valueEventListener now some part of my app not working and now I'm getting exception about indexOn
I don't how to add index for this kind of key as it keeps changing as per user.
if I hardcode users phone number then it is working but I can't add keys for every user as there are few thousand user so please let me know what i can do.
here are few attachments about database, query and rules
database
query
FirebaseDatabase.getInstance()
.getReference("2 line poetry").orderByChild(number).equalTo("heart");
Rules(currently used which works on previous version)
Rules(Hardcoded version which is working in new version)
I want to make this rule dynamic like using variable $phone or something, I have read almost all threads but didn't found any answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71401495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ZeroClipboard - Using multiple elements ZeroClipboard for single click copy. Both the links are giving the same output, rather than different. Demo link HERE
<a id="c101" href="javascript:void(0);">OBJ1</a>
<a id="x101" href="javascript:void(0);">OBJ2</a>
<script type="text/javascript">
var dom_obj1 = document.getElementById('c101');
var dom_obj2 = document.getElementById('x101');
var clip1 = new ZeroClipboard();
clip1.glue(dom_obj1);
clip1.addEventListener( 'dataRequested', function(client, args) {
client.setText('text1');
});
clip1.addEventListener( 'complete', function(client, args) {
alert('clip1 text: '+args.text);
});
var clip2 = new ZeroClipboard();
clip2.glue(dom_obj2);
clip2.addEventListener( 'dataRequested', function(client, args) {
client.setText('text2');
});
clip2.addEventListener( 'complete', function(client, args) {
alert('clip2 text: '+args.text);
});
</script>
A: Give a common class to all these elements, and then make all of them available to ZeroClipBoard :
< a id="c101" class="toBeCopied" href="something">
< a id="c102" class="toBeCopied" href="something else">
Then load them like this :
var clip = new ZeroClipboard($(".toBeCopied"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18710339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter: LateError (LateInitializationError: Field 'user' has not been initialized.) I am nit sure about this error because user should be inithialized in Auth Provider and then I will be able to use it in User Provider but flutter continue giving this error.
Here is my code. Can someone help to solve or tell me a better form to organize it?
AuthProvider
class AuthProvider extends ChangeNotifier {
late final FirebaseAuth _auth;
late final NavigationService _navigationService;
late final DatabaseService _databaseService;
late UserData user;
AuthProvider() {
_auth = FirebaseAuth.instance;
_navigationService = GetIt.instance.get<NavigationService>();
_databaseService = GetIt.instance<DatabaseService>();
_auth.authStateChanges().listen((_user) {
if (_user != null) {
//_databaseService.updateUserLastSeenTime(_user.uid);
_databaseService.getUser(_user.uid).then(
(_snapshot) {
if (_snapshot.exists) {
if (_snapshot.data() != null) {
user =
UserData.fromJson(jsonDecode(jsonEncode(_snapshot.data())));
notifyListeners();
}
}
_navigationService.removeAndNavigateToRoute('/home');
},
);
} else {
_navigationService.removeAndNavigateToRoute('/login');
}
});
}
User Provider
class UserProvider with ChangeNotifier {
final DatabaseService _databaseService = DatabaseService();
UserData _user = AuthProvider().user;
UserData get getUser => _user;
Future<void> refreshUser() async {
UserData user = await _databaseService.getUserDetails();
_user = user;
notifyListeners();
}
// update user name
Future<void> editName(String name) async {
try {
await _databaseService.getUserDoc(_user.uid).update({'name': name});
} catch (err) {
print(err.toString());
}
}
// update user last name
Future<void> editLastName(String lastName) async {
try {
await _databaseService
.getUserDoc(_user.uid)
.update({'lastName': lastName});
} catch (err) {
print(err.toString());
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71423823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB: Search Query to return an object inside the array I have a Journal Schema which contains an array of notes. I want to implement MongoDB search in my application so that it returns the note that matches the query. Right now it returns the entire Journal Object which contains the matched note.
Journal Schema:
{
userid: {
type: String,
required: true,
},
notes: [
{
content: {
type: String,
},
},
],
}
Right now my query syntax is:
[
{
$search: {
index: 'Journal-search-index',
text: {
query: 'asdf',
path: 'content'
}
}
}
]
It returns the entire Journal object but I only want the note that matches the query. is there any way to implement that?
A: You are currently searching for documents that match current query, but not filtering the data inside of documents, particulary notes array.
You have to add filter on the next aggregation operation
const query = "asdf";
db.collection.aggregate([
{
$search: {
index: "Journal-search-index",
text: {
query: query,
path: "content",
},
},
},
{
$project: {
notes: {
$filter: {
input: "$notes",
as: "note",
cond: {
$regexMatch: {
input: "$$note",
regex: query,
options: "i",
},
},
},
},
},
},
]);
Playground Example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71507954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I apply drop Shadow right and bottom of transparent view in Android? I want to apply drop shadow right and bottom on view (TextView/LinearLayout) with transparent background.
I have draw shadow using Layer-list as said in this link:
Add shadow on right and bottom side of the layout
but it is not giving me desired transparency.
can any one help me out?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30436790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting Value from Another Form: Apostrophes are not displaying Simply put, the apostrophes are not displaying inside my text field.
The result is here: www.unidrones.co.za/VRentals
In the search box, try typing something with an apostrophe like 1920's car or something. You will see a new form that appears. The "Model" field is supposed to accept the exact same string the user typed.
I viewed this nearly duplicate question: The apostrophes are not displayed when getting data from MySQL into bootstrap table but in my case I am not getting my value from the database, I'm getting the value directly from the previous form the user submitted.
I've tried escaping the string, I've tried utf8_encode() and utf8_decode(), I've tried prepared statements and I even tried changing all the "POST" methods to "GET" methods to see if that made any difference. Yet still, if I tried searching for something like 1920's Chrysler the apostrophe would turn into a backslash and the rest of the sentence would be gone.
My code:
<form action='inc/request.inc.php' method='POST' class='request-form' id='request-form'>
<label class='bold required'>Model</label>
<input type='text' name='searchvalue' class='searchvalue' value='".mysqli_real_escape_string($conn, $_POST['search'])."' required >
<label class='bold required'>Full Name</label>
...
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50750249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ templated container scanner here's today's dilemma:
suppose I've
class A{
public:
virtual void doit() = 0;
}
then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subclasses like say list<A*> or vector... The function should call all the doit methods while scanning the iterators... How to do this? I've thought of:
template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
for (; begin != end; begin++) {
A *elem = (serializable*) *begin;
elem.doIt();
}
}
but gives weird errors... do you have better ideas or specific information? Is it possible to use list<A> instead of list<A*>?
A: Why do you think you need the cast? If it is a collection of A * you should just be able to say:
(*begin)->doIt();
A: You can use the std::foreach for that:
std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );
The std::mem_fun will create an object that calls the given member function for it's operator() argument. The for_each will call this object for every element within v.begin() and v.end().
A: You should provide error messages to get better answers.
In your code, the first thing that comes to mind is to use
elem->doIt();
What is the "serializable" type ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1873766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Import Scala from Groovy Is there a way, preferred standard way to import Scala code (local jar, or local maven, or remote artifactory)?
We are using Groovy on Grails, and some library we want to use are written in Java or Scala. Considering they are all JVM languages, there must be a way to interplay.
I've search the net, but have not get a clear answer.
A: Both Scala and Java compiles into Java Bytecode (.class files) and packed as .jar files. It's same bytecode, and can be used from any other JVM language under same classpath.
So your app can mix java bytecode produces from any other JVM language, including Java, Groovy, Scala, Clojure, Kotlin, etc. You can put such jars into /lib dir (if your Grails version supports this; it's less preferred way) or as dependency from Maven repository (local or remote). Then you can use such classes from your code
See:
*
*https://en.wikipedia.org/wiki/Java_bytecode
*http://grails.github.io/grails-doc/2.4.x/guide/conf.html#dependencyResolution for grails 2.4.x
*http://grails.github.io/grails-doc/latest/guide/conf.html#dependencyResolution for latest grails
PS there could be some incompatibilities with some classes, because of different nature of sources languages. But in general it should work.
A: Did some simple tests. In hello-world example, just use
groovy -cp the-assembly-SNAPSHOT.jar main-file.groovy
And in the main-file.groovy, should have an import, like in Java/Scala
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31015822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android base library module implementation We are currently updating the app code, and we are splitting the code into different library modules, which are used by one application module. The problem is that the app compiling time has increased exponentially and all of a sudden the 64k multidex limit has been exceeded. Here how we are building our app:
Is the base module recompiling each time for each library module? What could be changed to improve the compile time?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48065961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Renaming Row Count Column in SQL I can’t find how to rename the row counting column in a table in an SQL Server RDMS. When you create a table and you have user created columns, A and B for example, to the farthest right of those columns, you have the Row Number column.
It does not have a title. It just sequentially counts all the rows in your table. It's default. Is it possible to manipulate this column denoting the row numbers? Meaning, can I rename it, put its contents in descending order, etc. If so, how?
And if not, what are the alternatives to have a sequentially counting column counting all the rows in my table?
A: No. You can create your own column with sequential values using an identity column. This is usually a primary key.
Alternatively, when you query the table, you can assign a sequential number (with no gaps) using row_number(). In general, you want a column that specifies the ordering:
select t.*, row_number() over (order by <ordering column>) as my_sequential_column
from t;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61493197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Travis CI simple bash broken with latest update any "n" character seen as "\n" line break Travis CI seems to be misbehaving very oddly since yesterday. I know they pushed out an update on the 21st June 2017 to Travis but this issue only started happening yesterday to me causing a total mess of one of my repo's but luckily I reverted back to the last commit where everything was still OK and have done no more commits since then just been running tests on a different test repo all day today and it's still broken.
During my Travis build process I run a number of bash scripts that do various things like create files based on templates. But since yesterday the output of any echo or printf see's any "n" character as a line break \n
For example:
This simple printf in my bash script:
for line in $(cat $INPUT1); do
printf "\t\"~${line}\"\t\t$ACTION1\n" >> whateverfile.txt
My inputs are defined earlier as:
ACTION1="0;"
INPUT1=$TRAVIS_BUILD_DIR/myfile.txt
Travis breaks the output of any ${line} which contains an "n" in the output.
So for example a ${line} from the cat statement that contains the word bingbot for instance should output as follows:
"~bingbot" 0;
but Travis is doing this because it see's any n character as a line break, this below is the output of running the script with sh -x ./scriptname
bi"\t\t0;\n
+ printf \t"~gbot
and in the actual output file this is what travis prints with printf
bi" 0;
"~gbot
Anyone else seeing this behavior? I have tweeted and emailed them but no response yet. Tried various things to fix it and in some cases capitalising all my variables, inputs, filenames and directories fixes it but that is not a solution. What has Travis done to simple bash? or am I missing something. This has worked perfectly for over a year.
Note: my default scripts all run using #!/bin/bash I have changed them to use #!/bin/sh but it is still happening.
A: I solved this thanks to the help of a number of people in this question - Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
It wasn't a Travis CI issue after all. It's all explained in the link above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44826148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: github webhook with flask - Github not trigger or not send requset I tried to write a flask app that when every time you do a push event to the Github repo it sends a webhook to the flask server. My code for flask app is:
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def getGitUpdate():
#some of code
return 'hello world'
if __name__ == '__main__':
app.run("0.0.0.0",8000)
The way I set up the webhook on Github is like this:
enter image description here
It is important to note that the firewall is turned off, and in addition I am using the ubuntu 21.04 operating system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73149792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Purge cache in Cloudflare using API What would be best practice to refresh content that is already cached by CF?
We have few API that generate JSON and we cache them.
Once a while JSON should be updated and what we do right now is - purge them via API.
https://api.cloudflare.com/client/v4/zones/dcbcd3e49376566e2a194827c689802d/purge_cache
later on, when user hits the page with required JSON it will be cached.
But in our case we have 100+ JSON files that we purge at once and we want to send new cache to CF instead of waiting for users (to avoid bad experience for them).
Right now I consider to PING (via HTTP request) needed JSON endpoints just after we have purged cache.
My question if that is the right way and if CF already has some API to do what we need.
Thanks.
A: Currently, the purge API is the recommended way to invalidate cached content on-demand.
Another approach for your scenario could be to look at Workers and Workers KV, and combine it with the Cloudflare API. You could have:
*
*A Worker reading the JSON from the KV and returning it to the user.
*When you have a new version of the JSON, you could use the API to create/update the JSON stored in the KV.
This setup could be significantly performant, since the Worker code in (1) runs on each Cloudflare datacenter and returns quickly to the users. It is also important to note that KV is "eventually consistent" storage, so feasibility depends on your specific application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66207019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort Dictionary swift 3.0 At some point of coding, I require to sort dictionary to get ordered data based on the Dictionary's Key.
I tried to get the result by:
let sortedDict = dict.sorted { $0.key < $1.key }
It results into:
let dict = ["a0":1, "a3":2 , "a10":2, "a20":3]
Though, desired result:
let dict = ["a0":1, "a10":2, "a20":3, "a3":2]
Any suggestions would be most appreciated.
Thanks In advance.
A: Dictionary is an unordered collection of data, so you can't create an ordered dictionary.
A: Try This:
for i in 0..<parameters!.count {
let key = "q\(i)"
if httpBody.contains(key){
let regex = try! NSRegularExpression(pattern: "\\b\(key)\\b", options: .caseInsensitive)
httpBody = regex.stringByReplacingMatches(in: httpBody, options: [], range: NSRange(0..<httpBody.utf16.count), withTemplate: "q")
}
}
Simple sort function will not work here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47826640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits