text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
How to work with complex numbers in C without the complex.h library in a non-C99 compliant program?
I'm trying to create a Discrete Fourier Transform in C for a university project, which is a guitar tuner. The university basically forces us to use CodeVisionAVR because it works well with the ATmega168p they gave us. CVAVR works only in C, and is non-C99 compliant, which means <complex.h>, will not work. If i am to create a vector of let's say 800 samples for the guitar tuner, the DFT requires working with complex numbers, respectively with the real and imaginary parts of the input.
This is the code that i'm trying to modify for the task.
float read_voltage(unsigned char channel)
{
channel &= 0b00000111;
ADMUX = ADMUX_NOCHANNEL | channel;
ADCSRA |= 0b01000000;
while (ADCSRA & 0b01000000);
ADCSRA |= 0b00010000;
return (float)(ADCH) * 0.0275;
}
#define M_PI 3.14159265358979323486
#define N 800
float computeDft()
{
// time and frequency domain data arrays
float x[N];
float X[N];
float Xre[N] = {0};
float Xim[N] = {0};
size_t n = sizeof(x);
int k;
int t;
int i = 0;
while(i<N)
{
x[i] = read_voltage(0b00000000);
i++;
}
for (k = 0; k < n; k++)
{ // For each output element
for (t = 0; t < n; t++)
{ // For each input element
double angle = 2 * M_PI * t * k / n;
Xre[t] += Xre[t] * cos(angle) + Xim[t] * sin(angle);
Xim[t] += -Xre[t] * sin(angle) + Xim[t] * cos(angle);
}
X[k] = Xre[k] + Xim[k];
}
return X[k];
}
The problem is that X[k] is actually equal to the complex Xre[k] + jXim[k], not just adding the 2 numbers together.
You could just write your own functions and structs couldn't you?
I afraid you have chosen the wrong tool for this task. AVR s do not have enough resources and computing power.
The university asks of us to use CVAVR, we didn't choose it. They also told us that the code would handle a DFT which i was having a hard time believing.
(a) You can define your own complex type with typedef struct { float re, im; } MyComplexType;. (b) You should probably seek existing DFT implementations rather than writing your own. (c) In the example, you show, there is no need for Xre and Xim to be arrays. Just use single elements initialized in each iteration on k. (d) That’s an O(n^2) DFT implementation. Use something that is O(n log n). (e) Given your processing power limitation, use float, not double: Change sin to sinf, change double to float, append f to floating-point constants (use 3.1415926f for π).
on AVR uC. tft is usually done on inter numbers as floats are fat too expensive . the simple multiplication takes more than 1900 cycles. division is far more time consuming.
besides, sin and cos can be calculated at the same time which is far less costly. But this is definitely not a job for the AVR. You need at least a DSP or a CPU for practical purposes. But using fixed-point numbers may help a bit
| common-pile/stackexchange_filtered |
react native how to memoize inline function
I want to memoize a button if anyone click it.
I heard this creates a new Instance which is bad:
onPress={() => makeData('hello')}
So I should make it like this:
onPress={makeData}
But I have to pass a Parameter so I have to do this in the first example.
So what I can do now to memoized it ? its creates every time a new instance.
where is the problem? if you have a function
const makeData = () => console.log('hello');
and when you click each time it logs, where is the problem ?
you should memorize your function when you pass it as props to other components which has many items and so when you click this button it should render only the clicked item.
How I memoize my function ? With callback?
| common-pile/stackexchange_filtered |
How to get range of dates that are representable/accepted by date(1)/mktime(3)?
On my modern 64bit Mac, the date 1901-12-14 is the earliest accepted by the following command:
date -ju -f "%F" "1901-12-14" "+%s"
I checked the source for the macOS date command here (Apple Open Source) and it is a failed mktime call that gives date: nonexistent time error for earlier dates.
I've looked over the source for mktime here (Apple Open Source) and I think that its a integer representation issue, but I'm not sure.
How can I find or compute the accepted range of dates of the date command (really of mktime)?
And if I wanted to get the Unix time for a date that can't be represented by mktime internals, what other libraries or functions can handle earlier dates?
The current macOS (OS X) implementation of mktime(3) has a minimum supported Unix time of INT32_MIN (-2147483648). This is because localtime.c:2102 assumes the result will fit in a 32-bit integer if the value is less than INT32_MAX:
/* optimization: see if the value is 31-bit (signed) */
t = (((time_t) 1) << (TYPE_BIT(int) - 1)) - 1;
bits = ((*funcp)(&t, offset, &mytm) == NULL || tmcomp(&mytm, &yourtm) < 0) ? TYPE_BIT(time_t) - 1 : TYPE_BIT(int) - 1;
Between 1901-12-14 and 1901-12-13 the Unix time dips below INT32_MIN, requires more than 32 bits, and is still less than INT32_MAX causing the function run out of bits.
This is not much of an issue considering that values before the year 1900 are explicitly disallowed by localtime.c:2073:
/* Don't go below 1900 for POLA */
if (yourtm.tm_year < 0)
return WRONG;
(POLA: Principle Of Least Astonishment)
Additionally, time_t is not required to be signed.
from your links, I learned how to get syntax highlighted source listings at that site
https://opensource.apple.com/source/ntp/ntp-12/ntp/libntp/mktime.c
becomes
https://opensource.apple.com/source/ntp/ntp-12/ntp/libntp/mktime.c.auto.html
thanks
| common-pile/stackexchange_filtered |
Domain name suggestions
Note:
We are closing this domain naming thread. It is asking the entirely wrong question. See this blog post for details: Domain Names: Wrong Question
We're going to keep the name apple.stackexchange.com. But we WILL be setting up redirects from the more "popular" domains names. (e.g. seasonedadvice.com to cooking.stackexchange.com, basicallymoney.com to money.stackexchange.com, and others as we go through the list).
New question: "Write and Elevator Pitch / Tagline!"
Click here to contribute ideas and vote.
[original message text below]
List them off, try to only put one in each answer though instead of a list of ten. This allows people to upvote individual answers instead of a block.
AskDifferent.com
(It's currently available.)
A brilliant suggestion!
Great name! Beautiful.
I'm pretty sure this represents the first and last time I'll be referred to as being either brilliant or beautiful, but I'll take it all the same.
Someone has this now gents, unless it's one of you it's off the table.
I think it's being held for this purpose by SE.
Yes, I snagged it for this purpose.
@Robert: I was thinking of doing the same, but didn't want to snafu the thing if it was chosen. Much thanks!
Old-time apple users can maybe somehow relate to this, but it took me a while to understand why it is so :-(
"Ask Different" isn't even proper English!! English is my fourth foreign language and even I can see it's plain wrong. Is "Different" a person? Did you mean "Ask differently"? Do people really want a title that sounds like we can't even get basic grammar right?
http://apple.stackexchange.com
seems perfectly acceptable to me.
MacOverflow.com
It rhymes with Stack Overflow!
Why put overflow everywhere ?
I don't think it needs Overflow in the name
@Adam: are we suffering from an overflow of overflows?
askaboutapple.com
available
TalkingApples.com
Available
Maybe to similar to talkingapple.com, which is taken.
finelytunedmagic.com
available
applequeries.com
available
infinitelyloop.com
as courtesy to http://en.wikipedia.org/wiki/Infinite_Loop_(street).
As variation: infinitelylooping.com
It is taken but seems not used.
Sadly... InfiniteLoop.com is already taken
AisForAnswer.com
available
From an Apple II ad.
http://www.wired.com/gadgets/mac/multimedia/2006/04/appleads?slide=2&slideView=8
I can donate http://coverflowexchange.com/
| common-pile/stackexchange_filtered |
How to switch the views form address book to mailing view
This might be a trivial thing but I am new to xamarin/monotouch or iPhone/IOS development,
I am trying to make an application(sort of gallery+mail) in which I want to share the image.At longpress
it should open the contacts from where I can select the person from contact and it should take me to the
mailing view. I do not want to do this usung "pushview", but want to just switch the views using "PresentModalViewController"
Now I am getting the addressbook but as soon as I select the contact person instead of displaying the
mailing view it goes back to the homeview.
I even tried dismissing the view after the mailing view is dismissed but the output is still the same..
please help out with this.
what I am doing is as follows:(just merged the two programs given on Xamarin website)
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AddressBookUI;
using MonoTouch.MessageUI;
namespace ChooseContact
{
public partial class ChooseContactViewController : UIViewController
{
public ChooseContactViewController () : base ("ChooseContactViewController", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
ABPeoplePickerNavigationController _contactController;
UIButton _chooseContact;
UILabel _contactName;
_chooseContact = UIButton.FromType (UIButtonType.RoundedRect);
_chooseContact.Frame = new RectangleF (10, 10, 200, 50);
_chooseContact.SetTitle ("Choose a Contact", UIControlState.Normal);
_contactName = new UILabel{Frame = new RectangleF (10, 70, 200, 50)};
View.AddSubviews (_chooseContact, _contactName);
_contactController = new ABPeoplePickerNavigationController ();
_chooseContact.TouchUpInside += delegate {
this.PresentModalViewController (_contactController, true); };
_contactController.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) {
//_contactName.Text = string.Format(e.Person.GetEmails());
_contactName.Text = String.Format ("{0} {1}", e.Person.FirstName, e.Person.LastName);
_contactController.DismissModalViewControllerAnimated (true);
MFMailComposeViewController _mailController;
string[] Emailid =<EMAIL_ADDRESS>
_mailController = new MFMailComposeViewController ();
_mailController.SetToRecipients (Emailid);
_mailController.SetSubject ("mail test");
_mailController.SetMessageBody ("this is a test", false);
_mailController.Finished += ( object s, MFComposeResultEventArgs args) => {
Console.WriteLine (args.Result.ToString ());
args.Controller.DismissModalViewControllerAnimated (true);
};
this.PresentModalViewController (_mailController, true);
};
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
}
}
Try removing this line
_contactController.DismissModalViewControllerAnimated (true);
dosent work, it freezes as i select the contact and gives me the following warning:
ChooseContact[499:c07] Warning: Attempt to present <MFMailComposeViewController: 0x12369c70> on <ChooseContactViewController: 0xe1eb220> whose view is not in the window hierarchy!
| common-pile/stackexchange_filtered |
How to implement == or >= operators for generic type
I have a generic type Foo which has a internal generic class Boo. Boo class a property Value of type K. In a method inside Foo i want to do a boo.Value >= value Note that second operand value is of type T. while compiling i am getting following error:
Operator '>=' cannot be applied to operands of type 'T' and 'T'
Can anyone please tell me whats the problem here?
Restrict the type argument to IComparable , then you can implement the operations with the CompareTo method. Of course, you won't be able to use your generic class with every type, but I think every built-in type which can be compared using such operators like >, <=, ... implements this interface.
Best Regards,
Oliver Hanappi
| common-pile/stackexchange_filtered |
Why is the computed property being updated even though I didn't specify its dependencies?
I have a schema structured something like this:
App = {};
App.Outer = Ember.Object.extend({
inner: null,
quantity: 0,
count: function () {
var self = this, inner = self.get('inner');
return self.get('quantity') * inner.get('count');
}.property('nothing')
});
App.Inner = Ember.Object.extend({
count: 0
});
Yes, the 'count' computed property really is set to depend on a totally nonexistent property 'nothing'. However it seems to get updated anyway:
var o1 = App.Outer.create({
quantity: 2,
inner: App.Inner.create({count: 4})
});
console.log(o1.get('count')); // => 8
o1.get('inner').set('count', 5);
console.log(o1.get('count')); // => 10
o1.set('inner', App.Inner.create({count: 10}));
console.log(o1.get('count')); // => 20
Am I missing something? It knows what to update without me telling it what to depend on... can't be right, can it? What am I misunderstanding about Ember computed properties?
Thanks
note that .property('nothing') is equivalent here to .property() --- that might simplify the question.
By using this.get('quantity'), inner.get('count') you are telling it what it depends on. Every time you call .get('count') the function will go off and get the current values for those properties and therefore return the up to date result.
The .property() part comes into play when you bind the computed property count to something else e.g. a view. When you do that then making a change to quantity will automatically recalculate the count, and this new value will be propagated to whatever you have bound the count too.
You can see the difference in action here: http://jsfiddle.net/tomwhatmore/6gz8x/
Makes perfect sense, thanks. If I want to test this behaviour from a unit test, how should I proceed? I'm guessing make a temporary View object and bind to that property then check its bound property changes when the bound-to one changes...
@AsfandYarQazi I have to admit that I'm still working out the best way to test Ember projects, there's not much documentation on the topic around, so I've been trying some different things out over the last few days. This specific example though strikes me as not ideal for a unit test, you're basically just testing the framework, rather than your code. Ember already has plenty of tests for that. I think it would be covered better as part of an integration test.
As of Ember 0.9.5, property values are not cached unless cacheable() is called on them. e.g.
...
count: function () {
var self = this, inner = self.get('inner');
return self.get('quantity') * inner.get('count');
}.property('nothing').cacheable()
...
For more background, see the discussion on this GitHub issue: https://github.com/emberjs/ember.js/issues/38
Yeah, but in this case I was wondering why it was acting as if it was BEING cached :)
@AsfandYarQazi I've created a JSFiddle to try to better show how cacheable fits in: http://jsfiddle.net/pNC8t/
You can think of a property dependencies as "subscription". You're saying I want to know when this property changes. Bindings use this to know whether to update. The "cacheable" functionality uses this to know whether to execute the function again or just return the same result as the last time it ran.
@AsfandYarQazi Another take on explaining this clearly: When you use .property('foo'), you're saying make this function a property and notify me when foo changes. Bindings are another form of subscription. For bindings to update on a property change, you must have a subscription chain from the changing property to the binding. Lastly,cacheable lets you say don't reexecute the function again unless I've been notified something I depend on has changed.
Well, that seems like a more in depth version of the same answer as the previous one, but it's info that's welcome so up-vote :)
| common-pile/stackexchange_filtered |
How is the Jacobian linked to the determinant of a transformation?
I need to show that
if $(X,Y,Z)^T = A(x,y,z)^T$ then
$\dfrac{\partial(X,Y,Z)}{\partial(x,y,z)} = \det(A)$
I sort of understand the link between change in volume and Jacobians and determinants but I have no idea how to show this.
Any hints would be appreciated, thanks
take a look [ http://en.wikipedia.org/wiki/Determinant#Volume_and_Jacobian_determinant ]
For any linear function $L:{\Bbb R}^n\longrightarrow{\Bbb R}^n$ and any ${\bf x}\in{\Bbb R}^n$:
$$DL({\bf x})=L:{\Bbb R}^n\longrightarrow{\Bbb R}^n,$$
and by definition Jacobian $=\det DL({\bf x})=\det L$.
Thanks for the answer, what is $D$ here?
Differential, the matrix of partial derivatives.
| common-pile/stackexchange_filtered |
Why can't I set the default Ruby version in Ubuntu?
I'm trying to set my Ruby version to be 1.9.2, but I can't change it from the system Ruby installation. What am I doing wrong?
My terminal output is:
$ rvm list
rvm rubies
=> ruby-1.9.2-p180 [ i386 ]
$ rvm use default
Using /usr/share/ruby-rvm/gems/ruby-1.9.2-p180
$ ruby -v
ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-linux]
Normally under Ubuntu you need to do:
sudo update-alternatives --config ruby
That will allow you to set the default to any available version of ruby installed on your system. This is easily installed from repositories.
I would avoid setting particular version to default, better to use .rvmrc files with gemset and ruby version per project.
RVM way should be:
rvm 1.9.2-p180 --default
rvm use default
Also, I guess you might better to switch to 1.9.3. It is quite easy to do with rvm:
rvm install 1.9.3
RVM way will allow you to follow same approach on different platforms (Mac for example)
| common-pile/stackexchange_filtered |
How to create nested JSON response using Node Js
I am using Node.js and My-SQL to create a rest API. I want my response like nested JSON object which will easy to read on my frontend. I tried with for loop, but it does not give me the proper result, is there any plugins available to format this response or is there any easy way to do this nested JSON response.
my SQL query is
var sql ='SELECT comments.comment_id,comments.photo_id,comments.comment_message,comments.comment_date ,tb_users.username as comment_usename,tb_users.first_name as comment_firstname ,tb_users.profile_icon as comment_profile_icon,tb_reply.id,tb_reply.comment_id,tb_reply.photo_id,tb_reply.reply_message,tb_reply.create_date as reply_date,u2.username as r_usename,u2.first_name as r_first_name,u2.profile_icon as r_profile_icon '+
' FROM comments LEFT JOIN tb_reply ON tb_reply.comment_id=comments.comment_id '+
' INNER JOIN tb_users ON tb_users.id=comments.user_id '+
' LEFT JOIN tb_users u2 ON tb_reply.user_id = u2.id '+
' WHERE comments.photo_id= '+photoid+' ORDER BY comments.comment_id DESC LIMIT ' +(pageNo-1)*20+ ', 20 '
and I am getting the response is like
[
{
"comment_id": 20,
"photo_id": 68,
"comment_message": "@singh wow nod.gif ⛑ ",
"comment_date": "2018-06-03T11:12:50.000Z",
"comment_usename"<EMAIL_ADDRESS> "comment_firstname": "love",
"comment_profile_icon": "",
"id": 1,
"reply_message": "lol ",
"reply_date": "0000-00-00 00:00:00",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "sud3",
"r_profile_icon": ""
},
{
"comment_id": 20,
"photo_id": 68,
"comment_message": "@singh wow nod.gif ⛑ ",
"comment_date": "2018-06-03T11:12:50.000Z",
"comment_usename"<EMAIL_ADDRESS> "comment_firstname": "love",
"comment_profile_icon": "",
"id": 2,
"reply_message": "lol hahahhaha . ",
"reply_date": "0000-00-00 00:00:00",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "sud4",
"r_profile_icon": ""
},
{
"comment_id": 20,
"photo_id": 68,
"comment_message": "@singh wow nod.gif ⛑ ",
"comment_date": "2018-06-03T11:12:50.000Z",
"comment_usename"<EMAIL_ADDRESS> "comment_firstname": "love",
"comment_profile_icon": "",
"id": 3,
"reply_message": "r2t3s",
"reply_date": "2018-06-01T18:42:49.000Z",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "love",
"r_profile_icon": ""
},
but I need like
[
{
"comment_id": 20,
"photo_id": 68,
"comment_message": "@singh wow nod.gif ⛑ ",
"comment_date": "2018-06-03T11:12:50.000Z",
"comment_username"<EMAIL_ADDRESS> "comment_first_name": "love",
"comment_profile_icon": "",
"reply" [
{
"id": 1,
"reply_message": "lol ",
"reply_date": "0000-00-00 00:00:00",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "sud",
"r_profile_icon": ""
},
{
"id": 2,
"reply_message": "lol hahahhaha . ",
"reply_date": "0000-00-00 00:00:00",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "sud4",
"r_profile_icon": ""
},
{
"id": 3,
"reply_message": "r2t3s",
"reply_date": "2018-06-01T18:42:49.000Z",
"r_usename"<EMAIL_ADDRESS> "r_first_name": "love",
"r_profile_icon": ""
}
]
}
}
1st step query all the comments make it equal to a variable call result
For loop on the result array, call the query to load all the replies that have foreign key to the comment and save the results as result[x].reply
| common-pile/stackexchange_filtered |
Start Google Maps for navigation not working when using longitude and latitude
I have my longitude and latitude values in my andoroid app and i am passing them to the url as the official android docs says, like so -
String query_string = "google.navigation:q=" +location.getLatitude()+","+location.getLongitude();
Uri gmmIntentUri = Uri.parse(query_string);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
//mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
Google maps opens up quiet alright but it allows says route cant be found.
And i can see the longitude and latitude values i passed in the Google maps address bar. It shows 'finding best route' then shows the error message 'no route found'. It also happens in all modes (walking, driving....). Not Sure why.
Can you share values of lat,lng? Also, what is your current position? Can you try Google Maps URLs as the latest (2017) and recommended by Google way to generate map links?
xomena i added an image to the post
Why is mapIntent.setPackage("com.google.android.apps.maps"); commented out?
I've had a look at your screenshot. I can see that you try to find a driving directions from your current location to coordinate 3.2949945,6.5993606.
However, the 3.2949945,6.5993606 is located in the water inside Gulf of Guinea. You can see this in geocoder tool:
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D3.294995%252C6.599361
I guess your intention is to find a route to the 6.5993606,3.2949945:
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D6.599361%252C3.294995
Yes thats the intention. Let me try to adjust my code and swap the latitude and longitude values and see what happens.
The problem was i saved the longitude as latitude and the latitude as longitude in the program.
| common-pile/stackexchange_filtered |
Select two ranges, one immediately after another using regular expressions
Long story short, I'm trying to "clean up" a script file from a drawing program for playback. The program (ArtRage for iPad) will record all strokes to an XML script file that. You can then export this file and play back the entire drawing process in the iPad or desktop version of the application. I want to clean out all of the "undo" operations.
The drawing "step" looks like this:
<StrokeEvent>
<StrokeHeader>
<EventPt> Wait: 0.428s Loc: (806.416, 439.849) Pr: 1 Ti: 1 Ro: 0 Fw: 1 Bt: 0 Rv: NO Iv: NO </EventPt>
<Recorded> Yes </Recorded>
</StrokeHeader>
Wait: 0.000s Loc: (805.622, 437.537) Pr: 1 Ti: 1 Ro: 0 Fw: 1 Bt: 0 Rv: NO Iv: NO
</StrokeEvent>
I've shortened it up a bit, but the entire thing is contained in opening and closing tags.
The undo operation looks like this:
Wait: 0.661s EvType: Command CommandID: Undo
and it comes right after the step you are undoing.
So ... I'd like to search for just those instances of the complete tag that have an undo operation immediately after it, and then delete both the complete tag and undo line.
I think regex would be a good way to do this, but I don't know it very well. I'm going through a regex class online, but it will just take me a bit to ramp up and this particular solution could come in handy sooner. I've been able to select complete tags, but I can't select just those that have an undo statement following them. I tried using look forward but that selects ALL preceding tags.
Here's the closest I was able to get (excuse the sloppy newbie code):
(<StrokeEvent>[\s\S]+?</StrokeEvent>)\nWait:.*Undo
I thought the "?" after the "+" would enable the lazy option and stop at the first occurrence of , but I may be understanding it wrong.
Anyway, thanks for any tips you can give me!
Replace [\s\S]+? with (?:(?!<StrokeEvent>)[\s\S])*?
Even though [\S\s]+? is un-greedy, this is one of those cases where it becomes greedy to get to the Wait: literal. It's going to find the first event, and go all the way to the last event where it finds a followning Wait no matter what is in between.
Your description with "immediately after" and "following them" (etc) does point to lookahead (in perlretut). But they are a little tricky and one needs to play around with them to get it. They do come very handy sometimes.
Fwiw, should that sample be Wait: 0.000s Loc: (805.622, 437.537) Pr: 1 Ti: 1 Ro: 0 Fw: 1 Bt: 0 Rv: NO Iv: NO </StrokeEvent> or </StrokeEvent> Wait: 0.000s Loc: (805.622, 437.537) Pr: 1 Ti: 1 Ro: 0 Fw: 1 Bt: 0 Rv: NO Iv: NO ?
So your sample XML doesn't contain any examples of what you want to remove. Is that right?
@sin What makes it a bit confusing is that there can be "Wait" statements inside of the tags too. I'm just targeting the "Wait" commands that come right after a tag and are at the same "level" and end in "Undo". Hopefully that makes sense.
@WiktorStribiżew That did it! Thanks very much.
@Shawn You are welcome.
@Borodin I actually want to eventually delete what I'm selecting. So, in the actual XML file, I want to select every instance of tag immediately followed by a "Wait" command that ends in "Undo", and then select that "Wait" command as well. I figured my first step is just being able to select them.
| common-pile/stackexchange_filtered |
Renovate prevent query for local dependencies in maven
I have maven multi module project.
Parent pom.xml:
<groupId>com.group</groupId>
<artifactId>product-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
Child pom.xml:
<parent>
<groupId>com.group</groupId>
<artifactId>product-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>product</artifactId>
When I run Renovate I see in log that product-parent dependency is queried to maven central. But I want Renovate to ignore local (in project) dependencies - in other words, ignore dependencies when dependency have filled in relativePath.
This behavior has other side effects such as when release version of local dependency exists, Renovate prioritize it over SNAPSHOT (unstable) and creates merge/pull request on this product-parent dependency which is for local dependencies unwanted behavior.
Tested with self hosted renovate v37.173
As workaround I list all affected local parent poms in ignoreDeps
The relative path shows that you have a parent which is by default referencing to a parent of a multi module... why should it be ignored?
@khmarbaise I mean ignore it from querying to remote registry or even dependency updates.
In example which I described, I do not want to let dependency to product-parent being updated. Even if somewhere exists newer or stable version. Versions of modules in one project/repository should be aligned.
Please show the project structure and is the pom which is addressed by using relativePath>../pom part of a multi module build (which is strongly assume) ...
https://github.com/jakoubektom/stackoverflow-renovate-78006971
I don't get how you can be in a situation where Renovate finds a newer version of the parent.
One acceptable scenario which I want resolve is if I have multimodule project with application and result of pipeline is image pushed to docker registry but no artifact pushed to maven registries. In that case I want renovate to ignore local parents as well as do maven - to reduce warnings or extra calls (which can be significant number in larger monorepo and multiple maven datasources). With this feature I would resolve also some less acceptable scenarios.
| common-pile/stackexchange_filtered |
Ubuntu 17.04 why chrome-remote loops back ubuntu default dekstop environment?
I have installed Ubuntu 17.04. For a while it worked great. Then I have installed a couple of packages which I don't remember. When I rebooted my laptop, I couldn't login from the default login desktop environment. Every time I try to login, it accepts the password, but loopsback to login screen again. But from the Unity8 desktop environment I can login without a problem. its not a startx, lightdm,owner problem etc..
See this https://askubuntu.com/questions/590561/ubuntu-14-04-login-loop-problem
I have found out one reason for loop login: I had installed Chrome Remote Desktop to my laptop. I uninstalled Chrome Remote Desktop, and that solved the problem. Now I can log in to both desktop type Ubuntu Default and Unity8 without any problem.
To uninstall Chrome Remote Desktop:
Go to a terminal from the login screen with: Ctrl+Alt+F1.
Enter the command: sudo apt-get autoremove chrome-remote-desktop.
Reboot the system.
I had the same problem. Uninstalling chrome remote desktop solved it.
Use anydesk remote app instead of chrome-remote. Anydesk is compatible with Ubuntu, windows, and android
| common-pile/stackexchange_filtered |
Prevent Logout on page refresh in React+Redux App
Logging out on page refresh in React + Redux Application, but if I store token in localstorage, then it works fine, but i don't want to store token in localstorage. Is there any other way to achieve it?
keep the token in Cookies. And pick the token directly from cookies wherever you are making api call or handling the logic of redirection to logged in state app.
@simbathesailor, but cookies will be accessible in react ?
Yup cookies have nothing to do with reactjs. Its browser feature.
You can accept cookies with document.cookie. document is a global object and is accessible from javascript, so if from reactjs.
| common-pile/stackexchange_filtered |
Returning array to show in the html ANGULAR
I'm not sure how this is done in Angular.
i have this mapped item
currentSuper?: any[];
this.currentSuper = response.builder?.superintendents?.filter((x) => x.id ===
this.builderSuperintendentId);
response.builder.superindentents returns
[0:{id:'', firstName: '', lastName:''},
1:{ id: '', firstName:'', lastName:''}]
the index number is throwing this off since currentSuper looks like this:
[0:{id:'', firstName: '', lastName:''}]
<span class="text-secondary">Superintendent:</span><span class="mx-2">{{
order.value.currentSuper?.firstName }} {{ order.value.currentSuper?.lastName }}</span>
Where firstName is null now. I cannot do order.value.current[0].firstName either. so how to i get this data to actually render correctly?
currentSuper is an array so use ngFor syntax to iterate over it in the template. See https://angular.io/guide/structural-directives. I suggest making your types stricter too. Can you remove the optional of currentSuper?: any[]; by assigning initial value [] and make any a type e.g. type SuperIndentent = { id: string, firstName: string, lastName: string }
i did change to <div class="mx-2" *ngForOf="let currentSuper of order.value.currentSupers">? {{ currentSuper.firstName }} {{ currentSuper.lastName }}
however it is just empty now on the UI side
*ngForOf is the wrong syntax, it's *ngFor - see the link. If you want to see the data you're trying to render as a debugging step stick <pre>{{ order.value.currentSupers | json}}</pre> before this div
thanks!! i got with the ngFor. also didnt need the order.value.currentSupers and just needed to have it as let currentSuper of currentSupers
Because it returns an array, you'll need to "grab" an item from the list, or render all the filtered items.
Take a look at the following examples that uses itemList as an array of items.
Grab an item (not recommended) using the index:
<div>
{{itemList[0].id}}
</div>
Render all items using ngFor:
<div *ngFor="let item of itemList">
{{item.id}}
</div>
Another option is to use find instead of filter so that it returns an object instead of a filtered array.
To me, this seems like what you're looking for
this.currentSuper = response.builder?.superintendents?.find((x) => x.id ===
this.builderSuperintendentId);
In the html you can just render the currentSuper:
<div>{{ currentSuper?.id }}</div>
| common-pile/stackexchange_filtered |
Alternative ways to display available rooms in drop-down menu?
For some time now, I'm trying to generate a reservation form, where only available rooms are listed for the arrival and departure dates chosen in that same reservation form. Unfortunately, until now I didn't manage to do so.
I set out a question already on my previous attempt, without any success. => https://stackoverflow.com/posts/59083421/edit
I'm now trying to look for alternative ways to get there. For reference, please find my previous attempt below.
Previous attempt: general idea
Tried to send/receive an AJAX. Cannot reach the success stage, and the bug seem lie in the dataType the AJAX call is expecting/I'm sending (JS vs JSON). Unfortunately, I don't know how to solve this.
When I use format.js in my controller, I do not reach the success stage in my ajax call
when I use render json: {:rooms => @rooms} I do not reach my hotels/rooms_availability.js.erb file and subsequently am not able to insert my available rooms.
Previous attempt: code
reservations/new.html.erb
<%= simple_form_for [@hotel, @reservation] do |f|%>
<div class="col col-sm-3">
<%= f.input :arrival,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "start_date"} %>
</div>
<div class="col col-sm-3">
<%= f.input :departure,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "end_date"} %>
</div>
<div class="col col-sm-4">
<%= f.input :room_id, collection: @rooms %>
</div>
<%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>
script for reservations/new.html.erb
<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
const checkInAndOut = [checkIn, checkOut];
checkInAndOut.forEach((item) => {
item.addEventListener('change', (event) => {
if ((checkIn.value.length > 0) && (checkOut.value.length > 0)){
checkAvailability();
}
})
})
function checkAvailability(){
$.ajax({
url: "<%= rooms_availability_hotel_path(@hotel) %>" ,
dataType: 'json',
type: "POST",
data: `arrival=${start_date.value}&departure=${end_date.value}`,
success: function(data) {
console.log('succes')
console.log(data);
},
error: function(response) {
console.log('failure')
console.log(response);
}
});
};
</script>
hotels_controller
def rooms_availability
hotel = Hotel.includes(:rooms).find(params[:id])
arrival = Date.parse room_params[:arrival]
departure = Date.parse room_params[:departure]
time_span = arrival..departure
@unavailable_rooms = Room.joins(:reservations).where(reservations: {hotel: hotel}).where("reservations.arrival <= ? AND ? >= reservations.departure", arrival, departure).distinct
@hotel_cats = hotel.room_categories
@hotel_rooms = Room.where(room_category: hotel_cats)
@rooms = hotel_rooms - @unavailable_rooms
render json: {:rooms => @rooms}
#respond_to do |format|
#format.js
#end
end
def room_params
params.permit(:arrival, :departure, :format, :id)
end
hotels/rooms_availability.js.erb
var selectList = document.getElementById('reservation_room_id')
function empty() {
selectList.innerHTML = "";
}
empty();
<% unless @rooms.empty? %>
<% @rooms.each do |room|%>
selectList.insertAdjacentHTML('beforeend', '<option value="<%= room.id %>"><%= room.name %></option>');
<% end %>
<% end %>
what do u get as a response??
Thank you for your comment. I added the response to the question.
instead of respond to try adding render json: {:rooms => @rooms} you will get the rooms as json object in js. iterate though the json object to create drop down options
also, check the format of the date you passing from js to ruby
Thank you for helping me. I tried what you proposed and this provides me with the 500 error message Failed to load resource: the server responded with a status of 500 (Internal Server Error). The response text I get is: "{"rooms":[{"id":8,"name":"3","room_category_id":4,"created_at":"2019-11-19T16:21:16.239Z","updated_at":"2019-11-19T16:21:16.239Z"},{"id":16,"name":"1","room_category_id":9,"created_at":"2019-11-26T11:40:16.951Z","updated_at":"2019-11-26T11:40:16.951Z"}]}". The date formats seem to parse successfully and are of the format Date.
whats your error in server log when you getting 500
I added it at the bottom of my question, as it's too long for a comment.
you are still getting invalid date error.....maybe the date is not in the ruby format
Added the logs of the dates as well.
Fixed, the invalid date issue (see also updated question)
you have multiple ways to populate the drop-down, format.js will access the room_availabilty.js.erb , render json: will give you rooms in json object and you have to iterate through and populate the dropdown from your js.
Let us continue this discussion in chat.
| common-pile/stackexchange_filtered |
AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token
xamarin forms with office 365 authentification
the authentification works fine but lately i receive this error message :
AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.
with some research i find that i need to refresh the token. -->
https://support.workspace365.net/hc/en-us/articles/360010259114--RESOLVED-Technical-issue-Workspace-365
the question is how to refresh the token can anyone guide me.
Thank you
This my code :
public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
{
AuthenticationResult authResult = null;
try
{
var authContext = new AuthenticationContext(authority);
if (authContext.TokenCache.ReadItems().Any())
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
var uri = new Uri(returnUri);
PlatformParameters platformParams = null;
android
platformParams = new PlatformParameters((Android.App.Activity)Forms.Context);
ios
Device.BeginInvokeOnMainThread(() =>
{
UIViewController controller = new UIViewController();
controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
platformParams = new PlatformParameters(controller);
});
UserDialogs.Instance.HideLoading();
Authresult need to return the token so i can use it from office 365 authentification but instead i receive the message AADSTS54005: OAuth2 Authorization...
authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
authContext.TokenCache.Clear();
}
catch (Exception e)
{
Console.WriteLine("Execption : " + e.Message);
}
return authResult;
}
any help will be appreciated Thank you
Maybe this article can be helpful.https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token @Soufiane BENHADDOU Or you can Change the token lifetime to have a try.
| common-pile/stackexchange_filtered |
What is the definition and purpose of a pre-amplifier?
I find in many places mentions of pre-amplifiers being used to boost audio signals prior to feeding to a power amplifier.
Wikipedia's article on pre-amps gives some hints at their usage, but it doesn't really explain why it would be necessary to have two amplifiers in series rather than a single one with greater gain.
If a pre-amp is just a power amp with a smaller gain, what's the point, and why the distinction between the two kinds? Is the distinction in function, or simply purpose?
Usually there's other stuff between the pre-amp and the power amp. The pre-amp prepares the signal to go through the other stuff without degradation.
There are many reasons why you would want a pre-amp and a power amp. The easiest to understand is when your source and destination are far away from each other. In this situation a pre-amp can be helpful so that the noise that is picked up on the line to the power amp is minimal compared to the signal itself.
Another situation is if you were going to be performing some filtering on a signal. All of the filtering elements can add noise to your system and by adding a preamp the noise in the filtering is minimized compared to the signal. Also the preamp can act as a simple buffer between your source and the filtering equipment.
And yet another reason you would want it is because your preamp isn't able to provide the current gain required for the power amp. You may still wonder why not just use a power amp? Power amps are more difficult to directly change the volume on while a preamp is much easier. So you can change your volume on the preamp and have a fixed gain on the power amp.
Simplistic view: There are N different kinds of pre-amplifiers and M different kinds of power amplifiers. For an application, you can pick one of the N pre-amps and one of the M power amps, instead of having to find a combined unit that is one of M * N.
Think about pro audio for instance. There exist microphone pre-amps. A mixing board will have a whole bunch of them, one for each mic input. It would be silly to replicate that in a power amp. The power amp just gets the mixed result. In fact there may be more than one power amp. One for the "house", and a different one for local monitoring.
A microphone pre-amp is a different beast from, say, a guitar pre-amp, etc.
Why would a guitarist want a separate pre-amp and power amp? Well, not all do. There are "combo" amplifier that have a preamp, power amp and speaker cabinet all in one. (And there have been electric guitars with a built in speaker, yielding complete integration.)
But having separate units in a rack: pre-amp, equalizer, effects processor, power amp, gives you flexibility.. Don't like how the power-amp drives the speakers? Swap it out; see how the setup sounds with a different one. You can change one "variable" at a time in search of tone.
A preamplifier processes a signal to make it fit for the next stage in the signal chain.
A stereo set 20 years ago would have a phono preamp. Other signal inputs than phono would have a sensitivity of for instance 500mV, while the record player only would give 3mV. So you needed a preamp to pump this up to 500mV. That same phono preamp would filter the signal because the phono's frequency characteristic wasn't flat. That was the infamous RIAA correction. So the preprocessing isn't always limited to changing levels.
A microphone preamp also has the function of amplifying the low input voltage to a more common level.
Further in an audio amplifier you'll have a preamp to create the required output voltage for the speakers. This will drive the output stage which supplies the required current/power. Amplifying voltage and current may be separated.
Modern AV receivers have started including phono pre-amps again since the popularity of vinyl records have taken off again.
The best way i can answer the above question is that, this is the section of any stereo system that sets the TONE control,the bass and treble which help create the "quality" in the signal,which delivers the signal on to the amp,then on to the voice of the stereo system,the speakers..
How well the preamp deliver a "quality signal" to the amp is determined by research and the TUBES or TRANSISTORS put in by engineers of that company.. Now all i can say at this point, you get what you pay for..
What is the value addition to the question from your response?
| common-pile/stackexchange_filtered |
RemotingMultiClientsHelp c# code
I am making a remote desktop application. When I connect one client I can easy remoting but I cant connect more clients.
MyCode:
Server
void start()
{
try
{
URI = "Tcp://"+textBox1.Text+":6600/MyCaptureScreenServer";
chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
obj = (ScreenCapture)Activator.GetObject(typeof(ScreenCapture), URI);
connected = true;
timer1.Enabled = true;
textBox1.ReadOnly = true;
this.FormBorderStyle = FormBorderStyle.None;// Full Size Mode
this.WindowState = FormWindowState.Maximized;
textBox1.Visible = false;
menuItem5.Enabled = true;
}
catch (Exception) {
stop();
}
}
Client:
TcpChannel chan = new TcpChannel(6600);
ChannelServices.RegisterChannel(chan);
RemotingConfiguration.RegisterWellKnownServiceType(Type.GetType("ScreenCapture, ScreenCapture"), "MyCaptureScreenServer",WellKnownObjectMode.Singleton);
It might help if you provided any exception messages you may be receiving.
I assume the second client is complaining that port 6600 is already in use?
A specific port number can only be registered once, this is generally done by one server component. This will also register the types for remoting. Multiple clients can then connect to the server.
Yes, problem is with port. Can you please tell me how to change port for new connection
@StarGag We'd probably need more information on how you want it to work. Usually you would have 1 server that would register the port and remoting types. You seem to want multiple servers (which you call the client)?
I want one server. I want connect more clients on server. Now I can connect only one.
@StarGag The 'server' component should register the channel on a specific port number and call RegisterWellKnownServiceType. Then one to many clients can connect to it. In your example do you have server and client the wrong way round? Your client is registering the channel on a specific port number and calling RegisterWellKnownServiceType.
| common-pile/stackexchange_filtered |
Confusing Behavior with Array Initialization -- Processing (Java)
I'm encountering some confusing behavior when trying to create an array of certain length. The length is obtained by a file read in the function getTermNums. When I try to create an array of this size, my code runs in a strange order, my i values are skewed, and the code generally doesn't run as intended. When I instead create an array of a set integer amount, the code runs as intended without error.
double[] terms;
int numTerms = getNumTerms(lines[0]);
terms = new double[numTerms];
int i = 1;
for (i = 1; i<terms.length; i++){
//terms[i] = calculateTerm(T, lines[i]);
}
the above code runs incorrectly.
double[] terms;
int numTerms = getNumTerms(lines[0]);
int myNum = 200;
terms = new double[myNum];
int i = 1;
for (i = 1; i<terms.length; i++){
//terms[i] = calculateTerm(T, lines[i]);
the above code runs correctly
int getNumTerms(String line){
int i = 60;
int j = 0;
char[] word;
word = new char[4];
int numTerms;
int numTermLen = 0;
while(new String(word).compareTo("TERM") != 0){
for (j=0; j<4; j++){
word[j] = line.charAt(i + j);
}
i++;
}
j = i - 3;
while( new Character(line.charAt(j)).equals(' ') == false){
numTermLen++;
j--;
}
j++;
println("i in here: ", i);
numTerms = Integer.parseInt(line.substring(j, j + numTermLen));
return numTerms;
}
this is the function that I'm calling to read the numterms for the size of the array in the first example that doesn't work correctly.
When I use the function call to set the size of array terms[], i starts at some value like 380, and the iteration through array lines[] begins somewhere in the middle of the array.
When I use the integer myNum to set the size of array terms[], i starts at 1, and the iteration through array lines[] begins at the first line, as intended.
Any explanation is appreciated! I'm new to coding in java and am confused by the source of this error.
Thanks in advance.
can you post a sample of the text you're parsing ? there might be a problem with how you parse the numTerms integer value.
Have you used debugger?
Without seeing the text it's tiresome to deduct where in your getNumTerms the error occurs.
You can make use of String's indexOf() to find the index of "TERM" and substring() to extract the String containing the integer value.
As far as I understand the ideal string would have "TERM" followed by an integer then a space character. If these items are found and the value fits within 32 bits you should be able to use something like this:
String line = "LINE START TERM-1238847 LINE END";
int getTerm(String line){
int result = Integer.MAX_VALUE;
final String SEARCH_TOKEN = "TERM";
// look for TERM token and remember index
int termIndex = line.indexOf(SEARCH_TOKEN);
// handle not found
if(termIndex < 0){
System.err.println("error: " + SEARCH_TOKEN + " not found in line");
return result;
}
// move index by the size of the token
termIndex += SEARCH_TOKEN.length();
int spaceIndex = line.indexOf(' ',termIndex);
if(spaceIndex < 0){
System.err.println("error: no SPACE found after " + SEARCH_TOKEN);
return result;
}
// chop string extracing between token end and first space encountered
String intString = line.substring(termIndex,spaceIndex);
// try to parse int handling error
try{
result = Integer.parseInt(intString);
}catch(Exception e){
System.err.println("error parsing integer from string " + intString);
e.printStackTrace();
}
return result;
}
System.out.println("parsed integer: " + getTerm(line));
| common-pile/stackexchange_filtered |
Possible? Internet connected VST audio plugin placed on midi/audio tracks on DAWs, e.g. Ableton, Logic, etc
Is this possible to create?
Requirements
VST can send messages to a webserver
VST can receive messages from a webserver
VST can automatically receive/send messages to/from the webserver, e.g. in the background, without the user having to open the plugin window, pressing a button etc.
Thanks
Yes, this is possible. You can build a VST to do most anything you want.
@Brad. Thanks! Even send/receive audio files to/from webserver?
Sure, why not? It's your code, you can do what you like!
@Brad haha thanks. I will never let anybody tell me what I can or can't do with my code
@Brad another question I just posted: https://stackoverflow.com/questions/70357690/possible-vst-audio-plugin-evaluate-sound-note-pattern-similarity-of-a-track-o
| common-pile/stackexchange_filtered |
convert from long long to int and the other way back in c++
How to convert from long long to int and the other way back in c++ ??
also what are the properties of long long , especially its maximum size,
thank in advance ..
Type long long is typically 64 bits.
Type int is likely to be 32 bits, but not on all machines.
If you cast an int to a long long, you can do
my_long_long = (long long) my_int
and it will be just fine. If you go the other direction, like
my_int = (int) my_long_long
and the int is smaller than 64-bits, it won't be able to hold all the information, so the result may not be correct.
Does it just truncate the higher order bits when casting to a smaller size?
@adu: Maybe. That's the typical behavior, but the result is implementation-defined for a signed target type. For an unsigned target type, the result is defined by the language, and is equivalent to discarding the high-order bits.
Downvoting this, since I believe a C++ cast like static_cast should always be preferred over C-style-casts when coding C++ .
@FourtyTwo static_cast is too verbose and for that simple digital to digital conversion c-cast looks better, imho.
@Guinzoo This is what most programmers think when they start using C++. But please reconsider: Somebody might refactor the code to actually make my_int a pointer instead of a local variable (the variable name might not reflect this). Then, guess what: The cast still succeeds, but gives you the address instead of the value of the variable. With static_cast, you get a compiler error. There are many ways of creating undefined behavior or even crashes of an application like this! Let the compiler help you where it can - the new C++ casts are there to help, and are not verbose at all!
The casts aren't necessary. You can just assign the values: my_long_long = my_int; or my_int = my_long_long; and the conversion will be done implicitly. This is actually safer, since there's no risk of using the wrong type in the cast.
int is guaranteed to be at least 16 bits wide. On modern systems, it's most commonly 32 bits (even on 64-bit systems).
long long, which didn't originally exist in C++, is guaranteed to be at least 64 bits wide. It's almost always exactly 64 bits wide.
The usual way to convert a value from one integer type to another is simply to assign it. Any necessary conversion will be done implicitly. For example:
int x = 42;
long long y =<PHONE_NUMBER>854775807;
y = x; // implicitly converts from int to long long
x = y; // implicitly converts from long long to int
For a narrowing conversion, where the target type can't represent all the values of the source type, there's a risk of overflow; int may or may not be able to hold the value<PHONE_NUMBER>854775807. In this case, the result is implementation-defined. The most likely behavior is that the high-order bits are discarded; for example, converting<PHONE_NUMBER>854775807 to int might yield<PHONE_NUMBER>. (This is clearer in hexadecimal; the values are 0x7fffffffffffffff and 0x7fffffff, respectively.)
If you need to convert explicitly, you can use a cast. A C-style cast uses the type name in parentheses:
(long long)x
Or you can use a C++-style static_cast:
static_cast<long long>(x)
which is somewhat safer than a C-style cast because it's restricted in which types it can operate on.
Size of int is only 2 bytes whereas the other one is usually larger than int. So if you are looking to convert long into int then you would end up loosing information. But the other way is possible without sacrificing the correctness of information.
Suppose a is of long type and b is of int type. Then int to long covertion:a=(long)b; . For other way:b=(int)a;.
The width of int is at least 16 bits. It's typically 32 bits on modern systems. (sizeof (int) could be as small as 1, but only if CHAR_BIT >= 16, which is unusual.)
| common-pile/stackexchange_filtered |
Compensating for an iPhone Safari Rotation Bug
Here are some steps to mess up the iPhone's rotation when in Safari
Holding the phone in vertical mode and navigate to google.co.cr with Safari
Rotate the phone horizontally
Rotate the phone vertically
The page is clipped as seen here:
A simple horizontal swipe will bring it back.
This is not a problem with google.com, only with google.cr.co, but it illustrates the problem I am having.
Oddly enough, if you do the search from the Google Search box in the Safari Header, this resizes back to normal.
My web page has the same problem when following the same steps... it gets clipped.
How can I fix this?
I'm not hitting this problem with iOS5
You are right. I am in Costa Rica, and it is redirecting to google.co.cr and it is having a problem with that. Obviously not a problem with iOS, but rather with the page. Can you duplicate it with co.cr?
I have the same problem on my web app! I think this is a good question and I would be very interested in its answer, too.
Simply reset the viewport on orientation change.
window.addEventListener('orientationchange',function() {
if(window.orientation === 0) {
window.scrollTo(0,0);
}
},false);
| common-pile/stackexchange_filtered |
Use LaTeX to simulate old typewriter written texts
This question led to a new package:
typewriter
I'm giving my students an old exam and barely remembered to change the date at the top. A colleague and I joked about how long we could reuse the same exam, and it made me wonder if I could use LaTeX to create an exam that looked like it was written in 1963 on a typewriter.
Here's what I'd like to see:
Typewriter font even in math mode. (Several ways to accomplish this; is there a "best" way?)
Slight inconsistencies in the printing of each letter. I attempt this below adapting code taken from here. Each word has a random vertical shift, though I'd like to see it reduced to each letter having its own vertical shift. Other typewriter-like irregularities would be great.
It would be great if math-mode delimeters \left(, \right}, etc., can be created in a piece-meal fashion as they did in days of old.
Fraction bars, tops of square-root symbols -- any horizontal line, really -- is made up of a series of en-dashes that don't quite match up.
Here is what I've come up with so far:
\documentclass[10pt]{article}% This is a document class providing more font size options
\usepackage{graphicx}
\usepackage{ifthen}
\usepackage[textwidth=7.5in,textheight=9.5in]{geometry}
\pagestyle{empty}
% thanks to Bruno Le Floch: https://tex.stackexchange.com/q/9331/4012
% and in his comments to https://tex.stackexchange.com/a/29458/4012
\usepackage[first=-1,last=1]{lcg}% you can play around with these values
\makeatletter
\newcommand{\globalrand}{\rand\global\cr@nd\cr@nd}
\makeatother
\newcommand{\randomvshift}[1]{\globalrand\raisebox{\value{rand}pt}{#1}}
%%% thanks to Martin Scharrer: https://tex.stackexchange.com/q/11598/4012
\makeatletter
\def\typewriter#1{%
\@typewriter#1 \@empty
}
\def\@typewriter#1 #2{%
\randomvshift{#1}\space
\ifx #2\@empty\else
\expandafter\@typewriter
\fi
#2%
}
\makeatother
\begin{document}\tt
\typewriter{Math 101 Fall 1963}
\begin{enumerate}
\item \typewriter{$\frac{\texttt{d}}{\texttt{dx}}\texttt{(x)}^2$}
\item \typewriter{State the Fundamental Theorem of Calculus.}
\end{enumerate}
\end{document}
Did people typset math with a typewriter in 1963? I only know math texts from that time typed with a typewriter where all math symbols added carefully handwritten. So maybe all math should simulate handwritten math symbols (also with slight inconsistencies).
I'm a bit young for this (but don't often get to say that any more). But wouldn't you want the vertical offset to be consistent for each character? Just checked somethign and it does seem so (in the example I found every "y" was above the baseline by about 0.1ex)
@student -- there did exist gadgets that provided extra "keys" with symbols to avoid (most) handwritten inclusions. see the section on "typewriter" composition at http://tex.stackexchange.com/a/244126
@ChrisH Yes, it would be best if all "e's" had the same shift. I'd love that.
@student I used 1963 because it is well known around here that our school president graduated from here in 1963. But yes, that may be going back too far. I have a Springer text, copyright 1977, that is all typewriter-written.
I have a 1997 data book on my desk that's typewritten with handwritten Greek letters.
See http://tex.stackexchange.com/q/122970/5763
Perhaps someone could provide a definition for mimeograph purple. Only the stencil would come from the typewriter itself.
Related: What's a good typewriter template?.
This is now available as the typewriter package on ctan and texlive etc
Improved version with some Greek and mathematics, and avoiding small numbers being written using 2e-5 notation into the pdf (and crashing the pdf reader)
This version assumes that the CM Unicode opentype fonts are available.
2nd update now works with texlive 2016 stable release, and also a texlive 2015 updated to luatex 0.95 (Previous version only seemed to work in a texlive 2017 test release).
Slightly updated code available as a package here
https://github.com/davidcarlisle/dpctex/tree/master/typewriter
\documentclass{article}
% luaotfload exlicitly loaded for latex formats before 2017/01/01
\usepackage{luaotfload}
% load cmuntt here not from lua (for everyone except me, it seems)
\font\cmuntt = cmuntt at 12pt \cmuntt
\edef\cmunttid{\fontid\cmuntt}
\expandafter\let\expandafter\%\csname @percentchar\endcsname
\directlua{
local cbl = luatexbase.callback_descriptions('define_font')
% print('\string\n======' .. cbl[1] .. '===\string\n')
original_fontloader = luatexbase.remove_from_callback('define_font', cbl[1])
luatexbase.add_to_callback(
'define_font',
function(name, size, i)
if (name=='cmtt10x') then
% this works in my dev version but for older setups
% make sure cmuntt.otf has been loaded before we mess
% up the font loader.
% f = original_fontloader('cmuntt.otf',size)
f = font.getfont(\cmunttid)
f.name = 'cmtt10x'
f.type = 'virtual'
f.fonts = {{name = 'cmuntt', size = size}}
for j, v in pairs(f.characters) do
local gr = 0.4*math.random()
local gr2 = 0.4*math.random()
v.commands = {
{
'lua',
'r1 = 0.01*math.random(-10, 10)
pdf.print(string.format(
" q \%f \%f \%f \%f 0 0 cm ",
math.cos(r1), - math.sin(r1),
math.sin(r1), math.cos(r1)
))'
},
{'special', 'pdf: ' .. gr2 .. ' g'},
{'push'},
{'right', math.random(-20000,20000)},
{'down', math.random(-20000,20000)},
{'char', j},
{'pop'},
{'lua', 'pdf.print(" Q ")'},
{'down', math.random(-20000,20000)},
{'special', 'pdf: ' .. gr .. ' g'},
{'char', j},
{'special', 'pdf: 0 g'}
}
end % end of for
return f
else
return original_fontloader(name, size, i)
end % end of if
end, % end of function
'define font'
) % end of add_to_callback
}
\def\sqrt#1{^^^^221a\overline{#1}}
\begin{document}
$\relax$
\font\myfont= cmtt10x at 12pt \myfont
\font\myfonts= cmtt10x at 7pt
\let\selectfont\relax
\textfont0=\myfont
\scriptfont0=\myfonts
\scriptscriptfont0=\myfonts
\textfont1=\myfont
\textfont2=\myfont
\textfont3=\myfont
\section{Introduction}
ABCD one two theee four five
TTTTTTTooooooWWWWW
\begin{enumerate}
\item red yellow blue green
\item black blue purple
\end{enumerate}
[some greek text θ]
and in math $x^2-\cos θ$
\[\left(\frac{x^2}{\sqrt{1+y}}\right)\]
\raggedleft
typeset by egreg design services
\end{document}
Original:
This introduces randomness on every use of each letter of the document. It requires luatex. (math is possible but not yet)
\documentclass{article}
\directlua {
local cbl = luatexbase.callback_descriptions('define_font')
original_fontloader = luatexbase.remove_from_callback('define_font', cbl[1])
luatexbase.add_to_callback(
'define_font',
function(name, size, i)
if (name=='cmtt10x') then
f = font.read_tfm('cmtt10', size)
f.name = 'cmtt10x'
f.type = 'virtual'
f.fonts = {{name = 'cmtt10', size = size}}
for j, v in pairs(f.characters) do
local gr = 0.4*math.random()
local gr2 = 0.4*math.random()
v.commands = {
{'lua',
'
r1 = 0.05+0.1*math.random()
pdf.print
(" q "
.. math.cos(r1) .. " "
.. - math.sin(r1) .. " "
.. math.sin(r1) .. " "
.. math.cos(r1) .. " 0 0 "
.. " cm "
)
'
},
{'special', 'pdf: ' .. gr2 .. ' g'},
{'push'},
{'right', math.random(-30000,30000)},
{'down', math.random(-30000,30000)},
{'char', j},
{'pop'},
{'lua', 'pdf.print(" Q ")'},
{'down', math.random(-30000,30000)},
{'special', 'pdf: ' .. gr .. ' g'},
{'char', j},
{'special','pdf: 0 g'}
}
end % end of for
return f
else
return original_fontloader(name, size, i)
end % end of if
end, % end of function
'define font'
)
}
\begin{document}
\font\myfont= cmtt10x at 12pt \myfont
\let\selectfont\relax
\section{Introduction}
ABCD one two theee four five
TTTTTTTooooooWWWWW
\begin{enumerate}
\item red yellow blue green
\item black blue purple
\end{enumerate}
\raggedleft
typeset by egreg design services
\end{document}
This emulates a really poor typewriter with dodgy print hammers that wobble and move around as each key is hit:-)
My ”tesi di laurea“ was typed with a much better typewriter.
Epic indentation is epic.
Man, had I been given an exam subject like this, I would have quit math. Oh wait, I did.
@egreg math added for you
MY THESIS WILL USE THIS.
@DavidCarlisle, is there a way to control how bad the typewriter is? I mean, egreg's design services has a really bad old typewriter, poorly maintained. But maybe carlisle's design services has an old one too, but a good one. ;)
@GuilhermeZanotelli yes see the arbitrary scale factors on the random number gen eg the rotation of one of the over-printed characters is r1 = 0.01*math.random(-10,10) make that 0.001* and you wil have a tenth of the angle in each case, while debugging I had it as 1* just to check something is happening (but you can't read it all then) similarly the two random numbers used for gray colour are set to arbitrary values. 0 is black 1 is white so you can limit the range and make that range blacker or whiter
@GuilhermeZanotelli my thesis (1985) was set on an IBM golfball typewriter so had no wobbly print hammers at all.
@DavidCarlisle -- are you saying the golf ball wasn't wobbly?
How to compile this? I tried it with lualtex, but it resulted in ! LuaTeX error [\directlua]:1: attempt to concatenate field '?' (a nil value)
stack traceback:
[\directlua]:1: in main chunk.
Sigh - looks great but I also can't get to run on my Windows machine. I get \myfont=cmtt10x at 12pt not loadable: metric data not found or bad. Thought that I had the computer modern fonts installed, but I also don't know how to confirm. Any help out there? (Running LuaTeX Version 0.95.0.)
Absolutely beautiful -- except superscript size needs to be the same as the text size.
@ScottSeidman see comment above, I had (access to) a fancy typewriter:-)
Got it! How about erasure smears and white-out outlines? I had the fancy white-out film that you typed on.
@DavidCarlisle I have tried it. Got different error this time: Font cmuntt.otf not found.' Looked online for a copy of this font, placed cmuntt.otfin the same directory as my file. Now I get the oldFont \myfont=cmtt10x at 12pt not loadableagain. I did back up into my log file and found I also have the commentattempt to index global 'f' (a nil value). ` error.
Not here - but my TL2015 apparently has luatex v0.80.0
@GregH answer updated with a version tested with luatex 0.95 as in public texlive 2016 .
@DavidCarlisle, will do though I'm away from that machine for the weekend and can't remember what versions I've got on my personal machines.
@DavidCarlisle -- I was able to typeset your top example with TL 2016 and current updates. Nice, typically devious, work. To my eye the minus sign and the horizontal rules for the square root look a little thin, though. :)
@musarithmia fix for that on the way:-)
@DavidCarlisle The update works for me, marked this as the "correct" answer, though would enjoy other's take, too. FWIW, commands such as \pi don't display for me (no errors, no blank space either) but I can copy/paste a pi symbol (from MS Word). This worked too for a theta, though capital Sigma for summations didn't render; \sum renders as a capital P. Overall: Well done & thanks!
@GregH \sum will work if you get the version from github as will all the greek commands \muppi from unicode-math
@DavidCarlisle How can one add characters that are affected by your code? I defined an "underline leader" to mimic underlining by repeatedly pressing "_", via \def\underlineleader{\leaders\hbox to .35em{\hss\_\hss}\hfill\ }. However, the lines are "too nice"; they are typeset regularly, rather than with the "typewriter." It would be fun to typeset all vertical & horizontal rules in a table in a similar fashion.
@GregH I'll add some more bits to the typewriter package on github. use \string_ not \_ see the version of \overline I put there already
@GregH package in github has support for tables and usual commands such as \alpha makes this output
@DavidCarlisle The tables are perfect. (I wonder if Knuth is chuckling "I created TeX to get away from this very look...")
@DavidCarlisle I tried the version from github which worked very well. My lualatex is 0.80.0.
@Julia thanks for letting me know:-)
The couple of minor tweaks that I would suggest, (remembering back to when it wasn't unusual to see internal exams prepared this way), would be that where Greek letters were made with over-typing, e.g. Theta would be 0- there was often variability of the (miss)alignment of the two components both vertically and horizontally. Bold was often attempted with double typing. Also some typewriters had a) some damaged hammers and poor paper alignment/retention. I love the effort that has gone into this!
Is there a way to simulate typewriter exponents that are full-sized characters typed on a line above?
@Evpok probably:-) (not today though)
I even discovered a typo.
Strangely, I can't compile a simple file with LuaTeX, Version 1.0.4 (TeX Live 2017) on Ubuntu 16.04. I have installed the oft versions of the fonts, run fc-cache -f -v and I still get the error Font \cmuntt=file:cmuntt.otf at 12pt not loadable: metric data not found or bad. \font\cmuntt = file:cmuntt.otf at 12pt \cmuntt. Suggestions as to what I should try?
@thymaro cmuntt.otf is the typewriter font from the Computer Modern Unicode collection. You need to install cmunicode in texlive or miktex, whichever you use.
hmm, the error persists, even after rebuilding formats and updating the fmdb. LuaLaTeX says the error is on line 28 in typewriter.sty \font\cmuntt = file:cmuntt.otf at 12pt \cmuntt
@thymaro it is nothing to do with the format, do you have cmuntt.otf installed? If you don't have it, luatex can not use it, it should be at a location such as /usr/local/texlive/2017/texmf-dist/fonts/opentype/public/cm-unicode/cmuntt.otf
that's exactly where I found it.
sorry can't really help (and comments under this question not a good format) make a simple luatex document using cmuntt.otf either directly or via fontspec (no need for the typewriter package) and if it doesn't load the font you could ask a new question about that with a log file etc that people can debug
I've taken the liberty of assigning better pretty-printing to the Lua code block. Feel free to revert.
@Mico That inserts code window breaks though
@percusse - What breaks?
@Mico Now the code is broken into 3 pieces
@Mico I think I'll revert, as percusse says this means you can't copy the text in one operation,
Is possible to introduce (micro)-randomness in common Computer Modern family? Small variations in serif for example and similar. I am not a typographer, but according to some university course on math typsetting, there is goood reason for using these imperfections. Unfortunately, I have never found any article about the topic. Are there any?
@JanFilip not yet but as support for the (new) opentype variable font features start to appear, then perhaps.
Is there a way how to get it when its released? I mean if there is some channel which I have to follow to get news about it?
@JanFilip you say "it" as if there was some specific thing, I just meant that someone could perhaps write something, so the same places as any tex news: here, the ctan-announce mailing list, etc
I am not used to LuaTex, but I love this font. Is it easy to port to / use within xetex?
@Tim no not possible at all, sorry, this is using Lua to programmatically distort the characters on each use
Thanks for your package! However, I have downloaded the newest version and \in, \sum, \subseteq, \oplus seems not to work. Would you do me a favor to add a minimal working example to these symbols?
| common-pile/stackexchange_filtered |
Customizing a UITableView with Searchbar
I have a TableView with a search bar. But I want to add another view (lets say a label) in to the TableView (so it scrolls with the tableview) . For an example, if you open iPhones Phone Contacts application, under All Numbers, you can see a lable called "My Number:". Which must be at the same hierarchical level as the searchbar. I tried to add a new label just above the search bar, but storyboards don't allow me to do that.
In here if I drag and drop a UILabel to this hierarchy it either replaces the searchbar at the top , or the label drops inside of the prototype cell. There is no other way of showing searchbar and Label both at once.
Is there any way of doing this?
Create a separate view outside the view controller's view (or inside, it doesn't matter. you can even create this programmatically) and link it to an IBOutlet myCustomView.
Create an IBOutlet searchBar and link your UISearchBar
in viewDidLoad; you can use
[searchBar addSubView:myCustomView];
and add your custom view above the search bar.
you can show/hide (myCustomView.hidden = YES / NO) the custom view or add and remove it from superview whenever you need.
ex.
- (IBAction)didTapShowCustomHeaderButton {
myCustomView.hidden = NO;
}
- (IBAction)didTapHideCustomHeaderButton {
myCustomView.hidden = YES;
}
add the below two delegates in the code
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)] autorelease];
label.text = @"My Label";
label.backgroundColor = [UIColor clearColor];
return label;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
return 30 // this height should be equivalent to the myLabel height u declared in headerView above
}
Hi thanks for the reply. But I need this label to go off the screen with the searchbar when scrolling the table down.
where exactly do ya want it..i supposed you need it as a part of tableview
I need to hide the searchbar at runtime and display another UIcontrol when searchbar is hidden. In order to do this I think I have to add that other UIcontrol to the place where searchbar is exactly positioned (hierarchically)
| common-pile/stackexchange_filtered |
C++ Postfix Calculator not working with 2 operands in a row
Hello I have written a postfix calculator using vectors (which is required) and have run into trouble. When I enter two operands in a row, it won't give the correct answer. For example, "5 4 + 3 10 * +" gives the answer "36" when it should give 39. I understand why it isn't working I just can't think of a way to do it where it handles that case. Can someone give me a hand?
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
//splits the string into different parts seperated by space and stores in tokens
void SplitString(string s, char delim, vector<string> &tokens)
{
stringstream ss;
ss.str(s);
string item;
while(getline(ss, item, delim))
{
tokens.push_back(item);
}
}
//preforms the operation denoted by the operand
void operation(string operand, vector<int> &eqVec)
{
int temp1 = eqVec.at(0);
int temp2 = eqVec.at(1);
if(operand == "+")
{
eqVec.push_back(temp1 + temp2);
}
else if(operand == "-")
{
eqVec.push_back(temp1 - temp2);
}
else if(operand == "*")
{
eqVec.push_back(temp1 * temp2);
}
else if(operand == "/")
{
eqVec.push_back(temp1 / temp2);
}
}
int main()
{
const char DELIM = ' ';
int total;
string eq;
vector <int> eqVec;
vector<string> tokens;
cout<<"Welcome to the postfix calculator! " << endl;
cout<<"Please enter your equation: ";
//gets the input and splits into tokens
getline(cin, eq);
SplitString(eq, DELIM, tokens);
//cycles through tokens
for(int i = 0; i < tokens.size(); ++i)
{
//calls operation when an operand is encountered
if(tokens.at(i) == "+" || tokens.at(i) == "-" || tokens.at(i) == "*" || tokens.at(i) == "/")
{
operation(tokens.at(i), eqVec);
}
//otherwise, stores the number into next slot of eqVec
else
{
//turns tokens into an int to put in eqVec
int temp = stoi(tokens.at(i));
eqVec.push_back(temp);
}
}
//prints out only remaining variable in eqVec, the total
cout<<"The answer is: " << eqVec.at(0) << endl;
return 0;
}
I just can't think of a way to do it where it handles that case -- You should have first created a plan to handle these cases before writing any code. What can wind up happening is that you've coded yourself "into a corner" that would require a total rewrite.
After taking a break and coming back I found a way to solve it. Posting here in case anyone in the future has the same problem. The following block of code is now at the beginning of the operation function before the series of if statements.
int temp1, temp2;
int size = eqVec.size();
if(size > 2)
{
temp1 = eqVec.at(size - 1);
temp2 = eqVec.at(size - 2);
eqVec.pop_back();
eqVec.pop_back();
}
else
{
temp1 = eqVec.at(0);
temp2 = eqVec.at(1);
eqVec.pop_back();
eqVec.pop_back();
}
| common-pile/stackexchange_filtered |
how to create and make a custom.css file work
I need to create custom.css file using local.xml. I tried adding this command
<action method="addCss"><stylesheet>css/custom.css></stylesheet></action> to local.xml file but it doesn't do anything, I can't edit my page. I'm not even sure where the custom.css saves. Could somone tell me the steps to do this with paths to the files?
What @kothari posted will work, but since I can't comment on his answer, I'll answer your question about where it looks for it here.
Basically what this does:
<default>
<reference name="head">
<action method="addCss"><stylesheet>css/custom.css</stylesheet></action>
</reference>
</default>
Is it tells Magento to add the CSS in this file path:
http://yourwebsite.com/skin/frontend/$package/$theme/css/custom.css
$package and $theme referring to the active package and theme. For example, if you're using the default base theme, this would resolve to:
http://yourwebsite.com/skin/frontend/base/default/css/custom.css
It does NOT create the CSS file for you, you have to create that CSS file and add it to that folder.
Try this, in your local.xml
<default>
<reference name="head">
<action method="addCss"><stylesheet>css/custom.css</stylesheet></action>
</reference>
</default>
Thank you, but I can't find it. Do I need to create it? and if so whats the path?
First check page source it will call or not
Adding new CSS
<theme-dir>/blank/layout/default_head_blocks.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="css/newtheme.css" />
</head>
</page>
Remove static resources (JavaScript, CSS, fonts)
To remove the static resources, linked in a page , make a change similar to the following in a theme extending file
app/design/frontend///Magento_Theme/layout/default_head_blocks.xml
<head>
<!-- Remove local resources -->
<remove src="css/styles-m.css" />
<remove src="my-js.js"/>
<remove src="Magento_Catalog::js/compare.js" />
<!-- Remove external resources -->
<remove src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"/>
<remove src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"/>
<remove src="http://fonts.googleapis.com/css?family=Montserrat" />
http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-manage.html#layout_markup_css_remove
the question is for M1.9 but your answer is for M2
| common-pile/stackexchange_filtered |
how to disable all smileys and char combinations in teams?
MS Teams was selected as a communication tool in our company. We do post code into it. And that code contains asterisks, underscores and even numbers! I understand it's business critical feature, but will never, ever, ever need smiley face, smiley face with sunglasses, or part of my code arbitrarily missing stars/underscores and get arbitrarily boldened/empahsized. Even if I write message as code, the asterisks still mingles the text.
Is it somehow possible to turn all these off? Settings or some message header? To send message 'as it was written', without any teenage beautifications?
UPDATE: regarding pressing > to enter verbatim text:
I entered "does not", shift enter, then "really work", go up and created section for text supposed to be verbatim. It really does not work. Then I tried to start immediately with "> " and it equally does not work. On 3rd attempt I noticed some glitching, as I was able to enter bold text, but smiley face did not replace :) To conclude, I'd say "> " unlocks new layer of MS Teams instability and bugs, but cannot be used to enter verbatim text.
If you just need a simple code block, you can send text as code by starting the line with > (enter > then press Space).
Typing in this code block will still replace matching patterns with smilies/emoji, but pasting will not. You should be able to paste your code without issue.
Press Enter twice to escape the code block.
Formatting is retained after sending the message (including leading whitespace which would have been stripped without the code block).
If you need more advanced features, there's a code snippet button hidden in the advanced editor.
After clicking the code snippet button, a modal will open.
You can name the snippet, choose whether or not to wrap text in the snippet, and pick a language to provide highlighting in the snippet. Under these options is a field to paste your code.
Once you finish setting up the snippet, click the Insert button to add the snippet to the current message. You can continue editing the message.
Click the "Send Message" (arrow) button as normal to send the message.
Click the "Expand Preview" link to show the whole code block with the chosen language syntax applied.
Sorry, does not work. See update.
fair enough, so it works for pasting, but not for typing. Meaning if you're writing the code from top of your head, it will get mingled in this code block as well as without it. Especialy if you use ` it will become ugly. Then it's actually not that useful, because if you're typing and not pasting, you have to open external editor and write it there. If you copy-paste this, even without code block, it will be treated as literals. :) won't become smiley, not bold formatting etc. So workaround: create script,which lauches dialog to enter text and does copy paste to teams on exit. Shameful,works.
@MartinMucha I found another feature and have added it to the answer
| common-pile/stackexchange_filtered |
Timezone Datetime with offset in php , getting it easy
I have timestamp from specific timezone (Jamaica) and i want to get GMT timestamp of it. Is there more elegant solution than this one :
$start = DateTime::createFromFormat('U',<PHONE_NUMBER>);
$start->setTimezone(new DateTimeZone('America/Jamaica'));
$start->format('Y-m-d H:i:s');//2012-02-29 19:00:00 NO NO NO
$tz = new DateTimeZone( 'America/Jamaica' );
$transition = $tz->getTransitions($start->getTimestamp(),$start->getTimestamp());
$offset = $transition[0]['offset'];
$start = DateTime::createFromFormat('U', $params['start'] - 2*$transition[0]['offset']);
$start->setTimezone(new DateTimeZone('America/Jamaica'));
$start->format('Y-m-d H:i:s'); // "2012-03-01 05:00:00" YESSSS!!!
Timestamps are invariant across timezones. Specifically,<PHONE_NUMBER> is 2012-03-01 00:00:00 UTC. If that's not the time you want, the code that produced this timestamp is buggy.
@Jon<PHONE_NUMBER> is Jamaican( or any other time zone with | without DST ) time and I need UTC time ( 2012-03-01 05:00:00)
@user1222955: No,<PHONE_NUMBER> is not "Jamaican time". It is a specific moment in time, which is 00:00:00 in UTC and 2012-02-29 19:00:00 in Jamaica (obvious, UTC-5). What PHP does here is correct; it's your expectations that are wrong. If the result that should be reached is the one you expect, the code that produced the timestamp is also wrong.
Can you help me write function that somehow assume that is actually 2012-03-01 00:00:00 Jamaican time and that it need be converted to UTC, 2012-03-01 05:00:00?
This is a part of my class that create a well-formatted time stamp as I wrote in the comment of the function, it's very easy to use just pass the string of the date, time zone and the identifier.
Hope it helps you
/**
* Default timestamp format for formatted_time
* @var string
*/
public static $timestamp_format = 'Y-m-d H:i:s';
/**
* Returns a date/time string with the specified timestamp format
* @example $time = Date::formatted_time('5 minutes ago');
* @link http://www.php.net/manual/datetime.construct
* @param string $datetime_str datetime string
* @param string $timestamp_format timestamp format
* @param string $timezone timezone identifier
* @return string
*/
public static function formatted_time($datetime_str = 'now', $timestamp_format = NULL, $timezone = NULL){
$timestamp_format = ($timestamp_format == NULL) ? Date::$timestamp_format : $timestamp_format;
$timezone = ($timezone === NULL) ? Date::$timezone : $timezone;
$tz = new DateTimeZone($timezone ? $timezone : date_default_timezone_get());
$time = new DateTime($datetime_str, $tz);
if ($time->getTimeZone()->getName() !== $tz->getName()){
$time->setTimeZone($tz);
}
return $time->format($timestamp_format);
}
Unix time, or POSIX time, is a system for describing instances in time, defined as the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970.
source Wikipedia
The idea of the UNIX timestamp is that it is always in UTC (everywhere in the world xD ). If it does not represents the time in UTC it's not a UNIX timestamp anymore
thanks for clarification. Ok, so<PHONE_NUMBER> is jamaican time , not UTC. I want UTC
@user1222955 It IS UTC, not jamaican. Just set GMT time zone and then format your DateTime. In script you posted change line 2 to $start->setTimezone(new DateTimeZone('GMT'));, and delete that ... whatever that is after line 4. DateTime::format() formats time for current timezone that is set for it. So if you want it to print GMT time - feed it with GMT DateTimeZone. Want it jamaican again - set timezone back to jamaica. And timestamp is always UTC, it's equal in whole world unless your clock is set wrong.
| common-pile/stackexchange_filtered |
Find the next date based on Interval (month/quaterly)
CREATE TABLE @Temp(
Date datetime,
Flag bit)
@Temp table as data from 01-04-2019 to 31-04-2020 (366 records) and flag=0
DECLARE startdate date='12-04-2019', interval int =1 OR 3
Expected Result: If interval is 1 month, based on startdate, flag to be updated as 1 below records and rest for 0
date flag
01-04-2019 0
. 0
. 0
12-05-2019 1
. 0
. 0
12-06-2019 1
. 0
. 0
12-07-2019 1
.. 0
31-04-2020 0
If interval is 3 month, flag to be updated as 1 for quarter
date flag
01-04-2019 0
. 0
. 0
12-07-2019 1
. 0
. 0
12-10-2019 1
. 0
. 0
12-01-2020 1
. 0
31-04-2020 0
I am stuck trying get the result. I am using SQL Server 2017.
Took me awhile to realize that your dates were in different format than I'm used to.
I would go with a common table expression as opposed to a cursor. Besides that, consider the month difference between any given date and the start date. Take the modulo of that difference (that's what the '%' symbol is). If it's 0, then your interval has been hit and so activate your flag.
declare
@startdate date = '04.01.2019',
@interval int = 3; -- or 1, or whatever
with
dates as (
select @startdate dt, 1 flag
union all
select ap.nextDt,
flag =
case
when day(ap.nextDt) <> day(@startdate) then 0
when (month(ap.nextDt) - month(@startdate)) % @interval = 0 then 1
else 0
end
from dates
cross apply (select nextDt = dateadd(day,1,dt)) ap
where dt <= dateadd(year,1,@startdate)
)
select *
from dates
option (maxrecursion 367)
if i give startdate date as '31.01.2019' , in feb month ther is no 31 so is it possible to set flag for month end date i.e 29th and same for April month is 30 th & soon..
Making a flag out of it in your situation will have some complexities. Like, if you enter '28.01.2019', '29.01.2019', '30.01.2019', or '31.01.2019', is your program supposed to pick up on the fact that it should output the last day of february? Sounds like you're going to put in a lot of work for this requirement. Is it worth it? In general, you can find the month end date via eomonth or dateadd(day, -1, firstdayofnextmonth). If you do decide to attempt to implement this flag and get stuck and then ask another question (showing what you've tried). It's too much for the comments.
| common-pile/stackexchange_filtered |
Why does Windows 10 add files to the desktop in columns, but selects files in rows?
When I save files to the Desktop, it automatically stacks them in columns. Meaning, each added file is placed underneath the previous until it reaches the bottom. Then it wraps, and starts stacking files in a new column.
When selecting files using the keyboard, files get selected in rows. For example, if you have 5 columns of files, select (single-click) a file in the bottom of the last column, then on the keyboard press Shift+Up, it will highlight not just the file above, but the entire row beneath it.
Since files get added in columns, I expected the selection to follow the columns, meaning Shift+Up in the previous scenario would only add the above file to the selection. I can't imagine why the current way would make sense. I feel like this is bad design.
Is this bad design, or is there a UX principle behind this decision?
Is there somewhere else this behavior can be seen?
(I checked MacOS (Catalina), and using Shift and arrows keys just selects individual files in the direction of the arrow keys you press; it doesn't attempt to select rows nor columns.)
I run into this regularly because I've set my browser to download files directly to the Desktop. So imagine downloading 3 files, they are stacked vertically on the Desktop. Then a few days later, you're done with those files, so you select the last file, Shift+Up+Up, Delete, and boom you just deleted potentially 20 files...
There are a lot of questions about Windows in UXSE but often the only way to get the answer for this is if someone who worked on the design can explain it. But I am curious as to what the community thinks.
| common-pile/stackexchange_filtered |
Why do M_PI_2, M_PI_4, M_1_PI, and M_2_PI exist?
I do understand why we have this in standard headers:
#define M_PI 3.14159265358979323846 // pi
However, I don't see much benefit in having these:
#define M_PI_2 1.57079632679489661923 // pi/2
#define M_PI_4 0.785398163397448309616 // pi/4
#define M_1_PI 0.318309886183790671538 // 1/pi
#define M_2_PI 0.636619772367581343076 // 2/pi
Is there any advantage in using these instead of M_PI/2, M_PI/4, 1/M_PI and 2/M_PI in actual code? (In 2020 and beyond?)
Aren't the spelled-out expressions much more readable?
I'm asking for a couple of reasons really.
Firstly, one day I accidentally mixed up M_PI_2 and M_2_PI (and maybe even 2 * M_PI). Took a while to figure out something was wrong, and after that took another while to find out what exactly was the root cause. Still think it's not super obvious what M_PI_2 and M_2_PI mean, if you are just reading code using them and don't see the definitions. And why should I memorize something like that? So, is it safe to say that using these definitions is actually an anti-pattern that degrades code readability?
Secondly, having these definitions available may still be an issue, e.g. in Windows (Visual C++). Instead of defining all these, I'd prefer to define only M_PI, and then say M_PI/2 and not M_PI_2 in the code. Is there something I'm missing?
You'll lose precision if you calculate them arithmetically.
None of these constants are part of the C or C++ standards. Rather they are part of the POSIX standard. In case of C++, starting with C++20, these constants will be standardized in std::numbers (at least pi and 1/pi).
Because 2 and 4 are powers of two, M_PI_2 and M_PI_4 really are redundant and 100% equivalent to M_PI/2 and M_PI/4. However, M_1_PI is not necessarily equivalent to 1/M_PI; the latter has two roundings (approximation of pi, then inexact division) rather than just one (approximation of 1/pi).
M_PI_4 != M_PI / 4, M_PI / 4 == 0.785398163397448309615
M_PI_2 and M_PI_4 are redundant if FLT_RADIX is 2. But it is not required to be 2, and the prevalence of other radices may have been more of a consideration when they were created.
@AlanBirtles: In any implementation with FLT_RADIX == 2, the resolved value for M_PI_4 should equal the resolved value for M_PI / 4, even if the numerals used to define them do not satisfy that property. In other words, they may be defined using some strings of decimal numerals that are sufficient to specify the desired binary floating-point values, but those two strings might not be such that their decimal numbers are in the ratio 4:1.
@AlanBirtles: What Eric said. You have to look at the actual floating point values they round to, not the decimal strings, to check equality.
The reasoning in this answer is also used by the proposal introducing mathematical constants to C++20 in std::numbers to not include equivalents of M_PI_2 and M_PI_4, see P0631.
Is M_2_PI redundant as well, being equal to 2*M_1_PI? I think we'd be better off without M_2_PI, as it looks extremely easy to misinterpret (and misuse) as 2π.
| common-pile/stackexchange_filtered |
How do I set the height (width) of vertically set column headers in a datagrid?
I am using this code for my DataGrid:
<DataGrid
Grid.Row="1"
Name="myDataGrid"
SelectedItem="{Binding chosenReport, Mode=TwoWay}"
ItemsSource="{Binding Reports, Mode=TwoWay}"
IsReadOnly="True"
FontSize="14"
AutoGenerateColumns="False">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="LayoutTransform">
<Setter.Value>
<RotateTransform Angle="270" />
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Field 1. Bla blabla blabla blabla blabla blablablabla blablablabla blabla" Binding="{Binding Path=Field1}" />
<DataGridTextColumn Header="Field 2. Bla blabla blabla blabla blabla blablablabla blablablabla blabla Bla blabla blabla blabla blabla blablablabla blablablabla blabla" Binding="{Binding Path=Field2}" />
<DataGridTextColumn Header="Field 3. Bla blabla blabla blabla blabla blablablabla blablablabla blabla tralalaalalalaal" Binding="{Binding Path=Field3}" />
<DataGrid.Columns/>
<DataGrid/>
Yes, it works and it shows all DataGrid fields vertically. However, since the text in the column headers are quite long, I don't see the data in the datagrid, because it is covered with text from the headers.
How can I tell the DataGrid to make some sort of word wrap to put the text in each column header in several "vertical rows"?
Or maybe there is height(width) of the column header?
Use a content template to put the text in a TextBlock with text wrapping, and then limit the width and rotate the whole thing 270 degrees:
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid MaxWidth="160">
<Grid.LayoutTransform>
<RotateTransform Angle="270" />
</Grid.LayoutTransform>
<TextBlock
TextWrapping="WrapWithOverflow"
Text="{Binding}"
/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
UPDATE
Add this to the grid if your users have a limited attention span, or if you just don't like them very much:
<Grid.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
From="0"
To="270"
Duration="0:0:2"
DecelerationRatio=".9"
Storyboard.TargetProperty="LayoutTransform.Angle"
/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
Lol!! Funny effect. But I it might be useful to turn from 270 back to 0 degrees and get back to 270 after the mouse is away from the column header :)
| common-pile/stackexchange_filtered |
Can't get my ZF2 application to work on a shared server
After developing my Zend Framework 2 website in local, I just bought a hosting and deployed it, but can't get it to work!
First of all, my hosting service doesn't allow me to use the public folder as root, so I found this solution (adding an index.php to the root that includes the public/index.php, and an .htaccess that redirects everything to it):
ZF on shared host
I tested it in local, and works great, and I can access it from both mysite.loc and mysite.loc/public
However, on remote it doesn't work, and looks like it can't find the classes:
Fatal error: Class 'Zend\MVC\Controller\AbstractActionController' not found in /web/htdocs/www.mysite.com/home/module/Cycling/src/MyModule/Controller/IndexController.php on line 8
I'm getting crazy and really need some help, what could be the problem if even from root it works in local?
Zend\MVC\Controller\AbstractActionController is not the correct class name, it should be Zend\Mvc\Controller\AbstractActionController (note the case of 'Mvc'). I'm guessing you developed the site on a case-insensitive file system (such as OS X or Windows), which is why you are only seeing this problem on your shared server.
Seriously, that was driving me crazy, and I would have never find that out! Thanks a lot!!
| common-pile/stackexchange_filtered |
Error constructing an Object from a custom C++ Library in Arduino
I attempted to compile this Arduino sketch with a custom library in it (jtaServoController), and the Arduino IDE claims that my constructor in the Arduino sketch was written incorrectly (more precisely, 'jtaServoControllerFour' does not name a type).
#include <jtaServoController.h>
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);
#define SERVOMIN 0
#define SERVOMAX 600
jtaServoControllerFour pointerFinger(1,2,3,4); //line in question
void setup() {
Serial.begin(9600);
pwm1.begin();
pwm1.setPWMFreq(60);
}
void loop() {
pointerFinger.jtaSetPWMFour(300,400,500,600);
}
My Question is whether the line in question actually is written wrong or is there an issue in another part of my code?-probably in the library itself which I have below. (btw I found the information for constructing an object in the Arduino tutorial on libraries).
These are the Header and .cpp files respectively:
#ifndef jtaServoController_h
#define jtaServoController_h
#include "Wire.h"
#include "Adafruit_PWMServoDriver.h"
#include "Arduino.h"
class jtaServoControllerFour
{
public:
jtaServoControllerFour(int servo1, int servo2, int servo3, int servo4);
void jtaSetPWMFour(unsigned int servo41, unsigned int servo42, unsigned int servo43, unsigned int servo44);
private:
int _servoOne;
int _servoTwo;
int _servoThree;
int _servoFour;
};
#endif
CPP file
#include "Arduino.h"
#include "jtaServoController.h"
#include "Adafruit_PWMServoDriver.h"
#include "Wire.h"
jtaServoControllerFour::jtaServoControllerFour(int servoOne, int servoTwo, int servoThree, int servoFour)
{
_servoOne = servoOne;
_servoTwo = servoTwo;
_servoThree = servoThree;
_servoFour = servoFour;
}
void jtaServoControllerFour::jtaSetPWMFour(int servoFourOne, int servoFourTwo, int servoFourThree, int servoFourFour)
{
pwm1.setPWM(_servo1, 0, servoFourOne);
pwm1.setPWM(_servo2, 0, servoFourTwo);
pwm1.setPWM(_servo3, 0, servoFourThree);
pwm1.setPWM(_servo4, 0, servoFourFour);
return;
}
#include <jtaServoController.h>
You may need to use the following instead (double quotes):
#include "jtaServoController.h"
And/or check the path to your header file.
See here for the difference between the two.
| common-pile/stackexchange_filtered |
Can it be defined as inner product of two vectors?
I have formulated something like
For $V_n$ where ${\bf x}=(x_1,x_2,x_3, \ldots,x_n)$, ${\bf y}=(y_1,y_2,y_3,\ldots,y_n)$
and I define ${\bf x} \cdot {\bf y}$ to be $(x_1+x_2+x_3+ \cdots+x_n)(y_1+y_2+y_3+\cdots+y_n)$
it seems like it works for all four axioms.
Is there mistake here?
$\def\\#1{{\bf#1}}$An inner product should have the property that if $\\x\cdot\\x=0$ then $\\x=\\0$. This is not true for your example (except in the case $n=1$). For example, if $\\x=(1,-1,0,0,\ldots)$, then
$$\\x\cdot\\x=(1-1+0+\cdots)(1-1+0+\cdots)=0\ ,$$
but $\\x\ne\\0$.
when x=0, you are meaning that x=(<IP_ADDRESS>.0...0) for all xi where i->n ?
Yes, the zero vector, all components zero.
david, one more thing. What I have to do is define inner product and see whether it violates axioms in my book, where there are four axioms. 1. (x.y)=(y.x) 2.(x.y+z)=(x.y)+(x.z) 3. c(x.y)=(cx.y) 5 (x.x)>0 if x is not 0 . But, there is no such axiom that u mentioned in my book.
and besides that, does my definition satisfy 1,2,3 axioms that I just mentioned above?
oh my god so stupid I understand what you mean by that
Your definition seems to be OK for axioms 1,2,3. The property I stated is just another way of saying your 4th axiom.
Thanks, May god bless your family and you and i love you
| common-pile/stackexchange_filtered |
WSO2: Configuring xml multiple in a single project
I am using WSO2 ESB 6.5.0.
In the WSO2HOME/conf/synapse.properties I set property
synapse.commons.json.output.xmloutMultiplePI=true
for set the XML output to an xml-multiple processing instruction in XML to JSON transformations. (As this says )
This works fine, but In my WSO2 EI I have many Carbon Applications (CARs) and I need to apply this configuration only for a specific car, not to all because I have projects that stop working properly.
I know that all the properties set in synapse.properties will apply globally.
Is there a way to configure xml-multiple in a single project/sequence?
| common-pile/stackexchange_filtered |
SQL - How do I calculate the sum only for distinct rows of another column?
I have a table with covid data containing a lot of different data entries. Each row has the Country, Continent, Population and different data which is not relevant for this.
I want to simply calculate the population per CONTINENT, but I can't figure out how.
Continent
Country
Population
...
Europe
Bulgaria
690.000
Europe
Bulgaria
690.000
Europe
Bulgaria
690.000
America
Brazil
212.000.000
America
Brazil
212.000.000
America
Brazil
212.000.000
America
Brazil
212.000.000
...
...
...
SELECT distinct country, continent, SUM(population) as TotalPopulation
FROM PortfolioProject..CovidDeaths
GROUP by continent
This is what I tried before but it produces an error: Column 'PortfolioProject..CovidDeaths.location' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
And this code snippet sums up each row of a country. Therefore the continent populations are ridiculously high.
SELECT continent, SUM(population) as TotalPopulation
From PortfolioProject..CovidDeaths
GROUP by continent
Can somebody help me?
A DISTINCT with a GROUP BY is always a sign of a flaw in your query. A GROUP BY already causes your data to be returned in distinct sets, so if you are getting duplicates, it likely means your GROUP BY is wrong. Otherwise the DISTINCT is redundant and unneeded overhead. What you actually want here, however, is a windowed SUM; so there should be no GROUP BY at all.
Also note that syntax like DatabaseName..ObjectName is not recommended. Don't rely on the default schema, be explicit and define the schema you want. Also, as you're only querying one table, do you need to use 3 part naming? Why not connect to the PortfolioProject database and then just include the schema and table (presumably dbo.CovidDeaths).
Remove the duplicate rows - that is the source of your problem. Alternatively, you remove the duplicates BEFORE you sum, not AFTER.
@Larnu Thanks for the help! I wasn't aware that PortfolioProject.dbo.CovidDeaths was the recommended way of putting it.
And I didn't really understand what you mean with "do you need to use 3 part naming?"
3 part naming means literally what it sounds like, using 3 parts for the name; in this case database name, schema name, object name. Do you really need the database name? Why are you not connected to the database PortfolioProject?
Thanks! I changed the naming into FROM PortfolioProject.dbo.CovidDeaths now.
That data probably also contains a column that indicates when the population total was reported.
In that case you'd want the latest reported population totals for the countries.
So let's assume there's such a date column named "ReportedAt"
Then you can use ROW_NUMBER to get the latest record per country.
And then aggregate for the continent.
SELECT continent, SUM(population) AS TotalPopulation
FROM
(
SELECT country, continent, population
, rn = ROW_NUMBER() OVER (PARTITION BY country ORDER BY ReportedAt DESC)
FROM PortfolioProject..CovidDeaths
) q
WHERE rn = 1
GROUP BY continent
ORDER BY continent;
Good spot. Though just to be extra cautious, you may want to partition by continent as well. Otherwise, the results would drop countries that appeared under multiple continents for some reason (like a typo).
@SOS Well, but then those populations would be counted to much? So I'll keep my solution as is. The OP also sees your comment, so he can check if that's needed or not. Thanks for warning.
No, it's counting the data as it actually exists. If the base data is corrupted, that's a different problem altogether. One that needs to be solved, yes, but it's not the job of this query to do that IMO. So respectfully, I disagree with omitting it, but we'll agree to disagree (-:
Thank you very much! I didn't have a column with information of ReportedAt, however it is also not necessary. The population is the same for every row of the partition.
Finally, this was the solution which made my query work:
SELECT continent, SUM(population) AS TotalPopulation
FROM
(
SELECT location, continent, population
, rn=ROW_NUMBER() OVER (PARTITION BY location ORDER BY location)
FROM PortfolioProject.dbo.CovidDeaths
) q
WHERE rn = 1 AND continent IS NOT NULL
GROUP BY continent
However, I am still wondering, what the letter "q" is doing?
In Sql Server a sub-query is required to have an alias name. 'q' is just the first letter of the word 'query'
| common-pile/stackexchange_filtered |
Mechanize visit a link and get page title
I am using mechanize to scrape some data. Unfortunately I can't seem to get it to visit the link and get the page title of the visited page.
here is my task:
task :estimateone => :environment do
require 'mechanize'
mechanize = Mechanize.new
page = mechanize.get('https://www.city.com/city/list/50-city-cafes-you-should-have-eaten-breakfast-at')
page.css('ol li a').each do |link|
mechanize.click(link).each do |property|
puts property.title
end
end
end
After clicking on the link, you don't need the block, you're already in a block, iterating over each anchor you found in your "main" URL.
If you click any link, it returns you the page it points to (anchor's href). You can see this inspecting what's on your mechanize variable after that:
page.css(<selector>).each do |link|
mechanize.click(link)
mechanize
=> #<Mechanize
...
#<Mechanize::Page
{url #<URI::HTTPS https://www.theurbanlist.com/brisbane/directory/scout-cafe>}
{meta_refresh}
{title "Scout Cafe, Petrie Terrace | Brisbane | The Urban List"}
{iframes
There you are. Mechanize handles for you now the data belonging to the current page. So now you're able to, through mechanize, using its page method, access its title and all others:
page.css('div[itemprop="articleBody"] ol li a').each do |link|
mechanize.click(link)
puts "Title: #{mechanize.page.title}"
end
Title: Scout Cafe, Petrie Terrace | Brisbane | The Urban List
Title: Southside Tea Room | Brisbane | The Urban List
Title: Spring Hill Deli Cafe, Spring Hill | Brisbane | The Urban List
Notice the use of the itemprop attribute isn't really needed, but I recommend you to add more specific CSS rules/selectors to make the elements easy to recognize.
| common-pile/stackexchange_filtered |
removing numbers from a list python
Trying to create a function which removes odd numbers. When I run this code, it prints out only [2,3,4,5,6,7,8,9]. Is this because the return is cancelling my loop after the first iteration? If so, how can I modify this to run the loop and print out a list with all the odd numbers removed?
def evens(numbers):
for i in range(len(numbers)):
if numbers[i] % 2 != 0:
del numbers[i]
return numbers
numberlist = [1,2,3,4,5,6,7,8,9]
print evens(numberlist)
Before you all jump to downvoting me for a repeated question... I'm asking why my particular code is broken. And this has uncovered an interesting trip-up which is that using the del method in a loop means you actually need to iterate in reverse.
Indeed, you return after the first loop, change the indentation of the return statement to be one tab less. Further, you should iterate from the end of the list back to the beginning, in order not to run out of range because you're modifying the list (deleting elements) while iterating it.
Modify:
def evens(numbers):
for i in range(len(numbers), 0):
if numbers[i] % 2 != 0:
del numbers[i]
return numbers
to:
def evens(numbers):
for i in range(len(numbers)-1, -1, -1): # <-- change the iteration from end to beginning, in order not to run out of index range
if numbers[i] % 2 != 0:
del numbers[i]
return numbers # <-- change in indentation
OUTPUT
[2, 4, 6, 8]
In fact, you have to iterate in reverse order. Otherwise the del statement will break the intended iteration order.
Yes i thought that would be a fix, but then I get a list index out of range error??
Good catch @HuazuoGao - fixed!
@Dude see the changes above.
I'm trying to get my head around how the del statement breaks the iteration order.. can someone help explain that to me? Thanks
@Dude by removing elements you're shortening the list. If you deleted index 7, now index 8 becomes index 7. Which means that when you iterate from zero to the full length and delete elements you'll get index out of bounds error. The way to work around it is start from the end, if you delete index 8 and move on backwards - index 7 will not get affected.
ah so the range length stays locked as the original list length, and doesnt become updated to a smaller range as each iteration removes a value?
@Dude not that "it stays locked" but rather: since you go backwards deleting keys will not change the indexes of elements that you'll iterate in the future. Try to run manually a small example (say, list of 3 elements).
Thanks @alfasin yeh I've tried running a few on paper and I just find that as elements are deleted from the list, the list range also decreases (thus decreasing the amount of iterations in the for loop) and therefore it shouldn't be trying to access indexes which are beyond the loop range. Anyway, must be doing something wrong.. I dont expect you to explain this to me any further!
so just to answer my own question for anyone who cares, Ive read that the range of the for loop is created based on the value of the range AT THE TIME IT IS CALLED --anything that happens to the range afterwards is irrelevant.
@Dude sorry I thought that it's obvious... otherwise, how would you get out of bound index error ? ;)
ha yeh it is obvious, but I wanted to know WHY, because the range appeared to contain a value which was variable - i.e len(numbers), but in fact this is a situation where changing the variable won't affect the loop. It also appears there are ways to mutate the range of a for loop during the loop, but that is more complex.
@Dude AFAIK you cannot "mutate the range of a for loop" while running, if you know a way to do it I'd appreciate a link!
http://stackoverflow.com/questions/11905606/changing-the-number-of-iterations-in-a-for-loop some complex stuff towards the bottom of the page that my newb brain doesnt understand
@Dude if you're referring to this example then it's not a for-loop and it doesn't use range. If you were referring to this answer then pay attention that the loop doesn't use the range - once a range was created - it will not change!
yeh i understand those are while loops, I was referring to the stuff further down that page, but honestly its too complex for me to bother with right now.
| common-pile/stackexchange_filtered |
Share HTML content between pages
I'm sure this is an FAQ and probably answered many times on Google but I'm struggling to work out what to search on.
I want to write a bit of HTML on one page and then include a reference to the same HTML on another page. The pages will be in different sites but the same site collection. The requirement is a master "Hints & tips" page which contains thinks like this (although typically the tip will be longer like a paragraph):
Use www.tinyurl.com to shorten long links
Ctrl-0 resets zoom to 100% in Internet Explorer
Ctrl-F5 completely refreshes the page
When a new tip is added, the web master might want to put a copy on the home page as "tip of the day". I don't want to duplicate the text, I want to reference the HTML on the master hints & tip page.
I'm very familiar with DotNetNuke and this is bread & butter functionality in there. You simply insert a reference to an existing HTML module.
Maybe web parts are the solution here but not sure if you can reference on web part in one site from another site. It's a publishing web site BTW.
What you are looking for is called "Reusable content". The following links will help you on your journey to wisdom:
Use reusable content
SharePoint Reusable Content
SharePoint 2010 Reusable Content
Bear in mind that Reusable Content is only meant for HTML content or other content and can only be used on certain pages - just give it a go and see whether it fulfills your needs.
Thanks - for me the problem went away by me moving on from the company but thanks for the reply. I can't mark it as the correct answer as I'm unable to clarify but it sounds like it's barking up the right tree
Apart from Re-usable content you can use a Content Editor WebPart (CEWP)
Do not put any Content in it, but set the reference Link, it will execute the HTML (including script tags> from that file inline... depending on what to do you may want to wait till everything is loaded
Content needs to come from an accesible location, so can span Site Collections.
You can call scripts from another domain, provided you have tackled all the CORS issues.
I can't vote for the answer but I planned to answer the same thing before reading moontear's post.
Reusable content is a powerful function and I used it at large for a big SP project, it did the job !
| common-pile/stackexchange_filtered |
MacBook won't eject DVD on bootup
I'm trying to do a fresh install of OSX on a new hard drive and the MacBook keeps ejecting the installation DVD. To see if the dvd reader has the problem itself, I tried another random dvd. The problem is it didn't get ejected and now I'm stuck because holding down the eject button doesn't eject it. I can hear that it is being read though.. since the hard drive is new, there is no OS in it so I'm stuck with the blinking question mark upon bootup and I can't also eject the random dvd i put in.
Any ideas what to do?
Okay, I decided to just take the plunge and took it apart.. After opening the optical drive itself, the DVD seems to have been lodged badly so that's how I got it out.
Thank you for the question and answer. Can you expand on 'lodged badly'? Did the installation disc work once you got the other disc out?
Well it seemed the optical drive tried closing the the cover even if the disc was only 75% inside the drive. So it pretty much held the disc in place and started trying to read it. That disc had quite a lot of scratches when I got it out. Horrible stuff. And yeah, the installation disc worked after I took apart the optical drive.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.