text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
What data structure fits this description?
I need a data structure that holds unique values (like a set), but also sorts them (like a priority queue) and allows random access for binary searching (like an array). Which type of data structure would fit these needs? I could live without the sorting (I can always sort it myself at the end)
That sounds like a balanced binary tree, with a restriction of uniqueness in its insert operation, and implementing the OS-SELECT operation (see: Introduction to Algorithms, chapter 14 in the 3rd edition) for retrieving an element given its rank ("index") in O(lg n).
The proposed data structure and augmented operations will allow you to:
Hold unique values, performing the insertion operation in O(lg n)
Keep the elements sorted, with a O(lg n) search operation
Access an element given its rank in O(lg n)
@KingsIndian: The OP hasn't specified a desired time complexity for random access...
@OliCharlesworth Since OP mentioned "like-an-array", I thought OP expects constant-time access.
@KingsIndian certainly, it's possible to retrieve an element given its rank in O(lg n) in a binary search tree (see: procedure OS-SELECT in CLRS)
@KingsIndian My requirement for random access was for efficient searching. If a binary tree gives me efficient searching, I don't need random access.
@baruch I updated my answer with the time complexity for the required operations, I hope it's enough for your needs.
how about a TreeSet or a TreeMap?
unique values - both store unique values only
sorting - both sort entries either using natural order of elements or by the custom Comparator provided to them
random access - both provide random (O(1)) access.
The question doesn't specify that the data structure has to be implemented in Java. Besides, both TreeSet and TreeMap are balanced binary trees, implemented as Red-Black trees. And your last point is incorrect, they do not offer O(1) random access. For the TreeMap the documentation specifies O(lg n) time cost for the containsKey, get, put and remove operations and O(lg n) for add, remove and contains operations of the TreeSet
| common-pile/stackexchange_filtered |
Is there a way to measure how sorted a list is?
Is there is a way to measure how sorted a list is?
I mean, it's not about knowing if a list is sorted or not (boolean), but something like a ratio of "sortness", something like the coefficient of correlation in statistics.
For example,
If the items of a list are in ascending order, then its rate would be 1.0
If list is sorted descending, its rate would be -1.0
If list is almost sorted ascending, its rate would be 0.9 or some value close to 1.
If the list is not sorted at all (random), its rate would be close to 0
I'm writting a small library in Scala for practice. I think a sorting rate would be useful, but I don't find any information about something like that. Maybe I don't know adequate terms for the concept.
https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test
Would this be used to determine the ideal algorithm to sort the list? E.g. for values close to 0, QuickSort would be ideal, but values on either end of the scale (nearly sorted or nearly reverse sorted), MergeSort would be much faster, since QC devolves to O(N^2) in those cases.
+1 for "ratio of sortess"
Do you need this measurement to be made in O(n) time, or is O(n log n) acceptable?
Based on the popular answer http://stackoverflow.com/a/16994740/1168342 would such a function be of much practical use (i.e., you partially have to perform a sort to measure sortedness)?
@Fuhrmanator The stochastic version of the algorithm does not have to perform a sort to arrive at a probabilistic estimate of the sortedness. It's only if you want to get an exact measure that you need to perform a sort.
Sarcastic but funny first instinct: You could insertion sort the list and see how long it takes, and then compare that to how long it takes to sort (the now sorted) list and the reverse of it.
related: Minimum number of swaps needed to change Array 1 to Array 2?. It also covers O(n log n) algorithm for counting inversions.
You can simply count the number of inversions in the list.
Inversion
An inversion in a sequence of elements of type T is a pair of sequence elements that appear out of order according to some ordering < on the set of T's.
From Wikipedia:
Formally, let A(1), A(2), ..., A(n) be a sequence of n numbers.If i < j and A(i) > A(j), then the pair (i,j) is called an inversion of A.
The inversion number of a sequence is one common measure of its sortedness.Formally, the inversion number is defined to be the number of inversions, that is,
To make these definitions clearer, consider the example sequence 9, 5, 7, 6. This sequence has the inversions (0,1), (0,2), (0,3), (2,3) and the inversion number 4.
If you want a value between 0 and 1, you can divide the inversion number by N choose 2.
To actually create an algorithm to compute this score for how sorted a list is, you have two approaches:
Approach 1 (Deterministic)
Modify your favorite sorting algorithm to keep track of how many inversions it is correcting as it runs. Though this is nontrivial and has varying implementations depending on the sorting algorithm you choose, you will end up with an algorithm that is no more expensive (in terms of complexity) than the sorting algorithm you started with.
If you take this route, be aware that it's not as simple as counting "swaps." Mergesort, for example, is worst case O(N log N), yet if it is run on a list sorted in descending order, it will correct all N choose 2 inversions. That's O(N^2) inversions corrected in O(N log N) operations. So some operations must inevitably be correcting more than one inversion at a time. You have to be careful with your implementation. Note: you can do this with O(N log N) complexity, it's just tricky.
Related: calculating the number of “inversions” in a permutation
Approach 2 (Stochastic)
Randomly sample pairs (i,j), where i != j
For each pair, determine whether list[min(i,j)] > list[max(i,j)] (0 or 1)
Compute the average of these comparisons
I would personally go with the stochastic approach unless you have a requirement of exactness - if only because it's so easy to implement.
If what you really want is a value (z') between -1 (sorted descending) to 1 (sorted ascending), you can simply map the value above (z), which is between 0 (sorted ascending) and 1 (sorted descending), to this range using this formula:
z' = -2 * z + 1
It's kind of fascinating to me that sorting a list is (typically) O(n*logn), and the naive/obvious method of computing inversions is O(n^2). I wonder if there are better algorithms out there for computing the number of inversions?
There are a couple of interesting approaches in this SO question: http://stackoverflow.com/questions/6523712/calculating-the-number-of-inversions-in-a-permutation Basically, they amount to sorting the array in order to figure out how many inversions there are.
@MarkBessey Thanks for the link! I've incorporated it in the answer.
I naively thought you could just count adjacent pairs that are out of order. But that will severely undercount: 1 2 3 1 2 3 only has one adjacent inversion, but it's 50% inverted by the more correct measure.
Great answer. Might it benefit from a precise definition of inversion?
@ChristopherJamesCalo I pulled in the definition from the Wikipedia page I link to.
@TimothyShields, I meant define it in words. Also from Wikipedia: "In computer science and discrete mathematics, an inversion is a pair of places of a sequence where the elements on these places are out of their natural order." But maybe that's understood by this audience. I didn't know what it was.
@ChristopherJamesCalo Is the following not a definition in words (albeit with some minimal math lingo)? -- Formally, let A(1), A(2), ..., A(n) be a sequence of n distinct numbers. If i < j and A(i) > A(j), then the pair (i,j) is called an inversion of A.
@Barmar I think that list 1 2 3 1 2 3 would qualify as sorta sorted ;-)
@TimothyShields, well, no, it isn't. But I won't belabor the point. Just a suggestion to add a non-formal definition that is more accessible to the less symbolically inclined.
@ChristopherJamesCalo Suggestion taken. :)
@Barmar The sequence 1, 2, 3, 1, 2, 3 has only 6 inversions, but 6 choose 2 is 15. So it's actually 60% sorted, not 50%.
It seems like there might be another optimization approach where you move sequentially across the list in O(N), with each check asking if this is/is not inverted relative to the last. If you weighted agree/disagrees in the middle more highly than those towards the ends, and strong disagreements more highly than mild ones, you might get a similar answer to the O(N log N) approach.
@ChrisMoschini I invite you to try to come up with such a thing. :) I'll warn you that I have a pretty good hunch that computing the inversion number of a sequence using element-based comparisons is Omega(n log n) - meaning it can't be done with lower complexity - but it's not something I've proven. Computing the list of inversions (as opposed to the inversion number) is definitely Omega(n log n).
@TimothyShields In the stochastic approach, need one prevent duplication of pairs or swapped pairs? (I'm sure there are formal terms for what I'm describing...) That is in the random testing, should one ensure that each pair tested is unique (beyond just ensuring that i != j for each pair).
@BenFletcher Duplicate pairs do present any problem. All that is important is to choose pairs independently from one another. For small lists, you can exhaustively look at every possible pair and still be very fast. For larger lists, the difference in convergence speed between including duplicates or not including duplicates is extremely negligible.
@TimothyShields Thank you for the quick response! I researched more to realize that my question of whether duplicates should be prevented is asking in statistical terms whether 'with replacement' vs. 'without replacement' was important. As you said, it seems that the difference is more important (or only important) with a small population size. But, generally, 'with replacement', i.e., allowing duplicates, is preferred when possible. It certainly makes implementation of this algorithm much easier.
I'm not sure I understand normalizing by N choose 2 in the stochastic case. That means the larger the list, the smaller the maximum sortedness score. For example, the sortedness score of a reversed list of size 2 is 1, 3 is 0.33..., 4 is 0.16... since the unnormalized score is 1, which is then divided by 1, 3, or 6, respectively. If 1 is supposed to indicate a reversed list, shouldn't the score just be the average score of the samples?
Another question - shouldn't the inequality be less than or equal to rather than less than? Less than counts identical entries as unsorted IIUC
I needed an implementation so https://gist.github.com/MrCreosote/b72a5dd0248b7a601a2944501a0b1fc0
The traditional measure of how sorted a list (or other sequential structure) is, is the number of inversions.
The number of inversions is the number of pairs (a,b) st index of a < b AND b << a. For these purposes << represents whatever ordering relation you choose for your particular sort.
A fully sorted list has no inversions, and a completely reversed list has the maximum number of inversions.
Technically, 5 4 3 2 1 is fully sorted since order isn't specified, but I'm being pedantic :-)
@paxdiablo That depends on the definition of <.
@paxdiablo, well one could measure sortedness by the distance from the number of inversions to the closest of 0 or n choose 2.
You can use actual correlation.
Suppose that to each item in the sorted list, you assign an integer rank starting from zero. Note that a graph of the elements position index versus rank will look like dots in a straight line (correlation of 1.0 between the position and rank).
You can compute a correlation on this data. For a reverse sort you will get -1 and so on.
I'm sorry, but this leaves too much unexplained, like how you assign the integers.
You need the sorted list to assign the integers; then it is just an enumeration of the items.
Exactly what I was going to suggest. Determine the correlation between the position of the object in the original list and its position in the sorted list. The bad news is that correlation routines probably run in O(n^2); the good news is they are probably off-the-shelf for your environment.
Yeah, just Spearman's rho http://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient
I'm curious... is this approach equivalent to scaling the count of the number of inversions?
There has been great answers, and I would like to add a mathematical aspect for completeness:
You can measure how sorted a list is by measuring how much it is correlated to a sorted list. To do that, you may use the rank correlation (the most known being Spearman's), which is exactly the same as the usual correlation, but it uses the rank of elements in a list instead of the analog values of its items.
Many extensions exist, like a correlation coefficient (+1 for exact sort, -1 for exact inversion)
This allows you to have statistical properties for this measure, like the permutational central limit theorem, which allows you to know the distribution of this measure for random lists.
Apart from inversion count, for numeric lists, mean square distance from the sorted state is imaginable:
#! ruby
d = -> a { a.zip( a.sort ).map { |u, v| ( u - v ) ** 2 }.reduce( :+ ) ** 0.5 }
a = 8, 7, 3, 4, 10, 9, 6, 2, 5, 1
d.( a ) #=> 15.556
d.( a.sort ) #=> 0.0
d.( a.sort.reverse ) # => 18.166 is the worrst case
I think that's the square of the standard correlation function, see http://en.wikipedia.org/wiki/Correlation_ratio . And applies equally to non-numeric lists; the two values which are compared are the object's position in the two lists.
I am a simpleton. I don't even know what correlation ratio is. When I read that Wikipedia article, right at the top, I'm asked to learn what "statistical dispersion" is, then "standard deviation", then "variation", then "interclass correlation coefficient". I learnt all of that, several times, and several times, I forgot it again. In this pragmatic answer of mine, I simply measure the distance between the two vectors with Pythagoras theorem, that I remember from the elementary school, that's all.
I am not sure of the "best" method, but a simple one would be to compare every element with the one after it, incrementing a counter if element2 > element 1 (or whatever you want to test) and then divide by the total number of elements. It should give you a percentage.
I would count comparisons and divide it to the total number of comparisons. Here is a simple Python example.
my_list = [1,4,5,6,9,-1,5,3,55,11,12,13,14]
right_comparison_count = 0
for i in range(len(my_list)-1):
if my_list[i] < my_list[i+1]: # Assume you want to it ascending order
right_comparison_count += 1
if right_comparison_count == 0:
result = -1
else:
result = float(right_comparison_count) / float((len(my_list) - 1))
print result
If you take your list, calculate the ranks of the values in that list and call the list of ranks Y and another list, X that contains the integers from 1 to length(Y), you can obtain exactly the measure of sortedness that you are looking for by calculating the correlation coefficient, r, between the two lists.
r = \frac{\sum ^n _{i=1}(X_i - \bar{X})(Y_i - \bar{Y})}{\sqrt{\sum ^n _{i=1}(X_i - \bar{X})^2} \sqrt{\sum ^n _{i=1}(Y_i - \bar{Y})^2}}
For a fully-sorted list, r = 1.0, for a reverse-sorted list, r=-1.0, and the r varies between these limits for varying degrees of sortedness.
A possible problem with this approach, depending on the application, is that calculating the rank of each item in the list is equivalent to sorting it, so it is an O(n log n) operation.
But that won't ignore the curve shape. If his array is sorted, but, say, contains values increasing exponentially, the correlation will be small where he wants it to be 1.0.
@LeeDanielCrocker: Yes, that's a good point. I've amended my answer to address this by taking ranks of the values.
How about something like this?
#!/usr/bin/python3
def sign(x, y):
if x < y:
return 1
elif x > y:
return -1
else:
return 0
def mean(list_):
return float(sum(list_)) / float(len(list_))
def main():
list_ = [ 1, 2, 3, 4, 6, 5, 7, 8 ]
signs = []
# this zip is pairing up element 0, 1, then 1, 2, then 2, 3, etc...
for elem1, elem2 in zip(list_[:-1], list_[1:]):
signs.append(sign(elem1, elem2))
# This should print 1 for a sorted list, -1 for a list that is in reverse order
# and 0 for a run of the same numbers, like all 4's
print(mean(signs))
main()
This only counts adjacent inversions. If you look at the other answers you’ll see that this is insufficient.
@KonradRudolph: I think this answer satisfies the question as asked. The fact that other answers are more comprehensive doesn't mean that this one is insufficient; it depends on the OP's requirements.
We could sort our L1 list with the criteria we want and produce L2 list which would be our ideal sorting.
Then we could calculate the Levenstein distance of each pair of items between L2 and L1 and sum the distances.
The further away from zero, the most unsorted L1 is.
| common-pile/stackexchange_filtered |
I want to make my php know if there is a number in the password
I want to know if there is a number in one string (PHP CODE)
This is what i have:
if (!preg_match('/0/',$p) || !preg_match('/1/',$p) || !preg_match('/2/',$p) || !preg_match('/3/',$p) || !preg_match('/4/',$p) || !preg_match('/5/',$p) || !preg_match('/6/',$p) || !preg_match('/7/',$p) || !preg_match('/8/',$p) || !preg_match('/9/',$p)){
echo "<p>The password need to contain atleast one number</p>";
exit();
}
Might I suggest using if(!preg_match('\d+', $p))? That will match on having at least one number in the string.
@ChrisForrence Good point on the shorthand class \d, but you should probably suggest delimiters too. Also, testing whether a \d exists, + is unnecessary.
That's a valid pint, @Wiseguy. I'm just in the habit of using + (to make the intent clear) (well, as much as regex can be clear)
I think this one is better:
if(!preg_match('#[0-9]#', $p))
So that way you can avoid that unnecessary if jungle.
Test it here.
This should be what you're looking for.
if (!preg_match('/[0-9]/',$p)) {
echo "<p>The password need to contain at least one number</p>";
exit();
}
I'd suggest using this:
if (!preg_match('/\d/',$p)) {
echo "<p>The password need to contain at least one number</p>";
exit();
}
| common-pile/stackexchange_filtered |
Dotnet and Azure Event Hubs: Retrieve an event by its position
I've been trying to retrieve events by its position using Microsoft.Azure.EventHubs.
I've been told that there is a way to calculate an event position using its offset or sequenceNumber, so everytime I'm adding an event to an EventBatch, I cache in redis an id and the event's offset and sequenceNumber.
Then, whenever I want to retrieve an specific event, I search for its Id on redis, retrieve its offset and sequenceNumber and could pottentially retrieve it in the event hub streams.
The problem is that the offset and sequence numbers are a negative long which I couldn't understand how to use it as an index.
Do you guys know how could it be done?
Here is both my publisher and the retriever classes
public class EventHubPublisher
{
public static async Task SendMessage(string _connectionString, string _eventHubName, string _message, string onboardingid)
{
var producerClient = new EventHubProducerClient(_connectionString, _eventHubName);
var eventBatch = await producerClient.CreateBatchAsync();
var data = new EventData(Encoding.UTF8.GetBytes(_message));
eventBatch.TryAdd(data);
addDatatoRedis(data.SequenceNumber,data.Offset,onboardingid);
await producerClient.SendAsync(eventBatch);
}
private static void addDatatoRedis(long sequenceNumber, long offset, string onboardingid)
{
try
{
var redisConnection = ConnectionMultiplexer.Connect(ConnectionStringsSettings.Properties.Redis);
var redis = redisConnection.GetDatabase();
var value = new
{
sequence_number = sequenceNumber.ToString(),
offset = offset.ToString(),
};
redis.StringSetAsync(onboardingid, JsonSerializer.Serialize(value));
}
catch (Exception)
{
throw;
}
}
}
public class EventHubRetriever
{
public static async Task GetEvent(string _connectionString, string _eventHubName, JObject existentEvent)
{
try
{
var client = EventHubClient.CreateFromConnectionString($"{_connectionString};entityPath={_eventHubName}");
var partitionRuntimeInformation = await client.GetPartitionRuntimeInformationAsync("0");
var eventHubRunTimeInformation = await client.GetRuntimeInformationAsync();
var eventPosition = EventPosition.FromOffset(existentEvent["offset"].ToString());
var lastEnqueuedOffset = Convert.ToInt32(partitionRuntimeInformation.LastEnqueuedOffset);
var offset = existentEvent["offset"];
// var offsetPosition = lastEnqueuedOffset + offset;
// var receiver = EventHubClient.Create();
}
catch (System.Exception)
{
throw;
}
}
}
It looks like you're using Azure.Messaging.EventHubs for publishing and the legacy library Microsoft.Azure.EventHubs for consuming. While the two libraries are compatible and this scenario is supported, we'd recommend using Azure.Messaging.EventHubs unless you've got an existing legacy investment.
I just changed to the Azure.Messaging.EventHubs.
I was using the legacy while trying to mimic the approach I showed bellow (which I got from a java implementation and it was using a library that matched this Microsoft.Azure.EventHubs).
The Offset and SequenceNumber are broker-owned fields that aren't populated when you create your EventData instance. The Event Hubs service will assign an offset and sequence number only after the event has been accepted and assigned to a partition. It is not possible to predict what those values are when publishing; those members are only valid when the event is consumed.
The values that you're storing in Redis are long.MinValue, corresponding to uninitialized data. (this is detailed in the remarks section of the docs)
Unfortunately, the random-access scenario that you're looking to implement isn't one that fits well with Event Hubs. The closest that occurs to me would be to assign a unique identifier to an application property when creating the event and then store that and its approximate publishing time (with a buffer to account for time drift) in Redis. When you want to retrieve that event, use the publish time as your starting point and the read forward until you find the event.
For example, something like:
(DISCLAIMER: I'm working from memory and unable to compile/test. Please forgive any syntax errors)
public class EventHubPublisher : IAsyncDisposable
{
// NOTE: You want the client instance to be static; by creating
// each time that you wish to send, you're paying the cost
// of establishing a connection each time.
//
private static readonly EventHubProducerClient ProducerClient =
new EventHubProducerClient(
_connectionString,
_eventHubName);
// NOTE: You should query the Event Hub for partition identifiers; it is
// not safe to assume "0" as the first partition. This is used here
// for illustration only.
//
private static readonly SendEventOptions FirstPartitionOptions =
new SendEventOptions { PartitionId = "0" };
// NOTE: There is no benefit to using the batch overload, as you
// are publishing only a single event at a time. It's worth
// mentioning that this isn't an efficient pattern for publishing;
// if you can batch events, you'll see better throughput.
//
public async Task SendMessage()
{
var data = new EventData(Encoding.UTF8.GetBytes(_message));
data.Properties.Add("Id", Guid.NewGuid.ToString());
await producerClient.SendAsync(new[] { data }, FirstPartitionOptions);
// Allow for up to 5 minutes of clock skew. This may need to be tuned
// depending on your environment.
var publishTime = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(5));
addDatatoRedis(publishTime, data.Properties["Id"]);
}
private void addDatatoRedis(DateTimeOffset enqueueTime, string id)
{
// ... Save to Redis
}
public virtual async ValueTask DisposeAsync()
{
await ProducerClient.CloseAsync().ConfigureAwait(false);
GC.SuppressFinalize(this);
}
}
I'm illustrating using Azure.Messaging.EventHubs, which is the current generation Event Hubs client library. The concept would be the same if you need to continue using the legacy version as your question does.
public class EventHubRetriever : IAsyncDisposable
{
// NOTE: You want the client instance to be static; by creating
// each time that you wish to send, you're paying the cost
// of establishing a connection each time.
//
private static readonly EventHubConsumerClient ConsumerClient =
new EventHubProducerClient(
EventHubConsumerClient.DefaultConsumerGroupName
_connectionString,
_eventHubName);
private static readonly ReadEventOptions ReadOptions =
new ReadEventOptions { MaximumWaitTime = TimeSpan.FromSeconds(1) };
public async Task GetEvent(JObject persistedEvent)
{
var firstPartition = (await consumer.GetPartitionIdsAsync()).First();
var enqueueTime = DateTimeOffset.Parse(persistedEvent["publishTime"]);
var eventId = persistedEvent["id"];
await foreach (PartitionEvent partitionEvent in
consumer.ReadEventsFromPartitionAsync(
firstPartition,
EventPosition.FromEnqueuedTime(publishTime),
ReadOptions))
{
if (partitionEvent.Data == null)
{
// We're at the end of the event stream and didn't find
// your event.
}
else if (partitionEvent.Data.Properties["Id"] == eventId)
{
// This is your event. Do what you want and break
// the loop.
}
}
}
public virtual async ValueTask DisposeAsync()
{
await ConsumerClient.CloseAsync().ConfigureAwait(false);
GC.SuppressFinalize(this);
}
}
Well Jesse, thank you very much. I changed by implementation to follow your approach. Changed to the newer library, used the published time to get the event position and I check all returned events for the one that matches the ID (which I was already generating in my business logic). t's working!
Well I'm not sure if what I did was the right approach, but it seems to be working.
When I'm going to publish the message, I get the lastEnqueuedNumber, from the GetPartitionRunTime, add 1 and add it as a property to eventData.
Since I'm also adding the event to a redis cache, I'm able to retrieve its sequenceNumber.
public class EventHubPublisher
{
public static async Task SendMessage(string _connectionString, string _eventHubName, string _message, string onboardingid, string partition)
{
var client = EventHubClient.CreateFromConnectionString($"{_connectionString};entityPath={_eventHubName}");
var partitionRuntimeInformation = await client.GetPartitionRuntimeInformationAsync(partition);
var sequenceNumber = partitionRuntimeInformation.LastEnqueuedSequenceNumber + 1;
var data = new EventData(Encoding.UTF8.GetBytes(_message));
data.Properties.Add("Id", onboardingid);
data.Properties.Add("Message", _message);
data.Properties.Add("SequenceNumber", sequenceNumber);
await client.SendAsync(data);
addDatatoRedis(onboardingid, sequenceNumber, data.Body.Offset, _eventHubName);
}
private static void addDatatoRedis(string onboardingid, long sequenceNumber, int offset, string topic)
{
try
{
var redisConnection = ConnectionMultiplexer.Connect(ConnectionStringsSettings.Properties.Redis);
var redis = redisConnection.GetDatabase();
var value = new
{
offset = offset,
id = onboardingid,
sequenceNumber = sequenceNumber,
topic = topic
};
redis.StringSetAsync(onboardingid, JsonSerializer.Serialize(value));
}
catch (Exception)
{
throw;
}
}
Then, when retrieving the event from EventHub, I'm able to get the sequenceNumber from the cached event and get the event on the eventhub by its index.
public class EventHubRetriever
{
public static async Task<EventData> GetEvent(string _connectionString, string _eventHubName, JObject existentEvent)
{
try
{
var client = EventHubClient.CreateFromConnectionString($"{_connectionString};entityPath={_eventHubName}");
var eventHubRunTimeInformation = await client.GetRuntimeInformationAsync();
var partitionsIds = eventHubRunTimeInformation.PartitionIds;
var sequenceNumber = (long)existentEvent["sequenceNumber"];
var retrievedEvent = GetEventByPosition(client, sequenceNumber, partitionsIds);
return retrievedEvent;
}
catch (Exception exc)
{
throw new EventRetrieveException(exc, "An error ocurred while retrieving data from Event Hub.");
}
}
private static EventData GetEventByPosition(EventHubClient client, long sequenceNumber, string[] partitionsIds, string eventHubName)
{
var eventPosition = EventPosition.FromSequenceNumber(sequenceNumber, true);
var partitionReceivers = partitionsIds
.Select(id => client.CreateReceiver(eventHubName, id, eventPosition));
var events = partitionReceivers.Select(receiver => receiver.ReceiveAsync(1)).SelectMany(x => x.Result).ToList();
return events.ElementAt(0);
}
}
I wouldn't recommend the approach. You're not guaranteed that other events are not in a pending state and waiting to be committed to the partition, whether form other publishers or due to the non-deterministic nature of when events are made available. Event Hubs also does not guarantee contiguous sequence numbers (only that they'll be in increasing order.) While this approach may work most of the time, it is not robust and reliable.
| common-pile/stackexchange_filtered |
How to get data from last number and still before space in javascript using regular expression
This is my problem below
var id = "10101-Building and Construction 21";
Basically, I have got id's data from other calculation , i want to separate to 21.
Here result will be 21;
How can i remove id's value without 21 .
Please any help?
Can't you make that other calculation return something more meaningful than a string?
Are you looking to grab the last numeric value after a space (ie, 21 in your example above)? Will the data always be in that same format where the last numeric value is of interest?
id = id.replace('10101-Building and Construction', '') :)
@adeneo: Better id.substring(33) then :-)
@Bergi - Good one! It was a joke, but I see someone has posted it as an answer!
Basically id data will come dynamically and length is not fixed so, i need from last to still before space . any suggestion
Basically id data will come dynamically and length is not fixed so, i need from last to still before space . any suggestion , Anthony , adeneo, Bergi
@MD.ABDULHalim Is there a special format your data being returned will follow? Are all values delimited by a space? If so, you won't need regular expression as an example @Bergi posted above should be sufficient.
Maybe combining substring and lastindexOf, something like:
var result = id.substring(id.lastIndexOf(' ')+1);
your code is not work , please another suggestion ? here id will come dynamically and not fixed it's length so i need from last to still before space.
This code extract the part of the id located after the last space (blankspace), i can show you width a fiddle if needed, can you explain why doesn't it fit your needs so as i can eventually modify it ?
$(document).ready(function(){
var id = 10101-Building and Construction 21;
var result=id.substring(id.Length-2,id.Length)
});
Basically id data will come dynamically and length is not fixed so, i need from last to still before space . any suggestion
id will come dynamically and not fixed it's length so i need from last to still before space
Assumptions made based on your question :
- The id you wana extact from the string is always at the last
- The id is always a number
If above assumptions are true :
then you can write a javascript function and perform the following functions.
loops from the last and check for numbers till it finds a string
as soon as it encouters a character it stops and you get the requiered id
the function in javascript
function express()
{
var str="10101-Building and Construction 21";
var temp,id;
for(var t2=1;t2<=str.length;t2++)
{
temp = str.substring(str.length-t2);
var condition = isNaN(temp);
if(condition == true)
{
break;
}
id=temp;
}
document.write("<br>"+id);
}
this will extract the id
and the result:
id = 12
Click Here : And the fiddle for a live example of this based on your values
| common-pile/stackexchange_filtered |
Why would I want to use Angular with Ruby on Rails?
I'm a studying CS and lately I've got myself really enjoying learning about web development..
Now, I have tried to learn AngularJS for a few times but then I wanted to focus more on backend first, since I already know the stuff like html/css/js which makes good part of frontend so wanted to see what backend feels like..
So I started learning Rails.. Now, since with my previous attempts of trying to learn AngularJS I learned that it is all about MVC, sending data from one to another etc.. My problem is, at first glance at least, Rails seems to work in the really similar fashion. The question is, why would anyone want to use both AngularJS and Rails at the same time, when, at least in the newbie's eyes -> Rails seems that it can handle both backend and frontend? Like, views are our frontend, and we can use css/js in those .html.erb files, wouldn't that be considered frontend after all?
Now, I'm almost positive there is a good answer to this since googling "why use angular with rails" usually comes with results of tutorials that explain to you how to integrate them, I just want some reasons so that I wouldn't be as confused as right now..
Thanks!
Sorry, this really is the not the right place to be asking a question like this. StackOverflow is designed to be used when you have a specific programming problem.
Hi and welcome to Stack Overflow! This is an interesting question (and answered by a couple of people below), but I'm afraid that it isn't the usual kind of question we tend to like on Stack Overflow. It's not that it isn't interesting or useful - just that Stack Overflow is aimed towards solving specific, technical questions, rather than "why would I choose framework X"? kind of open questions. The reason for this is that in the past, these kinds of questions have caused all kinds of flame wars... so now we tend to try and avoid that where possible.
The reason I'm telling you this is that your question is likely going to be voted to be closed very shortly - and I hope you won't take it too personally. Like I said it's interesting, and you even got an answer or two! but it just doesn't fit the S/O template very well. I do hope you'll stick around and ask any other questions you might have :)
So, where do we ask such conceptual questions ? :(
Taryn East, thanks for feedback, you're really kind! :) I'm aware that this is more of an open question than some others, and to be honest I hesitated for a bit before posting it, but in my eyes no flame wars should ever happen with this question because I'm not asking is it better to use X or Y, I am simply asking why should one use X with Y, and from googling I already get it that we should, so I still believe this answer does have an answer indeed, it's perhaps not as open as it might look at the first glance. In the end, if it does get closed, I'm really sorry. But I couldn't find answer:(
Rails is a server-side framework that produces HTML, JSON, and JavaScript as well as manages CSS and image assets.
AngularJS is a client-side framework. Generally, without a server component it really can't do much.
By default Rails doesn't have a client-side framework. You can use EmberJS, Angular, or others to make your client-side interface more responsive and flexible. Rails alone can't do this, it can't run in your browser.
Likewise, AngularJS can't run on your server. You need to combine them.
To both tadman and Skeptor so in the end the only reason why someone will use AngularJS with Rails is purely based on aesthetics and creating a better user experience? Like I've seen demos of twitter-alike sites being built purely in Rails, and if that's possible I can see quite a few other possibilities for a web app sort of thing.. But now that I think, isn't frontend all about aesthetics after all? I guess a lot web apps can be built using backend + forms + buttons, the jQuery for example is the one responsible for slickness.. Correct me again if I'm wrong, still learning :/
Rails alone can't do much more than HTML. You need JavaScript to push it beyond that. You can write it using only basic JavaScript (annoying), with jQuery (better), or with a front-end toolkit like AnguarJS if you're doing a lot of scripting. With HTML alone all you can do is reload pages. With JavaScript you can have real-time interaction, and AngularJS makes this sort of thing a lot easier to do.
So technically it's all about a better user experience, but sometimes it enables functionality that's impossible or impractical without scripting. Keep in mind, there's nothing that says we need images or CSS, but sites look pretty awful without them. Today the same is true for JavaScript.
Alright, thank you tadman for quick but detailed replies.. I get it now, in the end I didn't really knew there were such limitations for rails's layout/view(html) part.. Thank you again :) And really sorry all for creating trouble by posting such question, I'll try to be more strict in future.. But in my defense I really couldn't find an answer on google, every time I tried looking for one I'd get spammed by all the tutorials on how to combine them, not a page describing why you should do it.. :)
No trouble. The whole web thing is pretty confusing to someone who's approaching it from anew. Glad I could help.
One more point why frontend development is preferred, In application where views are loaded from backend, everytime you load a page, whole bunch of elements get loaded each time . You need to fetch them server and thats an overload. Slows down the application. IF its built using front end, only required data alone is fetched from backend.
MVC at frontend is a recent development. Earlier days we used to develop everything at backend and use frontend only for animation, UI etc.,
Slowly with Ajax introduction we started doing more at frontend and less at backend.
Now we migrated completely to frontend. We use backend only for logics which should be decided at server side and database management.
Single line answer, we need rails or any backend only to serve few logics which SHOULD happen in the backend, User can change the logic if it is at client side. So we force them to happen in the server side. And ofcourse database should be at the backend.
Other than that , there is absolutely no need to use rails views and others.
| common-pile/stackexchange_filtered |
Custom UIView wrap-around
I have an NSArray of custom UIViews (ACTileView). They act as one row. I would like to be able to slide them left or right (which is currently already possible) but have the wrap-around (to create the effect of endless "Tiles" much like the UIDatePickerView on the iPhone). I don't have any ideas anymore on how I can achieve this effect.
Help would be greatly appreciated
kind regards, JNK
I once did something similar with 50+ views one could page through. Clearly, for memory reasons you should not load all those views into an array if they are not visible.
So what I did was to have the amount of visible views +2 on each side in my array. Which each change of the position, I would update the array by popping one view off one side and adding the next one on the other side.
I put this logic into the scrollViewDidEndDecelerating delegate method of the UIScrollView, but you could also put it into scrollViewDidScroll and then check for the necessary adjustments of views.
You can re-assign an new NSArray each time and discard the old one, or do everything in a MSMutableArray.
If your views are all visible at the same time, use this method and just double the chain.
There are between 3-5 views in one array. All of the views are visible. The leftmost view is supposed to appear on the right (and left at the same time) if you slide left.
See the last line of my answer.
| common-pile/stackexchange_filtered |
How to get an accurate LTSpice model of a real inductor after impedance analysis?
I want to get an accurate model of a real inductor in LTSpice. Therefor I used an Bode 100 Network Analyzer und measured its impedance in a range of 100 Hz to 20 MHz. My idea was to calculate the capacitance of the inductor from the resonant frequency of the inductor like this (rearranged formula from wikipedia for a real parallel resonant circuit):
$$ C=\dfrac{1}{L\omega_r^2+\dfrac{R_L^2}{L}}$$
However, I have not been that satisfied with the results, when using this model in LTSpice. The inductor will be used in a resonant circuit, whose resonant frequency is approximately at 7 MHz. Can this inductor be modelled more accurately?
Impedance of the inductor (measured in inductance and serial resistance, the narrow one is the serial resistance):
Comparison of the impedances in LTSpice and the Bode 100:
The standard model of an inductor that comes with LTSpice is very likely an ideal inductor in series with a resistor. That will not behave in the same way as your real world inductor. But you can build your own model from ideal components. Just search for "Inductor model" to find some examples.
LTSpice has parameters like parallel capacitance, series resistance etc. in its inductor model. I just don't know how to get the most accurate values out of the measured impedance of the real inductor.
How close do you get if you calculate your series R and parallel C and plot your impedance in LTspice?
@winny I have added a comparison.
@TonyDublov The analysis clearly shows multiple resonances which are displayed as slight notches because they involve damping. This means that a simple RLC won't do, you'll have to add more RLC cells (there may be reflections, too). This is commonly done. At any rate, judging by the pictures, it looks like either you didn't specify Rpar, or you did but it needs a lower value (more damping). Here is a quick hack (single cell).
Plot both in either lin-log or log-log?
@aconcernedcitizen I indeed did not specify Rpar. This seems to do the trick and should be accurate enough. Thank you very much!
@winny The comparison is log-log, isn't it?
Oh! There was a third. Thanks! Is it the dip at 700 kHz you are concerned about?
usually the analyzer software has tools for creating models… for these resonances you usually model them as RLC groups in parallel with the main component
"The inductor will be used in a resonant circuit, whose resonant frequency is approximately at 7 MHz. Can this inductor be modelled more accurately?" why would you need to?
The analysis clearly shows multiple resonances which are displayed as slight notches because they involve damping. This means that a simple RLC won't do, you'll have to add more RLC cells (there may be reflections, too). This is commonly done. At any rate, judging by the pictures, it looks like either you didn't specify Rpar, or you did but it needs a lower value (more damping). Here is a quick hack (single cell):
| common-pile/stackexchange_filtered |
How to show the gnome3 activities menu only on the monitor where it was triggered?
Additional information:
Whenever the gnome3 activities menu is triggered (e.g. when I'm using the gnome search tool to search for a program) the menus effect is triggered on all monitors e.g. showing all open windows for each monitor. I find this very annoying.
The following screenshot shows what I don't want, since I triggered the menu on the screen in the middle the activities menus effect should only be shown here.
Question:
Is there a way to show the activities menu only on the monitor where it was triggered ? (leaving the windows on the other monitors as they are)
| common-pile/stackexchange_filtered |
How to acquire fully qualified names of installed applications in Android
I try to create an application that can start other applications (f.e. Gmail or Facebook or any installed one).
I tried to use the following code:
PackageManager pm = MainActivity.this.getPackageManager();
try
{
Intent it = pm.getLaunchIntentForPackage("FULLY QUALIFIED NAME");
if (it != null)
MainActivity.this.startActivity(it);
}
catch (ActivityNotFoundException e)
{ }
However, it requires the fully qualified name of the application.
How can I acquire it? Is there any built-in method to get them?
Wouldn't it be better simply to find the launchable activities, the way home screen launchers do?
Can you elaborate this a little bit more?
An application may have zero, one, or several activities that belong in a launcher. Hence, a launcher should not be asking "what are all the applications, and what is the launch Intent for each?" A launcher should, instead, be asking "what are all of the activities that I should show?"
That is accomplished using PackageManager and queryIntentActivities(). This sample project implements a complete launcher. The key lines are:
PackageManager pm=getPackageManager();
Intent main=new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables=pm.queryIntentActivities(main, 0);
Then, you can use whatever mechanism you want to render that launchables collection. The sample project puts them in a ListView.
Great explanation, it helps a lot.
You can get a List of all applications like this:
final PackageManager packageManager = getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Now you've stored all applications with their meta data in a List. You can get their package name like this:
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, packageManager.getLaunchIntentForPackage(packageInfo.packageName));
}
Good to know these things, too.
| common-pile/stackexchange_filtered |
Excel macro runtime error 424
I can't find the root cause of my runtime error 424. I know it's to do with a missing object, but I'm not sure where or which object that would even be in this case. My assumption is has to do with ActiveSheet but I'm a bit lost.
Sub Macro1()
'
' Macro1 Macro
'
'
Sheets.Add
Error begins here
PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ActiveSheet.Range("A1").CurrentRegion.Select, Version:= _
xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Error end here
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Source Type")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Category")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("Category").Orientation = _
xlHidden
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Activity")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("USD Amount"), "Sum of USD Amount", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Quantity"), "Sum of Quantity", xlSum
End Sub
I rarely need to create pivot tables programatically so, to get an understanding of what's going on I created a little sub to step through:
Sub CreatePivotOnNewSheet()
Sheets.Add
ActiveSheet.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ActiveSheet.Range("A1").CurrentRegion, Version:= _
xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
End Sub
This compiles OK but throws an error 438: Object doesn't support this property or method. I searched the Object Browser for PivotCaches and found that it is a member of Workbook and PivotTable. It isn't a member of Worksheets! This makes sense when you consider that pivot tables on different sheets can use the same pivot cache.
So, change the code:
Sub CreatePivotOnNewSheet()
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ActiveSheet.Range("A1").CurrentRegion, Version:= _
xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
End Sub
and now we get a run-time error:
Which needs to be bigger to display the full reason (thanks Microsoft!) but I guess it goes on to say reference to a range that contains at least two rows and has no blank cells in its top row. While in break mode I went to the newly added sheet and created a little 2x2 data table. Back in the IDE, pressed F8 and it worked although the pivot table didn't have any rows/columns etc. defined. I haven't attempted to test your remaining code which seems to create the definitions - I'll leave that to you.
It is the problem with recorded Macros, that there is no Objects defined at all.
I would suggest to replace all "Active" phrases with variables. Here is the start:
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = wb.Sheets(1)
Set ws2 = wb.Sheets(2)
Dim Caches As PivotCache
Set Caches = wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ws2.Range("A1:C3"), Version:= _
xlPivotTableVersion12)
| common-pile/stackexchange_filtered |
pygame TypeError: Rect argument is invalid
I have read many threads with the same issue as me, but haven't found any that solve my problem, so have decided to ask here. I am currently following this tutorial. At 1:01:58, when he runs he gets no error, but I receive the error in the title above:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/networkTutorial1/client.py", line 80, in <module>
main()
File "C:/Users/User/PycharmProjects/networkTutorial1/client.py", line 78, in main
redrawWindow(win,p,p2)
File "C:/Users/User/PycharmProjects/networkTutorial1/client.py", line 54, in redrawWindow
player2.draw(win)
File "C:/Users/User/PycharmProjects/networkTutorial1/client.py", line 22, in draw
pygame.draw.rect(win, self.colour, self.rect)
TypeError: Rect argument is invalid
Many websites mention ensuring that self.rect and self.colour are both tuples, and I'm pretty certain that they are, so don't know what's causing the problem.
The code for my client, server and network py files, respectively, are:
import pygame
from network import Network
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
clientNumber = 0
class Player():
def __init__(self, x, y, width, height, colour) :
self.x = x
self.y = y
self.width = width
self.height = height
self.colour = colour
self.rect = (x,y,width,height)
self.vel = 3
def draw(self, win):
pygame.draw.rect(win, self.colour, self.rect)
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.x -= self.vel
if keys[pygame.K_RIGHT]:
self.x += self.vel
if keys[pygame.K_UP]:
self.y -= self.vel
if keys[pygame.K_DOWN]:
self.y += self.vel
self.update()
def update(self):
self.rect = (self.x, self.y, self.width, self.height)
def read_pos(str):
str = str.split(",")
return int(str[0]), int(str[1])
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
def redrawWindow(win,player,player2):
win.fill((255,255,255))
player.draw(win)
player2.draw(win)
pygame.display.update()
def main():
run = True
n = Network()
startPos = read_pos(n.getPos())
p = Player(startPos[0],startPos[1],100,100,(0,255,0))
p2 = Player(0,0,100,100,(0,255,0))
clock = pygame.time.Clock()
while run:
clock.tick(60)
p2Pos = n.send(make_pos((p.x, p.y)))
p2.x = p2Pos[0]
p2.y = p2Pos[1]
p2.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
p.move()
redrawWindow(win,p,p2)
main()
import socket
from _thread import *
import sys
server = "<IP_ADDRESS>"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2) #max clients on server
print("Waiting for a connection, Server Started")
def read_pos(str):
str = str.split(",")
return int(str[0]), int(str[1])
def make_pos(tup):
return (str(tup[0]) + "," + str(tup[1]))
pos = [(0,0),(100,100)]
def threaded_client(conn, player):
conn.send(str.encode(make_pos(pos[player])))
reply = ""
while True:
try:
data = read_pos(conn.recv(2048).decode())
pos[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = pos[0]
else:
reply = pos[1]
print("Received:", data)
print("Sending:", reply)
conn.sendall(str.encode(make_pos(reply)))
except:
break
print("Lost connection")
conn.close()
currentPlayer = 0
while True:
conn, addr = s.accept()
print("Connected to:", addr)
start_new_thread(threaded_client, (conn, currentPlayer))
currentPlayer += 1
import socket
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "<IP_ADDRESS>"
self.port = 5555
self.addr = (self.server, self.port)
self.pos = self.connect()
def getPos(self):
return self.pos
def connect(self):
try:
self.client.connect(self.addr)
return self.client.recv(2048).decode()
except:
pass
def send(self, data):
try:
self.client.send(str.encode(data))
return self.client.recv(2048).decode()
except socket.error as e:
print(e)
Thanks for spending the time to read this question and help me out.
Please repeat MRE from the intro tour. Extract only the code needed to reproduce the problem; give us that with a values trace and the full error message.
@Prune, I have included all of the code as the files all interact, and thus could influence the code that causes the error. Unfortunately, I don't know enough about this specific structure to know how to cut the content down, because server.py is required to run before client.py can be run, but client.py references network.py also. According to that link, references files should be included in case the error is in an unexpected location. As for Values trace and error message, I am not sure what you mean, as I have copied over the text in the console.
Turns out I was missing a read_pos before n.send on line 67, problem fixed now. I have encountered another issue, but will open a new question as this one is solved.
| common-pile/stackexchange_filtered |
Gitlab-Runner service not working in windows
I'm starting with gitlab CI.
I'm using Windows 7. I registred my GitlabRunner, but when I try to install it, I have this issue :
←[0;33mWARNING: Since GitLab Runner 10.0 this command is marked as DEPRECATED and will be removed in one of the upcoming releases←[0;m
←[31;1mFATAL: Failed to start gitlab-runner: The specified service does not exist as an installed service.←[0;m
Can you help me, please ? thnks :)
I found the solution, The service was launched by the Local System user, which does not add the Windows\system32 in the PATH.
I changed the user who launches the service to %username% of the session and it works :)
Sorry if I can't help. This issue seems to be happening in Windows and Linux as well.
I also received the following messages in the terminal:
Setting up gitlab-runner (10.0.0) ...
GitLab Runner: creating gitlab-runner...
WARNING: Since GitLab Runner 10.0 this command is marked as DEPRECATED and will be removed in one of the upcoming releases
gitlab-runner: Service is not running.
WARNING: Since GitLab Runner 10.0 this command is marked as DEPRECATED and will be removed in one of the upcoming releases
gitlab-ci-multi-runner: Service is not running.
WARNING: Since GitLab Runner 10.0 this command is marked as DEPRECATED and will be removed in one of the upcoming releases
WARNING: Since GitLab Runner 10.0 this command is marked as DEPRECATED and will be removed in one of the upcoming releases
thnks for answering, I found the solution :D
| common-pile/stackexchange_filtered |
How to run tkinter function with both a key bind and a button command?
Is it possible to run a function with both a button press and an event? When I try to run this function by pressing the button, it, understandably, gives an error
TypeError: listFiller() missing 1 required positional argument: 'event'.
Couldn't find a similar problem, but maybe that is just my lack of programming knowledge.
Code:
class MyClass:
def __init__(self, master):
self.myButton = tk.Button(master, text='ok', command=self.listFiller)
self.myButton.pack()
self.myEntry = tk.Entry(master)
self.myEntry.bind("<Return>",self.listFiller)
self.myEntry.pack()
def listFiller(self, event):
data = self.myEntry.get()
print(data)
Try setting event=None for the function and then passing event from the bind only, like:
self.myButton = tk.Button(master, text='ok', command=self.listFiller)
.....
self.myEntry.bind("<Return>", lambda e: self.listFiller()) # Same as lambda e: self.listFiller(e)
def listFiller(self, event=None):
data = self.myEntry.get()
This way, when you press the button, event is taken as None. But when bind is triggered(i.e.,Enter is hit), event is passed on implicitly(works even if you pass it explicitly) as e.
So after you have understood how this works behind the hood, now even if you remove lambda, e would still get passed as event as it happens implicitly.
self.myEntry.bind("<Return>",self.listFiller) # As mentioned by Lafexlos
Though keep in mind, when you press a tkinter button, you cannot use any attributes from event, like event.keysym or anything, but it would work if you use Enter key.
I don't think you need lambda in the bind. you can directly use self.myEntry.bind("<Return>", self.listFiller) and that should pass event parameter automatically.
@Lafexlos Yes, that is true too. I wanted to show the working behind it. Ill add that in. Thanks for mentioning it.
| common-pile/stackexchange_filtered |
Separate data and text from one cell to provide a duration with a summary
There.
I am trying to solve a problem with our current data collection at my office. As of now every Friday the entire team use a shared excel sheet to update their assigned project about the next activities with a date and a small description.
For example " 11/17/23 Awaiting proposal approval; 11/10/23 project cost review; 11/03/23 contract proposal due on Monday...........etc." So the project history is in one cell showing as I mentioned.
I am trying to get a monthly data table showing a monthly duration (start and finish) with all notes associate with it for that month (and so on for each month). I have attached a snip how our data looks like and what I would like to accomplish, I am new to excel world and I am not as smart as anyone in this group.
I would really appreciate if you could help, guide, or explain to me how we can accomplish this.
Here is an image of what I am trying to accomplish
I have tried to Delimiters by semicolon, but I can't group weekly dates to months and separate texts to group.
| common-pile/stackexchange_filtered |
ftruncate not working on POSIX shared memory in Mac OS X
I have written a code on Mac OS X to use POSIX shared memory as shown below:
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
int fileHandle = shm_open("TW_ShMem1",O_CREAT|O_RDWR, 0666);
if(fileHandle==-1) {
//error.
} else {
//Here, it is failing on Mac OS X
if(-1==ftruncate(fileHandle, 8192)) {
shm_unlink("TW_ShMem1");
fileHandle = -1;
} else {
return 0;
}
}
return 1;
}
ftruncate on Linux is working without any problem. On Mac OS X, it is returning -1 and errno is EINVAL (as seen in the debugger).
Why is it failing? What is being missed here?
The OS X man page for ftruncate claims it can fail with EINVAL only if it's a socket rather than a file, it's not open for writing, or the length argument is less than zero. So, what's the value of p_size? And does the same thing happen if you open & ftruncate a regular file, and then mmap it?
Can you provide a self-contained compilable example?
memoryName is "TW9_Shm1" and size is 8192.
It works on Linux but not on Mac OS X. It failed at ftruncate.
@Useless: Yes. It is same thing. Open and ftruncate shared memory file and mmap it. mmap is done in the next function.
That still isn't a self-contained compilable example, this is. You can edit the code into your question.
@Useless: See the edit. It must help. It must compile without any problem on Mac OS X and Linux.
This looks like OSX behaviour - ftruncate only works once on the initial creation of the segment. Any subsequent calls fail in this manner. The earliest reference I can find to this is a post to the apple mailing list.
If I put an shm_unlink before the shm_open the ftruncate works consistently.
assuming that you only want to resize the shared memory segment the once, you could wrap the ftruncate in an fstat to determine the current size and resize it in the case that st_size == 0
e.g.
struct stat mapstat;
if (-1 != fstat(fileHandle, &mapstat) && mapstat.st_size == 0) {
ftruncate(fileHandle, 8192);
}
Note that this may introduce a race if this code runs in different threads or processes.
The OSX kernel code for shared memory regions says: It can only be done once per shared memory region. The only race would be if you chose different sizes. You're still left with the same limitation - one truncate per lifetime.
Sorry, I meant the fstat check could raise in different processes. Of course, if one just ignores the ftruncate return value it still works, but the fstat check isn't strictly speaking necessary then.
| common-pile/stackexchange_filtered |
How to solve mousemove event bug in Chrome
I give mouseup mousedown mousemove different event handler:
var body = document.querySelector("body");
body.addEventListener("mouseup", function () {
console.log("mouseup");
});
body.addEventListener("mousedown", function () {
console.log("mousedown");
});
body.addEventListener("mousemove", function () {
console.log("mousemove");
})
when I click right mouse button, open the context menu, without mouse move, it will trigger the mouse move event,
the more strange thing is, if I open the context menu again, event the mouse down event couldn't be trigger, could only trigger the mouse move event
http://jsfiddle.net/WZSva/
How can I solve this problem?
| common-pile/stackexchange_filtered |
SQL - update query - update to next date value that is not NULL
I have a bunch of values that are currently on dates with NULL value (i.e. no data available on those particular dates).
How would I go about updating those values to the next date where there is data available?
I have a select query currently which highlights all values that lie on a date with NULL value (or false data defined by a value of less than 0):
select * from table1 a
left join table2 b on a.id=b.id and a.date=b.date --joins dates table to main data set
where a.id in (select c.id from table3 c
left join table4 d on c.id=d.id where c.value = 000000) -- sub query identifying sub set of data I want to use as 'id' list
and a.date is not NULL and a.date > '1900-01-01' --a.date not NULL just identifies illegitimate date values that I don't want to see
and (b.value is NULL or b.value < 0) --identifies legitimate values that fall on dates where there are NULL values or false dates
So this query gives me all values from a chosen data set that fall on dates with false data or NULL values. There are a few more 'where' and 'and' variables I've used in the query but this hopefully gives a good base of understanding.
I would like to update all of these values to the next date in the future that is not NULL (i.e. has legit data).
Just a small example of what I'm thinking: update table1 set date = (assume there would be some sort of select sub query here to define next date value that is not NULL).
Just another note to take into consideration: the next date that the value is not NULL is dynamic - it could be 2 days from given date but it could be 2 years.
Posting some sample data, and the expected results, along with your attempt(s) to solve the problem will be really helpful. here.
You say you can't post your actual query, but you can post a dummy dataset with fake column names that match the data types of your source data as well as a simple version of the query you have, adjusted to use the dummy schema. SO users are offering to help you free of charge and on their own time, so do please try to be as helpful as possible
In addition, it is unclear what you actually want to achieve here. What does How would I go about updating those values to the next date where there is data available. actually mean? Source data and desired output would really help in clarifying this.
You can modify your query to replace the confidential information with dummy variables. The question is a little hard to understand in its current state. Do you want to change dates based on info (your query says "update table1 set ex_date =") or copy over info from other dates?
Thanks for replying so soon guys, I'll add more context tomorrow - apologies, wrote this at the end of the day in a hurry - thank you for your help so far
/*I would create a variable table @mytab in which I will put sample sample data
with dates and null*/
--Kamel Gazzah
--07/03/2019
declare @mytab as table(id int identity(1,1),mydate date)
insert into @mytab values('01/01/2018')
insert into @mytab values(NULL)
insert into @mytab values('01/05/2018')
insert into @mytab values('01/07/2018')
insert into @mytab values('01/08/2018')
insert into @mytab values(NULL)
insert into @mytab values(NULL)
insert into @mytab values(NULL)
insert into @mytab values('01/08/2018')
select * from @mytab
--First Method with **OUTER APPLY**
update t1 set mydate=t2.mydate
--select t1.*,t2.mydate
from @mytab t1
OUTER APPLY (select top 1 * from @mytab where mydate is not null and id > t1.id order by mydate) t2
where t1.mydate is null
--SCOND METHOD WITH **LEFT OUTER JOIN**
update ta set mydate=tc.mydate
--select ta.id,tc.mydate
from @mytab ta
inner join(
select id1,min(id2) id2 from(
select t1.id id1,t2.id id2,t2.mydate from @mytab t1
left outer join @mytab t2 on t2.id > t1.id and t2.mydate is not null
where t1.mydate is null) v group by id1) tb on ta.id=id1
inner join @mytab tc on tb.id2=tc.id
select * from @mytab
Will give this a go!
You can solve it using apply
UPDATE T
SET Date = N.Date
FROM yourTable T
OUTER APPLY (
SELECT TOP 1 Date FROM YourTable
WHERE ........
ORDER BY ..........
) N
WHERE T.Date IS NULL
Will give this a go too...didn't even realise outer apply was a thing...learn something new every day - only been doing SQL for a month but really enjoy it
| common-pile/stackexchange_filtered |
Is there any way to test if a function running only on plugin update is successfully running?
Is there any way to test if a function running only on plugin update is successfully running? Right now I am calling function if WP version present in configuration file is not same as plugin version's value in database and so testing by changing value of constant. But is there any other better approach?
Is there any way to test if a function running only on plugin update is successfully running?
Yes.
Background
When you update a plugin, WordPress does several actions behind the scenes.
Download the new version of the plugin
Deactivate the old plugin version
Delete the old plugin version
Extract the new version
Activate the new version
In addition to the hooks that WordPress fires during those actions, it fires upgrader_process_complete. This hook passes two parameters to the callback: $this, which is obviously the object instance, and $options['hook_extra'], which are extra arguments passed to the filter hooks called by WP_Upgrader::install_package(). The Plugin_Upgrader class passes the following array:
array( 'plugin' => $plugin,
'type' => 'plugin',
'action' => 'update',
)
Upgrader Hook
Therefore, if we want to run a function on a plugin upgrade, we can use this hook.
add_action( 'upgrader_process_complete', 'wpse_262412_upgrader_process_complete' );
function wpse_262412_upgrader_process_complete( $instance, $extras ) {
//* Only interesting when 'our' plugin updates
if(
'plugin' !== $extras[ 'type' ] &&
'update' !== $extras[ 'action' ] &&
'my-plugin-name' !== $extras[ 'plugin' ]
) {
return;
}
//* Do something useful after your plugin updates
wpse_262412_something_useful();
}
Checking
If you are developing a plugin and want to makes that a particular function runs on plugin update, then you can add an option to the database:
function wpse_262412_something_useful() {
include_once( ABSPATH . '/wp-admin/includes/plugin.php' );
$data = get_plugin_data( 'my-plugin-name' );
update_option( 'my-plugin-update-option', $data[ 'version' ] );
}
Then we can add an action to init that checks that option value. If the option value is equal to the current plugin version, then we know that the function has run. Then we can make sure we can see that the function has been run, like add an admin notice.
add_action( 'init', 'wpse_262412_init' );
function wpse_262412_init() {
$data = get_plugin_data( 'my-plugin-name' );
$option = get_option( 'my-plugin-update-option' );
if( $data[ 'version' ] === $option ) {
//* The plugin update function ran successfully
add_action( 'admin_notices', 'wpse_262412_update_notice' );
}
}
function wpse_262412_update_notice() {
?>
<div class="updated notice">
<p><?php _e( 'The function has run correctly.', 'wpse-262412' ); ?></p>
</div>
<?php
}
But is there any other better approach?
Is this better than your approach? I don't know. Depends on your application. It doesn't involve opening and reading a configuration file, so it will likely be faster. But probably not noticeably much. I wouldn't do either method on a production site. Make sure your code works on a development server, then use it. If you're talking about comparing plugin version numbers, that seems like as good as any way to do it to me.
| common-pile/stackexchange_filtered |
What are some more detailed dictionaries?
In the past few days I read through half of the excellent grammar book by Claudia Ross and Jing-heng Sheng Ma and all of the very enlightening "Aquisition of Word Order in Chinese as a Foreign Language" by Wenying Jiang (I recommend reading both). One of the things that the first book really managed to clear up for me was that the traditional Western grammar terms don't really transfer over to Chinese. A lot of the questions I've had about the language after studying it for several years were cleared up by learning about how stative verbs, open-ended action verbs, change-of-state action verbs, adjectival verbs, complements, etc. are used in quite different ways in Chinese.
The problem is, when I go look up a word in a dictionary, at most it's gonna say "verb" or "adjective", which isn't very helpful to me. I know that I can just translate "adjective" to "adjectival verb", but I wish the dictionary took into account the unique structure of Chinese grammar, rather than presenting simple, familiar terms.
So my question is: are there any Chinese-English dictionaries that provide a, shall we say, less eurocentric grammar?
"adjectival verb"seems to be a term adopted by the authors Claudia Ross and Jing-heng Sheng Ma of the textbook available free on the web,hardly used elsewhere, to call readers' attention to the absence of link verb "是",when used predicatively, which incidentally also applies to such European languages as Russian (not necessarily other Slavic languages). Chinese grammars still call it 形容词,adjective。
Exactly what is expected of such a more detailed dictionary?As far as different types of verbs are concerned, these can be recognized from definition given in the praised text. As far as complements are concerned, grammar tells how to recognize and construct them. 对这样更为详尽的词典的要求到底是什么?就动词不同种类而言,为了识别这些动词,就够使用受到提问者的赞扬的课本中的定义了。就补语而言,语法也会说明怎样识别而构造。
The reason I gave "adjectival verb" as an example, was to show that ordinary dictionaries are fine for that particular aspect. It's all of the other terms I was missing.
I asked the same question on Reddit and was recommended the ABC Chinese-English dictionary. It uses many of the terms I have outlined by design.
"terms outlined by design": stative verbs, open-ended action verbs, change-of-state action verbs, adjectival verbs, complements, it seems dictionary not to merely say a, v, but where appropriate uses one of the above terms, it seems quoted types have an easily recognized characterization making such notation questionable, as far as complements (word or phrase attached to a verb or adjective predicate to complete the meaning ...) are concerned, it seems all that could be expected is giving examples where words in dictionary (of which there are many) are commonly used to form complements.
Sorry, but I'm having a bit of a hard time trying to understand what you wrote. Regardless, this dictionary solves my problem, so I'm happy with it.
comments are restricted in length, therefore users using comments often feel obliged to omit words, in order to only use one comment space
for other users' info: ABC C-E dictionary contains the following 4 abbreviations related to verbs: v. 动词 verb, rv. resultative v. 动补式,vp. verb phrase 动词词组,vo. verb-object 动宾离合词,none of the terms " stative verbs, open-ended action verbs, change-of-state action verbs" mentioned in Q among them, reference to (resultative) complement, however is implicit in rv. verb-complement construction e.g. 看见, after long search user found one entry with vp.:扫地出门,
using the definition "the component of a sentence that contains the verb and an object" would yield many more, e.g. 扫地.耕地/田,交税 which are in ABC with notation "vo."only, 付钱 is not, readers are reminded that their "vo." means a special type of verb-object construction, namely 离合词。
The online dictionary Wiktionary (a brother of Wikipedia) offers some usage notes and technical information on individual words, and they have a knowledgeable and active Chinese userbase. Some entries are a bit spotty, but you can expect most of them to be pretty good.
It's ok as a dictionary, but doesn't solve this specific issue.
| common-pile/stackexchange_filtered |
How to resolve : javax.xml.transform.sax.SAXSource cannot be cast to java.io.Serializable [BonitaSoft]
I'm trying to create a task in BonitaSoft and connect it to a webService created using Spring Boot I finished all the steps and when i want to test my web service i get this Error :
I can see that the Web service is running or consumed here :
So the problem is when i want to get the result, ... here is the code where I parse the XML to get the result :
if you need any additional information please feel free to ask
Did you test your connector by running the process? This warning message tell you that when the Studio test the execution of the connector it will not be able to deal with connector output that are not Serializable. If you add one or several Groovy script(s) to process the connector output(s) they will not be used when testing the connector in the Studio. Your only option to actually verify that you get the expected output is to run the whole process (or run the connector outside the Studio but that would require to add some stubs for Bonita Engine execution context).
Thank you so much it's work (y)
@AntoineMottier please do you have an idea if i want to restart the process automatically if the web Service return false
well I have an instantiation form which is an authentication form so after submitting email and pwd from the form to the service and the service get the result then if it's true we pass to the next task (I did this) but if it's return False i want to come back to the instantiation form thats what i couldn't do it
this is a different question so I recommend to create a separated one in order to avoid polluting this thread. Thanks.
@AntoineMottier yeah i created a new question here is the link if could help me on it : https://stackoverflow.com/questions/54406353/how-to-restart-the-process-if-the-result-of-the-web-service-is-false-bonitasoft thank you in advance
This warning message tell you that when the Studio test the execution of the connector it will not be able to deal with connector output that are not Serializable.
If you add one or several Groovy script(s) to process the connector output(s) they will not be used when testing the connector in the Studio.
Your only option to actually verify that you get the expected output is to run the whole process (or run the connector outside the Studio but that would require to add some stubs for Bonita Engine execution context).
| common-pile/stackexchange_filtered |
Grammar for Unix command line options
This is a homework question. I would like to write a simple parser for Unix command line options.
First, I would like to define a grammar with BNF.
Options = Option | Options, space, Option;
Option = OptionName | OptionName, OptionArguments;
OptionName = '--', any character excluding '-' | OptionName, any character;
OptionArguments = OptionArgument | OptionArguments, space, OptionArgument;
OptionArgument = any character excluding '-' | OptionArgument, any character;
("any character" here is any alphanumeric character).
Does it make sense ? The next question is how to add "old" Unix options, which start with a single hyphen and can be grouped together (e.g. ls -lht)
You ought to tag it as homework.
@khachik: he isn't excluding it, he's only excluding it in the first occurrence. Although it may appear in the first occurrence indeed.
Just notice that the given grammar is quite ambiguous - for example, if you have a few words in a row, you wouldn't know if these are different options or an option with some arguments.
As for your second question (regarding "old" unix), you could add another rule to the grammar, something of the sort:
option -> optionGroup | (anything that was there before);
optionGroup -> '-', flags;
flags -> flag | flag, flags;
flag -> single letter;
| common-pile/stackexchange_filtered |
Can I use In-App-Purchases when distributing outside of Apple's App Store?
I'm new to mac os app development and the documentation doesn't ever say that this is not supported (as far as I could tell).
Can I use IAPs if I don't submit to the App Store?
Is there anything different that I should do to setup IAPs when distributing outside of the App Store?
It looks like this is not possible, as documented here:
https://developer.apple.com/macos/distribution/
Only iCloud and Push Notifications are available.
I think its possible by following instructions below.
Go to itunesConnect , Users and Roles, Create a sandbox user . I am thinking you have already made the in app purchase items in your app in itunes connect. Now in your device log out the Appstore ID from settings. Do the in app purchase using the Test user credentials you created, and it will make the in app using a sandbox environment.
For more info about In App follow this link :
https://www.raywenderlich.com/122144/in-app-purchase-tutorial
| common-pile/stackexchange_filtered |
increase size of multiple histograms
i have the following small multiples but i cannot increase their size. Anyone any idea on how to increase their size?
from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300 + ['D']*500
y = np.random.randn(1500)
df = DataFrame({'Letter':x, 'N':y})
#plt.figure(figsize=(70,90))
df['N'].hist(by=df['Letter'])
plt.show()
The output is this:
image
df['N'].hist(by=df['Letter'], figsize=(10, 10))
Please review https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html
plt.rcParams['figure.figsize'] = (20, 10)
| common-pile/stackexchange_filtered |
'df' command doesn't show file system requested in ubuntu 14.04
This strange behavior begins a few day ago. This is df of all file system
michele@OptiPlex-360:~$ df
File system 1K-blocchi Usati Disponib. Uso% Montato su
udev 1974808 8 1974800 1% /dev
tmpfs 397120 1340 395780 1% /run
/dev/sda1 45225008 14448892 28455736 34% /
none 4 0 4 0% /sys/fs/cgroup
none 5120 4 5116 1% /run/lock
none 1985596 80 1985516 1% /run/shm
none 102400 68 102332 1% /run/user
/dev/sda6 190822060 65912468 115193268 37% /media/volume1
Now I ask for sda1 and it gives me a wrong answer
michele@OptiPlex-360:~$ df /dev/sda1
File system 1K-blocchi Usati Disponib. Uso% Montato su
udev 1974808 8 1974800 1% /dev
instead sda6 works
michele@OptiPlex-360:~$ df /dev/sda6
File system 1K-blocchi Usati Disponib. Uso% Montato su
/dev/sda6 190822060 65912468 115193268 37% /media/volume1
Well, what's wrong?
Ah, same issue I have on my other PC with same Ubuntu installed.
Additional output as muru asked for:
michele@OptiPlex-360:~$ mount | grep /dev/sda1
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
michele@OptiPlex-360:~$ df /
File system 1K-blocchi Usati Disponib. Uso% Montato su
/dev/disk/by-uuid/2438603c-1bfd-4e79-9f6c-ad6575988aee 45225008 14448908 28455720 34% /
[Edit] your post to include the output of mount | grep /dev/sda1 and df /, please.
My personal explanation to this effect is the following: df reads /proc/self/mountinfo file but doesn't find /dev/sda1 there.
I know it reads /proc/self/mountinfo because when I do strace df /dev/sda1 I get the following line in the output
open("/proc/self/mountinfo", O_RDONLY) = 3
Now, if we examine that file, /dev/sda is not there, but it does find /dev/sdb there, which explains correct reports for those partitions.
================
xieerqi:
$ grep 'sda' /proc/self/mountinfo
================
xieerqi:
$ grep 'sdb' /proc/self/mountinfo
43 22 8:18 / /media/WINDOWS rw,nosuid,nodev,noatime - fuseblk /dev/sdb2 rw,user_id=0,group_id=0,allow_other,blksize=4096
49 22 8:21 / /media/xieerqi/0ca7543a-5463-4a07-8bbe-233a7b0bd625 rw,nosuid,nodev,relatime - ext4 /dev/sdb5 rw,data=ordered
Why it's not there ? I don't know. I can only provide what I've found.
But why does it report udev in the output ? df looks at filesystems, and /dev/sda1 is under /dev folder, which is where udev virtual filesystem is mounted. It's the same behavior if we'd call df FILE, like df /home or df /media/MYWINDOWSPARTITION/RANDOMFILE.txt
I would suggest reporting it as a bug or at least ask the GNU developers about this behavior (copied from man page )
REPORTING BUGS
Report df bugs to<EMAIL_ADDRESS> GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
Report df translation bugs to <http://translationproject.org/team/>
Edit
In addition, the df / behavior is explained again by /proc/self/mountinfo file having the following entry
22 0 8:1 / / rw,noatime,nodiratime - ext4 /dev/disk/by-uuid/86df21bf-d95f-435c-9
292-273bdbcba056 rw,errors=remount-ro,data=ordered
The root filesystem itself is mounted as /dev/dis/by-uuid/ACTUAL-UUID-NUMBER.
But I don't have explanation for df with no arguments reporting /dev/sda1 rather than the path to disk by uuid. Probably the reason is because /dev/dis/by-uuid/ACTUAL-UUID-NUMBER itself is a symlink to /dev/sda1, so it resolves it fully without arguments, but with arguments needs to search /proc/self/mountinfo file
That's normal (for the second output) as partitions are mounted by their uuid, not using device names (that's the older style)
Some Linux distributions use the old style and some use the new ones.
Here is a note to better explain the issue mount partitions by uuid
This mechanism protects against changing disk drive order of you swap disks inside your hardware. If you want, you can easily change this by specifying the device name in /etc/fstab.
All my partitions are mounted using UUIDs, but df -h /dev/sdXY works as intended.
| common-pile/stackexchange_filtered |
Alternative to RemoveAt and Insert list items
I am looking for a better data structure or method to simply replace an object in an dynamic array. It seems like list is the choice, however I read and notice that the performance of RemoveAt and Insert is not as good as I had hoped.
Let me elaborate on what I am trying to achieve:
List1
List item 1
List item 2
List item 3
List2
List item 1
List item 2
Null
Both list uses the same object types. I want to replace the null list item of List2 with List1[1] -- List item 1 clone. I use a clone so the value of the copied list item is a separate instance.
I also want to replace list item 2 of List2 with a clone of list item 1 of List2.
Here is some example code of what I am trying to achieve:
projCraneVertices.RemoveAt(projCraneVertices.Count - 4);
projCraneVertices.Insert((projCraneVertices.Count - 3), realCraneVertices[botPoint].clone());
projCraneVertices.RemoveAt(projCraneVertices.Count - 3);
projCraneVertices.Insert((projCraneVertices.Count - 2), projCraneVertices[botPoint].clone());
projCraneVertices.RemoveAt(projCraneVertices.Count - 2);
projCraneVertices.Insert((projCraneVertices.Count - 1), realCraneVertices[topPoint].clone());
projCraneVertices.RemoveAt(projCraneVertices.Count - 1);
projCraneVertices.Insert((projCraneVertices.Count), projCraneVertices[topPoint].clone());
I also want to replace list item 2 of List2 with a clone of list item
1 of List2.
Well, you can do it simpler like this:
proCraneVertices[2] = realCraneVertices[1].Clone();
I thought it should be this easy. I tried something similar to this before without the clone function and it was not working as intended. Thank you.
From what I can understand, you want a Replace method. Try this extension:
public static class Extensions
{
public static void Replace<T>(this IList<T> list, int index, T item)
{
list[index] = item;
}
}
Call like:
List<int> ints = new List<int>() { 1, 2, 3 };
List<int> ints2 = new List<int>() { 4, 5, 6 };
ints.Replace(0, ints2[0]);
The above will make the first list - 4, 2, 3.
using List of T will solve you problem of removeAt and inset this uses Array under the hood and will expose some good functions to you that will help to ridoff these anoing methods.
you can use some of function provided by List like below.
Replace // Replact the item from one item to another item
List of T Class
| common-pile/stackexchange_filtered |
Negative Rotation Speed (vsini)
I've repeatedly seen the rotation speed of a star given as a negative. Does this mean that the star started spinning in the opposite direction at some point?
Your link doesn't work for me.
| common-pile/stackexchange_filtered |
Dispatcher forward method from POST to GET
I need to forward from my FooServlet doPost method to BarServlet doGet method. Is there a way to solve this?
Currently I'm calling the doGet method from my doPost but I'm sure that this isn't the best practice.
You fail to understand the meaning of HTTP methods. Please read our servlets wiki page: http://stackoverflow.com/tags/servlets/info
Assuming HTTP servlets intended for web-based use, I would recommend a ServletResponse.sendRedirect(...) to have the client request service from BarServlet in order to convey some insight into the server's view on things, and to avoid unintended re-POSTs, and so on.
You probably want to do a redirect "303 See Other" (see the HTTP spec, RFC1626).
| common-pile/stackexchange_filtered |
Syntax puzzle with derived template class and inherited member variables
While porting some Windows legacy code and trying to get it to compile with gcc/clang I ran into the following problem which I don't fully understand:
template<typename T> class Base
{
public:
Base() {}
T m_var;
};
template<typename T> class Derived : public Base<T>
{
public:
Derived()
{
#if 1
Base<T>::m_var = 0; // fix - compiles with gcc/clang now
#else
m_var = 0; // original - compiles only with MSVC++
#endif
}
};
The error from gcc/clang is:
error: use of undeclared identifier 'm_var'
Unfortunately there are hundreds of places where the unqualified member variables are referenced in the derived class methods, and I don't really want to have to change all these so that they are qualified with Base<T>:: if I can help it.
Can anyone explain why gcc/clang seems to need this while MSVC++ doesn't, and suggest possible workarounds ?
Since Base<T> is a dependent base, its members are not accessible through unqualified lookup. As you noted, you can access them through Base<T>::m_var. Another option would be this->m_var.
I'm not sure there's a succinct workaround for this. One option would be to add a T& m_var; data member to Derived and initialize it to reference Base<T>::m_var. If you can't live with the extra reference member, you could add a T& m_var = this->m_var; to the start of any function with an unqualified m_var access.
Thanks for the concise explanation - presumably then MSVC++ is just wrong to compile this without complaint?
@PaulR most likely, yes. I vaguely remember that a few years ago, g++ didn't complain about this kind of code, and that I had to fix some similar code when it started enforcing the rule.
@PaulR Yeah, it's because of their lack of two-phase lookup. The member is just looked for at instantiation time and ignored when the template definition is checked AFAIK.
As @TartanLlama said, the member is not available through unqualified lookup because of the base type that depends on the template parameters. Apart from accessing it as Base<T>::m_var or this->m_var, there is a workaround that I strongly prefer since it has to be typed only once for each class member that you want to make accessible:
Simply add a using Base<T>::m_var; to the class definition of Derived. This way, m_varwill be found by the normal name lookup.
Thanks for the workaround suggestions - the using ... idea is perfect in this instance as it means that I can avoid butchering all the derived methods.
@PaulR You're welcome! Sorry that I might use the respective terms in a slightly loose/non-standard fashion. I'm not that familiar with the standardese language here...
| common-pile/stackexchange_filtered |
How to use web workers with svelte and esbuild?
I'm following this tutorial on how to use web worker in svelte but I'm getting an error
https://publish.obsidian.md/kometenstaub/50-Programming/Esbuild+web+worker
Svelte file Codeblock where I use worker
import Worker from 'src/timerWorker'
const worker = Worker();
worker.postMessage(['hello world']);
timerWorker.ts
self.onmessage = function(e) {
console.log(e);
}
In esbuild config I specify plugins
plugins: [
esbuildSvelte({
compilerOptions:{ css: true },
preprocess: sveltePreprocess(),
}),
inlineWorkerPlugin(),
],
The error:
My worker file was named in wrong format.
Supported file extensions for the worker are .worker.js, .worker.ts, .worker.jsx, .worker.tsx. Source: https://github.com/mitschabaude/esbuild-plugin-inline-worker#esbuild-plugin-inline-worker
| common-pile/stackexchange_filtered |
$-\Delta u = f$ in $L^2(0,T;H^{-1}(\Omega))$ (as opposed to $H^{-1}(\Omega)$)
Why does nobody consider the equation $-\Delta u = f$ in the space $L^2(0,T;H^{-1}(\Omega))$?
Eg. given $f \in L^2(0,T;L^2(\Omega))$ find a solution $u \in L^2(0,T;H^1_0(\Omega))$ such that
$$\int_0^T \int_\Omega \nabla u(t) \nabla v(t) = \int_0^T\int_\Omega f(t)v(t)$$
for all $v \in L^2(0,T;H^1_0(\Omega))$. This solution exists by Poincare's inequality which applies on a.e. time:
$$\int_\Omega |\nabla v(t)|^2 \geq C\int_\Omega |v(t)|^2\quad\text{for a.e. $t$}$$
and then we apply Lax-Milligram.
Of course I know that Poison's equation is an elliptic equation, and Bochner space is for parabolic equations. But is there anything wrong with what I wrote?
There is no time derivative or dependence in $-\Delta f=u$, so why should we look for a function depending on time?
@YiorgosS.Smyrlis But I want $f$ to be time-dependent. (I don't want a time derivative $u_t$ in the equation either).
There is nothing that can stop you.
| common-pile/stackexchange_filtered |
PHP - Parse XML with simplexml_load_string - Getting empty values with CDATA?
When parsing an XML array like:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<Code>ABC-1001</Code>
<Brand>ZCOM</Brand>
</Product>
</Products>
I get an output of:
Array
(
[0] => Array
(
[Code] => AP1024-DDRII640
[Brand] => ZCOM
)
}
But when the XML is like:
<?xml version="1.0" encoding="utf-8"?>
<Products Code="ABC-1001">
<Product>
<Code><![CDATA[ABC-1001]]></Code>
<Brand><![CDATA[ZCOM]]></Brand>
</Product>
</Products>
It returns:
array
0 =>
array (size=12)
'@attributes' =>
array (size=1)
'Code' => string 'ABC-1001' (length=8)
'Code' =>
array (size=0)
empty
'Brand' =>
array (size=0)
empty
This is how the XML is parsed from a URL:
$updateUrl = file_get_contents('http://www.someplace/xmlfeed/xml.cfm?asd=12345&uhg=9999');
$updateXml=<<<XML
$updateUrl
XML;
$updateXmlObject=json_decode(json_encode((array) simplexml_load_string($updateXml)), 1);
$updatePHPArray=$updateXmlObject['Product'];
And:
var_dump($updatePHPArray);exit;
Gives the output as above.
Now, why am I getting empty values in the second instance and how could I remedy this without access to the XML source?
what exactly is the point of getting a string, stuffing that string into ANOTHER string using a heredoc, then stuffing that second string into xml, forcing it to an array. json_encoding, json_decoding? That is just total cargo-cult programming.
@MarcB I am a noob... This was the best that I could come up with. Open to any better solutions hey :)
@MarcB I think that i encoded and decoded it to normalize the data if that makes sense? I recall having some characters or something that were giving me a hard time.
SimpleXML with cdata -> http://stackoverflow.com/questions/2970602/php-how-to-handle-cdata-with-simplexmlelement
@BrainFooLong Thanks, did not spot this one.
@MarcB I'd still love to see how you would tackle this task, just saying :)
well, since there's some normalizing going on, then that's ok. but just for raw conversion: $xml = simplexml_load_file('http:/...'); would do.
By using that json_decode(json_encode()) hack, you've simultaneously thrown away all the features of SimpleXML, and introduced a whole load of unnecessary problems for yourself. The result of simplexml_load_string/simplexml_load_file is an object with lots of useful magic powers, don't just throw it away at your first opportunity.
@IndigoIdentity: Why do you convert the product to an array in the first place?
@hakre To process the data in various ways.
@IndigoIdentity: I have good news for you then: You don't neeed to convert to array. So this solves your problem already. Just access the data from the SimpleXMLelement object and you're already done. The problem you describe you have also immediately disappears.
The problem seems to be that the cast you're doing to array can return results different than the actual structure of the XML object.
Something like the following code should give you an array with the correct info:
$array = array_map('strval', (array) $xml->Product);
Take care you cast those parts to string of which you'll get the data from (in the example done via strval()). In the opposite, json_encode() is not working well with SimpleXMLElement.
Thanks, reading this and after the comment by @BrainFooLong , simply passing LIBXML_NOCDATA as the third argument within simplexml_load_string() will solve this. I saw this in the docs while reading the comments as u had suggested :)
@IndigoIdentity I can't stress enough that LIBXML_NOCDATA is not necessary. Just don't use hacks like json_decode(json_encode($blah)), and don't trust var_dump. Instead, read the examples of how to use SimpleXML properly.
| common-pile/stackexchange_filtered |
How to make the facebook comments on my website and on page's wall post binded?
everybody.
I am developing the facebook tab application. The functionality is pretty simple and is close to the blog.
Page Admin writes articles in the app, and the link to each article is posted on the page's wall via Graph API.
The wall post from step 1 contains a link to the application tab of the page with post_id passed via app_data parameter.
The article itself contains the facebook like and comments plugins on it. To attach this plugins I use the url of the external website on which pages are prepared for Facebook scraping (Open Graph tags and stuff).
And finally the question!
Is it possible to somehow manage the situation whenever user posts the comment inside an application tab, his comment automatically appears near the wall post performed in step 1?
I really hope that the question is clear. Any help, please?
How you posted on page's wall
I was using facebook-php-sdk. The info about the procedure was found here http://developers.facebook.com/docs/reference/api/page/#posts
I am using the same procedure.but the link is posted under the label "Recent Posts by Others on aBC".But I want to post it on Page wall.Have you used page access_token for posting
Yes, I was using page access token with publish_stream and manage_pages permissions requested before.
Thank you. Page acces_token worked for me
You can publish comments to a Post via the Graph API:
https://developers.facebook.com/docs/reference/api/post/#comments
You will need to ensure that you have:
Requested publish_stream permission from the user
Indicate to the user very clearly that you are going to publish a comment when they do this (to do otherwise would not only break Platform Policy, but would be a crappy experience for users)
Subscribe to the Javascript comment.create event which is fired when someone posts a comment in a comments plugin: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
Thanks, this seems to be an appropriate solution
| common-pile/stackexchange_filtered |
Installing GRUB on a different disc
I'm not sure what does the "Device for bootloader installation" do exactly. My Ubuntu install is on a separate drive but I'd rather put a separate EFI partition on an SSD and have kernels and all that stuff load from an SSD. I also have a separate Windows partition and its EFI on there so I removed boot and esp flags from it in hopes that Windows loader wouldn't override GRUB.
So... The question is, how would I go about doing all that. Do I create /boot on my SSD and use it as an install path, Do I NOT create any /boot partitions and just pick the nvme0 drive, I'm used to partitioning /boot and /efi instead of /boot/efi, maybe I create /efi on my SSD. I haven't reinstalled Linux in so long, I'm so out of touch right now.
How large is Windows on SSD? If only one drive, both Windows & Ubuntu share that ESP in different folders. If only using grub the Windows default of 100MB on older Windows is large enough. ESP must be FAT32 with boot,esp flags. A /boot partition must be Linux format default in Ubuntu is ext4. I remove all snaps with Kubuntu and use about 16GB in / with 30 to 40GB as partition size. Then have all data in other drive or separate partiiton(s). You can most some Windows data to 2nd drive and have Linux data on 2nd drive so operating systems are on faster drive.
You can install grub on any drive, but it will only boot from the boot drive.
This is a function of your system firmware. The EFI standard allows you to put the bootloaders for all operating systems in the same EFI partition. If you have multiple EFI partitions, you will need to alter your bios settings to select which one is used. Some bioses only support using the EFI partition on the first disk.
Having said that, the EFI partition typically only contains the bootloader which is very small. You can move the /boot partition (which usually contains the kernel and initrd) to any disk, or sometimes even merge it with the main operating system disk.
The partition is called the EFI partition, but this has nothing to do with where it is mounted. The standard is to mount it at /boot/efi and grub may not install correctly if you mount it at /efi instead.
Thank you, sure I will change the EFI partition used in BIOS. Separating /boot and /efi may not work on other Bootloaders, it works on GRUB2. /efi is used for the GRUB itself, it can look for kernels in /boot. I have a laptop with this kind of partition table, I made a mistake there by keeping a windows /efi which created problems down the line due to 300mb size. The separation of /efi and /boot was a solution to that. Anyway, I don't have to worry about it here, should I make a /boot on an SSD and select it as a file path then&
efi and boot must be separate partitions. Where they are mounted in the filesystem is irrelevant except to the grub configuration itself and the things that build that configuration. Partition size is always an issue.
| common-pile/stackexchange_filtered |
How can i call directly Java Arraylist to be printed to a txt file?
This is my code, this is not a specific program. I just exercise myself with the java ArrayLists and making txt File and to store Arraylist variables in this file. I try to make class where i make method for scanner to make a input and then to store it to arraylist. The second method is to make txt file. And the third method is to add thing to this txt file. All methods work, but i don't know how to import Arraylist data to the txt file. I am a begginer and question maybe stupid for some people, i am sorry.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
import java.io.FileWriter; // Import the FileWriter class
public class Bon2Scanner {
public static void Scaner() {
Scanner scanner = new Scanner(System.in);
System.out.println("Write String name:");
ArrayList<String> Name = new ArrayList<>();
Name.add(scanner.next());
System.out.println("Write age int :");
ArrayList<Integer> Age = new ArrayList<>();
Age.add(scanner.nextInt());
System.out.println("Array list with name" + " " + Name);
System.out.println("Array list with age " + " " + Age);
}
// method for making a file
public void bonMetodScanner() {
try {
File bon2 = new File("Bon2Scanner.txt");
if (bon2.createNewFile()) {
System.out.println("File created: " + bon2.getName());
} else {
// System.out.println("File already exists. ");
return ;
}
} catch (IOException e) {
System.out.println("An error occured. ");
e.printStackTrace();
}
}
// method for writing in a file
public void bonMetodWriteScanner() {
try {
FileWriter Bon1Write = new FileWriter("Bon2Scanner.txt");
// Bon1Write.write(getYearCar() + System.lineSeparator());
//
Bon1Write.write("some text 2" + System.lineSeparator());
Bon1Write.write( ?Here i need to add my ArrayList? + System.lineSeparator()); ?????
Bon1Write.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occured.");
e.printStackTrace();
}
}
}
Advice: Forget I/O until you have everything working. Just write what you would write to the file to System.out. Once everything's working, it's actually pretty easy to take what you've be sending to the console and send it to a file
You've made a good start with reading in data and adding it to your ArrayList.
I would recommend leaving I/O until you've got everything working, using System.out instead.
It looks like you want to use the data entered into the ArrayLists you create in the method Scaner() in another method (bonMetodWriteScanner()).
I would recommend making these ArrayLists global variables (meaning they can be used by all methods of your program) by declaring the age and name ArrayLists outside of the methods at the top of the class:
public class Bon2Scanner{
public static ArrayList<String> name = new ArrayList<>();
public static ArrayList<Integer> age = new ArrayList<>();
From here you can access and modify these variables in any method by using
public static void Scaner(){
Scanner scanner = new Scanner(System.in);
System.out.println("Write String name:");
name.add(scanner.next());
Now when you're writing to the file, you can use the ArrayLists.
Some notes:
Scattering static variables throughout a program is considered pretty bad practice, but for the purposes of learning java syntax and variable scope I think it's fine.
Standard practice for naming variables is usually a lower-case character to begin with, which is why I changed your ArrayList variable names to all lower case.
| common-pile/stackexchange_filtered |
Django sessions don't work with Apache installed on Ubuntu
In production server I can't login to my website.
I know that it is some bug of Django with MD5 crypt or something like that, but unfortunately I don't remember what I should do. I am searching the answer since half day, but I can't find this website where was explained this problem.
DO you know how I can do sessions working.
Does everything work fine for you when you go through runserver?
yes, in runserver all is ok, I think that I have this page:
http://code.djangoproject.com/wiki/ModPython#MD5Issues
I will check it is working.
Sorry, but problems is otherwise. I am using subdomains like pl.domain and uk.domain and domain. User is only logged in one subdomain, but I want make it logged in all website. Is it possible?
In answer to this bit the comments
Sorry, but problems is otherwise. I
am using subdomains like pl.domain and
uk.domain and domain. User is only
logged in one subdomain, but I want
make it logged in all website. Is it
possible? – Thomas
you need to allow cross-domain sessions that don't just refer to a subdomain. By default, Django will give you different sessions for bar.example.com and foo.example.com.
In your settings.py set SESSION_COOKIE_DOMAIN to .domain.tld (don't forget the leading dot!) and you'll be sorted.
| common-pile/stackexchange_filtered |
Azure pipeline to run two or more independent pipelines from a wrapper pipeline?
Is it possible to create a wrapper pipeline in Azure DevOps that simply runs two or more independent pipelines (in parallel) and does nothing else?
I have a problem to solve. and the scenario looks like this "*
In my project, I have say 9 teams and each designing separate Sanity Test Script. All of them have their own existing Sanity Pipeline. i.e. 9 Sanity Pipelines*
There is a plan that there will be only One Master/ Wrapper pipeline and this in turn calls upon 9 child pipelines pertaining to Sanity
When master run by Release Engineer or IT Area lead to get report, the child pipelines run in Parallel
Also in master Pipeline, I do not want to be too much lengthy. Simply I want to mention the name of Child pipeline in my individual Job tag ( with params may be ) and it will run. easy configurable " So I was thinking to use following at my master pipeline: resources: pipelines:
pipeline: Sanity1 Source: P00xxx-Sanity1-Pipeline
pipeline: Sanity2 Source: P00xxx-Sanity2-Pipeline
This list should be easily expandable.......
Then How in Jobs--> Job --> Steps can I run the pipeline using alias, e.g. Sanity1 ?? Any example code snippet?
I don't have a ready answer but you can split the steps from the rest of the build process by using templates. That was both the individual builds can include their 1 steps template in a job and the big build can include 9 jobs each referencing a different steps template, one from each sanity build.
This repo shows how to split the steps from the job definition, making is easy to re-use the steps in multiple pipelines: https://www.github.com/Microsoft/vsts-team-calendar/tree/master/
Another approach would be to take the pipeline and leverage templates. The wrapper pipeline can call a template which will leverage all the desired tasks and execution and can be setup to run in parallel as part of the pipeline.
Here's a blog post about this
You can use PowerShell and rest API (Builds - Queue). Add PowerShell step and compose any run sequence. Here you can find different examples to queue builds:
Build Pipeline using powershell
Trigger another build exist in project in Azure Devops
According to your description, you can try to use parameters and conditions to set up the pipeline.
You can try the following Yaml sample:
trigger:
- none
parameters:
- name: pipeline1
displayName: Gradle sample #PipelineName
type: boolean
default: false
- name: pipeline2
displayName: groovy-spring-boot-restdocs-example.git #PipelineName
type: boolean
default: false
- name: pipeline3
displayName: Gradle sample-CI #PipelineName
type: boolean
default: false
pool:
vmImage: 'windows-latest'
steps:
- ${{ if eq(parameters.pipeline1, true) }}:
- task: TriggerPipeline@1
inputs:
serviceConnection: 'TestBuild'
project: '966ef694-1a7d-4c35-91f3-41b8c5363c48'
Pipeline: 'Build'
buildDefinition: 'Gradle sample' #PipelineName
Branch: 'master'
- ${{ if eq(parameters.pipeline2, 'true') }}:
- task: TriggerPipeline@1
inputs:
serviceConnection: 'TestBuild'
project: '966ef694-1a7d-4c35-91f3-41b8c5363c48'
Pipeline: 'Build'
buildDefinition: 'groovy-spring-boot-restdocs-example.git' #PipelineName
Branch: 'master'
...
Explanation:
I use the Trigger Azure DevOps Pipeline task from the Trigger Azure DevOps Pipeline Extension to trigger the child pipelines.
The parameters is used to list the pipeline names and the if condition is used to determine whether the pipeline name is selected.
Result:
When you run the pipeline you could select the checkbox.
If the pipeline name has been selected, the corresponding task will run and trigger the corresponding pipeline.
This should make the selection interface clearer.
Let me check with my Azure Admin to install this plugin. I will come back..
Hi @user2571588. Feel free to let me know your progress. if you have any questions, I will still be here to help you.
Hi @user2571588. To follow up, do you have any update about this ticket?
| common-pile/stackexchange_filtered |
Why are the "Internal IP address"s of my nodes set to their external IP?
I have recently set up a kubernetes cluster in Digital Ocean. I manually set up 3 machines and created the cluster using kubeadm with the calico network plugin.
I used the following argument with kubeadm init: --apiserver-advertise-address=<IP_ADDRESS> to make sure nodes use the internal IP to communicate with each other.
However, once I set everything up, I issued kubectl get nodes -o wide and found that the INTERNAL-IP for each node is set to the external one:
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
cluster-a-master-1 Ready master 22m v1.15.4 <IP_ADDRESS> <none> Ubuntu 18.04.3 LTS 4.15.0-58-generic containerd://1.2.6
cluster-a-worker-1 Ready <none> 10m v1.15.4 <IP_ADDRESS> <none> Ubuntu 18.04.3 LTS 4.15.0-58-generic containerd://1.2.6
cluster-a-worker-2 Ready <none> 9m24s v1.15.4 <IP_ADDRESS> <none> Ubuntu 18.04.3 LTS 4.15.0-58-generic containerd://1.2.6
Why is it like this? what confused it and how can I correct it? And does this also mean that nodes communicate with each other using the external interface?
Are you sure you use calico network plugin? Because calico ip should start with 192 and there is 155
Where can you see that the internal-ip is set to the external one? Can you provide some screens?
Yes. Sure. I changed the default in the calico config
Also, the 155 is the external ip of the node, unrelated to the pod cidr (the default you are referring to)
Please provide more info: kubectl cluster-info, kubectl get cm kubeadm-config -n kube-system -o yaml, kubectl get pods -o wide
| common-pile/stackexchange_filtered |
How to append to an empty list in Julia?
I want to create an empty lsit and gardually fill that out with tuples. I've tried the following and each returns an error. My question is: how to append or add and element to an empty array?
My try:
A = []
A.append((2,5)) # return Error type Array has no field append
append(A, (2,5)) # ERROR: UndefVarError: append not defined
B = Vector{Tuple{String, String}}
# same error occues
Try append!(A, (2,5)), append not defined means there is no function append.
Take a look at this.
@AndreWildberg That will not actually put a tuple inside A, but instead add two distinct elements, 2 and 5. This is how append! works. But the desired behavior is achieved with push!.
You do not actually want to append, you want to push elements into your vector. To do that use the function push! (the trailing ! indicates that the function modifies one of its input arguments. It's a naming convention only, the ! doesn't do anything).
I would also recommend creating a typed vector instead of A = [], which is a Vector{Any} with poor performance.
julia> A = Tuple{Int, Int}[]
Tuple{Int64, Int64}[]
julia> push!(A, (2,3))
1-element Vector{Tuple{Int64, Int64}}:
(2, 3)
julia> push!(A, (11,3))
2-element Vector{Tuple{Int64, Int64}}:
(2, 3)
(11, 3)
For the vector of string tuples, do this:
julia> B = Tuple{String, String}[]
Tuple{String, String}[]
julia> push!(B, ("hi", "bye"))
1-element Vector{Tuple{String, String}}:
("hi", "bye")
This line in your code is wrong, btw:
B = Vector{Tuple{String, String}}
It does not create a vector, but a type variable. To create an instance you can write e.g. one of these:
B = Tuple{String, String}[]
B = Vector{Tuple{String,String}}() # <- parens necessary to construct an instance
It can also be convenient to use the NTuple notation:
julia> NTuple{2, String} === Tuple{String, String}
true
julia> NTuple{3, String} === Tuple{String, String, String}
true
| common-pile/stackexchange_filtered |
resize field and resize back outside click
I'm new to jquery and I kinda don't get around this. So I have a searchbox (.search) which I want to resize when it's clicked. That does work, the searchfield get's "bigger". But, when I click outside the searchfield I want it to grow back again. I tried doing it with a "body"-click-method. But it doesn't work.
So here's my code:
$(function() {
$('.search').click(function() {
$('.search').css('width', '450px');
});});
Another question: How can I combine this change with an animation?
$('.search').focus(function() {
$('.search').css('width', '450px');
});
$('.search').blur(function() {
$('.search').css('width', 'auto');
});
If you want to animate the width change you can do this:
$('.search').focus(function() {
$('.search').animate({width: '450px'});
});
$('.search').blur(function() {
$('.search').animate({width: '150px'});
});
Otherwise if you wish to animate another object you can do this:
$('.search').focus(function() {
$('.search').css('width', '450px');
$('#id_to_animate').animate({width: '200px'});
});
$('.search').blur(function() {
$('.search').css('width', '150px');
$('#id_to_animate').animate({width: '100px'});
});
This is perfect. Thanks. :)
Now, the only other question I have so far is: can I put to the resizing?
Could you expand your question a bit, I'm not sure what you mean.
http://api.jquery.com/animate/ is the documentation page for animate in JQuery. $('.search').animate({width: '450px'}, 3000, 'linear', function() {}); The 3000 corresponds to the time that the animation will take to complete, 'linear' corresponds to the type of easing (you can get the jquery easing plugin to get like 30 different types of easing), and 'function(){}' corresponds to a custom function that you can create that will run at the end of the animation. Here is the link to the JQuery easing plugin http://gsgd.co.uk/sandbox/jquery/easing/
You can use the jQuery blur event to resize the element back down after it loses focus:
http://api.jquery.com/blur
| common-pile/stackexchange_filtered |
Breeze theme color problem
I recently upgraded Kubuntu to 17.10 Artful using the dark theme, but when I switched to the default breeze theme, this happened( in Plasma 5.11. I used the backports PPA. And no, even in 5.10, the plasma version kubuntu 17.10 ships with, the default theme was messed up as well)
As you can see the pannel and the kickoff menu are all grayed out. They still work, but they are gray. I tried restarting many times but it did not work.
Here are what settings I use:
note:"Briză" means "Breeze"
Am I doing something worng?
Plese help me.
Have you tried switching back to the dark theme?
Yes, and it applies corectly, from what I tested, the dark theme applies corectly
White breeze has little bit of transparency (dark version does not) and this is how might look like if this effect does'n work correctly.
1.) Check if your graphics card drivers are installed correctly.
2.) Try disabling all transparency/bloor related effects in Desktop effects in system settings.
| common-pile/stackexchange_filtered |
SharePoint Calculated field in SharePoint Designer error?
I have taken calculated field as a data field number for adding weekdays excluding saturday and sunday.
It is working good. But the problem is in SharePoint Designer I have triggered action send an email there I have to send to the employee after submitting request. The error is
while triggering No. of days is coming like thet float # how to remove that?
But in Return field as it is taking default as a String ? How to enable that?
Can any one explain this issue?
Try creating workflow variable return field as number. and than instead of calling calling calculated field in mail body, call workflow variable.
It's SharePoint's CAML queries' way of working with calculated fields.
This problem is described in https://deannaschneider.wordpress.com/2012/07/06/associated-calculated-columns-in-reusable-workflows-sp2010/ and "float;#22.0000000000000" Number Returned From CAML Query
The straightforward workaround is to re-implement same calculations in the workflow once again.
Or you can create a workflow variable tempVar and set it's value to CurrentItem:No. of Days (as string), then use some Utility actions to get that 22 out of the string. Something like Extract Substring of String from Index with Length with args of tempVar, 7 and (the position of . char minus 7) will work. To find the position of ., use Find Substring in String. This will cut out 22 (basically, all chars between # and .) and put it in tempVar, so you can use it in emails.
| common-pile/stackexchange_filtered |
JPQL query to return items with at least one category belonging to a list of categories
I want to make a query similar to the following jpql query:
SELECT i FROM Item i WHERE i.category IN :categories
This query returns items with category belonging to the passed :categories list.
But the query I need needs to be something like this:
//This JPQL Query does not work (and is only used to explain the problem)
SELECT i FROM Items i WHERE i.categoryList IN :categories
Note: The biggest difference from the previous query is that this time items has a list of categories.
This query will return any item that has at leasy one of its category belonging to the :categories list.
I have read this page: http://www.java2s.com/Tutorials/Java/JPA/index.htm. But I can't seem to think of a proper way to do it.
My current options are doing a native SQL query (which isn't as elegant as a JPQL and not as efficient) and getting all the items list and filtering it with Java Code (which is probably what I will do in worst case scenario).
Thank you!
You need to learn about joins. https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#hql-explicit-join. select i from Item i join i.categoryList category where category in :categories. Use the singular form for your entties: an instance of Items is an Item, so the class should be named Item, not Items. Just like the class String is named String, not Strings.
Thank you. I'm going to learn about joins. "Items" was actually a typo in the second query.
| common-pile/stackexchange_filtered |
Can I use PBKDF2 for authentication and decryption?
I want to store a hash for authenticating a password. I also want to use the same password for decryption. Can I use PBKDF2 for both? (I plan to use different salts for the authentication and the decryption, of course, because otherwise the authentication result would be the decryption key!)
Is that appropriate/secure?
It's fine, as others have noted.
However, by invoking PBKDF2 twice (first to check the password, then to derive the actual key), you're essentially doubling a legitimate user's workload, whereas an attacker still only needs to run it once for each guessed password. Thus, you're cutting the legitimate user's advantage in half, or, equivalently, wasting one bit of password entropy.
(Also, the way PBKDF2 is defined, deriving more than one hash output length of key material is basically equivalent to invoking the whole PBKDF2 function two or more times, so you won't gain much that way. Other KDFs like scrypt may behave differently in this respect.)
Instead, I would recommend deriving a single "intermediate key" $K_I$ from the password $P$, using PBKDF2 with a suitably high iteration count, and then deriving both the password verification value $V$ and the actual encryption key $K_E$ from the intermediate key using a fast KDF (e.g. PBKDF2 with an iteration count of 1), like this:
$$\begin{aligned}
K_I &= \text{PBKDF2}(P,S,c,\max(\ell_P,\ell_V,\ell_{K_E})) \\
V \,\|\, K_E &= \text{PBKDF2}(K_I,S,1,\ell_V+\ell_{K_E})
\end{aligned}$$
where $S$ is the salt, $c$ is the iteration count, $\ell_P$ is the output length (in bytes) of the PRF used to instantiate PBKDF2, and $\ell_V$ and $\ell_{K_E}$ are the desired byte lengths of the verification token $V$ and the encryption key $K_E$ respectively, and $\|$ denotes their concatenation.
(The reason for choosing the intermediate key length as $\max(\ell_P,\ell_V,\ell_{K_E})$ is that we want the intermediate key to be at least as long as each of the final outputs $V$ and $K_E$, and there's no point in asking for output shorter than what the PRF naturally gives us; in fact, an even better choice could be $\max(\ell_V,\ell_{K_E})$ rounded up to the next multiple of $\ell_P$.)
The point about halving the attacker's workload is convincing!
As pointed in this other answer, the simplest way to solve the halved workload issue is to generate a wide output with one invocation of the KDF, and split that in two parts. On a different issue: when we care for the cost of attack, Scrypt is significantly better than PBKDF2, because it forces the adversary to mobilize RAM during attacks.
@fgrieu: That works, but is needlessly slow if the total amount of key material to be generated is more than the output length of the KDF used to instantiate PBKDF2. (Of course, if an attacker also needs to generate the same amount of key material to test each password guess, then the slowdown applies to them too, but that's not the case in the OP's scenario.)
Yes you can use PBKDF2 for both (from section 3 of this memo)
Another application is password checking, where the output of the key
derivation function is stored (along with the salt and iteration
count) for the purposes of subsequent verification of a password.
Also (as mentioned in the comments of this post), the memo also says (emphasis mine):
It is expected that the password-based key derivation functions may
find other applications than just the encryption and message
authentication schemes defined here. For instance, one might derive a
set of keys with a single application of a key derivation function,
rather than derive each key with a separate application of the
function. The keys in the set would be obtained as substrings of the
output of the key derivation function...
So you could use just one application of PBKDF2 to produce both the key, and the stored hash.
If you look at the algorithm, it would (depending on the underlying hash function and required key lengths), essentially be applying PBKDF2 twice - but with slightly different salts.
That should OK. PBKDF2 has sufficient collision resistance and pre-image resistance for password authentication, and the fact that the passwords to both are the same shouldn't cause any problems if the salts are different.
Indeed, probably not very much. We probably just want statistical collision resistance (aka, the wrong password has a low probability of succeeding).
| common-pile/stackexchange_filtered |
GitLab CI custom variable not recognized in rules
When defining a variable in the variables block which uses a predefined CI variable, it cannot be referenced in the rules blocks. Here, only job_1 gets executed:
variables:
PRODUCTION_BRANCH: $CI_DEFAULT_BRANCH
stages:
- stage_1
job_1:
stage: stage_1
script:
- export
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
job_2:
stage: stage_1
script:
- export
rules:
- if: '$CI_COMMIT_BRANCH == $PRODUCTION_BRANCH'
But when hardcoding the value for PRODUCTION_BRANCH it works as expected. Here, both jobs get executed:
variables:
PRODUCTION_BRANCH: "master"
stages:
- stage_1
job_1:
stage: stage_1
script:
- export
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
job_2:
stage: stage_1
script:
- export
rules:
- if: '$CI_COMMIT_BRANCH == $PRODUCTION_BRANCH'
When looking into the output of the jobs (since export logs the env-variables), in both cases there is the variable PRODUCTION_BRANCH with the correct value master.
Why does it behave like that and is there a fix / workaround?
What version are you using? Looks like similar issues are resolved as of 13.6: https://gitlab.com/gitlab-org/gitlab/-/issues/206929 & https://gitlab.com/gitlab-org/gitlab/-/issues/34272 and in 13.7: https://gitlab.com/gitlab-org/gitlab/-/issues/209864 . This one is still open though: https://gitlab.com/gitlab-org/gitlab/-/issues/35315
@Arty-chan I'm running version 13.5.3. Seems like the last issue relates to mine
user1452736 posted an Answer saying "it's maybe because on your gitlab instance disabled this feature https://docs.gitlab.com/ee/ci/variables/where_variables_can_be_used.html#enabling-the-nested-variable-expansion-feature"
Update 2022-09:
It appears that gitlab has fixed some issues related to this.
I haven't had a chance to re-test yet whether this is completely resolved issue or if there are still some pitfalls to be aware of.
Just be aware that the below answer may no longer be correct/current.
gitlab does not do variable expansion of the variables section when evaluating the yaml and determining what to run. Variable interpolation does work within the runner though.
So you have to be careful if you are using variable interpolation when defining custom variables. Are they for gitlab conditions (won't work) or are they for use in runner only (after gitlab has decided to run the job...this works)?
This is confusing and I couldn't find any warning/reference to this high-probability pitfall in the docs...but maybe I missed it.
So in your if: you can use
$CI_* variables
(except for a few ENVIRONMENT ones ...see description column for rules in the linked where variables can be used table.)
custom variables you have defined globally or within a job
variables:
PRODUCTION_BRANCH: "main"
But if your if: depends on custom variables (ie $PRODUCTION_BRANCH) that themselves require variable interpolation...
variables:
PRODUCTION_BRANCH: $CI_DEFAULT_BRANCH
...it won't work. $PRODUCTION_BRANCH will have the value you expect within the RUNNER (once the job is started) but gitlab doesn't do the interpolation when parsing the yaml and deciding which jobs to run.
In your case, simplest thing is just to use the $CI_DEFAULT_BRANCH variable directly in your if:.
Example .gitlab-ci.yml demonstrating this...
You can drop this in a new empty repo. Just update REPO_NAMESPACE, REPO_NAME and ONLY_DEPLOY_BRANCH to match the current repo/branch.
jobs:
debug - runs and outputs vars showing all the values you expect (in a runner context)
deploy1 - runs
deploy2 - does not run
deploy3 - runs (shows the variables are definitely not interpolated on the gitlab side).
variables:
REPO_NAMESPACE: "my-group/my-subgroup"
REPO_NAME: "my-project"
ONLY_DEPLOY_BRANCH: "main"
ONLY_DEPLOY_FROM: "${REPO_NAMESPACE}/${REPO_NAME}"
ONLY_DEPLOY_FROM2: "my-group/my-subgroup/my-project"
stages:
- debug
- deploy
# this runs
# variables all have expected values (in runner scope) and you would expect both deploy* jobs to run
debug:
stage: debug
script:
- export
# this runs
deploy1:
stage: deploy
image: alpine:latest
rules:
- if: $CI_PROJECT_PATH == $ONLY_DEPLOY_FROM2 && $CI_COMMIT_REF_SLUG == $ONLY_DEPLOY_BRANCH
when: always
script:
- echo "Hello world!"
# this doesn't run.
# Only difference to deploy1 job is using $ONLY_DEPLOY_FROM instead of $ONLY_DEPLOY_FROM2
# conclusion... gitlab must not do variable expansion of the variables section when determining which jobs run.
deploy2:
stage: deploy
image: alpine:latest
rules:
- if: $CI_PROJECT_PATH == $ONLY_DEPLOY_FROM && $CI_COMMIT_REF_SLUG == $ONLY_DEPLOY_BRANCH
when: always
script:
- echo "Hello world!"
# this runs which confirms that $ONLY_DEPLOY_FROM has not had CI variables replaced.
deploy3:
stage: deploy
image: alpine:latest
rules:
- if: $ONLY_DEPLOY_FROM == "$REPO_NAMESPACE/${REPO_NAME}" && $CI_COMMIT_REF_SLUG == $ONLY_DEPLOY_BRANCH
when: always
script:
- echo "Hello world!"
You can use the ci linter (https://gitlab.com/${CI_PROJECT_PATH}/-/ci/lint) to play with this. It is a good tool in general for troubleshooting problems without making a thousand commits in a row to .gitlab-ci.yml and burning through shared runner hours.
Open issue
Gitlab has ~40k open issues. Here are the relevant tickets though...
Supporting variable expansion for runner (resolved)
Supporting the gitlab side variable expansion -- this problem. still open issue. - closed Apr 27, 2022
This is a great pitfall and enormously limits the usage of rules against custom only/except job config. Great answer !!!
Just put the value in quotes:
variables:
PRODUCTION_BRANCH: "$CI_DEFAULT_BRANCH"
| common-pile/stackexchange_filtered |
Botframework how to authenticate first and than use the token to make graph api calls
Auth Dialog:
import { ChoicePrompt, DialogSet, DialogTurnStatus, OAuthPrompt, TextPrompt, WaterfallDialog, ComponentDialog } from 'botbuilder-dialogs';
import GraphClient from '../graph-client';
const MAIN_WATERFALL_DIALOG = 'mainWaterfallDialog';
const OAUTH_PROMPT = 'oAuthPrompt';
const CHOICE_PROMPT = 'choicePrompt';
const TEXT_PROMPT = 'textPrompt';
import moment = require('moment');
class AuthDialog extends ComponentDialog {
constructor() {
super('AuthDialog');
this.addDialog(new ChoicePrompt(CHOICE_PROMPT))
.addDialog(new OAuthPrompt(OAUTH_PROMPT, {
connectionName: process.env.ConnectionName,
text: 'Please login',
title: 'Login',
timeout: 300000
}))
.addDialog(new TextPrompt(TEXT_PROMPT))
.addDialog(new WaterfallDialog(MAIN_WATERFALL_DIALOG, [
this.promptStep.bind(this),
this.processStep.bind(this)
]));
this.initialDialogId = MAIN_WATERFALL_DIALOG;
}
/**
* The run method handles the incoming activity (in the form of a TurnContext) and passes it through the dialog system.
* If no dialog is active, it will start the default dialog.
* @param {*} turnContext
* @param {*} accessor
*/
public async run(turnContext, accessor) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(turnContext);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dialogContext.beginDialog(this.id);
}
}
public async promptStep(step) {
return step.beginDialog(OAUTH_PROMPT);
}
public async processStep(step) {
if (step.result) {
// We do not need to store the token in the bot. When we need the token we can
// send another prompt. If the token is valid the user will not need to log back in.
// The token will be available in the Result property of the task.
const tokenResponse = step.result;
// If we have the token use the user is authenticated so we may use it to make API calls.
if (tokenResponse && tokenResponse.token) {
await step.context.sendActivity(`Logged in.`);
} else {
await step.context.sendActivity('something wrong happened.');
}
} else {
await step.context.sendActivity('We couldn\'t log you in. Please try again later.');
}
return await step.endDialog();
}
}
export default AuthDialog;
I have a main dailog which is connected to luis and based on the intent recognized it executes corrosponding code:
for ex i have this in some cases:
case 'CalendarEvents':
return stepContext.beginDialog('AuthDialog');
const calendar = await new GraphClient('token').events();
let eventsBuilder: string = '';
// tslint:disable-next-line: prefer-for-of
for (let index = 0; index < calendar.length; index++) {
const element = calendar[index];
eventsBuilder += '\r\n' + moment(element.start.dateTime).format('dddd, MMMM Do YYYY, h:mm:ss a') + ' - ' + element.subject;
}
await step.context.sendActivity(`${eventsBuilder}`);
So if the intent is CalendarEvents then authenticate and than make some graph api call.
The problem I currently have is that the call to graph api is made before the auth is finished, I would like so first user authenticate and than receives some token and use that token for fetching graph api calls!
any idea how to achieve the above?
Please see the Graph Auth Sample. In particular,
It gets the token in MainDialog:
return step.beginDialog(OAUTH_PROMPT);
[...]
if (step.result) {
const tokenResponse = step.result;
if (tokenResponse && tokenResponse.token) {
const parts = (step.values.command || '').toLowerCase().split(' ');
const command = parts[0];
switch (command) {
case 'me':
await OAuthHelpers.listMe(step.context, tokenResponse);
break;
case 'send':
await OAuthHelpers.sendMail(step.context, tokenResponse, parts[1]);
break;
case 'recent':
await OAuthHelpers.listRecentMail(step.context, tokenResponse);
break;
default:
await step.context.sendActivity(`Your token is ${ tokenResponse.token }`);
}
}
}
[...]
Then, OAuthHelpers uses the token:
static async sendMail(context, tokenResponse, emailAddress) {
[...]
const client = new SimpleGraphClient(tokenResponse.token);
const me = await client.getMe();
await client.sendMail(
emailAddress,
'Message from a bot!',
`Hi there! I had this message sent from a bot. - Your friend, ${ me.displayName }`
);
await context.sendActivity(`I sent a message to ${ emailAddress } from your account.`);
}
This is how the sample works. For you, since you only want to do auth in the Auth dialog, you need to get the token from the user using the Auth dialog, then save it to their UserState, similar to this sample. You can then retrieve their UserState in any dialog and use the token if they have it.
Note
You can either use the Graph API through regular HTTP REST API requests, or use the Graph SDK like the sample does.
Hi, thanks for the answer, to me it kinda seems like this is tying together authentication with other stuffs, so basically If could it be possible to somehow when authenticating successfully just return the token and use that token in some other file or after the authentication dialog ends, if u took closely look at my example so I would like to do some calls using graph client sdk in maindialog and not from authenticationDialog, since Authentication dialog I would like to keep it just for authentication purpose and not anything else!
@Lulxim In that case, you need to get the token from the user using the Auth dialog, then save it to their UserState, similar to this sample. You can then retrieve their UserState in any dialog and use the token if they have it.
I think this answers my question, thank you, could you modify your answer with the last comment so I can accept it!
@Lulxim Updated!
| common-pile/stackexchange_filtered |
Why was this comment deleted?
The comment to this question on the screenshot below got promptly deleted.
What was wrong with it? Which Law.SE term did it violate? If it did, in the opinion of whoever deleted it, contain something prohibited, what was it, how do we define it and what test do we apply to see if the content reaches the threshold?
That comment unnecessarily violates the code of conduct. It could easily have been phrased so as not to contain "subtle put-downs or unfriendly language," and to "avoid sarcasm." Since it was directed at a new user I agree that it warranted prompt removal.
So, what exactly was a "subtle put-down" or "unfriendly language" in the comment?
Starting the comment with "do you assume" makes it seem somewhat unfriendly and sarcastic, IMO. The same view could have been expressed by something like:
Please be aware that laws differ significantly in different countries, and that Law.SE draws readers and posters from all over the world.
Can you see the difference in tone? I don't think a single "please" constitutes "mawkish pleasantries".
This form will not find out how come the user did not specify country/jurisdiction. That was the main thing I was interested in.
And yes, I do see the difference in tone — a minor shift towards mawkish pleasantries (although not reaching those of course). I think the tone gauge/sensor of many people is off: they tend to perceive perfectly neutral stuff as unfriendly/sarcastic etc. unless clear indicators of otherwise (e.g. "please") are added. This is frustrating and I stand for it to be corrected.
@Greendrake
I perceiveyour orginal comment as mildly sarcastic and significantly although not strongly unfriendly. Indeed the more I read it the more strongly I feel that way. And i still fail to see any legitimate reason to inquire into why the user failed to supply a jurisdiction, but if you really wanted to know that, it would be possible to politely ask about it directly rather than the oblique "did you assume". If I see such a comment in future, I will probably flag it as unfriendly, depending on the exact wording..
With such a sensor of unfriendliness as you have, I won't be surprised if the mere lack of ", sir" at the end of comments will soon be perceived as rude. We all come from different cultures here, so I believe decisions should be made based on objective tests rather than subjective perceptions.
@Greendrake I don't know of any objective test for politeness. That is why we here depend on trusted moderators, and on flagging by community members, and on discussions such as this one. I would never demand a "sir" as a standard of politeness on a site such as this. I don't think a single "please" is unreasonable, but the point is not to write things likely to put off a legitimate new user, who does not know the rules or problems of the site. Starting a comment with "did you assume" feels critical, and suggests "you were stupid not to realize otherwise". in my view [...]
[...] @Greendrake I am not a mod, and cannot delete anyone's comments except my own. But when dealing with a new user, I hope you will ysake extra care not to write things which might be mistakenly seen as hostile or aggressive, even though you did not intend them that way.
I am consciously reluctant to take that extra care because I stand to promote objectiveness, critical thinking and self-criticism. I don't think it is inappropriate to pour some cold water on new users to motivate them to think when asking questions (if they don't seem to), and if they won't, it is not at all inappropriate to put them off. This is not a blabbing site like Quora after all. If the community does not share these objectives, I would rather not participate at all than adapt.
@Greendrake I cannot speak for the community. I do not share those objectives and indeed think them harmful. I agree that we should encourage users, particularly new users, to ask good questions, which will often include "objectiveness, critical thinking and self-criticism." But in my view this is usually better done with positive feedback and polite explanation, with the goal of teaching, not excluding. Obviously spammers and those who abuse the site are in a different category. But otherwise, I do not think a modicum of politeness does harm, and it my help us have a new productive user.
The comment was deleted because the mod jumped to the conclusion that it was purported to criticize or humiliate the user.
The actual intention was straightforwardly direct and not subtle at all: to find out how it happens that users like that omit the country/jurisdiction. What is their way of thinking? I was genuinely curious.
Whereas I agree that the angle of view taken by the mod is not totally impossible (which was exactly why I took the screenshot as I thought the comment could end up deleted by this particular mod), I find it totally unacceptable that one has to dress their perfectly neutral comments with mawkish pleasantries just to avoid being perceived as unfriendly. The expectation is that people (both new users and mods) apply critical thinking and don't assume negativity without evidence.
The common "please specify a jurisdiction" comment does not have to be dressed up. Here's a simple, neutral example: "Which jurisdiction did you have in mind?"
@feetwet That question will not find out how it happened that the user did not specify jurisdiction in the first place.
@Greendrake Many people are not aware that there even is a legal system difference between states or countries.
@Trish Fair theory. An instance of that was exactly what the comment was directed to test. Or, whether people assume that only their country's users use websites they happen to be on. Or something else that I could not even think of.
@Greendrake Why do we need to test or know what the poster's knowledge was? We can explain the actual situation without quizzing the poster.
@DavidSiegel New users not specifying country/jurisdiction is a common issue on Law.SE. I think it can and should be resolved, or at least mitigated. To figure out how, we need to know how it happens: what makes users not specify it.
@Greendrake I don't see any plausible way to "resolve" it, nor any need to mitigate it. And do remember that our policy says that there is no requirement to provide a jurisdiction. Comments that suggest otherwise are out-of-line, in my view.
I would guess it's the same reason many new users on RPG.SE forget to specify the RPG system and edition they're asking about – they don't realize that it matters, or don't know that other systems/editions exist (and may have different rules). Sometimes it doesn't matter, because the problem isn't specific to any one system/edition – but if it does, you can always ask the author to clarify as needed.
| common-pile/stackexchange_filtered |
Is having only target SDK enough to develop UWP Application?
This question sound's to be little basic but I don't find any documentation on MSDN. Actually, in my machine, I have 4 UWP SDK version(17134, 16299, 14393, 15063) installed which is consuming a lot of disk space.
My App min version is 14393 and target version is 15063. So the question is that do I need 14393 SDK or having only 15063 strong text is sufficient?
You must have min sdk version- which states min version of win 10 will required in client/user side. Extra Note: Currently windows 10 mobile has version 10.0.15254.xxx and few limited to 10.0.14393.xxx so if you are considering all device Min version will play a role
My App min version is 14393 and target version is 15063. So the question is that do I need 14393 SDK or having only 15063 strong text is sufficient?
You could choose to install only 15063 SDK. Once you only install the 15063 SDK, then your target version could only set 15063 and the min version could be 10240 ~ 15063.
In short, only installing one SDK will not affect you to develop your UWP app, but you need to consider your app's users, their environment was not necessarily the same as yours.
For example, your project's target version is 15063 and min version is 10240, then, you develop and test your app on 15603 OS successfully, but your app can be installed on 14393 OS. In your code, once you call an API that is introduced from 15063, then the app run on 14393 will fail.
The document Choose which version to use for your app mentioned by @Bite has explained this scenario:
The value of Target Version is used to identify all the references (contract winmds) used to compile your project. But those references will enable you to compile your code with calls to APIs that won't necessarily exist on devices that you've declared that you support (via Minimum Version). Therefore, any API that was introduced after Minimum Version will need to be called via adaptive code. For more information about adaptive code, see Version adaptive code.
Target Version. This sets the TargetPlatformVersion setting in your project file. It also determines the value of the TargetDeviceFamily@MaxVersionTested attribute in your app package manifest. The value you choose specifies the version of the UWP platform that your project is targeting—and therefore the set of APIs available to your app—so we recommend that you choose the most recent version possible. For more info about your app package manifest, and some guidelines around configuring TargetDeviceFamily manually, see TargetDeviceFamily.
Minimum Version. This sets the TargetPlatformMinVersion setting in your project file. It also determines the value of the TargetDeviceFamily@MinVersion attribute in your app package manifest. The value you choose specifies the minimum version of the UWP platform that your project can work with.
Please read Choose which version to use for your app. It has explained all information.
This doesn’t answer the question.
| common-pile/stackexchange_filtered |
Excel .xlsx file not opening after downloading the file from the server in java
Here is my sample code. I am using eclipse , tomcat server .Browser as IE9.
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
ServletContext context = request.getServletContext();
@SuppressWarnings("unchecked")
List<Student> students = (List<Student>) context.getAttribute("students");
PrintWriter out = response.getWriter();
for(Student student:students){
out.println(student.getId()+"\t"+student.getName());
}
out.close();
}
I am getting the List of Student. But when i am opening the downloaded file file getting error saying that file format or extention is not valid. My downloaded file is .xlsx .
Please look this http://stackoverflow.com/questions/2937465/what-is-correct-content-type-for-excel-files
What you send is not an xslx file. You send a csv with tab as delimiter.
try application/vnd.ms-excel
@Jens where did you know that he sends a csv file??
@navin An xlsx file is in general a zip archive. Have you test it that is not corrupt?
@reporter OP prints student.getId()+"\t"+student.getName() as response.
I strongly recommend you to use HSSFWorkbook class to create your excel file. After its created (for creation process see: this example) you can write its contents to response like this:
Workbook workbook = new XSSFWorkbook();
// Add sheet(s), colums, cells and its contents to your workbook here ...
// First set response headers
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=YourFilename.xlsx");
// Get response outputStream
ServletOutputStream outputStream = response.getOutputStream();
// Write workbook data to outputstream
workbook.write(outputStream);
in this way i will be creating a .xls file not .xlsx file. Here i want to create a .xlsx file
Sorry I misread that requirement. Then you simply use XSSFWorkbook class instead and change YourFilename extension to xlsx. Both HSSFWorkbookandXSSFWorkbook` are implementing Wokbook interface, so its api will be same.
See http://poi.apache.org/spreadsheet/quick-guide.html
Updating answer
It is not so much an .xlsx file, more a CSV or tab separated value text file. It fakes to be an Excel file; and yes, then Excel opens it correctly,
Try to read it with NotePad. You also can make a .xlsx file with NotePad to check whether the trick works.
The following tries:
.xls
A Windows \r\n (CR+LF) line ending. Maybe the server is Linux and delivers \n (LF).
A defined encoding.
Then
response.setEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
ServletContext context = request.getServletContext();
@SuppressWarnings("unchecked")
List<Student> students = (List<Student>) context.getAttribute("students");
PrintWriter out = response.getWriter();
out.print("\uFEFF"); // UTF-8 BOM, redundant and ugly
for(Student student:students){
out.printf("%s\t%s\r\n", student.getId(), student.getName());
}
//out.close();
i have kept the response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); unchanged.
when i am opening the same downloaded(.xlsx) file in notepad++ , able to view the content.
response.setHeader("Content-Disposition", "filename=\"test.xsl\""; or so? Try the (downloaded, edited) text file as .xsl and .xslx by double-clicking it.
| common-pile/stackexchange_filtered |
Application C# for Skype
I just need a simple program that allows me to dial numbers and call via SkypeOut. I tried with Skype4, but I can't make a call. I just need to have 13 buttons (0 to 9 dial numbers) "+" "Call" "Finish". It will be for my car, and I need to develop it in C#. Can anyone help mi with that? Thanks in advice
Take a look at this:
http://forum.skype.com/index.php?showtopic=142821
Microsoft Visual C# 2008 Express Example Skype4COM
This Example Project with Source Code Supports ALL Event Handlers
| common-pile/stackexchange_filtered |
CSS3PIE & HTML5shiv printing issues IE8
I'm having problems using CSS3PIE & HTML5shiv for this huge website. It comes down to printing issues in IE8. Whenever I want to print a webpage, IE8 just seems to crash. I've done some research and this printing crash seems related to the use of CSS3PIE and HTML5shiv.
Any way I can avoid this problem in IE8? Thanks in advance!
I've turned off Shiv and it still happens. So it seems to be more CSS3PIE-related.
This is a known issue in CSS3pie they have fixed it in IE9.
| common-pile/stackexchange_filtered |
How does the duality functor with respect to $K$ behave on morphisms?
In A duality formalism in the spirit of Grothendieck and Verdier Boyarchenko and Drinfeld give the following definition of the terms dualizing object and duality functor:
An object $K$ in a monoidal category $M$ is said to be dualizing if for every $Y \in M$ the functor $X \mapsto Hom(X \otimes Y, K)$ is representable by some object $DY \in M$ and the contravariant functor $D : M \rightarrow M$ is an antiequivalence. $D$ is called the duality functor with respect to $K$.
After chosing a representing object $DY$ of the functor $Hom(- \otimes Y, K)$ for every object $Y \in Obj(M)$ we obtain an assignment $Y \mapsto DY$ on objects of $M$. However, what morphism $DZ \rightarrow DY$ do we assign to a morphism $f: Y \rightarrow Z$ in $M$? That is, how does $D$ become a functor?
According to page 33 in this paper, one can use the Yoneda lemma to show that "the assignment $X \mapsto DX$ extends to a functor." I do not see how. Any hints?
Your morphism $f:Y\to Z$ produces (because $\otimes$ is functorial) a morphism $X\otimes f:X\otimes Y\to X\otimes Z$, which in turn induces by composition a function $Hom(X\otimes Z,K)\to Hom(X\otimes Y,K)$. By the definition of $D$, this amounts to a morphism $Hom(X,DZ)\to Hom(X,DY)$.
Furthermore, all of the preceding works for all objects $X$ and the constructions are natural with respect to $X$. That is, we have a natural transformation $Hom(-,DZ)\to Hom(-,DY)$. By Yoneda, this corresponds to a morphism $DZ\to DY$. That morphism is $Df$.
Thank you! Is it standard practice in category theory to give a functor only on objects and then use representability together with Yoneda to specify what it does on morphisms? That is, to give an argument like this: "Since by representability $Hom(-,DZ) \cong F_Z(-)$ and $Hom(-,DY) \cong F_Y(-)$ and since we have a natural transformation $F_Z(-) \rightarrow F_Y(-)$ (somehow established by $f:Y \rightarrow Z$) we obtain by the Yoneda lemma a morphism $DZ \rightarrow DY$? Do you know any other examples where this is done? Is this assignment on morphisms in some way canonical?
A morphism $X \rightarrow Y$ induces a natural transformation $Hom(-\otimes Y, Z) \rightarrow Hom(-\otimes X, Z)$ and by the Yoneda Lemma, since $DX$ and $DY$ represent these functor this natural transformation corresponds to a unique morphism $DY \rightarrow DX$ (the Yoneda embedding is fully faithful). Functoriality follows from the naturality of the Yoneda Lemma.
Thank you! So it boils down to the following: One shows that the ("precomposition"-)assignment $Hom(X \otimes Z, K) \rightarrow Hom(X \otimes Y, K); g \mapsto g \circ (id_X \otimes f)$ is natural in $X$ (this is essentially due to the functoriality of the tensor product). Then one defines a natural transformation $Hom(-,DZ) \Rightarrow Hom(-,DY)$ as the vertical composition of three natural transformations (using the above precomposition natural transformation as well as natural isomorphisms obtained by the representability of the functor $Hom(-\otimes Y, K)$...
Using the Yoneda lemma one then obtains a morphism $Df: DZ \rightarrow DY$ from the above natural transformation $Hom(-,DZ) \Rightarrow Hom(-,DY)$. However, I don't see how this assignment is functorial? How does the naturality of the Yoneda lemma help?
| common-pile/stackexchange_filtered |
Read .bmp image and subtract 10 from 10th byte of the image and re-create the image in Java
I am creating an application which will read image byte/pixel/data from an .bmp image and store it in an byte/char/int/etc array.
Now, from this array, I want to subtract 10 (in decimal) from the data stored in the 10th index of an array.
I am able to successfully store the image information in the array created. But when I try to write the array information back to .bmp image, the image created is not viewable.
This is the piece of code which I tried to do so.
In this code, I am not subtracting 10 from the 10th index of an array.
public class Test1 {
public static void main(String[] args) throws IOException{
File inputFile = new File("d://test.bmp");
FileReader inputStream = new FileReader("d://test.bmp");
FileOutputStream outputStream = new FileOutputStream("d://test1.bmp");
/*
* Create byte array large enough to hold the content of the file.
* Use File.length to determine size of the file in bytes.
*/
char fileContent[] = new char[(int)inputFile.length()];
for(int i = 0; i < (int)inputFile.length(); i++){
fileContent[i] = (char) inputStream.read();
}
for(int i = 0; i < (int)inputFile.length(); i++){
outputStream.write(fileContent[i]);
}
}
}
Why are you using char[]? You don't have text data. Use byte[] instead.
"I want to subtract 10 (in decimal) from the data stored in the 10th index of an array." Why exactly?
I want to hide some information in this image, and later retrieve the same information.
I have tried using char[] also, it didn't work.
byte fileContent[] = new byte[(int)inputFile.length()];
for(int i = 0; i < (int)inputFile.length(); i++){
fileContent[i] = (byte) inputStream.read();
}
for(int i = 0; i < (int)inputFile.length(); i++){
outputStream.write(fileContent[i]);
}
outputStream.flush();
outputStream.close();
This is commonly known as [tag:steganography]. I've added the tag to the post. 2) It is typically not achieved by changing a specific byte in the File as you seem to be doing, but instead the 'data' of the image or sound itself. In this case you would read the fie into a BufferedImage, manipulate the image itself, and write it back out to file. 3) Add @JonSkeet (or whoever) to notify them of a new comment. 4) Code in comments is unreadable. Instead edit it into the question and use code formatting.
Instead of char[], use byte[]
Here's a modified version if your code which works:
public class Test {
public static void main(String[] args) throws IOException {
File inputFile = new File("someinputfile.bmp");
FileOutputStream outputStream = new FileOutputStream("outputfile.bmp");
/*
* Create byte array large enough to hold the content of the file.
* Use File.length to determine size of the file in bytes.
*/
byte fileContent[] = new byte[(int)inputFile.length()];
new FileInputStream(inputFile).read(fileContent);
for(int i = 0; i < (int)inputFile.length(); i++){
outputStream.write(fileContent[i]);
}
outputStream.close();
}
}
Its still not working even after using byte[] array instead of char[]
did you also remember to close the OutputStream?
Other have pointed you at errors in your code (using char instead of byte mostly), however, even if you fix that, you probably will end up with a non-loadable image if you change the value of the 10th byte in the file.
This is because, a .bmp image file starts with an header containing information about the file (color depth, dimensions, ... see BMP file format) before any actual image data. Specifically, the 10th byte is part of a 4 byte integer storing the offset of the actual image data (pixel array). So subtracting 10 from this value will probably make the offset pointing at the wrong point in the file, and your image loader doing bound checking will probably consider this invalid.
What you really want to do is load the image as an image and manipulate the pixel values directly. Something like that:
BufferedImage originalImage = ImageIO.read(new File("d://test.bmp"));
int rgb = originalImage.getRGB(10, 0);
originalImage.setRGB(rgb >= 10 ? rgb - 10 : 0);
ImageIO.write(originalImage, "bmp", new File("d://test1.bmp"));
To make your existing code work you should replace the FileReader with a FileInputStream. According to the FileReader javadoc:
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
Modifying your sample as below
public static void main(String[] args) throws IOException
{
File inputFile = new File("d://test.bmp");
FileInputStream inputStream = new FileInputStream("d://test.bmp");
FileOutputStream outputStream = new FileOutputStream("d://test1.bmp");
/*
* Create byte array large enough to hold the content of the file.
* Use File.length to determine size of the file in bytes.
*/
byte fileContent[] = new byte[(int)inputFile.length()];
for(int i = 0; i < (int)inputFile.length(); i++){
fileContent[i] = (byte) inputStream.read();
}
inputStream.close();
for(int i = 0; i < (int)inputFile.length(); i++){
outputStream.write(fileContent[i]);
}
outputStream.flush();
outputStream.close();
}
This work for me to create a copy of the original image.
Though as mentioned in the comments above this is probably not the correct approach for what you are trying to achieve.
| common-pile/stackexchange_filtered |
handling interruptions in insert
I'm processing(aggregating) a log file, and this is my process:
convert binary file to array of strings
start upsert at line $n (taken from a process_log record)
handle individual strings
parse string as object
insert object into various rollups
update $n record in process_log
The problem I have, however rare it may be, that when there is any interruption at any point and it will very likely happen during step 5. Meaning, that it will update the rollup but not the process_log record, and when it starts again it will process the last line twice.
Is there a way to prevent this from happening? Is it possible to upsert to several collections at once and would that resolve the problem, and a way to do so with mongoose?
| common-pile/stackexchange_filtered |
Search a file (10MB+) for keywords occuring in a similar context (<512 word length away)
I want to extract paragraphs from a file where input keywords occur together or a certain distance apart (maximum ~512 words apart). The file size is 10MB and although it would've been fine to do a naive search for every keyword, I am passing each of the paragraphs (in which the words occur) to a model which takes around ~1-2s to get results. There can also be more than 1000 occurrences of certain keywords. This makes it extremely slow.
What I have tried playing with is Longest Common Subsequence and Minkowski distance but they don't really fit here as in the former case ordering of keywords is important and the latter doesn't make sense to me in this particular case.
One thing I can possibly do is to remove unimportant words (such as stopwords) and then run this process again, but I doubt if it will still be better.
I will also need to use top k paragraphs, which I will keep around 10.
The text file are novels/books.
As an example, in Harry Potter book I want paragraphs where the keywords "Uncle Vernon", "Hogwarts", "Harry", "Letter" occur together.
How can I do it more efficiently?
why don't u use Lucene to index and retrieve the paragraphs?
in a single iteration make a list of word index for every key word, now you have a group of sorted lists, you want to find groups that appear in all lists in a boundary of 512 words, again a single iteration
@trigonom I think it could work here. What else do you suggest about getting the top few results following this method, something like absolute distance between each pair of words?
@Debasis can you recommend something for Python? I looked into pylucene but couldn't find good documentation or where to get started.
i would advise to use the Java version as a blackbox retriever... use my mavenized version (https://github.com/gdebasis/luc4ir) for which u don't need to write a single line of code... u just need to format ur documents as a 2 column file (id \t content) - which u can do in Python... for viewing the content there's a script in the repository called viewdocs.sh
suppose this is the table you have
you begin with every one first index and check the distance between lowest and highest,
in this case 77-5 = 72
you move to the next index with the lowest and check again
every time you move forward with the lowest index and check if the dif between lowest and highest is lower then distance you deiced
it might miss some cases
after a successful group you need to check all of the words next option
consider the above, after first group you will move forward with Harry and miss 2 groups of Hogwarts next index and of uncle vernon next index
| common-pile/stackexchange_filtered |
onEdit(e) not generating trigger event when cell value changes due to inbuilt function
Below code monitors cell value changes in between (Row 1 to Row 5, column 1 to column 5), and it tracks and log event in different sheet.
Which is working only when changes are being done manually in spreadsheet cells. (because onEdit(e) function only tracks the cell value changes edited manually not by any other functions)
If cell value changes due to some inbuilt mathematical functions (Example : B2 = C2+D2 where cell value of B2 will change automatically when C2 / D2 changes ) But with this code i can not see event getting triggered for value of B2 cell.
Can anybody help to find solution or workaround with below code.
Thanks
Code :
function onEdit(e) {
if (
e.source.getSheetName() == "SheetA" &&
e.range.columnStart >= 1 &&
e.range.columnEnd <= 5 &&
e.range.rowStart >= 1 &&
e.range.rowEnd <= 5
) {
//Logger.log("the cell is in range");
var sheetsToWatch = ['SheetA'];
var changelogSheetName = "Changelog";
var timestamp = new Date();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var sheetName = sheet.getName();
// if it is the changelog sheet that is being edited, do not record the change
if (sheetName == changelogSheetName) return;
// if the sheet name does not appear in sheetsToWatch, do not record the change
var matchFound = false;
for (var i = 0; i < sheetsToWatch.length; i++) {
if (sheetName.match(sheetsToWatch[i])) matchFound = true;
}
if (!matchFound) return;
var columnLabel = sheet.getRange(/* row 1 */ 1, cell.getColumn()).getValue();
var rowLabel = sheet.getRange(cell.getRow(), /* column A */ 1).getValue();
var changelogSheet = ss.getSheetByName(changelogSheetName);
if (!changelogSheet) {
// no changelog sheet found, create it as the last sheet in the spreadsheet
changelogSheet = ss.insertSheet(changelogSheetName, ss.getNumSheets());
// Utilities.sleep(2000); // give time for the new sheet to render before going back
// ss.setActiveSheet(sheet);
changelogSheet.appendRow(["Timestamp", "Sheet name", "Cell address", "Column label", "Row label", "Value entered"]);
changelogSheet.setFrozenRows(1);
}
changelogSheet.appendRow([timestamp, sheetName, cell.getA1Notation(), columnLabel, rowLabel, cell.getValue()]);
}
}
This is functioning as designed. The edit trigger will not fire unless the change is directly by a user.
Is there any other way or option where we can get trigger for cell value change even the value is being changed by other function
There is a workaround:
Create two separate spreadsheets - spreadsheet number 1 contains your original data and formula, spreadsheet number 2 contains your script and an empty SheetA
Assign to cell A1 in SheetA of Spreadsheet2 a formula =IMPORTRANGE(IMPORTRANGE(spreadsheet_url, range_string), whereby spreadsheet_url is the URL of Spreadsheet 1 and range_string the range of interest (e.g. "SheetA!A1:E")
Use Scriptproperties to store cell values
Find the modified cell by comparing old values against new values, each time there is a change in the sheet of interest
Modify your script as following:
var ss=SpreadsheetApp.getActive();
var sheetsToWatch = ['SheetA'];
function initialSetUp(){//run this function only once, unless your range of interest changes
for (var k = 0; k < sheetsToWatch.length; k++) {
var sheet=ss.getSheetByName(sheetsToWatch[k]);
var range=sheet.getRange(1,1,5,5); //change if required
var values=range.getValues();
for(var i=0;i<values.length;i++){
for(var j=0;j<values[0].length;j++){
PropertiesService.getScriptProperties().setProperty('values '+sheet.getSheetName()+i+"-"+j,values[i][j]);
}
}
}
}
function Edit() {
var sheet=ss.getActiveSheet();
var sheetName = sheet.getName();
var matchFound = false;
for (var k = 0; k < sheetsToWatch.length; k++) {
if (sheetName.match(sheetsToWatch[k]))
matchFound = true;
}
if (matchFound == true) {
var range=sheet.getRange(1,1,5,5); //change if required
var values=range.getValues();
for(var i=0;i<values.length;i++){
for(var j=0;j<values[0].length;j++){
var scriptValue=PropertiesService.getScriptProperties().getProperty('values '+sheetName+i+"-"+j);
var newValue=sheet.getRange(i+1,j+1).getValue();
Logger.log(scriptValue);
Logger.log(newValue);
if(newValue!=scriptValue){
var cell=sheet.getRange(i+1,j+1);
var timestamp = new Date();
var columnLabel = sheet.getRange(1, cell.getColumn()).getValue();
var rowLabel = sheet.getRange(cell.getRow(), /* column A */ 1).getValue();
var changelogSheetName = "Changelog";
var changelogSheet = ss.getSheetByName(changelogSheetName);
if (!changelogSheet) {
changelogSheet = ss.insertSheet(changelogSheetName, ss.getNumSheets());
//Utilities.sleep(2000); // give time for the new sheet to render before going back
changelogSheet.appendRow(["Timestamp", "Sheet name", "Cell address", "Column label", "Row label", "Value entered"]);
changelogSheet.setFrozenRows(1);
}
changelogSheet.appendRow([timestamp, sheetName, cell.getA1Notation(), columnLabel, rowLabel, cell.getValue()]);
PropertiesService.getScriptProperties().setProperty('values '+i+"-"+j,newValue);
}
}
}
}
}
Add to the new function Edit() an installable trigger onChange.
EXPLANATION:
onEdit trigger cannot detect changes in values triggered by a formula
onChange cannot detect changes caused by cell formulas, but it can detect changes triggered by IMPORTRANGE
Hi Ziganotschka, thanks for your suggestion and workaround. When tried your suggestion and followed all above steps, I see issue while generating a change log, it only updates the log for A1 cell in spreadsheet 2 where =IMPORTRANGE((spreadsheet_url, range_string) configured in A1 cell for spreadsheet 2.
Hi Ziganotschka thanks for your reply, unfortunately that is also not working, randomly it gives A1 value in log or sometimes even not generating the log even after change, even if i try populate specific address of specific cells.
I came up with a solution using script properties, see my updated response.
| common-pile/stackexchange_filtered |
How to change color of CAGradientLayer like screensaver?
I was created UIView with applying CAGradientLayer color effect as i attached Image Bellow. Now in this i want to change it's gradient color change top to bottom side smoothly like screensaver. I have Been tried using NStimer that bit Done but its changing color in CAGradientLayer look like jerk.
For above I have use Bellow method of Code:-
Timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TIMER) userInfo:nil repeats:NO];
-(void)TIMER
{
Count++;
[view_Color1 removeFromSuperview];
view_Color1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 341)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view_Color.bounds;
if (Count == 1)
{
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor greenColor] CGColor], (id)[[UIColor colorWithRed:44/255.0 green:255/255.0 blue:255/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:0/255.0 green:0/255.0 blue:254/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:252/255.0 green:0/255.0 blue:255/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:252/255.0 green:0/255.0 blue:6/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:253/255.0 green:131/255.0 blue:6/255.0 alpha:1.0f]CGColor], (id)[[UIColor colorWithRed:255/255.0 green:237/255.0 blue:10/255.0 alpha:1.0f]CGColor], nil];
}
else if (Count == 2)
{
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:255/255.0 green:237/255.0 blue:10/255.0 alpha:1.0f]CGColor],(id)[[UIColor greenColor] CGColor], (id)[[UIColor colorWithRed:44/255.0 green:255/255.0 blue:255/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:0/255.0 green:0/255.0 blue:254/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:252/255.0 green:0/255.0 blue:255/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:252/255.0 green:0/255.0 blue:6/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:253/255.0 green:131/255.0 blue:6/255.0 alpha:1.0f]CGColor],nil];
}
//and so on still count is 7 then again its 1 to continue here are count use for chagen 7 color gradient use and repeat.
[self.view addSubview:view_Color1];
[self.view_Color1.layer addSublayer:gradient];
[myappdelegare sharedinstance].str_LastColorClick = [[NSString alloc]initWithFormat:@"MultiColor"];
Timer = [NSTimer scheduledTimerWithTimeInterval:0.30 target:self selector:@selector(TIMER) userInfo:nil repeats:NO];
}
Can you please help me?
Thanks
It isn't smooth because you are rendering only 10/3 frames per second. Change the time interval to 0.04 (25 fps).
it also jerks in 0.04. thank for your help
I did not noticed first that you are "jumping" with colors at every step.
Here is a code which does the animation:
- (void) initGradient
{
if ( !gradient ) {
gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
[self.view.layer addSublayer:gradient];
NSArray *baseColors = [NSArray arrayWithObjects:(id)[UIColor yellowColor].CGColor, (id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor, nil];
NSMutableArray *colors = [NSMutableArray arrayWithArray:baseColors];
[colors addObjectsFromArray:baseColors];
gradient.colors = colors;
cnt = [baseColors count];
NSMutableArray *locations = [NSMutableArray array];
CGFloat step = 1. / (cnt - 1.);
CGFloat loc = 0;
for ( NSUInteger i = 0; i < [colors count]; i++ ) {
[locations addObject:@(loc)];
loc += step;
}
gradient.locations = [locations copy];
}
}
-(void)TIMER
{
NSMutableArray *locations = [NSMutableArray array];
CGFloat step = 1. / (cnt - 1.);
static const CGFloat speed = 3;
CGFloat initialStep = speed / gradient.bounds.size.height;
CGFloat loc = [gradient.locations[0] floatValue] - initialStep;
if ( loc <= -1 - step )
loc = initialStep;
for ( NSUInteger i = 0; i < [gradient.locations count]; i++ ) {
[locations addObject:@(loc)];
loc += step;
}
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
gradient.locations = [locations copy];
[CATransaction commit];
Count++;
if ( Count >= [gradient.colors count] )
Count = 0;
[self performSelector:@selector(TIMER) withObject:nil afterDelay:0.04];
}
It still has an small issue, that the top pixel of the view gets a mixed color but animates nicely. You can adjust the speed as well (static CGFloat speed). I leave it up to you to solve - maybe clip.
hi @Szabi Tolnai your work is very nice its give nice effect. but it goes from bottom to top. Can you please help in one more thing? How it goes from top to bottom
hi @Szabi Tolnai can you please tell me how to do it from top to bottom? thanks a lot
@BhaveshLakum Try to set the initial location from -1 and in TIMER instead of += use -= and adjust the limit and the if ( loc <= -1 - step ) accordingly.
hi @SzabiTolnai by doing this its not animate from top to bottom can you give proper solution? thanks
If you want to animate layer properties do not use NSTimer, use one of the classes of CAAnimation 'family'. In your case if you want to animate between several different gradients then CAKeyFrameAnimation is the right choice. Sample code to add layer animation to gradient layer:
- (void) addColorsAnimationToGradientLayer:(CAGradientLayer*)glayer {
NSMutableArray *colors = [glayer.colors mutableCopy];
NSMutableArray *animationColors = [@[] mutableCopy];
for (int i = 0; i < colors.count; ++i) {
[animationColors addObject:[colors copy]];
id lastColor = [colors lastObject];
[colors removeObjectAtIndex:colors.count-1];
[colors insertObject:lastColor atIndex:0];
}
CAKeyframeAnimation *kfAnimation = [CAKeyframeAnimation animationWithKeyPath:@"colors"];
kfAnimation.values = animationColors;
kfAnimation.duration = 5.0f;
kfAnimation.repeatCount = HUGE_VALF;
kfAnimation.autoreverses = YES;
[glayer addAnimation:kfAnimation forKey:@"colors"];
}
In the code listed above I create infinitely looping animation where gradient colors are obtained using cyclic permutation of colors in initial gradient:
KeyFrame0: [color0, color1, color2,…, colorN]
KeyFrame1: [colorN, color0, color1, color2,…, colorN-1]
…
KeyFrame(N-1): [color1, color2, color3,…, color0]
| common-pile/stackexchange_filtered |
Is encrypting credit card numbers one by one with rsautl secure?
I wish to encrypt credit card numbers one by one using asymmetric encryption on the command line. My current approach is this…
Encrypt:
/usr/bin/openssl rsautl -encrypt -inkey 'myKey.pub' -pubin | /usr/bin/openssl enc -base64
Decrypt:
openssl enc -base64 -d | openssl rsautl -decrypt -inkey myKey.pem
It is my understanding that this is secure, even when using the same key for each number, because rsautl introduces randomization to prevent finding patterns in the cyphertext.
Am I correct, and is the approach therefore secure?
As long as you use a secure padding mode (i.e. -pkcs or -oaep, not -raw). The default padding mode for openssl rsautl is -pkcs (i.e. PKCS#1 v1.5), so you should be OK. That said, OAEP is recommended over PKCS#1 v1.5 padding, so you might want to use the -oaep switch.
Just making this comment because it wasn't specified in the question - a 2048-bit key should be used as a minimum (but I'd go even higher if I were encrypting something as sensitive as credit card numbers).
@hunter The actual key management is not specified. The key management procedures around the private key are very important. Key size is important, but it is only a very small part of the key management. Then again, those would be more at place at http://security.stackoverflow.com. For credit card numbers I would certainly first check the requirements of the credit card companies themselves.
@owlstead - yup, key size is only a small part of key management - but one that often gets overlooked with RSA - I'm amazed at the number of people still using 1024-bit keys in the wild. Thought it was worthwhile making a PSA.
Great! We use a 4096 key with the public key in the codebase, and the private key on our local-network payment server. To decrypt the log, we login to the payment server and paste the cyphertext into openssl's stdin. We intend to change the key every couple years.
The phrase "We intend to change the key" implies imprecision. You really should be creating a full key management lifecycle policy to comply with PCI 3.5 and 3.6, something that specifies how you will generate, distribute, store, use, retire, and destroy the keys, how long each of those states last, plans if they're compromised, etc. See https://www.pcisecuritystandards.org/documents/pci_dss_v2.pdf for the requirement, and http://csrc.nist.gov for advice. http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-130.pdf deals directly with creating a key management strategy.
@JohnDeters Thank you, I was unaware this part of our plans was noncomplying. I will do as you suggested.
You're welcome. PCI DSS is a confusing, giant burden, and I know that finding out how to navigate it can take a lot of effort. Good luck!
Be aware that your solution will touch much more than cryptography. Your command shell, the account it runs on, the swap file, the whole machine falls under the purview of PCI DSS regulation and auditing.
If you can avoid storing or even handling the number, so much the better.
We are PCI certified so that's fine. But I agree it shouldn't be taken lightly; we decided payment processing is a core competency for us, because of the market edge it gives us in responding to customer needs combined with a software customization framework.
| common-pile/stackexchange_filtered |
How to define the size of List<Map<String, Object>>?
I am making a method that needs to return a list.
private List<Map<String, Object>> mapDO(List<dO> dOList) {
List<Map<String, Object>> ordersMapList = new ArrayList<>();
Map<String, Object> ordersMap = new HashMap<>();
for (int i = 0; i < dO.size(); i++) {
ordersMap.clear();
ordersMap.put("description", dOList.get(i).getDescription());
ordersMap.put("size", dOList.get(i).getSize());
System.out.println(i);
System.out.println(ordersMap);
ordersMapList.add(ordersMap);
System.out.println(ordersMapList);
}
return ordersMapList;
}
The problem is: Arraylist stores the reference and does not copy/create new objects. If you change the stored object reference, it will be reflected in the arrayList as well.
The output for the above code is:
0
{size=One size, description=Product 1}
[{size=One size, description=Product 1}]
1
{size=One size, description=Product 2}
[{size=One size, description=Product 2}, {size=One size, description=Product 2}]
2
{size=One size, description=Product 3}
[{size=One size, description=Product 3}, {size=One size, description=Product 3}, {size=One size, description=Product 3}]
I tried to use the .set(index, element) property because to fix this, I need to use setters but I can't seem to find a way to initialize the oMapList. I have tried the following but all of them give errors:
List<Map<String, Object>> oMapList = new ArrayList<>(dOList.size()); but this gives sets a capacity and doesn't actually have an effect.
List<Map<String, Object>> oMapList = Arrays.asList(new Map<String, Object>[dOList.size()]; which gives a Generic array creation error.
Is there any other way I can fix this?
If you need to fix the size of a list, just turn it into an array with List.asArray() or List.asArray(new TypeOfList[0]);.
@Schred, when I type List., the only options I see are class, new and try..
It's an instance method, you need to call it on a list: ordersMapList.asArray();
Not sure if I really understood the question but looking at the code it seems you want a List of Map, but you are adding only one Map to the List which doesn't make sense.
Perhaps what you want is this:
private List<Map<String, Object>> mapDO(List<dO> dOList) {
List<Map<String, Object>> ordersMapList = new ArrayList<>();
for (int i = 0; i < dO.size(); i++) {
Map<String, Object> ordersMap = new HashMap<>();
ordersMap.put("description", dOList.get(i).getDescription());
ordersMap.put("size", dOList.get(i).getSize());
System.out.println(i);
System.out.println(ordersMap);
ordersMapList.add(ordersMap);
System.out.println(ordersMapList);
}
return ordersMapList;
}
Which creates a new map in each iteration, and adds it to the List.
| common-pile/stackexchange_filtered |
vim-latex: "I can't write on ..." error
I am using vim-latex. I compile TeX document using \ll command, then \lv to view it. It generates a PDF file. So far, so good. The problem starts when I try to modify my TeX file and compile it again with \ll. I get an error:
I can't write on "filename".
I have to close the previously generated PDF file in order to compile again. How can I avoid this and make vim to refresh the PDF file? Any suggestions?
If you are using Adobe Reader it locks the file; If you are on Windows switch to Sumatra PDF. I don't know what linux PDF readers lock the file, but you should try switching to a different one.
If you are using Adobe Reader or certain other PDF readers it locks the file.
I don't know what OS you are on, but based on discussion in the chatroom Reader only locks the file on Windows. If you are indeed on Windows switch to Sumatra PDF, which does not lock the file.
I don't know what linux or Mac PDF readers lock the file, but you should try switching to a different one, as this is likely a PDF reader problem, not a vim-problem.
Thank you for the quick response. Yes, indeed, i am using Adobe and i have Windows 7. Your suggestion for Sumatra PDF worked. Still it makes me wonder why Adobe locks the file. I was using TexnicCenter with Adobe before and it was compiling and updating the files without at the same time, no locking.
Remember to accept the answer. I don't know how TexnicCenter got away with it, but this is a common problem.
Thanks for your help indeed after closing Adobe I have managed to compile my file nicely without any errors
| common-pile/stackexchange_filtered |
Google structured data
Before I ask I would like to mention that I have searched for solution...
I am trying to build Goggle's AMP page. I used their template and tested it with Chrome's Developer Tools, however, in Google's own Structured Data Testing Tool I get an error and two warnings. I'm stuck trying to figure this thing out. Here's my code and below is a screen capture of the errors I see.
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "NewsArticle",
"headline": "Remote Card Sorting and Prioritization Matrix Tools for usability testing and information architecture.",
"datePublished": "2016-10-08T12:02:41Z",
"dateModified": "2016-11-05T12:02:41Z",
"author": "usabiliTEST",
"image": [
"/i/usabilitestLogo.png"
],
"publisher": "usabiliTEST"
}
</script>
How can this be fixed? What am I still missing?
Image needs to be an 'Image Object'.
"image": {
"@type": "ImageObject",
"url": "https://google.com/thumbnail1.jpg",
"height": 800,
"width": 800
},
I answered a similar question here.
I think Google test tool is broken. Webmaster tool says no errors, but the tool is all over the place.
| common-pile/stackexchange_filtered |
Is a visually impaired person considered a Person with Reduced Mobility (PRM)?
In Europe, all airlines are required to assist people with reduced mobility. I'm visually impaired, and soon flying with Iberia. So, I called them to ask for assistance at the airport. The guy who answered said that they only offered assistance with wheelchair travel (or something of that sort, the person sproke broken English, and the connection was bad).
I'm going to call again tomorrow during Dutch business hours and ask for help in Dutch (my native language), but in the meantime, if there's any useful info you can give me, that's greatly appreciated.
Yes, you should be covered.
From Iberia web site:
Passengers with Reduced Mobility (PRM) In air transport, current legislation defines a person with a disability or a Passenger with Reduced Mobility (PRM) as "any person whose mobility when using transport is reduced due to any physical disability (sensory or locomotor, permanent or temporary), intellectual disability or impairment, or any other cause of disability, or age, and whose situation needs appropriate attention and the adaptation to his or her particular needs of the service made available to all passenger" (art. 2 of EC Regulation 1107/06).
and
"Transfers and accompaniment in airports. Transit through airports on occasions requires walking long distances or walking through installations that you are unfamiliar with and which may tire and/or disorient you."
That being said, you need to call the airline to let them know that you will be flying with them and that you are visually impaired, and you will probably be asked to come to the airport earlier, and you will (most) probably be escorted to at least to the departure gate by a airport staff, and there be escorted in the plane by the airline staff.
Alright. I've tried calling them, but I will call them again. Thank you very much!
| common-pile/stackexchange_filtered |
Essential supremum of function in real line
If the pre-image of the function is whole real line and is defined as following:
\begin{equation}
f(x) =
\begin{cases}
1 & \text{if}\,x\in\mathbb{Z} \\
0 & \text{otherwise}
\end{cases}
\end{equation}
What would be the essential supremum?
I understand that the essential supremum of a function is the smallest value that is larger or equal than the function values almost everywhere when allowing for ignoring what the function does at a set of points of measure zero.
Would it be still zero considering each individual integer essentially has measure zero? However, the measure of the integer set with value 1 is not zero, is it?
Thanks in advance.
The measure of $\mathbb Z$ is $0$.
@KaviRamaMurthy That makes sense considering union of sets of measure zero is still zero. In that case, the essential supremum would be 0. Right?
Yes, indeed the essential supremum of this function is zero given the fact that union of sets of measure zero is still zero.
| common-pile/stackexchange_filtered |
Issue with ejb-jar.xml Error processing EjbDescriptor
I have a strange issue where if the ejb-bar has one bean, all works well, as soon as I've adding another bean, I am getting the above error when deploying to GlassFish.
I have made the second bean almost identical to the first and added the @EJB annotation with the bean name to the class, then I've added a second <session> node to the xml file where the "ejb-name" is EXACTLY as I defined the name!
Is there anywhere else I need to make the reference? note that the ejb-jar.xml is in a different project than those two beans.
File is:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" version="3.1">
<display-name>ClinicService </display-name>
<enterprise-beans>
<session>
<ejb-name>PatientServiceBean</ejb-name>
<env-entry>
<description>Site deployment information for the patient service.</description>
<env-entry-name>SiteInfo</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Example</env-entry-value>
</env-entry>
</session>
<session>
<ejb-name>ProviderServiceBean</ejb-name>
<env-entry>
<description>Site deployment information for the provider service.</description>
<env-entry-name>SiteInfo</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Example</env-entry-value>
</env-entry>
</session>
</enterprise-beans>
</ejb-jar>
I'm almost certain you actually mean ejb-jar.xml and 2) add that file to the question, it's hard to understand your description without seeing the file.
Yes sorry! I've edit the question to add the file content
What error are you getting ? Could you post the two beans and the relevant fragment of the application server stack trace ?
You need to show more of your code and stack traces otherwise you're forcing us to take educated guesses
I think it was Eclipse issue with cleaning up projects...
Now the WebService is acting up, when using @EJB(beanName="ProviderServiceBean") then the Patient Web service works, the other one is throwing 500 error (when trying to see WSDL) , ugh!! Even in the patient the siteInfo does not work...
@SteveC, editing the question now.
I think it was Eclipse acting up, as today I checked and it works...(did not make any changes or redeploy anything, ghosts in the machine...)
| common-pile/stackexchange_filtered |
Google login in 3rd party app
I installed a 3rd party app and logged in using another Google account.
I then deleted the app.
Then when I opened google website on safari browser, it had already logged me in using my account.
How do I remove this?
| common-pile/stackexchange_filtered |
Why does my sound so dull?
I use beyerdynamics dt770 to mix.
I heard someone say that there was a problem with my EQing.
When I eq what I do is, I sweep for sounds that make the audio in question seem too resonant, like boxy then I reduce those.
I then compress and sweep for the sweet spots in the audio in question.
I pan most instruments that take up the mid range, so I don't obstruct the vocals. So if I have a piano, I will duplicate the track and pan one left and right.
Kicks and anything in the low range are centred.
My DAW is Logic Pro by the way. I use waves plugins to compress, and the Logic Pro native channel Eq to Eq.
I use he CLA2 and or the CLA76 on vocals and the CLA3A on instruments.
Thanks!
A few random things, I don't know how helpful they will or won't be. Bring the instruments forward -- you only have two of them after all. The drums could afford to punch a little more, and so could the chords. It might also not hurt to have a pad playing chord roots softly in the background to fill things out a little more. Finally, it seems to me that the vocal needs some reverb or delay. There are all sorts of arrangement tricks you can use to make things more interesting. Maybe mult some key vocal lyrics to a separate track with some overdrive, for example.
@Linuxios hey, thanks for the response. So there is nothing notably wrong with my eqing?
sounds like there is room reflections stealing presence from the vocals. maybe try getting closer and/or switching it out for another one.
@ScottRussell what about the instrumental itself? Minus the vocals. In your opinion is it EQd and compressed correctly?
@WeCanBeFriends: Nothing that I immediately hear. In general though, if you're making any big cuts or boosts without a specific reason to do so, it's probably doing your mix no favors. You also don't necessarily need to compress synth instruments -- most of the time their levels are so consistent that you don't need it for dynamic control.
@Linuxios I never knew that, I always thought I had to eq and compress everything. Thank you for the knowledge! Have a nice day! :)
@WeCanBeFriends: Of course! My pleasure. Generally you do need to compress things that you record from the "real world", because it let's you find a fader level that keeps things sitting well. But this song is so minimal in its instrumentation, that I'd say you can just leave everything the way it is, except maybe a small cut of the chords at the voice's most prominent frequencies -- but that's only if the two are fighting.
You wrote: "I pan most instruments that take up the mid range, so I don't obstruct the vocals. So if I have a piano, I will duplicate the track and pan one left and right." What does this do? Isn't the end result the same as what you began with? Aren't you confusing frequency mid range with the middle of a stereo 'space'. Disclaimer: I have no experience editing music.
I wouldn't say you have problems with EQing here necessarily.
A couple things I hear:
1)
The vocals sound very much like you recorded them in a room and not in a studio environment. Try hanging some heavy blankets and try to create an environment where you won't have as many reflections. 8. Minimise the room's influence on your sound. The mic picks up both direct sound from the singer and reflected sound from the room. Reduce the room's contribution by keeping away from the walls and by improvising screens using sleeping bags or duvets behind and to the sides of the singer. (from a Sound On Sound article: https://www.soundonsound.com/sos/oct98/articles/20tips.html)
2)
There's some mysterious background noise around ~1:04 that sounds like the wrong chords being played by something quietly? Do you hear that?
3) The main keyboard sound is a bit thin in general, and not too interesting. For example: try mangling the sound a little bit -- make an Aux send and put some distortions, maybe the amp simulator on the Bus and then through a reverb or delay (wet turned to 100%) and maybe a tremolo or something, then sidechain (
) that to the original chord sound.
Hope it helps!
Hey, thank you for replying! I hear the wrong chords, I hear the wrong chords! I downloaded the sampled keyboard. I should have processed it a bit. Or maybe it was because I planned it left and right. Thank you for all the advice! I will definitely record in a closet or try to dampen the surrounding sound! Thank you!
For sure ^__^ feel free to mark my answer as the correct answer to your question, I'm trying to get some rep in the stackexchange world
Vocals sound a little dry to me, maybe add some subtle reverb or delay. The method of EQing you're doing sounds right. Dullness usually comes from a lack of top end, maybe add a couple of DBs of top end to the vocals to bring them out a touch.
You could also bring the instruments forwards in the mix, and arrangement wise maybe add a bass instrument of some kid to fill out the bottom end.
Haha I did take out some of the top end, instead of using a de-esser for the s's and f's.. Could it also be the singer's articulation and the way he is talking/singing/rapping? Thanks for the insightful answer!
when you say bring the instruments forward what do you mean, louder or some eq changes?
| common-pile/stackexchange_filtered |
Failed to unmarshall yaml
I have an execute endpoint that runs a child process which in turn runs a rancher-compose command to start up some containers within a host on rancher. When I hit this /execute endpoint from the node app it work fine and starts the containers as expected. When hitting the /execute endpoint from a bash script through cURL command it fails and gives me the error below. I don't understand why it throws an error that it cannot unmarshall my yaml file just when the command is run through a bash script. This is leading me to believe that this is not an issue with my yaml file. Below I put the error and the command that's failing and the cURL command i'm using.
I'm absolutely lost and any help would be greatly appreciated!
ERROR starting job, unable to run sub-process for container deployment. >ERR=Error: Command failed: /rancher-tools/rancher-compose --project-name mic-iwbl3g97 --verbose --file docker-compose-job-submitter.yml up -d
job deployment output: time="2016-12-05T04:35:49Z" level=debug msg="Environment Context from file : map[]" time="2016-12-05T04:35:49Z" level=debug msg="Opening compose file: docker-compose-job-submitter.yml" time="2016-12-05T04:35:49Z" level=debug msg="Looking for stack mic-iwbl3g97" time="2016-12-05T04:35:49Z" level=info msg="Creating stack mic-iwbl3g97" time="2016-12-05T04:35:49Z" level=error msg="Failed to unmarshall: yaml: unmarshal errors:\n line 15: cannot unmarshal !!str NaN into int64\n line 16: cannot unmarshal !!str NaN into int64\ncommand:\n- mic-iwbl3g97\n- NaN\n- $input_csv_file\n- $start_year\n- $end_year\ncontainer-name: mic-iwbl3g97\ncpu_shares: 25\nimage: $repo_name:$tag\nlabels:\n io.rancher.container.pull_image: always\n io.rancher.container.start_once: true\n io.rancher.scheduler.affinity:host_label: MIC-Use=TPC_Modeling\n io.rancher.sidekicks: locking, input, output, param, input-helper\nmem_limit: NaN\nmemswap_limit: NaN\nnetwork_mode: none\nvolumes_from:\n- input\n- output\n- param\n- locking\n"
curl -s -X POST -H "Content-Type: application/json" -d '{"S3_param_file":"$input_csv_file", "memory_constraint":"$memory_constraint", "time_constraint":"$time_constraint", "start_year":"$start_year", "end_year":"$end_year", "tag":"$tag", "repo":"$repo_name"}' http://my_ip_address:3000/execute
What's the YAML meant to look like? Doesn't YAML have significant whitespace, could that be causing the unmarshalling error?
It does, but i'm skeptical it's the issue because it works properly when called from the web app as opposed to a bash script using a cURL. I've also tested it using many yaml checkers.
Parameters will not expand in single quotes: echo '$hello' prints $hello.
@andlrc, I have my parameters in double quotes as you can see?
@Mihado No: curl ...-d '{"S3_param_file":"$input_csv_file" ...
@andlrc I'm not following, can you elaborate briefly?
Variables will not be expanded in single quotes, use double quotes to expand:
curl -s -X POST \
-H "Content-Type: application/json" \
-d '{"S3_param_file":"'"$input_csv_file"'", "memory_constraint":"'"$memory_constraint"'", "time_constraint":"'"$time_constraint"'", "start_year":"'"$start_year"'", "end_year":"'"$end_year"'", "tag":"'"$tag"'", "repo":"'"$repo_name"'"}' \
http://my_ip_address:3000/execute
See how i swap between single quotes and double quotes:
'{"json_here": "'"$parameter_here"'"}'
sssssssssssssssssdddddddddddddddddssss
Where s represent single quotes, and d represent double quotes.
At evidenced above it quickly becomes a mess, one can however use jq to create JSON:
$ jq -n --arg a "a val" --arg b 'b val' '{$a, $b}'
{
"a": "a val",
"b": "b val"
}
IT WORKED! You sir, are my hero!
@Mihado I'm happy it worked for you. If you consider reading http://mywiki.wooledge.org/Quotes
| common-pile/stackexchange_filtered |
LinearLayout: layout_gravity="bottom" not working on Horizontal LinearLayout
Ok, First of all, I searched all the internet, but nobody has a similar problem like this. So, all I want is to have 3 textViews, bottom aligned with the screen and with the same width. Here is an image representing what I want:
And here is my code:
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<TextView
android:text="@string/help_1"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg1"
android:layout_gravity="bottom"/>
<TextView
android:text="@string/help_2"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg2"
android:layout_gravity="bottom"/>
<TextView
android:text="@string/help_3"
android:layout_weight="0.33"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/mynicebg3"
android:layout_gravity="bottom"/>
</LinearLayout>
</RelativeLayout>
Well, it works when the 3 textViews have the same height, but when their size differ, I get the following result:
Another strange behavior, is that when I set the layout_gravity of the biggest text to "center-vertical", I get the following result:
So obviously, I went crazy and tried another combinations with center-vertical, but nothing worked as I wanted initially:
So, any tips on how to solve this?
The Correct Answer
All the other answers are wrong. The important points:
You don't need RelativeLayout. You can do this with just a LinearLayout.
(Not critical but I guess you didn't know) Your weights don't need to sum to 1, you can just set them all to any equal value (e.g. 1).
The critical thing is you need android:baselineAligned="false". I actually only found this by looking through the LinearLayout source. It is in the docs but they don't mention that it is on by default!
Anyway, here is the code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false">
<TextView
android:text="dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeffee"
android:layout_gravity="bottom"/>
<TextView
android:text="asd asd asd asd asd asd asd asd asd asd"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeff"
android:layout_gravity="bottom"/>
<TextView
android:text="qweoiu qweoiuqwe oiqwe qwoeiu qweoiu qweoiuq weoiuqw eoiquw eoiqwue oqiweu qowieu qowieu qoiweu qowieu qowieu qowieu qowieu qoiweu qowieu qoiwue "
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffeeee"
android:layout_gravity="bottom"/>
</LinearLayout>
And how it looks:
A very simple fix, and it worked for me right away. I wish I had read this before the currently accepted answer.
@Timmmm I have my own TextView implementation extending TextView. And your solution of 'baseAligned' don't work for me. Please any guess?
No idea. Suggest you look at the code for LinearLayout to see how it uses baselineAligned and check where your code overrides its methods. You used baselineAligned rather than baseAligned right?
Ok. So I had the same issue, but with toggle buttons instead of text views. For some reason, if one of the elements in the LinearLayout(Horizontal) has a different height than the rest of the views in the layout and is set to have the same gravity as the others, the gravity is effectively "ignored".
I managed to have the desired behavior by wrapping each view inside a RelativeLayout and set the android:gravity on the relative layout instead of android:layout_gravity on each button. I also moved the android:layout_weight from the button to the relative layout.
So instead of having:
<LinearLayout
... >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_gravity="bottom"/>
</LinearLayout>
Which gives the same problem as reported, I instead did:
<LinearLayout
... >
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<RelativeLayout
...
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="bottom" >
<ToggleButton
...
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>
This is what I had to end up doing to get it fixed. I had a button inside a LinearLayout inside a ScrollView (inside another LinearLayout). The button wouldn't align to the bottom until I put the button within another LinearLayout
**EDIT:
If this doesn't do everything, add the baselinealigned flag as mentioned in one of the answers below by Timmmmm. That is a better way.
Use This
EDITED LAYOUT:
Ok I edited it and also added colors and gravity to let the textviews at the bottom have equal height and width and also aligh the text at the bottom and in the center of each view.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:gravity="fill_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="text1 jkjhh jhguk jvugy v ghjv kjhvygvusdioc jgytuayhashg hgyff"
android:textColor="#000000"
android:background="#FFFF00"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="t2"
android:textColor="#000000"
android:background="#FF0000"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:layout_gravity="fill_vertical"
android:gravity="bottom|center"
android:text="This is a long text. This is a long text. This is a long text. This is a long text.This is a long text. This is a long text. This is a long text."
android:textColor="#000000"
android:background="#00FF00"
/>
</LinearLayout>
It should do exactly what you asked.
It uses a LinearLayout inside a RelativeLayout but sometimes it is required to nest them to get what we want. Add any more views you might want in the relative layout and you will always have your texts at the bottom as long as the last child in your RelativeLayout is this LinearLayout as shown above.
Actually It's already inside a RelativeLayout, I ommited that.. But thanks anyway.. See the thing is, the texts are on the bottom, but they aren't aligned.
I tested it by setting the gravity to center as I have shown and they worked fine. I might not have understood how you are trying to align them. Can you describe it.
Your text must have more then one line. My first text has 5 lines, the second one 3, and the last one 7 lines. I tried to represent it on the images, but I can't submit screenshots of the app, as my employer wouldn't like it..
oh ok, in that case set the layout_height of each textview to match_parent. I also changed the code above. Please check it and see if it works.
@Paulo Cesar: I have edited the code to have the layout as you asked. I tested it and also added colors for each textview. Let me know if that is not what you are looking for.
Yeah, it works. Just one more little problem... I have a background on the TextView, and I wanted the background to have the same size of the text. This way, the 3 backgrounds will have the same height of the biggest text..
Found a workaround!! I put a RelativeLayout inside the LinearLayout, and the TextView inside the RelativeLayout. It's not permanent, because it will only work when I know which text will be the biggest
@PauloCesar let us continue this discussion in chat
I don't think the RelativeLayout is required at all, anywhere.
Same as Timmm's answer, but you also can use android:gravity="bottom" for LinearLayout attribute instead of android:layout_gravity="bottom" for each of TextView.
Like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="bottom"
android:baselineAligned="false">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 1......"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 2......"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="your text 3......"
android:layout_weight="1"/>
</LinearLayout>
thank you for your editing, TheEsisia. I don't have any experience :)
If you're ok with a RelativeLayout instead of Linear, this will do the trick, I guess:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/LinearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:id="@+id/TextView1" android:layout_above="@+id/TextView2"
android:layout_alignLeft="@+id/TextView2"></TextView>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:id="@+id/TextView2" android:layout_alignParentBottom="true"> </TextView>
</RelativeLayout>
But with RelativeLayout I can't use android:layout_weight="0.33" to make all the textViews the same size.. Unless there is a better way to make them have the same size?
In worst case you can work with dip values for width or height to get them to the same size, but I'm not sure if I'm getting your problem with the same sizes here...
Specifying the values won't work for me, I want them to adjust according to the parent width...
If you're trying to make all three child views the same height, then change height to "0", set the android:weightSum of the LinearLayout to 3, and the set the android:layout_weight of each view to 1.
Oh, I don't want them to have the same height. I want them to have the same width..
Are you trying to stack them horizontally or vertically?
Oops, I want to stack them horizontally, the title of my question was wrong. Sorry for the confusion..
Then set the orientation of LinearLayout to horizontal and the weight_sum to 3, and, for each child view, set the height of the views to match_parent, the width to 0, and the layout_weight to 1.
Well, I did what you said. Now the TextViews are correctely aligned, but they all have the same height. But I don't want them to have the same height...
Try changing the gravity or layout gravity of LienarLayout rather than setting it in the child views.
Are you trying to have the text within each TextView line up, and have all TextView bottoms line up? That is easy if you want the text within each TextView to be bottom-aligned (just set android:gravity="bottom" for each TextView).
However, you won't be able to do that when the TextViews have differing heights, unless you adjust their internal padding.
A much easier solution would be to use the < Space > tag:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" />
<TextView
android:text="Any Text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeffee"/>
<TextView
android:text="Any Text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeff"/>
<TextView
android:text="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffeeee"/>
</LinearLayout>
| common-pile/stackexchange_filtered |
Selection of primitives when clicked by mouse not working
I'm developing a solitary board game, which has a piece per square, and each piece can be of two colors. If I click a piece, the four adjacent ones (top, bottom, left and right) all change to the next color.
I'm having problems with detecting in which piece the mouse was clicked on.
I have the following code for the mouse callback:
GLuint selectBuf[BUFSIZE]; // BUFSIZE is defined to be 512
GLint hits;
GLint viewport[4];
if( ( state != GLUT_DOWN ) && ( button != GLUT_LEFT_BUTTON ) )
return;
glGetIntegerv (GL_VIEWPORT, viewport);
glSelectBuffer (BUFSIZE, selectBuf);
(void) glRenderMode (GL_SELECT);
glInitNames();
glPushName(0);
gluPickMatrix ((GLdouble) x, (GLdouble) y, 20.0,20.0, viewport);
draw(GL_SELECT); // the function that does the rendering of the pieces
hits = glRenderMode(GL_RENDER);
processHits (hits, selectBuf); // a function that displays the hits obtained
Now, the problem I have is that I don't quite know how to process the hits occurred which are on selectBuf. I have the following code for processHits:
void processHits (GLint hits, GLuint buffer[])
{
unsigned int i, j;
GLuint ii, jj, names, *ptr;
printf ("hits = %d\n", hits);
ptr = (GLuint *) buffer;
for(i = 0; i < hits; i++) {
printf("hit n. %d ---> %d",i, *(buffer+i));
}
}
Finally, in the draw function I have:
void draw(GLenum mode) {
glClear (GL_COLOR_BUFFER_BIT);
GLuint x,y;
int corPeca; //colourpiece in english
int corCasa; //colourHouse (each square has a diferent color, like checkers)
for (x =0; x < colunas; x++) { //columns
for(y=0; y < colunas; y++) {
if ( (tabuleiro[y*colunas+x].peca) == 1) //board
corPeca = 1;
else
corPeca = 2;
if((tabuleiro[y*colunas+x].quadrado)==1) //square
corCasa = 1;
else
corCasa = 2;
if (mode == GL_SELECT){
GLuint name = 4;
glLoadName(name);
}
desenhaCasa(x,y,corCasa); //draws square
desenhaPeca(x,y,corPeca, mode); //draws piece
}
}
}
Now, has you can see, I've just put 4 into the buffer with glLoadName. However when I pull the number out in processHits I always get 1. I know that's because of the structure of the buffer that gets the hits, but what is that structure and how can I access the number 4?
Thank you very much for helping me.
The structure of the selection buffer is a bit more complex than that. For each hit, a "hit record" consisting of several values is appended to the selection buffer. You can look at Question 20.020 in the OpenGL FAQ for details. In your case, where there is only one name on the stack at a time, the hit record will consist 4 values, with the name being the fourth one. So, in your processHits function, you should write
for(i = 0; i < hits; i++) {
printf("hit n. %d ---> %d",i, *(buffer+4*i+3));
}
Also, the size of your name buffer should probably be 4 times longer as well.
| common-pile/stackexchange_filtered |
How can I graphically visualize numerical data that I receive through a serial port?
I am trying to design an application in python to be able to read the data sent by a PIC microcontroller, for this I will use a UART-To-RS232 converter and then a RS232-To-USB converter to be able to receive the data on my computer, the PIC sends the voltage values of an AC signal and my application should be able to display these data on a graph, similar to the Arduino IDE serial plotter, but I want to get the effect of an oscilloscope, that is, to be able to see the graph as if it were the screen of a oscilloscope, being able to modify the time scale and amplitude of the signal that I am viewing and all those things that an oscilloscope does haha, how could I achieve this effect or what algorithms should I use to do this? I hope you can help me.
Regards.
A fairly simple option might be to throw the data into InfluxDB and then use Grafana to display it.
Or Python matplotlib can do animated plots...
pygame should be able to do this too, see https://realpython.com/pygame-a-primer/
| common-pile/stackexchange_filtered |
How to get CSS of a clicked div using jQuery?
Can anybody know how to get border-color of a div using jQuery.
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:#333333 solid 1px;" >
This is the target
</div>
In divcolor variable I am not getting anything.
Looks good to me .. except for I have some wierd feeling about #333333 being there for the color, I don't if JQuery returns that. Just speaking out loud. Thanks
I think by using JavaScript Reference we can get those style properties easily.
http://codepunk.hardwar.org.uk/css2js.htm
Thanks to all for helping me to finding the way.
Using the CSS jQuery function like you did:
http://docs.jquery.com/CSS/css#name
But read this paragraph:
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
@Mike background-color is coming but border-color is not coming.
Why was this answer chosen? It seems it doesn't answer the question.
Your mistake is elsewhere. That code works on Chrome and IE.
Try this one:
$("#divcolor").click(function (){
alert("dsf");
var divcolor = $(this).css("border-color");
alert(divcolor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divcolor" style="border:1px solid; border-color:#333333;" >
This is the target
</div>
You can write like this
$("#divcolor").click(function() {
var divcolor = $(this).css("border");
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
divcolor = divcolor.substring((divcolor.indexOf(' ') + 1), divcolor.length);
alert(divcolor);
});
But this will be applicable only when you are writing shorthand notations. The best practice is to use different class, as said earlier :)
$("#divcolor").click(function (){
var divcolor = $(this).css("borderColor");
alert(divcolor);
});
Good idea, though it gives me the four values: rgb(51, 51, 51) rgb(51, 51, 51) rgb(51, 51, 51) rgb(51, 51, 51)
Well, you can get the hex value by saying parseInt((a256256)+(b*256)+c, 16) ;-)
border-color isn't working for me either (on Firefox), but this works:
$(this).css("border-top-color")
http://jsbin.com/ezefu
@Kobi: I was curious to know how JQuery would get the color for different sides of the border, your answer clears this a bit :). Thanks
I always consider it better practice to work with CSS classes instead of CSS direct. Then you could have something like:
$(this).hasClass("MyClassWithTheBorderColorStyleInIt");
| common-pile/stackexchange_filtered |
Chaining WireGuard Servers: Can ping both from client, but can't access internet. IP routing issue?
I am attempting a chained/double-hop VPN setup where all client traffic passes through 2 servers before reaching the internet:
Client → Server1 → Server2 → Public Internet
All peers are on these private address blocks: <IP_ADDRESS>/24 (IPv4) and fd6f:9403:2887:9cd6:10:103:213:0/112 (IPv6). Below are the configurations of the peers and the IPTables rules in place. (Please also note the names of the configuration files, in case it matters.)
Server2 Configuration
File: /etc/wireguard/wg0.conf
# Server2
[Interface]
PrivateKey = SERVER2_PRIVATE_KEY
Address = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:2/112
ListenPort = 53701
SaveConfig = false
# CLIENTS
[Peer] # Server1
PublicKey = SERVER1_PUBLIC_KEY
PresharedKey = SERVER1_PRESHARED_KEY
# ↓ to allow traffic from client (<IP_ADDRESS>/32) via Server1 (<IP_ADDRESS>/32), allow both
AllowedIPs = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:0/112
Firewall config. commands:
ufw allow 53701/udp comment 'WireGuard VPN'
iptables -A FORWARD -i wg0 -j ACCEPT &&
iptables -A FORWARD -o wg0 -j ACCEPT &&
ip6tables -A FORWARD -i wg0 -j ACCEPT &&
ip6tables -A FORWARD -o wg0 -j ACCEPT
iptables -t nat -A POSTROUTING -s <IP_ADDRESS>/24 -o enp8s0 -j MASQUERADE
ip6tables -t nat -A POSTROUTING -s fd6f:9403:2887:9cd6:10:103:213:0/112 -o enp8s0 -j MASQUERADE
Server1 Configuration
File: /etc/wireguard/wg0.conf
# Server1
[Interface]
PrivateKey = SERVER1_PRIVATE_KEY
Address = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:1/112
ListenPort = 53701
SaveConfig = false
# CLIENTS
[Peer] # Server2
PublicKey = SERVER2_PUBLIC_KEY
PresharedKey = SERVER1_PRESHARED_KEY
Endpoint = SERVER2_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/32, fd6f:9403:2887:9cd6:10:103:213:2/128
#PersistentKeepalive = 25
[Peer] # PC
PublicKey = CLIENT_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
AllowedIPs = <IP_ADDRESS>/32, fd6f:9403:2887:9cd6:10:103:213:11/128
Firewall config. commands:
ufw allow 53701/udp comment 'WireGuard VPN'
iptables -A FORWARD -i wg0 -j ACCEPT &&
iptables -A FORWARD -o wg0 -j ACCEPT &&
ip6tables -A FORWARD -i wg0 -j ACCEPT &&
ip6tables -A FORWARD -o wg0 -j ACCEPT
Client Configuration
# CLIENT: PC
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:11/112
DNS = <IP_ADDRESS>, fd6f:9403:2887:9cd6:10:103:213:1
[Peer] # Server1
PublicKey = SERVER1_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
Endpoint = SERVER1_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/0, ::0/0
#PersistentKeepalive = 25
Now, like I said, I am able to ping Server1 (<IP_ADDRESS>) and Server2 (<IP_ADDRESS>) from the Client (<IP_ADDRESS>) on the private (WireGuard) network when the VPN is enabled on all peers, but I cannot access the internet.
I know I'm missing some much needed IP routes or IPTables rules, but despite trying to find a solution that I can understand for days, I've had no success. I see that there's little hope for me without actually reading a book on Linux networking/firewall.
For now, I am hoping someone can help me with a solution along with an explanation as to what we are doing and why, so I can understand better and take notes.
Thank you very much!
NOTES:
If I'm missing any useful information, please ask and I'll be happy to get it.
Client runs macOS. Server1 and Server2 run Debian 11 "Bullseye". Just an FYI, in case it's relevant.
Server1 and Server2 have Unbound installed and set up for local DNS resolution. That's why you see DNS = <IP_ADDRESS>, fd6f:9403:2887:9cd6:10:103:213:1 in Client config. If not for that, I'd be using either CloudFlare or Google's IPs there.
Someone on #wireguard IRC suggested that I try adding Table = 123 under [Interface] in Server1's WireGuard config. and then running the command ip rule add iif wg0 table 123. That didn't work and I couldn't understand what it's supposed to do either (I couldn't make sense of the man pages or the technical details).
From my reading I came to the conclusion that iptables and ufw can be used together—except one has to be careful when using iptables-persistent. You need to run netfilter-persistent save even after running ufw commands for the firewall rules to be persistent across reboots even if ufw status says they are in place. If for some reason you reboot before saving, delete the UFW rules and add them again and then run netfilter-persistent save.
Mixing UFW and iptables doesn't look like a good idea to me.
@iBug IDK, I did read up about it and pretty much came to the conclusion that they can be used together—except you have to be careful when using iptables-persistent (netfilter-persistent save even after running ufw commands). No others issues whatsoever.
The kind folks over at #wireguard IRC channel on Libera.Chat helped me out!
The issues with my config. were as follows:
Server1's config has Server2 with AllowedIPs of just Server2's IP addresses. That wont permit "The Internet". It needs to be <IP_ADDRESS>/0, ::0/0.
Server1's WireGuard interface must be configured to add routes (for all entries in AllowedIPs) to a custom IP routing table (let's call it wireguard2x) instead of the main table. Then add an IP policy rule that says that traffic with the input interface (iif) wg0 go to the custom table—which also means other kinds of traffic take the default route, per usual.
Corrected Configuration
Server2 Configuration
File: /etc/wireguard/wg0.conf
# Server2
[Interface]
PrivateKey = SERVER2_PRIVATE_KEY
Address = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:2/112
ListenPort = 53701
SaveConfig = false
# CLIENTS
[Peer] # Server1
PublicKey = SERVER1_PUBLIC_KEY
PresharedKey = SERVER1_PRESHARED_KEY
# ↓ to allow traffic from client (<IP_ADDRESS>/32) via Server1 (<IP_ADDRESS>/32), allow both
AllowedIPs = <IP_ADDRESS>/24, fd6f:9403:2887:9cd6:10:103:213:0/112
Firewall config. commands:
ufw allow 53701/udp comment 'WireGuard VPN'
iptables -A FORWARD -i wg0 -j ACCEPT &&
iptables -A FORWARD -o wg0 -j ACCEPT &&
ip6tables -A FORWARD -i wg0 -j ACCEPT &&
ip6tables -A FORWARD -o wg0 -j ACCEPT
iptables -t nat -A POSTROUTING -s <IP_ADDRESS>/24 -o enp7s0 -j MASQUERADE
ip6tables -t nat -A POSTROUTING -s fd6f:9403:2887:9cd6:10:103:213:0/112 -o enp7s0 -j MASQUERADE
Server1 Configuration
File: /etc/wireguard/wg0.conf
# Server1
[Interface]
PrivateKey = SERVER1_PRIVATE_KEY
Address = <IP_ADDRESS>/32, fd6f:9403:2887:9cd6:10:103:213:1/128
ListenPort = 53701
Table = wireguard2x
# ↓ should only be set if resolvconf or openresolv is installed on the system, otherwise let the system use defaults
# ↓ is unncessary if local DNS resolution is set up
#DNS = <IP_ADDRESS>, <IP_ADDRESS>, 2606:4700:4700::1111, 2606:4700:4700::1001
DNS = <IP_ADDRESS>, fd6f:9403:2887:9cd6:10:103:213:1
SaveConfig = false
# CLIENTS
[Peer] # Server2
PublicKey = SERVER2_PUBLIC_KEY
PresharedKey = SERVER1_PRESHARED_KEY
Endpoint = SERVER2_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/0, ::0/0
#PersistentKeepalive = 25
[Peer] # PC
PublicKey = CLIENT_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
AllowedIPs = <IP_ADDRESS>/32, fd6f:9403:2887:9cd6:10:103:213:11/128
Firewall config. commands:
ufw allow 53701/udp comment 'WireGuard VPN'
iptables -A FORWARD -i wg0 -j ACCEPT &&
iptables -A FORWARD -o wg0 -j ACCEPT &&
ip6tables -A FORWARD -i wg0 -j ACCEPT &&
ip6tables -A FORWARD -o wg0 -j ACCEPT
echo 123 wireguard2x >> /etc/iproute2/rt_tables
ip rule add iif wg0 table wireguard2x
Client Configuration
# CLIENT: PC
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = <IP_ADDRESS>/32, fd6f:9403:2887:9cd6:10:103:213:11/128
DNS = <IP_ADDRESS>, fd6f:9403:2887:9cd6:10:103:213:1
[Peer] # Server1
PublicKey = SERVER1_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
Endpoint = SERVER1_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/0, ::0/0
#PersistentKeepalive = 25
NOTES:
You can see all the policy routing rules that are currently in effect using this command: ip rule list or ip rule
View the routing tables with, for e.g., ip route show table wireguard2x or ip route list table wireguard2x.
To flush the route cache: ip route flush cache
Further reading: Linux Advanced Routing & Traffic Control (LARTC) HOWTO
You can monitor Client's network traffic flow—if on Linux, using sudo iptraf-ng; on macOS using sudo iftop. (To be run on the client.)
I found running that hard to parse due to too many live changes. So I was suggested trying route get <IP_ADDRESS> (which shows the interface being used, e.g., interface: utun2) and then running ifconfig <interface> (e.g., ifconfig utun2) on macOS. The latter should show the Client's private (WireGuard peer) IP address, e.g., <IP_ADDRESS>, confirming that the traffic is being routed through WG interface. It's not much, but it's a start.
UDPATE: traceroute is brilliant for this! For e.g., traceroute <IP_ADDRESS>. (Hat tip to Chrispus Kamau.)
curl ipinfo.io to check your IP address with the VPN enabled. (To be run on the client.)
RELATED:
https://superuser.com/a/1651179
except that AllowedIPs = <IP_ADDRESS>/32 on one peer will clash with AllowedIPs = <IP_ADDRESS>/0 on the other peer. Contrary to routes, there must be no overlap. Compute <IP_ADDRESS>/0 minus <IP_ADDRESS>/32 (eg with the help the netmask command) or use two different WG interfaces. The reason for this is explained there: https://www.wireguard.com/#cryptokey-routing . You can't have <IP_ADDRESS>/32 matching two different peers (because it also matches <IP_ADDRESS>/0)
its_me's answer is working great for me. Below are some changes I made to automate the creation/removal of the route table, iptables and ip rules. The automation happens as the wireguard interface is brought up and down. Please note I am not using ipv6 or ufw in this configuration:
Server1:
# Add a route table for this interface
PreUp = echo 1 wireguard2x >> /etc/iproute2/rt_tables
# Add ip rule to point this interface at the new route table
PreUp = ip rule add iif %i table wireguard2x
# Setup iptables
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -A FORWARD -o %i -j ACCEPT
# Remove the iptables
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -D FORWARD -o %i -j ACCEPT
# Find and remove the ip rule
PostDown = ip rule | grep "from all iif %i" | cut -d: -f1 | xargs -L1 ip rule del prio
# Remove the ip table
PostDown = sed -i '/wireguard2x/d' /etc/iproute2/rt_tables
Server2:
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -A FORWARD -o %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -D FORWARD -o %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
Yep, I am aware of PostUp and PostDown in WG config. I just like all my firewall rules (including system & other app rules) to be in one place and therefore prefer adding them manually.
@computerguy1
I tried your configuration and it can connect to Server-II but eventually lost SSH access to Server-I. Moreover, I can't connect to Server-I using any WireGuard client.
(Based on Chrispus Kamau's excellent Wireguard VPN tutorials for Typical Setup and Chained Setup, it appears I may have a solution (untested!) in a format that shows how somewhat unusual/complex setups could be handled—or at least give you an idea. Many thanks CK!)
Via: https://github.com/iamckn/chained-wireguard-ansible
How it works:
Client (vpn0) → <IP_ADDRESS>/24 → (wg0) → Middleman (gate0) → <IP_ADDRESS>/24 → (wg0) Gate (wg0) → Public Internet
Assumes that Unbound is set up on both the Middleman and Gate for local DNS resolution.
Gate Configuration
Configure the gate's VPN interface (wg0).
File: /etc/wireguard/wg0.conf
# SERVER
[Interface] # Gate
PrivateKey = GATE_PRIVATE_KEY
Address = <IP_ADDRESS>/24
ListenPort = 53701
SaveConfig = false
# CLIENTS
[Peer] # Middleman
PublicKey = MIDDLEMAN_PUBLIC_KEY
PresharedKey = MIDDLEMAN_PRESHARED_KEY
AllowedIPs = <IP_ADDRESS>/8
Firewall config. commands:
# Track VPN connection
## Track input chain
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
## Track forward chain
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# Allow incoming WireGuard connections/VPN traffic on the listening port
iptables -A INPUT -p udp -m udp --dport 53701 -m conntrack --ctstate NEW -j ACCEPT
# Allow both TCP and UDP recursive DNS traffic
iptables -A INPUT -s <IP_ADDRESS>/24 -p tcp -m tcp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -s <IP_ADDRESS>/24 -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
# Allow forwarding of packets that stay in the VPN tunnel
iptables -A FORWARD -i wg0 -o wg0 -m conntrack --ctstate NEW -j ACCEPT
# Set up NAT
iptables -t nat -A POSTROUTING -s <IP_ADDRESS>/24 -o enp7s0 -j MASQUERADE
Bring up the gate's VPN interface, and enable the WireGuard service to automatically restart on boot:
wg-quick up wg0
systemctl enable wg-quick@wg0
Middleman Configuration
Configure the middleman's gate-facing interface (gate0). Here middleman acts as the client.
File: /etc/wireguard/gate0.conf
[Interface] # Middleman
PrivateKey = MIDDLEMAN_PRIVATE_KEY
Address = <IP_ADDRESS>/32
DNS = <IP_ADDRESS>
SaveConfig = false
# PEERS
[Peer] # Gate
PublicKey = GATE_PUBLIC_KEY
PresharedKey = MIDDLEMAN_PRESHARED_KEY
Endpoint = GATE_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/0
#PersistentKeepalive = 21
Configure the middleman's client-facing interface (wg0). Here middleman acts as the server.
File: /etc/wireguard/wg0.conf
# SERVER
[Interface] # Middleman
PrivateKey = MIDDLEMAN_PRIVATE_KEY
Address = <IP_ADDRESS>/24
ListenPort = 53701
SaveConfig = false
# CLIENTS
[Peer] # PC
PublicKey = CLIENT_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
AllowedIPs = <IP_ADDRESS>/32
Firewall config. commands:
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 53701 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -s <IP_ADDRESS>/24 -p tcp -m tcp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -s <IP_ADDRESS>/24 -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -i wg0 -o wg0 -m conntrack --ctstate NEW -j ACCEPT
iptables -t nat -A POSTROUTING -s <IP_ADDRESS>/24 -o enp41s0 -j MASQUERADE
# Set up VPN chain NAT
iptables -t nat -A POSTROUTING -s <IP_ADDRESS>/24 -j SNAT --to-source <IP_ADDRESS>
Configure policy routing on the middleman to route traffic from the client to the gate.
echo "1 middleman" >> /etc/iproute2/rt_tables
# Forward all traffic to the gate
ip route add <IP_ADDRESS>/0 dev gate0 table middleman
# OR only forward traffic to <IP_ADDRESS> (for e.g.), to the gate
#ip route add <IP_ADDRESS>/32 dev gate0 table middleman
ip rule add from <IP_ADDRESS>/24 lookup middleman
Bring up the middleman's WireGuard interfaces, and enable the WireGuard service to automatically restart on boot:
wg-quick up gate0
systemctl enable wg-quick@gate0
wg-quick up wg0
systemctl enable wg-quick@wg0
Client Configuration
File: /etc/wireguard/vpn0.conf
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = <IP_ADDRESS>/32
DNS = <IP_ADDRESS>
# PEERS
[Peer] # Middleman
PublicKey = MIDDLEMAN_PUBLIC_KEY
PresharedKey = CLIENT_PRESHARED_KEY
Endpoint = MIDDLEMAN_PUBLIC_IP:53701
AllowedIPs = <IP_ADDRESS>/0
#PersistentKeepalive = 21
Finally activate WireGuard on the client.
| common-pile/stackexchange_filtered |
Dynamically find localstorage key using jQuery
I am trying to work out a way to DRY up the following code, which looks to see if certain local storage keys are present, then does something if they are. It could have many keys, but they will all be numbered to marry to the relevant element id, i.e, key: item1 > #item1 etc.
if (localStorage.getItem('item1')) {
$('#item1').addClass('active');
}
if (localStorage.getItem('item2')) {
$('#item2').addClass('active');
}
etc.
I recently learned to do something similar with element id's, so I was wondering if / how I could apply this type of logic to finding local storage key's instead of element id's?
$('*[id^=btn-item]').click(function () {
var id = $(this).attr('id').slice(-1);
$('#item'+id).addClass('active');
}
do you need to do this for every key in localStorage or only for some specific key that's known in advance (perhaps because you clicked on an element with a corresponding name) ?
There will be certain keys present, but not known specifically. I need to be able to say... if there are any keys available, apply their numeric value to a element with the same numeric value at the end of their id. This need to be able to work on a couple of different pages. Hope that makes sense?
To (correctly) iterate over the possible keys in localStorage without knowing in advance what the maximum possible key number is:
var re = /^item\d+$/;
for (var i = 0, n = localStorage.length; i < n; ++i) {
var key = localStorage.key(i);
if (re.test(key)) {
$('#' + key).addClass('active');
}
}
Alternatively, reverse the logic and look in the DOM first:
$('[id^="item"]').addClass(function() {
return localStorage.getItem(this.id) ? "active" : "";
});
With a reasonably full localStorage do you seriously think this would be more efficient than testing 100 keys ?
We don't know how full the OP's localStorage is. The real point is that you should never use a hard-coded limit. In any event, the second code I just added is probably better than both.
@dystroy look again - it's nothing like it. My second code iterates over each potentially matching DOM node using a CSS selector and then tests whether the matching element exists in localStorage.
I've read my answer again and you're right. I thought I had proposed it but I forgot to put it between the one with the click handler and the loop. This is the way to go. Slower for sure but cleaner.
@dystroy actually I doubt it's slower - on a modern browser the CSS selector will be handled directly and efficiently in the browser and it's then a simple case of checking whether the ID exists in localStorage.
Note that the slice code only works if your id is smaller than 10.
For greater id I would suggest $(this).attr('id').slice("btn-item".length); which gets 324 from "btm-item324".
This being said, why not just doing this ?
$('*[id^=btn-item]').click(function () {
var id = $(this).attr('id').slice("btn-item".length);
if (localStorage.getItem('item'+id)) {
$('#item'+id).addClass('active');
}
}
If you don't want to do this on a button action, you can iterate on the possible keys like this :
for (var i=0; i<100; i++) {
if (localStorage['item'+i]) $('#item'+i).addClass('active');
}
@Alnitak I doesn't iterate over all the keys, it just test the ones of the specified format. Do you have a more efficient solution to check those keys ? There is no query language for localStorage.
Cheers, but I need to be able to apply this to different pages. The click function I provided there was just to illustrate how I thought I could tackle this.
btw. Thanks for the heads-up of the slice thing which hadn't occurred to me. I guess I would have noticed eventually, so your tip will be handy!
@dystroy Perfect, that does exactly what I need. Loops have never been my strongpoint, but I can kind of understand that. Many thanks :)
@Jamie note that if you ever have more than 100 keys, this will fail. Similarly it inefficiently tries to test for 100 keys, even if there's only 5 in the list...
@Alnitak thanks. Presumably I could change the i<100 value if I know the amount of items.
@Jamie you could, but it's still not a great design
| common-pile/stackexchange_filtered |
Are there free cloud computing platforms for biology projects?
I want to implement the analysis found in the paper RNA-Seq of Tumor-Educated Platelets Enables Blood-Based Pan-Cancer, Multiclass, and Molecular Pathway Cancer Diagnostics The project id is 281708. It has 285 samples comprising about 300 Gb of read data. The reads are available on sra.
I want to apply a machine-learning pipeline to find important features in these data but I do not have access to computing resources to finish the project.
Question
Are there free cloud computing platforms that I can use to perform this research?
@Chris_Rands yes it is duplicate.
If you're getting started with a project and need some free computational resources you should look at https://galaxyproject.org/. There are some free servers that you may be able to use. However, Galaxy is designed to have pre-fabricated pipelines and a GUI to avoid having to deal with command-line tools. Therefore any sort of custom analysis will have to go through the galaxy API.
Otherwise, most of the free computational resources that were available several years ago like iPlantCollaborative are no longer available. Running servers costs money, after all, and the funding for such projects often runs out after a few years.
You may consider asking researchers at your local universities to collaborate and provide you with access to their servers.
| common-pile/stackexchange_filtered |
If a president is removed from office after being impeached, when does the vice president take office?
In the United States, if during an impeachment trial the Senate votes to convict the president, when does the vice president take office as the new president? Is is immediately after a vote is taken, or is there a waiting period?
Also, if there is a waiting period, is the impeached president still in office during that time or is there no president in between when the first president is convicted and when the new one takes office?
There is never not a President of the United States.
Immediately upon removal.
The Presidential succession clause in Article II of the Constitution was superseded by the 25th Amendment (emphasis mine):
Section 1.
In case of the removal of the President from office or of his death or resignation, the Vice President shall become President.
There is no gap between Presidents.
Compare this to what happens when a new President takes office through normal succession, as defined by the 20th Amendment:
Section 1.
The terms of the President and Vice President shall end at noon on the 20th day of January, and the terms of Senators and Representatives at noon on the 3d day of January, of the years in which such terms would have ended if this article had not been ratified; and the terms of their successors shall then begin.
We've had some discussion in the comments about the significance of the Presidential Oath of Office, as defined by Article II:
Before he enter on the Execution of his Office, he shall take the following Oath or Affirmation:-"I do solemnly swear (or affirm) that I will faithfully execute the Office of President of the United States, and will to the best of my Ability, preserve, protect and defend the Constitution of the United States."
Does the new President's power not "take effect" until this oath is administered? Or is it just a formality? Has this issue ever been adjudicated?
I'd contend that's not entirely clear. Take George Washington, for example:
What is the time relationship between a President’s assumption of office and his taking the oath? Apparently, the former comes first, this answer appearing to be the assumption of the language of the clause. The Second Congress assumed that President Washington took office on March 4, 1789 although he did not take the oath until the following April 30.
Modern Presidents do seem to view the oath as a key part of the process, Obama even took it a second time when some words were spoken out of order, although White House counsel said this was done only "out of an abundance of caution".
The VP becomes president as soon as the president is removed, but the VP can't actually do anything as president before taking the oath, so the oath is more than a formality. See article 2, section 1: "Before he enter on the Execution of his Office, he shall take the following Oath or Affirmation:...."
@phoog So, if the inauguration is delayed, then what, the newly elected President is only "acting President" between noon and 12:10pm? That they couldn't actually carry out any presidential duties, if necessary?
No, the newly elected president is a president who cannot yet act. The precise implications of the "before he enter" clause would be a matter for a court if there were any cause for the president to act before taking the oath. People try to avoid such questions, which is why Obama was sworn in twice in 2008, mistakes having been made during the inauguration ceremony. Nobody wanted to leave open possible challenges to its legitimacy.
@phoog Found a 1789 reference that suggests otherwise, see my edit. Although yes, modern Presidents do seem to behave as if the oath as required. I think "out of an abundance of caution" is key here.
The added material supports my position, which may have been unclear: the president assumes office at noon on January 20th (under normal circumstances) or immediately upon the removal of the previous president (in cases of impeachment and so on). The person holds the office of president from that point, but may not undertake any official acts before taking the oath. I assume that Washington did not actually purport to execute any official acts as president between March 4th and April 30th.
"Obama even took it a second time when some words were spoken out of order" And yet simply adding words to it is not considered an issue.
@Acccumulation To what do you refer?
@AzorAhai "so help me god."
@Chipster Didn't he? Perhaps he became President when Nixon's resignation took effect, but only felt comfortable behaving as President after taking the oath, due to non-binding tradition. That's the narrow distinction we're trying to thread. Anyway, in Ford's case, I'm not sure there was a meaningful gap in time; Nixon announced he was resigning "effective noon tomorrow", and Ford was sworn in at noon that next day.
If a president is removed from office after being impeached, when does the vice president take office?
Upon removal from office, under Article II, Section 1 paragraph 6, the duties of the president devolve upon the vice president.
In Case of the Removal of the President from Office, or of his Death, Resignation, or Inability to discharge the Powers and Duties of the said Office, the Same shall devolve on the Vice President, and the Congress may by Law provide for the Case of Removal, Death, Resignation or Inability, both of the President and Vice President, declaring what Officer shall then act as President, and such Officer shall act accordingly, until the Disability be removed, or a President shall be elected.
Later, the vice president, under Article II, Section 1, paragraph 8, takes the oath or affirmation and becomes president.
Before he enter on the Execution of his Office, he shall take the following Oath or Affirmation:-"I do solemnly swear (or affirm) that I will faithfully execute the Office of President of the United States, and will to the best of my Ability, preserve, protect and defend the Constitution of the United States."
Compare to the death of President Kennedy and Vice President Johnson becoming president. There was a time delay to bring a Federal judge to Air Force One for the oath or affirmation.
Or, the more recent resignation of Nixon making Ford president. Nixon resigned effective 11:35 a.m. Ford became president during a ceremony held at noon. For approximately 25 minutes, Ford was acting president. (The 25th Amendment was in effect.)
Richard M. Nixon’s Resignation Letter, 08/09/1974.
Following the revelations stemming from the investigation of the Watergate break-in, President Richard M. Nixon resigned the Presidency in this letter dated August 9, 1974. The President's resignation letter is addressed to the Secretary of State, in keeping with a law passed by Congress in 1792. The letter became effective when Secretary of State Henry Kissinger initialed it at 11:35 a.m.
Presidential Vacancy and Disability Twenty-Fifth Amendment.
President Richard M. Nixon resigned his office August 9, 1974, and Vice President Ford immediately succeeded to the office and took the presidential oath of office at noon of the same day.
Swearing in Ceremony of Gerald R. Ford as 38th President of the United States, August 9. 1974 (youtube video).
At 0:53, Chief Justice Burger referred to Ford as Mr. Vice President.
An oath was taken.
At 1:33, Chief Justice Burger referred to Ford as Mr. President.
In the United States, if during an impeachment trial the Senate votes to convict the president, when does the vice president take office as the new president? Is is immediately after a vote is taken, or is there a waiting period?
Only a time delay for the ceremony.
Also, if there is a waiting period, is the impeached president still in office during that time or is there no president in between when the first president is convicted and when the new one takes office?
Removal from office is immediate. There is always a president or one having the duties of the president.
By ceremony, I assume you don't mean the time it takes to organise a big thing on the Mall, but rather the time it takes for the Chief Justice to drive down Pennsylvania Avenue.
@JoeC - Not at all. Upon conviction of the president, the Senate could take a recess, usher the vice president into the Senate, and the Chief Justice could administer the oath or affirmation, at that time. Or, the vice president could prefer to wait a few hours.
I don't see any reason to conclude, from Article II (or the 25th Amendment), that the swearing in is in any way the mechanism that elevates the VP to President. It's a formality, nothing more.
@BradC The oath is more than a formality (see my comment on your answer), but you are right that it does not cause the vice president to become president.
@JoeC Yes, Rick Smith was talking about the swearing in, not inauguration festivities.
If I understand correctly: TL;DR - the Vice President becomes Acting President immediately, and is later sworn in as President (as long as nothing gets in the way).
| common-pile/stackexchange_filtered |
Unable to create an RDD from an existing RDD - Apache Spark
I'm trying to create a new RDD from an existing RDD.
Intilaize an Array
scala> var a1 = Array(1,2,3,4,5,6,7,8,9,10)
a1: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Create the first RDD
scala> var r1 = sc.parallelize(a1)
r1: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at <
console>:26
Create the 2nd RDD - It fails with the following error.
scala> var newrdd = sc.parallelize(r1.map(data=>(data*2)))
<console>:26: error: type mismatch;
found : org.apache.spark.rdd.RDD[Int]
required: Seq[?]
Error occurred in an application involving default arguments.
var newrdd = sc.parallelize(r1.map(data=>(data*2)))
^
But still the first array can be used to create another RDD. But it is not creating an RDD from an existing RDD.
scala> var newrdd = sc.parallelize(a1.map(data=>(data*2)))
newrdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[3] at parallelize
at <console>:26
Do you have any idea, What is the problem with this approach?
Or how I can create an RDD from an existing RDD?
Thanks for reading.
But why do you have to parallelize again, r1 is already a RDD you can just apply transformation and it returns RDD, Just use var newrdd = r1.map(data=>(data*2))
Thanks. I am a beginner and currently following a tutorial. From there I found this example. However, It seems like your argument is valid may be this is a mistake of the tutor.
Update: Tutor told me this is a mistake of him.
The signature of parallelize method is:
def parallelize[T](seq: Seq[T], numSlices: Int = defaultParallelism)(implicit arg0: ClassTag[T]): RDD[T]
,so you cannot pass a RDD as a parameter directly.
If you want to create an RDD from an existing RDD, you can use the methods defined for RDD. For example,
val newrdd = r1.map(data => data * 2)
Or simply, r1.map(_ * 2).
| common-pile/stackexchange_filtered |
How to create click-able link in MobaXterm
I would like to create an url link that can be CTRL-Click-ed in MobaXterm and opens the link in the default local the browser.
A simple web address (like http://example.com) is recognized by MobaXterm and you can click on it. However i need to add a port, which is not recognitzed. http://example.com:8888 only recognized till the colon.
However I saw on the MobaXterms initial screen other clickable links.
For more info, ctrl+click on help or visit our website
I tried to add clickable links like described below but it does not work with MobaXterm
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
| common-pile/stackexchange_filtered |
How to sort date strings (format example: 2014 7 23) in JavaScript?
In JavaScript I'm trying to sort an array of objects, each having a date, by date, but I ran into an obstacle. Also the date's are input from 3 dropdown boxes on a site, so I just want 3 numbers. This means I cannot use JavaScript's Date() object, since it also adds a time, timezone and writes month names in letters etc.
Example:
I added 5 objects into an array. I have tried using the JavaScript sort function, this one to be specific:
array.sort(function(a, b) {
if(a.date == b.date){
return 0;
}
else if (a.date < b.date){
return 1;
}
else {
return -1;
}
})
However, this only sorts by year.
So If I add:
2014 7 12
2017 8 16
2017 4 14
2017 1 31
2017 2 26
I get:
2014 7 12
2017 2 26
2017 8 16
2017 1 31
2017 4 14
This is the constructor I use to make different Label objects.
function Label(name, date, type) {
this.name = name;
this.date = date;
this.type = type;
}
var a = new Label("name1", "2016 5 16", 5);
var b = new Label("name2", "2016 7 20", 3);
var c = new Label("name3", "2016 3 15", 2);
My date attributes are just 3 numbers in a string. So I tried rewriting the sort function to this:
array.sort(function(a,b){
a = a.date.split(" ");
b = b.date.split(" ");
if(a[0] === b[0] && a[1] === b[1] && a[2] === a[2]){
return 0;
}
else if ((a[0] > b[0]) || (a[0] === b[0] && a[1] > b[1]) || (a[0] === b[0] && a[1] === b[1] && a[2] > b[2])){
return -1;
}
else {
return 1;
}
});
I.e. I tried to use the .split function to seperate the 3 numbers, which are then stored in an array. Date a is then assigned the array with 3 numbers, as is date b. Then I check if the values in both arrays are equal, if so, return 0 (do nothing).
If the year in array a is bigger than year in array b, move it down 1 space in the output array.
If the year is equal, then check the month. If the month is bigger in a than in b, move a down 1 space in the output array.
Etc.
However this doesn't happen. It basically gives me the same output, only sorting by year but ignoring month and day.
I have checked several similar StackOverflow questions, but most of them use the Date() object.
I specifically need the format "number number number".
Why doesn't my function work and how might I make it work?
EDIT: made my post a bit clearer with examples of dates and my constructor.
Looks like the date format is always the same as you're already splitting etc. and what you should do is use date objects and compare them instead
array.sort(function(a,b){
var arr1 = a.date.split(" ");
var arr2 = b.date.split(" ");
var time1 = new Date(arr1[0], arr1[1]-1, arr1[2]); // year, month, day
var time2 = new Date(arr2[0], arr2[1]-1, arr2[2]);
return time1 - time2;
});
Aren't you supposed to use the getTime method of the Date object to correctly get the millisecond-timestamp value?
Also this seems pretty inefficient for sorting code
You can compare date objects directly, and it might not be very efficient, but the strings must be converted to date objects to properly compare them.
@adeneo Hmm I see but why do you put a -1 here : arr1[1]-1, arr2[1]-1 and not at year and day?
Because in javascript months are zero based.
(Meaning they go from 0-11 not 1-12) That's so they can be easily cross-referenced with an array of month names to be more language independent.
Aha I see, okay that helps a lot thanks :) So you "transform" the date attributes of my Label objects to Date() objects, just to facilitate the sorting process, but the actual content of the "date" attributes of the Label objects remains untouched, that about right?
Anyway thanks guys. Johnathan your answer I see is correct aswell and possibly more efficient? But adeneo's code is easier to understand for newbies like me :)
First off, lets just sort a few things out.
Javascript Date objects are stored as the number of milliseconds since datum, when you output them to a string they may well have milliseconds, timezone information etc but thats got nothing to do with their internals.
Your sort function is an overly complex way of just doing a.date - b.date
Therefore what you want to do is have the properties as actual Date objects, and use the sort function
var sortedArray = array.sort(function(a, b) {
a.date - b.date;
});
DO use javascript's date object and do the following for sorting:
array.sort(function(a, b) {
return a.date.getTime()-b.date.getTime();
});
| common-pile/stackexchange_filtered |
Name 'Customer' is not defined CBV ListView
urls.py
from django.conf.urls import url
from system import views
app_name = 'project'
urlpatterns = [
...
url(r'^cust/([\w-]+)/$',views.PublisherBookList.as_view()),
...
]
views.py
from . import models
class PublisherBookList(ListView):
def get_queryset(self):
self.name = get_object_or_404(Customer, name=self.args[0])
return Customer.objects.filter(name=self.name)
models.py
class Customer(models.Model):
name = models.CharField(max_length=255)
I do visit http://<IP_ADDRESS>:8000/project/custo/customername/
got error name 'Customer' is not defined
whats i missed here?...
Did you import customer model?
yes already did, from . import models
You need to import Customer in your views.py
from .models import Customer
already did, i have lot of model. just error on views with def get_queryset(self): part.
You imported the module, but not the class. You can either change the import to from .models import Customer or use models.Customer everywhere instead of just Customer
ah gotcha. forgot do models. its work now, but nothing result. i check my db name John, put John on url and its show nothing.
By default Django detail view uses pk url kwarg, which is Django database ID of the object. If you want to use custom slug attr you need to add few things. Here's relevant question: https://stackoverflow.com/questions/46815655/django-using-slug-field-for-detail-url
Here it is explained how to alter default slug field https://stackoverflow.com/questions/5780803/how-to-specify-something-other-than-pk-or-slug-for-detailview/
| common-pile/stackexchange_filtered |
How to get some text values in python below text format
I have sentences like
// string1 = value1
// string2 = value2.....
so on, how can I get only "values" using python
Actually I am thinking that need to take values in a list. is it right.
print [line.split('=',1)[-1].strip() for line in s.splitlines()]
>>> strs="""
// string1 = value1
// string2 = value2
"""
>>> [x.split('=')[1].strip() for x in strs.split('\n') if x.strip()]
['value1', 'value2']
| common-pile/stackexchange_filtered |
PL/PgSQL calling a function inside a loop giving error
The code bellow is giving error on w_add_ax_extra(1, 'k', 'v') previously it was w_add_ax_extra(some_id, kv.k, kv.v) I changed it to k, v to reproduce the same error
declare
kv record;
begin
-- Lines skipped
for kv in select * from (select (each(extras)).*) as f(k,v) loop
raise notice 'key=%,value=%',kv.k,kv.v;
w_add_ax_extra(1, 'k', 'v');
end loop;
-- Lines Skipped
end
I am getting Syntax Error but could not understand what I am missing
ERROR: syntax error at or near "w_add_ax_extra"
LINE 1: w_add_ax_extra(1, 'k', 'v')
However If I do dummy = w_add_ax_extra(1, 'k', 'v') it works. Yes this function returns an integer. But I don't need to store it here. Is it mandatory to hold the return value ?
From the fine manual:
39.5.2. Executing a Command With No Result
[...]
Sometimes it is useful to evaluate an expression or SELECT query but discard the result, for example when calling a function that has side-effects but no useful result value. To do this in PL/pgSQL, use the PERFORM statement:
PERFORM query;
Emphasis mine. You're not calling the function by saying something like f();, you need to perform f(); or select f() into ...;:
for kv in select * from (select (each(extras)).*) as f(k,v) loop
raise notice 'key=%,value=%',kv.k,kv.v;
perform w_add_ax_extra(1, 'k', 'v');
end loop;
Thanks. It Fixed. But things are not clear :( I copy pasted that f(k,v) however only f works too. so I removed the (k,v) part. Oh! sorry it doesn't work without (k,v)
| common-pile/stackexchange_filtered |
Get type of obj.constructor in TypeScript
I am trying to get the keys of an object's constructor's prototype.
type PrototypeKeys<T> = T extends { constructor: { prototype: infer P } }
? keyof P
: never;
class Foo {
foo() { return 1; }
}
const foo = new Foo();
type FooPrototypeKeys = PrototypeKeys<typeof foo>; // expect 'foo'
const bar = {
foo() { return 1; }
};
type BarPrototypeKeys = PrototypeKeys<typeof bar>; // expect never
To my surprise, in both cases the resultant type is string | number | symbol.
I dug a little deeper and found that typeof foo['constructor'] is Function not Foo. Is there a way to retrieve the strongly typed constructor of an object?
I tried
type ConstructorOf<T> = T extends { constructor: infer C } ? C : never;
but this always returns Function as well (except for null and undefined).
TS Playground
No, you can't (at least not without manually annotating each class as having a constructor property of a particular type), see https://github.com/Microsoft/TypeScript/issues/3841. But even if you could this wouldn't work to give you prototype properties, since TypeScript represents the class constructor's prototype property as being of the instance type itself, so type PrototypeKeys<T> is going to be keyof T for any specific class which you could test yourself. So, this is going to be a no-go unfortunately.
Sad times. Alright. Want to throw that into an answer?
I think I've rambled about this before so I won't go over that again here. (The part about prototype is not really in scope of the question as asked, since you are specifically asking about getting a strongly typed constructor from an instance type.)
Kind of. I see it as a different question than the one I asked that this was marked as a duplicate of. In my previous question (which I'd forgotten I'd asked a year ago), I was specifically looking for the constructor arguments, but I can see how they technically have the same answer.
This could be reopened but they definitely have the same answer (which SO sometimes gets upset at me for, when I make a new answer that's too close to an existing answer elsewhere).
| common-pile/stackexchange_filtered |
Summation of only numbers in spreadtab package
I recently discovered the spreadtab package since I needed some spreadsheets with some calculations.
I would like to produce a LaTeX file with the grades of my students, i. e. something like this (eight problems 10 points each and the total sum). However, I also would like to put dash - instead of zero if the student didn't write anything for this problem. But then the usual sum is not working. Is it possible to adjust this?
Here is a standard code (without dashes). Ideally, modified sum should simply avoid cells with -, so some sort of conditional summation should work.
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{spreadtab}
\begin{document}
\begin{spreadtab}{{tabular}{|c|c|c|c|c|c|c|c|c|}}
\hline
@ 1 & @ 2 & @ 3 & @ 4 & @ 5 & @ 6 & @ 7 & @ 8 & @ $\sum$ \\
\hline
10 & 10 & 10 & 10 & 10 & 10 & 10 & 10 & sum(a2:h2) \\
\hline
\end{spreadtab}
\end{document}
Insert a @ before the dash.
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{spreadtab}
\begin{document}
\begin{spreadtab}{{tabular}{|c|c|c|c|c|c|c|c|c|}}
\hline
@ 1 & @ 2 & @ 3 & @ 4 & @ 5 & @ 6 & @ 7 & @ 8 & @ $\sum$ \\
\hline
10 & 10 & 10 & @ - & 10 & 10 & 10 & 10 & sum(a2:h2) \\
\hline
\end{spreadtab}
\end{document}
Thanks, Simon, that works!
| common-pile/stackexchange_filtered |
How to multiply 2 images in JavaCV
I currently have a binary black and white image that I have used cvThreshold on, and I would like to get the color back on the white part of the image.
From my understanding multiplying the original image with the binary image will result in this effect. I am however unsure how to do that. I am using JavaCV. Ive attempted to:
IplImage img.mul(im2);
And that hasn't really worked. How do I use the mul openCV function with JavaCV? Also if anyone has tips on generally converting opencv code to JavaCV I would be very grateful, the little there is on the JavaCV project page is barely enough to keep me afloat.
The JavaCV API is pretty similar to the C API and there are loads of examples out there.
This might help.
I have my own (maybe quite strange :)..) way to find functions working in JavaCV, but in many cases it works. There's OpenCV's wrapper for C# named emguCV , which have very similar functions to this in JavaCV. So if I want e.g find multiplying or adding function I write in google: cvMul emgu or something similar,and here is result of my searching:
Wiki emgu link 1
Wiki emgu link 2
So If you want to multiply 2 IplImages you could do something like that:
IplImage Red=IplImage.create(zdj1.cvSize(),8,1);
IplImage Green=IplImage.create(zdj1.cvSize(),8,1);
IplImage Result=IplImage.create(zdj1.cvSize(),8,1);
cvMul(Red,Green,Result,1);
| common-pile/stackexchange_filtered |
Is the bar resolution of complexes dg-functorial?
Let $k$ be a commutative ring, and let $V$ be a complex of $k$-modules (more in general, we can take an $\mathcal A$-dg-module, where $\mathcal A$ is a dg-category. We can construct the bar resolution $B(V)$ of $V$, which comes with a quasi-isomorphism $B(V) \to V$ (here is a related post). My question is the following:
Does $B(-)$ define a dg-functor from the dg-category of complexes to itself? Do the maps $B(V) \to V$ define a natural transformation of dg-functors?
I think that $B$ should at least be a (ordinary) functor from the (model) category of complexes to itself. It would be very nice if it were actually dg-functorial. Or, perhaps, is it $A_\infty$-functorial?
It's a fibrant replacement, so it's functorial.
It should be a cofibrant replacement, but this does not answer the question. I don't ask for functoriality, but for dg-functoriality, namely enriched functoriality.
Yes, sorry, I have misread the title. Anyway, I'm almost sure it's $A_{\infty}$ functorial because I have seen this implicitly used a lot of times in integration of representations.
| common-pile/stackexchange_filtered |
App Crashes when clicking in different TextViews very fast
I am new to android and have a Fragment with a container view (a framelayout). There are two TextViews on top of it, like tabs. Each TextView ie txt1,txt2 adds 2 fragments ie frgmnt1,frgmnt2 respectively. When the TextView is clicked, the corresponding Fragment is added. If clicked again, the Fragment is removed.
That part is working fine. However, but when I click in the TextView very rapidly, my app crashes and shows a "No Host" exception. Can anyone help me understand why this happens?
(Side note, the tab layout implementation is not required here).
Here is the stack trace:
07-04 18:22:25.600 10971-10971/integral.com.sellfie E/AndroidRuntime: FATAL EXCEPTION: main
Process: integral.com.sellfie, PID: 10971
java.lang.IllegalStateException: No host
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2046)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1989)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1092)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at integral.com.sellfie.Fragments.MemberFragment.addFragment(MemberFragment.java:319)
at integral.com.sellfie.Fragments.MemberFragment.showFragment(MemberFragment.java:270)
at integral.com.sellfie.Fragments.MemberFragment$3.onClick(MemberFragment.java:242)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
put your code here
Its probably because you are trying to remove the fragment even before it was added. Try disabling the view for a very short interval of time (say 300ms) after a click event has been identified.
Thanks Arpit Ratan, Vishal Patoliya for the response and sairam for proper editing . ie, i need to disable all button for 300ms.ok.i will check and will get back to you.
just testing ~code~
hi how to add the code in comment
i used this to make the delay but runonuithread showing error .the code is inside a fragment `myButton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
myButton.setEnabled(true);
}
});
}
}, 5000));`
@SanoopVasu - Not everyone reads comments. It is better edit the question and append any code as a update.
Hoping that this will help you.You just need to change your fragments using method below.
Note : Here I'm not using support Fragments so change the code accordingly.
//Change fragment in appropriate container
private void changeFragment(Fragment fragment) {
if (fragment !=
getFragmentManager().findFragmentById(R.id.frame_container)) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//now implementing the Hack
if (oldFragment != null)
transaction.detach(oldFrag);
transaction.replace(R.id.frame_container, fragment);
transaction.attach(fragment);
transaction.commit();
oldFragment = fragment;
}
}
| common-pile/stackexchange_filtered |
Is it possible to enforce two classes to implement the same field names but of differing type at compile time?
Let's say there's two parallel classes:
class A(
val stringField: String,
val intField: Int,
val floatField: Float
)
class B(
val stringField: Boolean,
val intField: Boolean,
val floatField: Boolean
)
Notice that both classes have the same field names but their types differ.
I was wondering whether it could be possible to enforce in some way at compile time so that it wouldn't compile when class A has a field name that class B doesn't have.
At runtime I could probably use some reflection to enforce this but I'm genuinely curious about whether it's possible at compile time and would also prefer not having to resort to reflection for this.
EDIT 1: I do see now that generics are probably part of the solution here, but in the real case scenario class A has a lot of fields of different types and in class B all fields are always of type Boolean. Ideally I don't have to add a generic for every different field type used in class A
EDIT 2: Further details about the use case at hand:
I need to transform a Full object into a Partial one based on some Configuration (the fields for which the configuration is false should end up being null in the Partial object). These three classes are showing a close resemblences, that's why I wanted to enforce a contract over them (so they don't get out of sync over time).
class Full(
val stringField: String,
val intField: Int,
val floatField: Float,
...
)
class Partial(
val stringField: String?,
val intField: Int?,
val floatField: Float?,
...
)
class Configuration(
val stringField: Boolean,
val intField: Boolean,
val floatField: Boolean,
...
)
See "kotlin generics".
Can you explain your case?
Pretty interested in the case here too. There might be more typical solutions for what you're trying to do.
Sure, added further clarification around the use case at hand
@vanyochek I've updated my post with the specific use case
@SebastiaanvandenBroek I've updated my post with the specific use case
It isn't a compile-time check but you can always write a test that enforces this constraint.
I, for example, wrote a test that finds all functions decorated with my DSL annotation and verifies that all of them are described in our doc(yes! testing the documentation!).
You can use reflections library which makes it more fun to work with reflection(kotlin-reflect is already good but still...).
| common-pile/stackexchange_filtered |
Why would zero-coupon perpetuity not be worthless (simple enough so grandma understands)
The context is the negative yielding treasuries in Europe (Germany). Here is a quote I found on the matter:
Why would a zero-coupon perpetuity not be worth exactly zero? Because
its nominal value adds to the stock of debt of the issuer and so it is
an option on recovery value - Michael Jezek, Deutsche Bank
This has a bit too much jargon for me to understand clearly, even after multi-tabbing investopedia.
Question
Can someone explain this concept to me in a very simple way, as if I were your grandma?
Is the problem that you don't understand that specific statement or is your grandma interested in zero coupon bonds? If it is that specific statement, it would probably be easier if you had linked to the original manuscript - the statement asks a question that is nonsensical - why indeed should a zero coupon perpetuity be worth exactly zero? That makes no sense at all in any case.
Are there any provisions requiring the bonds to be repaid in the event of a leveraged buyout (or other circumstances)? What is the seniority of these bonds?
Fundamentally it is worth nothing - you are buying a bond that never pays any interest and never has to be repaid.
It's not an investment. It's a financial instrument used to transfer money from the central bank to the government (as an alternative to "printing money").
If a company issued these (none ever has to my knowledge), then there might be some recovery value in a bankruptcy, but they would still have little to no value if the company was healthy.
There might also be bond covenants that make the debt senior to hypothetical future issuances of junior securities, and force redemption at (or above) face value if certain covenants are broken. For example, the bond could be redeemed at face value in the event of a leveraged buyout or other large borrowing by the company, or if earnings drop below a certain threshold.
Modern money is based on promises rather than intrinsic value.
A $10 bill (banknote / cash) is a promise that its issuer (bank / government) will provide $10 value on presentation of that note. That value is likely to be in the form of another $10 note, but that’s beside the point.
What would you expect to pay for a $10 bill, bearing in mind that you won’t get any interest on holding cash? Probably not $0.
Zero-coupon perpetuities are something like that. They have a face value that’s nonzero, and your quote says that the note represents how much the issuer owes the note holder. That debt gives the note its worth.
But money is redeemable. A Zero Perp is not - the issuer never has to pay anything back.
@DStanley The issuer could call the note, at which time the face value would be repaid. Or if the issuer is wound up, the notes may have some "recovery value", as the quote puts it. Everything else aside, the basis for the quote appears to be that the value of the notes must appear somewhere in the company's accounts.
Why would the issuer call the note? Issuers only call notes that are worth more than the call value. Why would they pay to get rid of a debt that they never have to repay?
@DStanley Maybe some kind of Basil x law that affects their capital ratios?
@DStanley I don't think zero-coupon perps really make sense. But if they emerged from a coupon-stripping exercise, any value associated with them would likely be based on residual value as the quote has it, or perhaps something like gold or currency, where the note is treated as a (quasi-) fiat currency. Certainly, the traditional D/r valuation would assign zero value to zero-coupon perps. (D = coupon per year, r = discount rate)
They don't make sense as an investment, because they're not. They're ways to legally transfer money from the central bank to the government.
@Lawrence do you mean Basel X? Basil X sounds delicious but doesn't affect capital ratios...
@MD-Tech Oops, apologies for the spelling. I just meant any legislation like that imposed on banks in recent years.
@Lawrence I'm revising the Basel accords for a professional exam right now and that made me chuckle
@MD-Tech More like Fawlty spelling. :P
| common-pile/stackexchange_filtered |
SSH.NET How to return a boolean from command execution
I am new to the SSH.NET library and I understand the basics of it such as connecting, executing a command and returning the output.
But my question is, how can I return a true/false statement if I wanted to check if a background process is running or not?
So for example:
using (SshClient client = new SshClient(host, user, pass))
{
client.Connect();
var cmd = client.RunCommand("uname -sn");
string serverResponse = cmd.Result;
Label1.Text = serverResponse;
client.Disconnect();
}
So if I wanted to replace my command with "ps -u user | grep procName" I would like to have it tell me yes or no if said procName is running.
How would I go about this?
Just check the exit status of the command object. grep will exit with code 0 if it finds the search pattern. Example: if (cmd.ExitStatus == 0) { DoStuff(); }
That wouldn't work because it will always return true with a grep... Even if I use the ExitStatus, it's going to exit with 0 because it sees the procname in the grep command.
Then use another grep command to exclude the grep commands e.g. "ps -u user | grep procName | grep -v grep"
| common-pile/stackexchange_filtered |
master's degree vs master's course
Before, I thought that "degree", when associated with an academic title (e.g. bachelor, master), always meant the qualification given to a student after he/she has completed his/her studies. However, I have recently found out by reading the Cambridge dict corresponding entry that it can also refer to "a course of study at a college or university". Therefore, a "master's degree" can mean both the qualification given to a student after he finishes the master's course or the master's course itself. Is there any difference in meaning between "master's degree" and "master's course", when "master's degree" has the second meaning? Is the first expression more idiomatic?
Example sentence: I will start a master's course/degree next year.
Interestingly, all of the examples they are giving are about the qualification.
It does normally mean the qualification, whatever Cambridge Dictionaries say.
I would say that yes, the first expression is more idiomatic. Perhaps even more idiomatic is "I'm starting my Master's next year", provided there is sufficient context.
I can see no difference in meaning. However, I have rarely heard people say 'I'm starting my Master's course next year".
Speculation: I suspect that the reason might be that the word 'course' covers all types of course, including the most basic 'learn to use a computer'-type course at your local library. When people talk about Master's degrees, they imagine (sometimes wrongly, of course) that they involve difficulty, prestige and respect, and so some people might unconsciously avoid the word 'course'.
| common-pile/stackexchange_filtered |
Sorting a list of lists by every list and return the final index
I want to sort a list with an arbitrary number of lists inside to sort by each of said lists.
Furthermore I do not want to use any libraries (neither python-native nor 3rd party).
data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]
I know I can achieve this by doing
list(zip(*sorted(zip(*data))))
# [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)]
but I would like to have the sorting-index of that very process.
In this case:
index = [4, 2, 0, 3, 1]
I found several answers for a fixed number of inside lists, or such that only want to sort by a specific list. Neither case is what I am looking for.
range and len?
Add a temporary index list to the end before sorting. The result will show you the pre-sorted indices in the appended list:
data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]
assert all(len(sublist) == len(data[0]) for sublist in data)
data.append(range(len(data[0])))
*sorted_data, indices = list(zip(*sorted(zip(*data))))
print(sorted_data)
# [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)]
print(indices)
# (4, 2, 0, 3, 1)
Try this
data = [["a", "b", "a", "b", "a"], [9, 8, 7, 6, 5]]
def sortList(inputList):
masterList = [[value, index] for index, value in enumerate(inputList)]
masterList.sort()
values = []
indices = []
for item in masterList:
values.append(item[0]) # get the item
indices.append(item[1]) # get the index
return values, indices
sortedData = []
sortedIndices = []
for subList in data:
sortedList, indices = sortList(subList)
sortedData.append(sortedList)
sortedIndices.append(indices)
print(sortedData)
print(sortedIndices)
| common-pile/stackexchange_filtered |
Show/hide span on hover
I'm trying to show a span when an li with the class of .image is hovered, then preferably hide it once the mouse is removed from the li. I'm using the code below but to no avail.
The HTML
<ul>
<li class="image">
<span class="post_meta">Test 40in x 9in</span>
<img src="http://web.com">
</li>
</ul>
THE CSS
span.post_meta {
background: none repeat scroll 0 0 #000000;
bottom: 7px;
color: #FFFFFF;
display: block;
padding: 0 2px;
position: absolute;
right: 86px;
}
The jQuery
$docuemnt.ready() {
$(function() {
$("li.image").hover(function() {
$(this).parent().next("span").show();
},function(){
$(this).parent().next("span").hide();
});
});
});
Are you using !important anywhere in your css for .post_meta?
No - updating to show CSS
why are you using dom ready twice?
You also spelled document incorrectly here.
Whoops. Thanks for the heads up.
just to be clear. the span starts out not displayed. then on hover it displays and then on hover out it hides again. If this is the case, shouldn't your css hide the span to start out with? So CSS should be display: none;
Use this
$(function() {
$("li.image").hover(function() {
$(this).find("span").show();
},function(){
$(this).find("span").hide();
});
});
You can also use $(this).children("span") instead of find() or parent().next().
That works perfectly, thanks. Just need to figure out how to incorporate a fadeIn and fadeOut to this code and i'm golden.
@NikkiMather i realize i'm late, but you can accomplish the fade in fade out with css transitions and toggle class on the span instead of show hide.
You can do this only with CSS
.post_meta {
display:none;
}
li.image:hover .post_meta{
display:block;
}
Edit
With Jquery try this: View the Demo http://jsfiddle.net/9RYhR/7/
$(document).ready(function () {
$('li.image').mouseenter( function() {
$(this).children('span').fadeIn();
});
$('li.image').mouseleave( function() {
$(this).children('span').fadeOut();
});
})
Thanks, i wanted to add a fade in and fade out to it too which is why i opted for this method.
You spelled document incorrectly and didn't pass a callback, but that's not really needed as $(function () { ... }) is an alias for $(document).ready(function () { ... }).
Try the following:
$(function() {
$("li.image").hover(function() {
$(this).parent().next("span").show();
},function(){
$(this).parent().next("span").hide();
});
});
Thanks, i didn't realise that function was an alias for $(document).ready. The code, however, didn't work.
<style>
#scope .post_meta{display:none;}
#scope li:hover{cursor:pointer;}
</style>
<ul id="scope">
<li class="image">
<span class="post_meta">Test 40in x 9in</span>
<img src="http://web.com">
</li>
</ul>
<script>
$(document).ready(function(){
$("#scope .image").hover(function() {
$('.post_meta').show();
},function(){
$('.post_meta').hide();
});
});
</script>
| common-pile/stackexchange_filtered |
How to debug a Windows 7 Install?
I am trying to do a fresh install of Windows-7 RTM. The machine keeps locking up at the same point of the install.. .
Finishes Copying Files
Finishes Expanding Files
Finishes Installing Features, etc.
Freezes at "Completing Installation"
Is there any way I can debug the install to figure out why its dying?
Installing to a newly formatted 1 TB WD-Caviar Black drive. 4 GB, Quadcore AMD 9850 Black edition.
It could be as simple as fault on the disc you have burnt for installation.
Re-burn the disc.
Attempt to create from the same disc on a Virtual Machine (preferably on a different machine to the one you're attempting to install on).
Or it could be a fault in your copy of the RTM disc.
Obtain a RTM disc checksum online, and perform a hash/crc check on the disc, compare the values.
Download the RTM disc again.
It could be faulty RAM on the computer, I've had this issue on an older machine trying to install windows, it doesn't always result in a blue screen error. You can debug faulty RAM and its impact on the install by just removing one of your RAM chips and attempting the install again, swap chip out and repeat if error occurs (assuming your 4GB RAM is 2 chips).
Did this machine work well with XP / Vista or whatever OS you used before, or is it new?
If it worked with existing hardware, Go to this Technet article which will tell you where all the logs are created on Windows 7 setup
If this is a new pc, the first thing I would do is to Check your ram. If that passes, unplug all and any devices you can and re try setup.
| common-pile/stackexchange_filtered |
How to get IMEI number programatically in swift iOS?
I am making an iOS enterprise app which need iPhone/iPad IMEI, serial number and UUID programatically in Swift but I am not getting any way to find it out.
Apple doesn't allow us to get IMEI number directly but please let me know if any third party frameworks/api that provide me IMEI and other device information.
I don't want to upload app in App Store so there is no issue with Apple rejection.
While not in Swift, see https://stackoverflow.com/questions/16667988/how-to-get-imei-on-iphone-5 for relevant info that should help.
From the Apple Developer forums: you shouldn't try and get an user's IMEI programatically, as is violates Apple's privacy policy.
It'll also probably get rejected from the App Store. The only allowed way to get that information for app store apps is to ask the user to type it in.
However, if you're developing an enterprise application to be deployed on MDM devices, you can use an integration with your MDM provider to offer you that information.
Please read the last sentence of the question. Your first two paragraphs don't apply here.
Sure, they might not apply exactly, but they explain the rationale for why there isn't a public API for this and are useful if anyone else stumbles into the question. The main point here is that there isn't a public API available for this.
If you read the question the OP already knows it's not public. And there are several duplicates covering trying to do this for the App Store. This question isn't a duplicate of those because the OP is specifically asking about doing this using non-public APIs for an app not going to the App Store. Your answer doesn't really apply to this question.
| common-pile/stackexchange_filtered |
I need an object to do anything
Or at least, to pretend to do anything.
>>> three = Three()
>>> three.value()
3
>>> three.sqrt()
3
>>> three.close()
3
>>> three.someRandomFunctionWithMadeUpParameters("hello, world", math.PI, True)
3
>>> three.stopSayingThreeDamnIt()
3
Is it possible to implement class Three in Python 2.6 ?
What are you trying to accomplish here?
@RussellBorogove -- I want to build a generic pipeline-error object as described here. It would return self in real life, not 3. Your wife isn't named Mimsy, is she?
In this case you might rather want to create a decorator that throws away the original return value (or stores it somewhere) and returns self instead. __getattr__ only works for things that don't exist and while using __getattribute__ would do the job, you'd still have to call a real function to perform something - using a decorator is clearly cleaner.
I need it to work only for things that don't exist. At the very end of the process, I need to ask, "Well, how'd it go?" and at that point, it has to stop saying "self, self, self" and say, "Sorry, boss, things went pear-shape about four steps back..."
class Three(object):
def __getattr__(self, name):
return lambda *args, **kw: 3
Make 3 a 4 and there you have an ultimate random number generator!
class MetaThree(type):
def __repr__(cls):
return '3'
def __getattr__(cls,key):
return Three
class Three(object):
__metaclass__=MetaThree
def __init__(self,*args,**kwargs):
pass
def __call__(self):
return Three
def __getattr__(self,key):
return Three
def __repr__(self):
return '3'
three=Three()
print(three.value())
# 3
print(three.someRandomFunc('hello'))
# 3
print(three.someRandomFunc)
# 3
print(three.someRandomFunc.foo.bar)
# 3
print(three()()())
# 3
| common-pile/stackexchange_filtered |
Entry of "bury one's head in the sand" into English
How did the phrase "bury one's head in the sand" meaning "to ignore a bad situation hoping it will disappear" (coming from the misbelief that ostriches do this to hide from predators) end up being part of English?
At what time did the idiom and perhaps stereotype enter general knowledge among English speakers? Was it a translation of an influencing language's idiom? Or originally coined by English based on the misconception, that may have been imported into common (mis)knowledge from ancient Rome (apparently).
According to the fourth definition here, it was the early 17th century.
This comes from ostriches. They do that.
Kate Bunting contributed the Free Dictionary entry, which cites The Dictionary of Cliches (Christine Ammer, 2013) which claims the concept emerges in the early 17th century in English.
However, the concept becomes an idiom later, possibly as late as the mid 19th century though plausibly in oral circulation earlier. In this answer I'll trace and give examples of the concept in the 17th century and then trace an early instance of its use as an idiom in text.
Believing that Ostriches Bury Their Head in the Sand
Certainly the ostrich is described that way by the late 17th century. In Matthew Poole's Annotations Upon the Holy Bible (written before his death in 1679 [Wikipedia], first published 1683 in Early English Books Online, 1696 in Google Books), Job 39:17 ("Because God hath deprived her [an Ostrich] of wisdom, neither hath he imparted to her understanding") is glossed by an explanation of the ostrich's foolishness:
z. Because God hath not implanted in her that natural instinct and providence and affection which he hath put into other Birds and Beasts towards their young. [...] The great folly of this Bird is noted by Arabick Writers who best know her, and that not onely for this property of forsaking her own Eggs, but also for other things, as that she eats any thing which is offered to her, as Iron, Stones, Glass, hot Coals, &c. Whereas other Birds and Beasts have so much sagacity as to reject improper and unwholsome things; that being pursued by the hunter she thinks her self safe and unseen by hiding her head in the Sand: For which and other such qualities it is a Proverb among the Arabians, More foolish than an Ostrich.
The myth derives itself comes from Roman author Pliny the Elder in his Natural History, a text well-known in early modern Europe, where he describes the stupidity of the bird that hides its head in the bush (Book X, chapter 1, translated by John Bostock, via Perseus Tufts):
They have the marvellous property of being able to digest6 every substance without distinction, but their stupidity is no less remarkable; for although the rest of their body is so large, they imagine, when they have thrust their head and neck into a bush, that the whole of the body is concealed.
By the early 17th century, several authors have adapted the ostrich story from Pliny to their own uses:
hey thinke themselues safe, like the foolish bird cal∣led the Ostrich, which putteth her head into a bush, and then thinketh that no body seeth her, though all her body be out of the bush. (William Burton, Ten Sermons, 1602).
[...]so foolish as the witlesse Ostrich, which as Iob reports in Cap 39. of his booke, leaueth his egges in the earth▪ and makes them h[...] in the dust, and forgetteth that the foe might scarter them, or that the wild beast might breake the [illegible]; and as Plinie further addeth, hee thrusteth his necke into the stumpe of a hollow tree (John Boys, Remaines of that reverend and famous postiller ..., 1631)
They perswade themselves that God and men are blinde. As the Ostrich hides his head, and then thinks all the body safe. (Francis Taylor, An exposition with practical observations upon the three first chapters of the proverbs, 1655)
Each of these quotes develops the concept we see in full in 1681, changing the location of where the ostrich hides its body until Poole hits on sand.
From Moral Dictum to Idiom
These quotes are still descriptions, not strictly an idiom. What I'm looking for is the first instance where the phrase works independently of mentioning an ostrich, that is, without someone having to explain the zoological myth.
One intermediary point is Instructions to a Statesman (1784, via ECCO; note paywall), where the concept is used directly to advise a young statesman (George Earl Temple, probably 1st Marquess of Buckingham) to not follow the ostrich's example:
When pursued by the hunters, he is said to bury his head in the sand, and having done this, to imagine that he cannot be discovered by the keenest search. Do not you, my lord, imitate the manners of the ostrich. Believe me, they are ungraceful; and, if maturely considered, will perhaps appear to be a little silly.
Then in Will Whimsical's Miscellany (1799; EEBO) the ostrich is again used as a brief moral example, used to describe how atheists approach evil:
[...] or as the ostrich, which hides its head in the sand, and because it no longer sees its pursuers, foolishly thinks it shall escape them.
These examples describe what becomes increasingly common in corpus results in the 19th century. Over time the references to the ostrich sometimes appear more abbreviated, as if this quality of the ostrich is more common-knowledge. Indeed, an article in Connecticut Courant ("Shipping News," 28 January 1843, via America's Historical Newspapers in Readex) features a quote from the London Globe where the phrase is glossed in a single word, ostrich-like:
"It is truly astonishing to us that the official organ of the federal government should, ostrich-like, thrust its head in the sand, and think to conceal its body."
The first idiomatic usage (no ostrich in sight) I can find appears in The Comic History of Rome (1852), chapter 30, where Crassus's manner against the Parthians is described as cowardly:
Crassus himself hid his head in the sand, and would see nobody; but ultimately he was induced to enter into a negotiation with the Parthian general.
By this point it is likely an idiom, recognizable without having to refer to an ostrich.
Also, William Bradshaw, The unreasonablnes of the separation made apparent (1640): "Or it may be it is with Maister Can, as some say of the Estrich, that when she hath hidden her head in a bush, she thincketh no body can see her. "
| common-pile/stackexchange_filtered |
Any book on the timeline of progress of mathematical concepts and applications?
I was wondering if there is any book that chronicles the progress of Math over the centuries and also mentions about how/when applications of various theories were discovered/invented.
I have been trying to study university level math and I keep thinking about applications. Applications like principal component analysis, cryptography needed modern computing power. So before computers, how was all this abstract algebra used?
What kind of math was required for the manufacturing industry since the industrial revolution started (manufacturing heavy and precise equipment from steam engines to transistors...)?
EDIT: I saw a lot of such "history of math" books on amazon, but I am looking for something like "this technology is dependent on that math/science theory", preferably written in somewhat "math history for kids/dummies" style.
I had asked this on math.stackexchange.com some time back, got no suggestions and now it can't be migrated here. So, posting this as a new question. Please advise.
I believe this is too broad and in fact can be divided in different questions. I particularly like: "What kind of math was required for the manufacturing industry since the industrial revolution started?". It'd be interesting to know in which way the industrial revolution influenced math and have a complete account on how it did on physics.
Some suggestions; not a single history, but some "pictures" :
Jacqueline Stedall (editor), The Oxford Handbook of the History of Mathematics (2008) [some chapters]
Jens Hoyrup, In Measure, Number, and Weight : Studies in Mathematics and Culture (1994)
Ad Meskens, Practical mathematics in a commercial metropolis : Mathematical life in late 16th century Antwerp (2013)
Frank Swetz, Capitalism & Arithmetic : The New Math of the 15th Century (1987)
I.Bernard Cohen, The Triumph of Numbers : How Counting Shaped Modern Life (2006)
Evelyne Barbin & Raffaele Pisano (editors), The Dialectic Relation Between Physics and Mathematics in the XIXth Century (2013).
@square_one: (This question was recently bumped to the front page, which prompted me to add to your list.) The 2-volume Companion Encyclopedia of the History and Philosophy of the Mathematical Sciences edited by Grattan-Guinness (1994) has 176 separately-authored entries, many of which (by design) provide excellent overviews of a wide range of applied mathematics. (The hardback price is now $650! I don't think I paid much more than $100 in 1994/5.)
I do not know of such book, and will be glad if someone suggest it.
But let me attempt a broad sketch of applications of Mathematics before 1900:-)
The first main application was astronomy, there is no doubt in this. It started in the Hellenistic Greece, and probably until the 18-th century this was the main application.
Astronomy and (after Newton) celestial mechanics. Ability to predict the Moon motion
and to predict the existence of new planets were probably the greatest "practical" achievements
of mathematics until the middle 19-th century.
Serious applications to physics and engineering begin in 17-th century.
With the invention of calculus, we see an explosive growth of applied mathematics.
Bernoulli's and Euler tried to model literally everything: blood flow in the blood vessels,
behavior of a ship at sea, behavior of a projectile inside the gun barrel (not only outside!) and so on. (It is questionable whether these early theories had any influence
on the industry and technology. The problems they considered were too complicated for mathematics of that time). One early example, of successful applications of mathematics that
I know besides astronomy is the design of clocks and watches.
Two entirely new playgrounds were opened in the beginning of 19-th century: electricity/magnetism and heat conduction. Here we already have examples of direct influence of mathematics on industry. I mean design of steam engines, design of rails and wires, and various machines, etc. One especially famous story is Lord Kelvin's
mathematical contribution to the design of
the first transatlantic cable. (He became a Lord because of this! This was around 1850-s)
He also improved the compass for marine navigation using modern mathematical theories.
These are just few examples. But in general, one can say that since the beginning of
19-th century, mathematics becomes a true productive force. Necessary for engineering and industry (not only for astronomy and physics). Hydrodynamics was successively applied to ship construction in the end of 19-th century, though the first attempts start with
Bernoulli and Euler.
You ask explicitly about algebra. Algebra had fewer applications before the modern period.
One of them was to coding. They say this application begins with Vieta, the founder of
algebraic notation, but I do not have precise references.
I did not mention applications of geometry to geodesy, and building construction, and this is
perhaps as old as applications to astronomy.
It will indeed be interesting if someone writes a book along these lines.
But the examples I mentioned are scattered in many books. One notable example is
T. Korner's books "The pleasures of counting" and "Fourier Analysis".
A remark on computation before electronic computers. Of course, massive computations were always needed. One milestone was invention of logarithms in the early 17 century.
This was not enough, and people were always working on the invention of computing machines, beginning from 17-th century. There were also "computing centers" where many people (called "computOrs") computed. Specialized tables for all kinds of computation were developed. There were quite advanced analog computing machines,
like harmonic analizers (invented by the same Lord Kelvin for tide prediction).
Of course, all this changed with the wide spread of cheap electronic computers, but this happened only very recently.
EDIT. I think, fdb's comment requires somewhat longer answer than fits in a comment.
Indeed, Pythagoras lived in Italy, Thales in Turkey:-) and Euclid in Egypt. However I think it will be a ridiculous anachronism to call Thales "a Turk". All these people are commonly called Greeks, and there are at least some reasons for this.
Second, and more important. I use the words "mathematics" and "astronomy" in a narrow sense. (You may use them differently, I do not want to argue about words). All human cultures had some means of counting and measuring the amounts of grain, beer, and the areas of land plots. Many of them also had a tax code. From my point of view this is not "mathematics" yet. Mathematics (in the narrow sense), as far as I know was invented by some Greeks (according to the legend, either by Thales or Pythagoras) and the earliest documentary evidence of it comes to us from Hellenistic times/states. Namely from Alexandria, now in Egypt.
Astronomy was first practiced in Babylon (and we have well-documented prime sources of this) but there was no much mathematics yet. Real APPLICATIONS of mathematics to astronomy
come from Hellenistic Greeks (who lived everywhere on the Mediterranean coast and islands.)
Eudoxus was a great mathematician, of course (judging by what is attributed to him) but his contribution to astronomy (comparable to the contribution of Aristarchus) is not really an application of mathematics to astronomy. Eudoxus's spheres (and Aristarchus determination of the ratio of distances to Sun and Moon) where nice, beautiful mathematical exercises, but they were not real "successful applications of mathematics to astronomy". Aristarchus proposal is not realistic, and it is clear that he did not even try to measure the quantities involved. If you do not believe me, try to determine the
ratio of these distances with Aristarchus method. I tried. Really. That the planets do not actually move as Eudoxus described was probably clear even to is contemporaries, and certainly to anyone who did
observations. So applications of mathematics to astronomy, to the best of my knowledge, begin with Apollonius and Hypparchus (who lived in Egypt:-)
Of course, astronomy in the narrow sense (as I understand it), does not include such facts
that there are stars and planets, or names of constellations, or the fact that that Sun raises in the East and sets in the West, and so on. The facts that anyone discovers once she looks at the sky regularly for few months.
The job for humans who compute was sometimes called computer rather than computor. See the heading and text of the 19th century New York Times ad here: http://danwin.com/2013/02/the-first-mention-of-computer-in-the-new-york-times/.
“It started in Hellenistic Greece….” I am not entirely sure what “Greece” means in this context (Is Alexandria in Greece?). But that is not the issue. The ancient Egyptians had at least a rudimentary form of algebra. Then there is the “Pythagorean” theorem (which may or may not have been first posited by Pythagoras). There is lots of geometry in Plato (e.g. in the Timaeus). And what about Eudoxus? All definitely pre-Hellenistic.
You are right:-) I should have said "Hellenistic states". The most important of them for mathematics was Ptolemy's state on the territory of current Egypt.
Concerning pre-Hellenistic mathematics, on my opinion there were no serious applications to astronomy, but of course it is always risky to say who did something "for the first time". Anyway, I do not insist on this statement:-) I just know too little about pre-Hellenistic math and astronomy.
As a general and high level overview, I enjoyed Mathematics for the Million by Lancelot Hogben. It's not very in-depth or modern, but it does put many mathematical developments in their historical context.
| common-pile/stackexchange_filtered |
changing title of page doesn't work with facebook meta tags
I'm trying to set my meta tags for facebook like, but I have like button on changing page which means that title will be always different. My meta tag look like:
<meta property="og:title" content="<?php echo $listing['Listing']['title']?>" />
or whatever code I put there. It shows my title at debuger like:
<?php echo $listing['Listing']['title']?>
Simply sad, what's in inverted comas, that's title. Why? why it doesn't accpet that php code?
This does not sound like a facebook related question at all. Sounds like you are having problems with the output of the php script. Facebook just reads what you return and it's after the process of the php. At the bottom of the debug result you have "Scraped URL: See exactly what our scraper sees for your URL" click that and you'll see what your page returns.
I see but why it ignores that php script? and simply uses it as title?
I have no idea, you did not supply enough information regarding that aspect of things since you thought it's fb related. Can you please show more of the php script? Also, is that the only place in that script that is has php parts? If not, do other parts act the same or just this title thing?
I'm using joomla. My fb script looks like:
and I'm using ITP meta component to edit my meta tags and there I have put that php meta tag.
Don't put that amount of code into comments, edit your original question and add code there (using the code format). Now, as I already wrote the problem is not a facebook one, but a php one, and now after you mentioned it might very well has to do with joomla. Since I've never used joomla before I can't really help you with that, but I'll modify the tags of your question since the ones you have obviously won't help you find the answer.
Is the file you are putting the PHP code into a .php file? or a template file?
What file did you post the code into? It looks like it's not where it's supposed to be... I'd advise putting the tag into your template (/templates/yourtemplate/index.php)
Alternatively there's alot of extensions that can handle this for you: http://extensions.joomla.org/search?q=facebook+open+graph
| common-pile/stackexchange_filtered |
unable to capture 'g-recaptcha-response' for Recaptchav2 with Selenium
So I've been trying to build a webscraper but some of the data I need to scrape is locked behind a reCaptcha. From what I've gathered scouring around on the internet is every captcha has a TextArea element with the 'g-recaptcha-response' that gets filled in as the captcha is completed. The current solution for testing is to simply get around the captcha with me manually doing it and trying to capture the response and feed it back into the headless browser however I'm unable to get the response since as soon as the answer is submitted it can no longer find the response element.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"*[name='g-recaptcha-response']"}
public static String captchaSolver(String captchaUrl) {
setUp();
driver.get(captchaUrl);
new WebDriverWait(driver,2);
try {
while (true) {
String response = driver.findElement(By.name("g-recaptcha-response")).getText();
if (response.length()!=0) {
System.out.println(response);
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
return "";
}
Recaptcha mechanisms exists to stop robots like selenium. Even if you manage to capture responce once, the verification starts to loop and never ends.
Try to find the element by CSS like this:
*[name*='g-recaptcha-response']
| common-pile/stackexchange_filtered |
Ruby - "bundle install" json gem error
I am working on Windows 10. I successfully installed Ruby, MSYS2 and DevKit, but after trying to run the following command:
bundle install
it throws me an error
An error occurred while installing json (1.8.1), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.
I tried the solution with
gem install json -v '1.8.1'
but it still doesn't work for me.
Does anybody knows how i can fix the error?
did you try bundle update then bundle install?
@AmrAdel No, i will try, hope it works ;)
What errors do you get from the Json geminstall?
Json 1.8 is an old gem you may have trouble to install on a recent Ruby version. Please see this similar case here https://stackoverflow.com/questions/50307653/bundle-install-error-json-gem#comment87639105_50307653
@AmrAdel Yeah i tried first bundle update, but then i got error for do_sqlite3 gem
@Joe i fixed the json gem error, but now i got the error for some do_sqlite3 gem
@Maxence i fixed the json gem error, but now i got the error for some do_sqlite3 gem
I doubt the problem is ruby version or something,
Sometimes I remove what is inside GEMFILE.lock and run bundle install again, could u try this?
@AmrAdel, i tried everything and still got this do_sqlite3 error. I also downloaded SQLite3 and place it in Ruby directory, but still nothing. Here is the image of an error: https://imgur.com/a/kbENwvm Please check it out. It happens when i try to run a "bundle update" command.
Add the errors you're getting to your post.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.