text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Group >70% similar MySQL TEXT field data using PHP I have a TEXT filed in the MySQL table. it has sentence
Example
Hello AAAA, where is your dog BBBB
Hello PPPP, where is your dog QQQQ
Hello XXXX, where is your dog YYYY
I am fine. thanks
I am fine. thanks
where are you going?
Thank you very much
here
first 3 sentence has 5 same word out of 7. so it is (5/7)*100=72% similar
4th and 5th 100% similar
my question is.
using php i want to group in a table like this
sample_sentence_group count
Hello AAAA, where is your dog BBBB 3
I am fine. thanks 2
where are you going? 1
Thank you very much 1
how can i do it?
the table has more than 100K record
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16849738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I install Google OR-Tools on Mac? Trying to install Google OR-Tools by running in the terminal:
python3 -m pip install -U --user ortools
I end up with errors:
ERROR: Could not find a version that satisfies the requirement ortools (from versions: none)
ERROR: No matching distribution found for ortools
What might I be missing?
OSX 10.14.6,
Python 3.10,
pip 21.3.1,
Homebrew 3.3.2
A: python 3.10 was released after or-tools 9.1.
Next release will contain the 3.10 wheel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69842574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stream.filter based on javax.validation I'm using Spring Boot. I know there is a @Valid annotation you can use on top of methods so it throws an Exception if it's not valid, but I don't want to throw an exception, I just want to ignore the invalid objects.
Let's say I have this model class:
public class User {
@NotNull
private String name;
@AssertTrue
private boolean working;
@Size(min = 10, max = 200)
private String aboutMe;
@Email(message = "Email should be valid")
private String email;
}
And this Stream:
Stream<User> stream = getUsers();
How can I filter based on the javax.validation annotations this class has?
stream.filter(u -> isValid(u));
A: It looks like spring won't be helpful here, but you still can do that.
This @Valid annotation processing implementation is basically in integration with project Hibernate Validator (Don't get confused with the name, it has nothing to do with Hibernate ORM ;) )
So you could create the engine and validate "manually".
An example of using the validation engine:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
User user = ...
Set<ConstraintViolation<User>> constraintViolations = validator.validate( user );
As you see, the Result of the validation in hibernate validator is not an exception (this is something that spring has added on top to better integrate with web mvc flow) but rather a set of "validation constraint violations". So basically is this set is not empty, there is at least one validation error so that you could filter it out.
I believe wrapping the this logic into filter is not that interesting once you're familiar with the foundations...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62676327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I replace the header and trailer of all files in a directory with a new header and trailer string, but only up to a certain character? I have files in a directory:
ex:
file1
file2
Both files have contents that look like the below (header, body, trailer words just for reference):
header: 123xxx xxx value=file1id
body: blah blah blah
trailer: 123zzz zzz value=file1id
I want to run a linux command that will replace the header and trailer of all the files in the directory, up to "file1id", so that they look like the below:
header: 321aaa aaa value=file1id
body: blah blah blah
trailer: 321bbb bbb value=file1id
I can easily find how to replace the whole header or trailer in a file on Google, but I need the file1id in my file. I need some guidance on how to loop through files in a directory and replace the header and trailer up to a certain character in the header and trailer.
I have seen a variety of sed and awk expressions that delete and replace the header or trailer.
sed -rne 's/(value=)\s+\w+/\1 yyy/gip'
As I mentioned above, I want to run a linux command that will replace the header and trailer of all the files in the directory, up to "file1id", so that they look like the below:
header: 321aaa aaa value=file1id
body: blah blah blah
trailer: 321bbb bbb value=file1id
A: This sed example has two replace commands, one for the first line (header) and one for last line trailer (denoted by $ in the second substitution). -i option of sed edits the file in place.
sed -i '1 s/^.*value=/yoursubstitution value=/; $ s/^.*value=/yoursubstitution value=/'
output:
yoursubstitution value=file1id
body: blah blah blah
yoursubstitution value=file1id
A: You can match from the beginning of the line (^) to value=
echo 'header: 123xxx xxx value=file1id' | sed 's/^.*value=/header: 321aaa aaa value=/'
header: 321aaa aaa value=file1id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56136049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't Get CSRF Token to Appear on a Django Template/View I'm trying to use a Django ListView sub-class to generate a page with a form on it. It's an old school manual HTML form, not a Django-generated one (though I do also have a Django-generated form elsewhere on the same page). Since Django bakes CSRF authentication in, I need to include the CSRF token in that form in order to make it work.
However, I'm not having much luck, even after looking at several related Stack Overflow posts (and fixing things accordingly).
Basically I've got a get method on a ListView subclass, and I've used the method decorator to decorate it with the CSRF decorator:
class FooView(ListView):
@method_decorator(ensure_csrf_cookie)
def get(self, request):
# code for otherwise working view
In my template I have:
<form>
{% csrf_token %}
However, when I view the source of the page after it's been rendered, I just see:
<form>
(no CSRF token).
I'm not explicitly adding the CSRF token to the context because I'm using ListView, and as per https://docs.djangoproject.com/en/1.6/ref/contrib/csrf:
If you are using generic views or contrib apps, you are covered already
I'm sure I'm just missing something basic, but any help explaining what that might be would be greatly appreciated.
A: You need import this:
from django.template import RequestContext
and then use it like so:
def example():
# Some code
return render_to_response('my_example.html', {
'Example_var':my_var
}, context_instance=RequestContext(request))
This will force a {% csrf_token %} to appear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25458624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Users reporting WPF controls with locked values; how could this happen? I have a relatively simple program that I have created using WPF and the .NET 4.0 Client Profile. I used an MVVM approach, where I have views with minimal code-behind which bind to properties on the corresponding view-models; those properties then access the model as necessary. The GUI contains checkboxes, sliders, and other controls as necessary. The sliders are set to have a minimum value of 0, a maximum value of 1, a large change of 0.1, and a small change of 0.05. It all works fine for me and most people.
Unfortunately, several users have reported some very strange issues. They report that the sliders are locked to a value of 0 or 1, and that the values cannot be changed. Normally, the sliders have a minimum value of 0 and a maximum value of 1, so the values are potentially correct (although they most likely should actually be showing values of 0.5 or so), but they definitely should be adjustable! However, I am not setting IsSnapToTickEnabled; it is left at its default value of false. The sliders are binding to decimal properties on the view-models. I have tried asking these users for more information, but it is unfortunately difficult to get into contact with them, so I am trying to solve it on my own.
I am running Windows 7 64-bit. I have tried experimenting by changing the view-model so that a slider binds to a value lower than its minimum or higher than its maximum, and in these cases the slider handles it fine by simply showing the minimum or maximum and allowing changes. I have tried experimenting by changing the view-model so that a slider binds to a property which throws an exception, and in this case the slider handles it fine by showing the minimum value and allowing changes. This suggests to me that the binding (and therefore, view-model and model) is not the problem, and so the issue is somewhere on the view side of things. I thought that it may be a problem with the style not getting applied, but even an unstyled slider works fine and allows changes normally.
No matter what I do I cannot reproduce the issues that these people are reporting! Therefore, I have come to you for help. Can you think of any ideas of what could be causing this? I'm not doing anything unusual as far as I know. I'm just using an ordinary WPF Slider control and binding to a decimal property!
I do know that at least one user who is getting these issues is using the classic theme, and I am forcing the Aero theme in my program, if this is of any relevance.
Here is some example code, but I do not think it will be very helpful...
Slider binding:
public decimal TestBinding {
get { return this.Model.Test; }
set {
if (this.Model.Test == value) return;
this.Model.Test = value;
this.OnPropertyChanged("TestBinding");
}
}
Slider control:
<Slider Grid.Row="1"
Grid.Column="1"
Value="{Binding TestBinding}"
Style="{StaticResource Slider0to1}" />
Slider style:
<Style TargetType="Slider" BasedOn="{Utilities:StaticApplicationResource {x:Type Slider}}">
<Setter Property="Margin" Value="0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="AutoToolTipPlacement" Value="TopLeft" />
<Setter Property="AutoToolTipPrecision" Value="2" />
<Setter Property="TickPlacement" Value="BottomRight" />
</Style>
<Style x:Key="Slider0to1" TargetType="Slider" BasedOn="{Utilities:StaticApplicationResource {x:Type Slider}}">
<Setter Property="AutoToolTipPrecision" Value="2" />
<Setter Property="Minimum" Value="0" />
<Setter Property="Maximum" Value="1" />
<Setter Property="TickFrequency" Value="0.1" />
<Setter Property="SmallChange" Value="0.05" />
<Setter Property="LargeChange" Value="0.1" />
</Style>
StaticApplicationResource markup extension:
[MarkupExtensionReturnType(typeof(object))]
public class StaticApplicationResource : MarkupExtension {
public StaticApplicationResource(object resourceKey) {
this.ResourceKey = resourceKey;
}
[ConstructorArgument("resourceKey")]
public object ResourceKey { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider) {
if (this.ResourceKey == null) return null;
return Application.Current.TryFindResource(this.ResourceKey);
}
}
A: You can do following things to gather some more information,
*
*Your report must include operating system.
*Version and screen size.
*DPI information, most users set high font size, this probably will change dpi to little bit causing controls to render little differently.
*WPF version, and also check default dependency property values. You may assume that you have set ticks to false but it may be true by default, or if your xaml is running within some other app and resources might set it to true.
*Users may only use keyboard, and check how keyboard behaves for these controls.
*Users may double click, lots of users have habit of double clicking everything (buttons, links)
*In smaller screen sizes, your controls may be out of views, this is very unlikely as you are receiving max values. Or even on big screens, changing text size may cause layout to hide your controls.
A: It's hard to know for sure if the classic theme is the issue, but I've had a LOT of issues with various themes and WPF. For example, projecting (to an external display) with the Aero theme almost always will eventually cause some quirky behavior with WPF. I've also had similar issues that seemed to manifest more on certain video cards than others. And don't get me started on LiveMeeting and WPF :-)
Definitely test classic theme, and make sure you test on XP too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8073541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is it ok to build an 64 bit ActiveX control with C# for enterprise application use I am planning to build an 64 bit ActiveX control to be used in my web page. So my question is it OK to build it with C#? Will it be able to handle complex business logic? The reason why I ask this is that I am more familiar with C# than ATL.
Before raising this question, I searched all the related posts, they are all about how to build ActiveX with C#. However I would like to know if it will be a good choice or ATL will be more better?
By the way, the previous version of my ActiveX control is in 32 bit coded with VB6, but VB6 is impossible to build 64 bit ActiveX control.
I appreciate any of your suggestions and comments!
Regards,
Shuping
A: If you're most comfortable with C#, why not build it in Silverlight? Will be a lot easier than building and deploying ActiveX controls.
A: How about a Windows Forms app launched from Clickonce or Java web start? You cannot run a 64bit ActiveX from a 32bit IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6126725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Guard Live-reload with Susy Has anyone used Guard Live-reload with Susy, here's the link to Guard: https://github.com/guard/guard.
I found where Guard is being used with Sass and Compass but so far I've not found where it's being used with Susy.
Any help will be appreciated
jrattling
A: Since Susy is simply a Sass/Compass library, there is usually no need to integrate Susy directly with other build tools. Use the Sass/Compass-guard setup, install Susy like you would without guard (see the docs), and it should all just work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26316316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there some way to rescale a slice of a canvas? My project includes a canvas element that is 800x2000. What I need to do is take a 200x2000 slice of the canvas and display it in the same 800x2000 location. What method or combination of methods might help me accomplish this?
A: Yes; use the 9-argument form of drawImage() to draw the slice of the canvas (i.e., the source) onto itself (i.e., the destination) as follows:
function rescale(slice_start) {
canvas.getContext('2d').drawImage(canvas, slice_start, 0, slice_start + 200, 2000, 0, 0, 800, 2000)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59248762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to reset datagridview having checkbox after filter is applied in c# I'm new to c# coding and i'm struck with this.
I have a DataGridView with a DataGridViewCheckBoxColumn column, which is databound to a list.
After applying filter to datagridview,filter works fine,but if i check the row using checkbox,i can't retain it since on clicking on back i load datagridview once again which looses checkbox selection also CheckBoxColumn is created once again.
I need to retain checkbox selection with/without filter also checkboxcolumn should appear once when i reset datagridview
public AddressReport1()
{
InitializeComponent();
loadData();//load gridview
}
public void loadData()
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmdSelect = new SqlCommand(@"SELECT ContactId,ReceiverName,City,Address,ContactNo1,ContactNo2,GSTNumber,State FROM tbl_contacts", conn);
SqlDataAdapter da = new SqlDataAdapter(cmdSelect);
DataTable dt = new DataTable();
da.Fill(dt);
dgvAddressReport1.DataSource = dt;
//create checkbox column dynamically in datagridview
DataGridViewCheckBoxColumn select = new DataGridViewCheckBoxColumn();
select.Name = "select";
select.HeaderText = "select";
select.Width = 50;
select.ReadOnly = false;
select.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
//add checkbox column in first row of gridview
dgvAddressReport1.Columns.Insert(0, select);
int dgvindex = dgvAddressReport1.Columns["select"].Index;
MessageBox.Show(dgvindex.ToString());
conn.Close();
}
private void btnBack_Click_1(object sender, EventArgs e)
{
loadData();[enter image description here][1]
}
A: First of all you can create DataGridViewCheckBoxColumn outside of loadData method, Maybe in constructor. So it will be created only once.
To retain Checkbox selection, you can add boolean field in datatable or in database. Everytime you click on a row , just update that flag.
When you have DataGridViewCheckBoxColumn , when rebinding datasource, this column is automatically checked or unchecked according to boolean flag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49531036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pytest fixture yield returns generator instead of object I'm running pytest-3. I'm defining a fixture that is supposed to return a falcon TestClient object. I also need a teardown, so I'm trying to yield it.
def client():
api=create_app()
c = testing.TestClient(api)
yield c
remove_db()
If I 'return' instead of 'yield', the test cases run just fine.
But with yield, my test cases get a generator object instead of a TestClient object
A: Probably because the function is not marked as a fixture. Try after decorating the function with @pytest.fixture. For example,
@pytest.fixture(scope="session")
def client():
api=create_app()
c = testing.TestClient(api)
yield c
remove_db()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54887336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Thumbnails from the Vimeo website harder than YouTube Our website lets people add videos by submitting a URL - usually one from YouTube or Vimeo. I'd like to show thumbnails, when giving people a list of videos.
YouTube make this easy for me - just slap "1.jpg" on the end of the URL, and you've got your image.
Vimeo seem to want me to make a HTTP request, and extract the thumbnail URL from the XML they return - what? Who's got time for that?!!! Plus, I'd have to store these URLs too, I can't get them on the fly for a page that lists 20 videos.
Is there an easier way to get Vimeo thumbnails? I can't find one...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/840765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Access Display Message Box if Query Conditions Met Hi I'm trying to display a Message Box based on values from a query. I've tried the DLookUp function of the following:
If (DLookup("ID1", "qry_CheckID") = Forms!MainForm!ID2) Then
MsgBox "Your ID is bad.", vbOKOnly, ""
End If
Basically I want to see if ID1 from my query matches with ID2 in my form. However the DLookUp isn't working as (I had) intended.
A: Include filter criteria in the DLookup. Concatenate variables, reference to the form field/control is a variable. If there is no match, Null will return. Since in your comment you said you want the message only if there is a match in the query:
If Not IsNull(DLookup("ID1", "qry_CheckID", "ID1 = " & Forms!MainForm!ID2)) Then
MsgBox "Your ID is bad.", vbOKOnly, ""
End If
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43858382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i generate all the permutations of the first n letters from the alphabet, lexicographically? Find a method to generate all the permutations of the first n letters from the alphabet, lexicographically, but ignore the results which have two vocals standing next to each other.
I tried this, but for some testcases it appears to be wrong, and also, it's very slow on others so I can't tell if it worked on those.. It works for a few cases only..Input:
4output
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
#include <bits/stdc++.h>
using namespace std;
int n;
bool verify(char sir[9]) {
char v[] = "aeiou";
for (int i = 1; i < n; ++i) {
char *p = strchr(v, sir[i]);
if(p != 0) {
p = strchr(v, sir[i - 1]);
if(p != 0)
return 0;
}
}
return 1;
}
int main() {
int lg = 0;
char sir[9];
cin >> n;
for (char c = 'a'; c < 'a' + n; ++c) {
sir[lg] = c;
++lg;
}
do {
if(verify(sir)) {
for (int i = 0; i < n; ++i)
cout << sir[i] << ' ';
cout << '\n';
}
} while(next_permutation(sir, sir + n));
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61477673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cosmos DB - CreateCollectionIfNotExistsAsync Generic method I am using cosmos DB and I have created below generic repository for CRUD operations.
public class CosmosDBRepository : ICosmosDBRepository
{
private readonly DocumentClient _client;
private readonly string DatabaseId = "FleetHub";
public CosmosDBRepository()
{
var endpoint = CloudConfigurationManager.GetSetting("CosmoDbEndpoint");
var authkey = CloudConfigurationManager.GetSetting("CosmoDbAuthKey");
try
{
if (endpoint == null || authkey == null)
{
throw new ArgumentNullException("CosmoDbEndpoint or CosmoDbAuthKey could not be found in the config file, check your settings.");
}
if (_client == null)
{
_client = new DocumentClient(new Uri(endpoint), authkey, connectionPolicy: new ConnectionPolicy { EnableEndpointDiscovery = false });
}
CreateDatabaseIfNotExistsAsync().Wait();
CreateCollectionIfNotExistsAsync().Wait();
}
catch (Exception e)
{
throw new Exception($"Initialise failed CosmoDbEndpoint {endpoint} or CosmoDbAuthKey {authkey} could not be found in the config file, check your settings. {e.Message}");
}
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="partitionkey"></param>
/// <returns></returns>
public async Task<T> GetItemAsync<T>(string id, string partitionkey) where T : class
{
try
{
string CollectionId = GetAttributeCosmoDbCollection<T>(typeof(T));
Document document = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), new RequestOptions { PartitionKey = new PartitionKey(partitionkey) });
return (T)(dynamic)document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public async Task<Document> CreateItemAsync<T>(T item) where T : class
{
string CollectionId = GetAttributeCosmoDbCollection<T>(typeof(T));
return await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
}
public async Task<IEnumerable<T>> GetItemsAsync<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> orderByDesc, int takeCount = -1)
where T : class
{
string CollectionId = GetAttributeCosmoDbCollection<T>(typeof(T));
var criteria = _client.CreateDocumentQuery<T>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), new FeedOptions { EnableCrossPartitionQuery = true })
.Where(predicate)
.OrderByDescending(orderByDesc)
.AsDocumentQuery();
IDocumentQuery<T> query = criteria;
List<T> results = new List<T>();
while (query.HasMoreResults)
{
if (takeCount > -1 && results.Count >= takeCount)
{
break;
}
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <returns></returns>
public async Task<Document> UpdateItemAsync<T>(string id, T item) where T : class
{
string CollectionId = GetAttributeCosmoDbCollection<T>(typeof(T));
return await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
}
#region private methods
private async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await _client.CreateDatabaseAsync(new Database { Id = DatabaseId });
}
else
{
throw;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private string GetPartitionKeyAttributeCosmoDbCollection(Type t)
{
// Get instance of the attribute.
CosmoDBCollection attribute =
(CosmoDBCollection)Attribute.GetCustomAttribute(t, typeof(CosmoDBCollection));
if (attribute == null)
{
throw new Exception("The attribute CosmoDbCollection was not found.");
}
return attribute.PartitionKey;
}
private string GetAttributeCosmoDbCollection<T>(Type t) where T : class
{
// Get instance of the attribute.
CosmoDBCollection attribute =
(CosmoDBCollection)Attribute.GetCustomAttribute(t, typeof(CosmoDBCollection));
if (attribute == null)
{
throw new Exception("The attribute CosmoDbCollection was not found.");
}
return attribute.Name;
}
#endregion
}
Here is CosmoDBCollection class:
public class CosmoDBCollection : Attribute
{
public string Name { get; set; }
public string PartitionKey { get; set; }
}
I am calling CreateCollectionIfNotExistsAsync().Wait(); in the constructor and this method required collectionId. How Can I pass CollectionId to this method? As this is the generic repository.
Do I need to create a Generic CreateCollectionIfNotExistsAsync() method?
A: If your collection name is based off <T>, why not simply have CosmosDBRepository<T> as the actual class. That way you can get the value also on the constructor.
Ideally it would also be a readonly private property that you only calculate once (on the constructor) and reuse on all operations to avoid paying the cost to construct it later on (since it doesn't change).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61885389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deallocating RTCMediaStream blocks the main Thread I'm building an iOS app that should use the WebRTC implementation form webrtc.org. I created the demo app and every thing works fine. After integrating the framework into my own app I'm experiencing a problem regarding deallocating resources.
As a first step I wanted to create a local media stream and add an audio and video track to it. In my tests I realized, that deallocating a RTCMediaStream (and VideoTrackProxy) object blocks the main thread for about 10 seconds.
To reproduce this, I created a separate test, that creates a media stream adds a video track to it and deallocates it afterwards (objects are released at the end of the scope).
@interface RTCTests : XCTestCase
@property (nonatomic, strong) RTCPeerConnectionFactory *factory;
@end
@implementation RTCTests
- (void)setUp
{
[super setUp];
self.factory = [[RTCPeerConnectionFactory alloc] init];
}
- (void)tearDown
{
self.factory = nil;
[super tearDown];
}
- (void)testLocalMediaStream
{
RTCMediaStream *mediaStream = [self.factory mediaStreamWithLabel:@"stream-a"];
XCTestExpectation *expectation = [self expectationWithDescription:@"Create Media Stream"];
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
completionHandler:^(BOOL granted){
dispatch_async(dispatch_get_main_queue(), ^{
if (granted == NO) {
XCTFail(@"Access to camera not granted.");
[expectation fulfill];
} else {
NSString *cameraID = nil;
for (AVCaptureDevice *captureDevice in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
if (captureDevice.position == AVCaptureDevicePositionFront) {
cameraID = [captureDevice localizedName];
break;
}
}
if (cameraID) {
RTCVideoCapturer *capturer = [RTCVideoCapturer capturerWithDeviceName:cameraID];
RTCMediaConstraints *mediaConstraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:@[]
optionalConstraints:@[]];
RTCVideoSource *videoSource = [self.factory videoSourceWithCapturer:capturer
constraints:mediaConstraints];
RTCVideoTrack *track = [self.factory videoTrackWithID:@"stream-a-v" source:videoSource];
if (track) {
[mediaStream addVideoTrack:track];
}
}
[expectation fulfill];
}
});
}];
[self waitForExpectationsWithTimeout:10.0 handler:^(NSError *error) {
XCTAssertNil(error, @"Failed with error: %@", [error localizedDescription]);
}];
XCTAssertEqual([mediaStream.videoTracks count], 1);
XCTAssertEqualObjects([[[mediaStream videoTracks] firstObject] label], @"stream-a-v");
NSLog(@"Done! %@", [NSDate date]);
}
@end
The test itself works as expected and it succeeds more or less immediately as you can see in the log below:
Test Case '-[RTCTests testLocalMediaStream]' started.
2015-03-02 14:51:36.458 App[9043:2810016] Begin! 2015-03-02 13:51:36 +0000
2015-03-02 14:51:36.643 App[9043:2810016] End! 2015-03-02 13:51:36 +0000
Test Case '-[RTCTests testLocalMediaStream]' passed (9.266 seconds).
But it takes another 9 seconds to deallocate the resources (in this case the VideoTrackProxy) which synchronously calls a method on an other thread in the destructor (if I read the sources of the proxy correctly). Unfortunately this thread seams to be the main thread, which results in a dead lock and is resolved by a timeout I guess.
* thread #1: tid = 0x2ae4a8, 0x00000001978db078 libsystem_kernel.dylib`__psynch_cvwait + 8, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
* frame #0: 0x00000001978db078 libsystem_kernel.dylib`__psynch_cvwait + 8
frame #1: 0x0000000197976fe4 libsystem_pthread.dylib`_pthread_cond_wait + 624
frame #2: 0x0000000100cbc2c0 RTCTests`rtc::Event::Wait(int) + 232
frame #3: 0x0000000100b210cc RTCTests`webrtc::VideoTrackProxy::~VideoTrackProxy() + 120
frame #4: 0x0000000100b206b0 RTCTests`rtc::RefCountedObject::~RefCountedObject() + 12
frame #5: 0x0000000100b20690 RTCTests`rtc::RefCountedObject::Release() + 52
frame #6: 0x0000000197152b1c libobjc.A.dylib`object_cxxDestructFromClass(objc_object*, objc_class*) + 148
frame #7: 0x000000019715ff38 libobjc.A.dylib`objc_destructInstance + 92
frame #8: 0x000000019715ff90 libobjc.A.dylib`object_dispose + 28
frame #9: 0x0000000100b58db4 RTCTests`-[RTCMediaStreamTrack(Internal) dealloc] + 92
frame #10: 0x0000000100b5ef6c RTCTests`-[RTCVideoTrack dealloc] + 356
frame #11: 0x000000018692d228 CoreFoundation`CFRelease + 524
frame #12: 0x0000000186935308 CoreFoundation`-[__NSArrayI dealloc] + 88
frame #13: 0x000000019716d724 libobjc.A.dylib`(anonymous namespace)::AutoreleasePoolPage::pop(void*) + 564
frame #14: 0x00000001011f1c54 XCTest`-[XCTestCase invokeTest] + 336
...
Can the WebRTC framework be configured to not use the main thread for its internal tasks? Or am I missing something else here?
I'm appreciating all kinds of tips.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28811742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to use Jira.CreateOAuthRestClient from C# code? I have downloaded Atlassian SDK from visual studio nuget manager. There is a method
public static Jira CreateOAuthRestClient(string url, string consumerKey, string consumerSecret, string oAuthAccessToken, string oAuthTokenSecret, JiraOAuthSignatureMethod oAuthSignatureMethod = JiraOAuthSignatureMethod.RsaSha1, JiraRestClientSettings settings = null)
I have base Jira URL and a secret access token. However, the above method seems to have many parameters. Request someone to share a sample c# code how I can use this method to fetch JIRA issues in c# code.
consumerKey:?
consumerSecret:?
oAuthAccessToken:?
oAuthTokenSecret: ?
What should be the value of these parameters?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72628707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sidekiq in dockerised rails application on AWS I have a docker compose file with this content.
version: '3'
services:
db:
image: postgres
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: pass
POSTGRES_USER: user
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: "redis:alpine"
ports:
- "6379:6379"
volumes:
- 'redis:/var/lib/redis/data'
sidekiq:
build: .
links:
- db
- redis
command: bundle exec sidekiq
volumes:
- '.:/app'
web:
image: production_image
ports:
- "80:80"
links:
- db
- redis
- sidekiq
restart: always
volumes:
postgres_data:
redis:
In this to run sidekiq, we run bundle exec sidekiq in the current directory. This works on my local machine in development environment. But on AWS EC2 container, I am sending my docker-compose.yml file and running docker-compose up. But since the project code is not there, sidekiq fails. How should I run sidekiq on EC2 instance without sending my code there and using docker container of my code only in the compose file?
A: The two important things you need to do are to remove the volumes: declaration that gets the actual application code from your local filesystem, and upload your built Docker image to some registry. Since you're otherwise on AWS, ECR is a ready option; public Docker Hub will work fine too.
Depending on how your Rails app is structured, it might make sense to use the same image with different commands for the main application and the Sidekiq worker(s), and it might work to just make it say
sidekiq:
image: production_image
command: bundle exec sidekiq
Since you're looking at AWS anyways you should also consider the possibility of using hosted services for data storage (RDS for the database, Elasticache for Redis). The important thing is to include the locations of those data stores as environment variables so that you can change them later (maybe they would default to localhost for developer use, but always be something different when deployed).
You'll also notice that my examples don't have links:. Docker provides an internal DNS service for containers to find each other, and Docker Compose arranges for containers to be found via their service key in the YAML file.
Finally, you should be able to test this setup locally before deploying it to EC2. Run docker build and docker-compose up as needed; debug; and if it works then docker push the image(s) and launch it on Amazon.
version: '3'
volumes: *volumes_from_the_question
services:
db: *db_from_the_question
redis: *redis_from_the_question
sidekiq:
image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/myapp/sidekiq:1.0
environment:
- PGHOST: db
- REDIS_HOST: redis
app:
image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/myapp/app:1.0
ports:
- "80:80"
environment:
- PGHOST: db
- REDIS_HOST: redis
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52290678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Impersonation file upload impact i have a admin system, currently allow login user to upload a file,
but i found that it can not overwrite the file with same file name, it return access denied error
im wondering if i set impersonation = true in web.config, what impact will have?
(i know there is another way to solve my upload overwrite issue, but just want to ask the impact of impersonation)
Thanks
A: This is obviously a permission related issue so you need to check for permissions on folder for the users application pool, network service and aspnet
Check read only attribute of the files that are throwing access denied. many times, user uploads images from CD.
When you are saving file, try to remove read only flag and save the file so that when overwritten not throw errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13171942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could not load file or assembly (SSIS) I am working with
*
*Visual Studio 2019 Community Edition
*Installed extension SQL Server Integration Services Projects
*64 Bit System
With a simple sample code from microsoft, I am getting an error:
System.IO.FileNotFoundException: "Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. Das System kann die angegebene Datei nicht finden."
I don't understand this, because I added the reference to that assembly. On my system it resides here:
C:\Windows\assembly\GAC_64\Microsoft.SqlServer.DTSRuntimeWrap\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.ManagedDTS.dll
How can I solve this issue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61476807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access level to elements in visitor pattern In the visitor pattern, i want the client to only have access to the getters of the elements, while the visitors should have access to getters and setters. How would you implement it?
I don't want the visitors in the same package as the model (there are a lot of classes already).
I was thinking about introducing IWriteable interface which contains setters and accept methods.
Is there a better way?
Thanks
A: @Angel O'Sphere:
The package would contains models, visitors and factories all that ~2x (interfaces and impls).
I had some thought about rogue programmer too, that's why I asked.
Another approach would be:
public class ModelImpl implement IRead {
@Override
public Foo getFoo() {...}
private void setFoo(Foo f) {...}
public void accept(Visitor v) {
v.visit(new ModelEditor());
}
private class ModelEditor implement IWrite {
@Override
public void setFoo(Foo f) {
ModelImpl.this.setFoo(f);
}
}
}
But this approach has many drawbacks and is cumbersome without generative techniques :o
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6705362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you write a Teradata SQL Statement with EITHER OR between two columns with multiple WHERE statements? I am trying to use two columns. DATA_IND gives values of "yes" or "no" and another column VIDEO_IND gives "yes" or "no".
I want my query to return if either column has a "yes".
Return CASE (yes, yes)(yes,no)(no,yes) DO NOT return if (no,no)
SELECT
t.email,
a.acct_sk,
a.snapshot_dt,
a.ACCT_SK,
a.ACCT_ESTBD_DT,
a.ACCT_TERM_DT,
a.CUST_EMAIL_ADDR,
a.VOICE_IND,
a.DSL_IND,
a.FIOS_IND,
a.DATA_IND,
a.VIDEO_IND,
e.acct_sk,
e.BILL_DT,
e.CURR_BILL_AMT
FROM Table 1 t
LEFT JOIN Table 2 a
ON t.email = a.CUST_EMAIL_ADDR
LEFT JOIN Table 3 e
ON a.acct_sk = e.acct_sk
WHERE t.email not in ('[email protected]')
AND a.ACCT_TYPE_CD ='B'
AND a.ACCT_ESTBD_DT between date '2019-09-01' and date '2019-09-30'
AND a.snapshot_dt = DATE '2020-01-01'
AND e.BILL_DT between date '2020-01-01' and date '2020-01-31';
Either of these two columns can be "yes", both can't be "No"
a.DATA_IND,
a.VIDEO_IND,
A: How about adding this to the where clause:
and not (date_ind = 'no' and video_ind = 'no')
Or, assuming that the values are binary:
and (data_ind = 'yes' or video_ind = 'yes')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60513703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read SOAP response php I have a SoapClient with PHP and I can't read the string response, I tried to use different methods that I found in this forum but nothing works.
This is my response:
<?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns0:Update_REGISTRYResponse xmlns:ns0="urn:DATA_BMC_CORE_REGISTRY_Modify" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:InstanceId>OI-291D85EF140A464EA9E7CA6918D1A4C7</ns0:InstanceId>
<ns0:Numero_REGISTRY>0712</ns0:Numero_REGISTRY>
And my code in PHP is:
$soap = simplexml_load_string($soapResponse);
$response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->Update_REGISTRYResponse;
$customerId = (string) $response->Update_ATMResponse->Numero_REGISTRY;
echo $customerId;
And the result is:
Notice: Trying to get property of non-object in
But exist the string in my $soapResponse;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27989933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I'm having trouble vertically centering this form I'm currently developing a web app using vue.js, and I'm having trouble vertically centering some elements.
This is what I currently have
I would like to have the div with the form(grey colored bit) to be vertically and horizontally centered.
This is the code for the form, the top navbar is a different component. Also, I'm using tailwindcss but am open to inline or internal styling options the same.
<template>
<div class="bg-gray-600">
<form action="">
<div>
<input type="email" name="email" id="email"/>
<label for="email">Email</label>
</div>
<div>
<input type="password" name="password" id="password"/>
<label for="password">Password</label>
</div>
</form>
</div>
</template>
The code below is in my base.css which was created when the vue project was created. I have no idea how much it affects the elements or what the former block of code(The one with *) does.
*,
*::before,
*::after {
box-sizing: border-box;
padding: 0;
margin: 0;
position: relative;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition: color 0.5s, background-color 0.5s;
line-height: 1.6;
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
I've tried most solutions I could find but they made little to no changes. I would like to avoid setting a fixed px height if possible because I would like it to be centered across viewports.
A: Here are a few methods on how to center an HTML element:
*
*The oldest trick in the book:
.form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
This works by moving the form element 50% to the left and 50% to the top of the container and move's it back 50% of its width and height.
*flex
.form-container {
display: flex;
align-items: center;
justify-content: center;
}
Set the container of the form to flex and align it to the center vertically and horizontally.
*grid
.form-container {
display: grid;
place-items: center;
}
Same thing as flex, but both justify-content and align-items are merged into the same line.
You can give the same CSS to your form using tailwindcss:
1.
<form class="absolute top-1/2 left-1/2 translate-x-1/2 translate-y-1/2">
*
<div class="bg-gray-600 flex items-center justify-center">
*
<div class="bg-gray-600 grid place-items-center">
Hope this helps!
A: Apply this css on the parent of your form, in this case, probably the bg-gray-600
.bg-gray-600 {
display:flex;
justify-content:center; /*horizontal center*/
align-items:center; /*vertical center*/
}
You might need to define width or height of the parent in order this to work. Depends on your CSS.
The * that you said you dont understand is used to select every element within the whole page, so the bg-gray-600 as well. In this case, none of its values effect the centering of your form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75050511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why is Android emulator asking for Flash Player to be installed when it is already installed? I am trying to run a flex mobile application on the android emulator(2.3). The app. uses StageWebView to display a local HTML file. When run in android emulator, it asks for flash player to be downloaded. I have already installed Adobe AIR 3.0 and Flash Player 10.1 in my emulator. Why does it ask for a Flash Player to be installed??
A: my guess is because its emulating. so either a. it needs flash installed in the emulator or b. it cannot access flash
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7884345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to define an environment variable by Python and use it in OS? I'm trying to create an environment variable in Ubuntu by Python.
Here is what I've done so far:
import os
os.environ['NEW_ENV_VAR'] = '1'
print(os.environ['NEW_ENV_VAR'])
Out:
1
Apparently, I can write and read this variable on this same code, but I couldn't read it on its OS or another code:
$ echo $NEW_ENV_VAR
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58248819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In what scenario would Classpath of a java project will be different from its Buildpath? Was just looking at Buildpath and Classpath for my Java project in Eclipse. I noticed all jars included in my project's buildpath are automatically included its classpath.
It makes sense why Eclipse does that. I mean , If I need to instantiate an external class in my code then I need those classes in by buildpath for the code to compile. And at runtime i need those very same classes loaded into the jvm too.
It then looks like all classes included in the buildpath are needed in classpath. Although I cannot think of a case where a project's classpath will be different from its buildpath .
Is the above understanding accurate ? Could you give me a scenario where classpath will have additional classes than those in the buildpath ?
A: There are many situations where classes are only needed at runtime, not compile time. One of the most typical is JDBC drivers; code is written/compiled against the JDBC API, but at runtime a driver class must be available on the classpath. There are any number of other examples, especially when you get into various frameworks that have a standard API and differing implementations that can be "injected" at runtime.
A: A very common example is classes that implement some API, such as the Servlet API. Each container (Tomcat, Jetty, WebSphere) supplies classes that the Web application usually knows nothing about, since it just uses the interfaces.
More broadly, this pattern is used in the Service Provider Interface to enable plugins that implement an interface to be added at runtime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26537360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Evenly spacing text and an icon within a snackbar So I'm super new to all this (read: this is the first task I've ever been given), and I'm trying to style an icon and some text in a snackbar so that they're evenly spaced and properly aligned.
<SnackbarContent
message={
<div>
<i className='ri-checkbox-fill' />
{general.snackMessage}
</div>
}
style={{
backgroundColor: snackColor,
width: '100%',
justifyContent: 'right',
display: 'flex',
}}
/>
The code above gives me this. I know I'm missing something super easy, but again as I've just started learning I don't even know where to begin on trying to get this working. Flex is treating them both as a single entity right now, and I've tried fragments, nested divs, etc to try and separate them out. Any help would be greatly appreciated!
A: You need to apply style to the div, not to the SnackbarContent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71928695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unlikely argument type for equals(): String seems to be unrelated to MemberSearchRequest Hi I just want to implement this error message but it seems like it is not being processed. My goal here is to make the error message appear when either of the three requests (generatedMemberNo, firstname, lastname) have no results. Here is my code:
public String searchMember(
@RequestBody(required = false) MemberSearchRequest request,
@RequestParam(value = "offset", required = false) @ApiParam(value = "offset") final Integer offset,
@RequestParam(value = "limit", required = false) @ApiParam(value = "limit") final Integer limit,
@RequestParam(value = "orderBy", required = false) @ApiParam(value = "orderBy") final String orderBy,
@RequestParam(value = "sortOrder", required = false) @ApiParam(value = "sortOrder") final String sortOrder) {
CommandProcessingResult result = null;
if(request.equals("generatedMemberNo") && this.clientRepository.getClientByMemberNo(String.valueOf(request.getGeneratedMemberNo())) == null ||
request.equals("firstname") && this.clientRepository.getClientByFirstName(String.valueOf(request.getFirstname())) == null ||
request.equals("lastname") && this.clientRepository.getClientByLastName(String.valueOf(request.getLastname())) == null) {
result = new CommandProcessingResultBuilder()
.setStatus("Failed")
.setMessage("MEMBER NOT FOUND")
.setRefNo("<YYYY-MM-DD-H-M-S-Count>")
.setPfsRefNo("1234567890")
.build();
return this.toApiJsonSerializer.serialize(result);
}
return this.searchMember(request.getGeneratedMemberNo(), request.getFirstname(), request.getLastname(),
offset, limit, orderBy, sortOrder);
}
And this is my code for MemberSearchRequest.java
@Data
public class MemberSearchRequest {
public String generatedMemberNo;
public String firstname;
public String lastname;
}
A: Your MemberSearchRequest isn't a String so the first parts of your compound if statement will never be true.
request.equals("generatedMemberNo") &&
request.equals("firstname") &&
request.equals("firstname") &&
It appears that you could remove them and the null checks would be met.
if(this.clientRepository.getClientByMemberNo(String.valueOf(request.getGeneratedMemberNo())) == null ||
this.clientRepository.getClientByFirstName(String.valueOf(request.getFirstname())) == null ||
this.clientRepository.getClientByLastName(String.valueOf(request.getLastname())) == null)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63047844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ImageMagick multiple operations in single invocation - round corner ImageMagick multiple operations in single invocation
Hello. I am not good at English.
I'd appreciate it if you understand.
I created a Mask Image.
convert -size 600x735 xc:none -draw "roundrectangle 0,0,600,735,45,45" mask.png
Create rounded edges for multiple files.
I'd like to make a single combined(joined) file.
convert in.png -matte mask.png -compose DstIn -composite after1.png
convert in2.png -matte mask.png -compose DstIn -composite after2.png
convert in3.png -matte mask.png -compose DstIn -composite after3.png
convert after1.png after2.png after3.png -append result.png
Can I do the above process at once?
I'd like to cut it down with one or two lines of command.
A: If you already created the mask, you may be able to simplify the rest of it into one command like this...
convert in.png in2.png in3.png null: ^
-matte mask.png -compose dstin -layers composite +append result.png
That would read in the three input images and do the mask composite on each of them all at the same time. Then it appends the three results into a single file for the output.
A: This will do what you ask in Imagemagick using parenthesis processing
Unix syntax:
convert \
\( in.png -matte mask.png -compose DstIn -composite \) \
\( in2.png -matte mask.png -compose DstIn -composite \) \
\( in1.png -matte mask.png -compose DstIn -composite \) \
-append result.png
Windows syntax:
convert ^
( in.png -matte mask.png -compose DstIn -composite ) ^
( in2.png -matte mask.png -compose DstIn -composite ) ^
( in1.png -matte mask.png -compose DstIn -composite ) ^
-append result.png
I note that you have in1.png in the third convert. Did you mean in3.png?
Please always identify your Imagemagick version and platform/OS, since syntax differs.
A: This may be of interest for those wanting to make rounded corners with Imagemagick. Unix syntax.
Input:
Imagemagick 6
Rounded Corners:
convert thumbnail.gif \( +clone -alpha extract \
\( -size 15x15 xc:black -draw 'fill white circle 15,15 15,0' -write mpr:arc +delete \) \
\( mpr:arc \) -gravity northwest -composite \
\( mpr:arc -flip \) -gravity southwest -composite \
\( mpr:arc -flop \) -gravity northeast -composite \
\( mpr:arc -rotate 180 \) -gravity southeast -composite \) \
-alpha off -compose CopyOpacity -composite thumbnail_rounded.png
Rounded Corners With Shadow:
convert thumbnail.gif \( +clone -alpha extract \
\( -size 15x15 xc:black -draw 'fill white circle 15,15 15,0' -write mpr:arc +delete \) \
\( mpr:arc \) -gravity northwest -composite \
\( mpr:arc -flip \) -gravity southwest -composite \
\( mpr:arc -flop \) -gravity northeast -composite \
\( mpr:arc -rotate 180 \) -gravity southeast -composite \) \
-alpha off -compose CopyOpacity -composite -compose over \
\( +clone -background black -shadow 80x3+5+5 \) \
+swap -background none -layers merge thumbnail_rounded_shadow.png
Imagemagick 7
Rounded Corners:
magick thumbnail.gif \
\( +clone -fill black -colorize 100 -fill white -draw 'roundrectangle 0,0 %w,%h 15,15' \) \
-alpha off -compose CopyOpacity -composite thumbnail_rounded2.png
Rounded Corners With Shadow:
magick thumbnail.gif \
\( +clone -fill black -colorize 100 -fill white -draw 'roundrectangle 0,0 %w,%h 15,15' \) \
-alpha off -compose CopyOpacity -composite -compose over \
\( +clone -background black -shadow 80x3+5+5 \) \
+swap -background none -layers merge thumbnail_rounded_shadow2.png
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58585556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a text area, that will have multiple lines of text I have a text area, that will have multiple lines of text and I need the output to keep all formatting as it is typed in to the text area. How can this be done? Here is how I am creating the text area:
<table border="0" cellpadding="5" cellspacing="5" width="95%">
<tr>
<td colspan="2">
<b>Status: </b>
<textarea name="Text2" id="styled"></textarea>
</td>
</tr>
</table>
A: It is not possible to maintain the format of the text in <textarea> as you requested.
You can achieve maintaining new lines (basically text is wrapped), if some exists in the text.
You have to use "wrap=Hard".
https://www.w3schools.com/tags/att_textarea_wrap.asp
Also refer stackoverflow answers, which has more explanation (look into comments also) about retaining format from text in <textarea>
HTML : How to retain formatting in textarea?
how to preserve formatting of html textarea
A: I was able to figure out how to do it by exporting the text area to a text file, appending the data, then import it back in using
fso.OpenTextFile("C:\file.txt",ForReading).ReadAll and formatting it using
( html body pre )
Doing it that way I was able to hold my line breaks then I send the information using CDO.Message.
Const FOR_APPENDING = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTSO = objFSO.OpenTextFile("C:File.txt", FOR_APPENDING)
objTSO.WriteLine strDT & ":" & vbCrLf & Text2.value & vbCrLf
objTSO.Close()
Sub SendEmail(strSubject, strBody, strBody8, strFrom)
Const ForReading = 1
Dim fso, BodyText
Set fso = CreateObject("Scripting.FileSystemObject")
strMailbox = "Address<[email protected]>"
' E-Mail address being sent to
strSMTPServer = "SMTP Server"
' Primary SMTP relay server name
strSMTPPort = 25
' SMTP Port Number
Set objEmail = CreateObject( "CDO.Message" )
BodyText = fso.OpenTextFile("C:\file.txt",ForReading).ReadAll
With objEmail
.From = strFrom
.To = strMailbox
.Subject = strSubject
.HTMLBody = "<html><body><pre>" & strBody & "<BR>" & BodyText & "<BR>" &
strBody8 & "</pre></body></html>"
With .Configuration.Fields
.Item( "http://schemas.microsoft.com/cdo/configuration/sendusing" ) = 2
.Item( "http://schemas.microsoft.com/cdo/configuration/smtpserver" ) =
strSMTPServer
.Item( "http://schemas.microsoft.com/cdo/configuration/smtpserverport" ) =
strSMTPPort
.Update
End With
.Send ' Send the message!
End With
Set objEmail = Nothing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43217943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Button click to show overlay over image (only CSS) I am trying to achieve that when you click the yellow circle with fa-icon inside that then the overlay shows over my image. Now the overlay shows below the image (green background with white text). My overlay code works, to see that, change div id="overlay" to div class="overlay".
How to make the button click show my overlay over the image (no javascript)?
/*@media screen and (max-width: 767px) {*/
.button i {
padding: 8px 13px;
display: inline-block;
-moz-border-radius: 180px;
-webkit-border-radius: 180px;
border-radius: 180px;
-moz-box-shadow: 0px 0px 2px #888;
-webkit-box-shadow: 0px 0px 2px #888;
box-shadow: 0px 0px 2px #888;
background-color: yellow;
color: red;
position: absolute;
left: 20%;
top: 20%;
}
/*}*/
.button i:hover {
color:#FFF;
background-color:#000;
}
/*@media screen and (min-width: 768px) {*/
.product-detailscar:hover .overlay {
opacity: 1;
}
/*}*/
.product-detailscar {
background-color: #E6E6E6;
text-align: center;
position: relative;
}
.intro, .userfield1car {
color:#fff;
font-weight:700;
font-size:22px;
text-align:center;
background-color:green;
}
.product-detailscar .overlay {
/*.well.carousel .overlay {*/
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
border-radius: 0;
background: blue;
color: #FFF;
text-align: left;
border-top: 1px solid #A10000;
border-bottom: 1px solid #A10000;
/*vertical-align: middle;*/
-webkit-transition: opacity 500ms;
-moz-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<div>
<a href="#" target="_blank">
<div class="product-detailscar">
<div class="image-video-linksidebar">
<img alt="#" src="http://lorempixel.com/200/200">
<div class="read-more"><a href="#overlay" class="button"><i class="fa fa-file-text-o fa-3x" aria-hidden="true"></i></a>
</div>
</div>
<div id="overlay">
<div class="intro">
Intro description car
</div>
<div class="userfield1car">
Userfield-1-car
</div>
<div class="userfield1car">
Userfield-2-car
</div>
<div class="userfield1car">
Userfield-3-car
</div>
</div>
</div>
<!--</div>--></a>
</div>
A: You can add the following part to your CSS:
#overlay {
display: none;
}
#overlay:target {
display: block;
}
And then in your code change:
.product-detailscar .overlay
To:
#overlay
And change opacity to more then 0, ex. 0.5;
Note that it will only work one way, so it will only show the overlay. If you want to show/hide overlay in pure CSS, the checkbox hack is the way to go. For more info check https://css-tricks.com/the-checkbox-hack/
Updated example (no checkbox hack):
.button i {
padding: 8px 13px;
display: inline-block;
-moz-border-radius: 180px;
-webkit-border-radius: 180px;
border-radius: 180px;
-moz-box-shadow: 0px 0px 2px #888;
-webkit-box-shadow: 0px 0px 2px #888;
box-shadow: 0px 0px 2px #888;
background-color: yellow;
color: red;
position: absolute;
left: 20%;
top: 20%;
}
.button i:hover {
color:#FFF;
background-color:#000;
}
.product-detailscar:hover .overlay {
opacity: 1;
}
.product-detailscar {
background-color: #E6E6E6;
text-align: center;
position: relative;
}
.intro, .userfield1car {
color:#fff;
font-weight:700;
font-size:22px;
text-align:center;
background-color:green;
}
#overlay {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0.5;
border-radius: 0;
background: blue;
color: #FFF;
text-align: left;
border-top: 1px solid #A10000;
border-bottom: 1px solid #A10000;
-webkit-transition: opacity 500ms;
-moz-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
}
#overlay:target {
display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<div>
<a href="#" target="_blank">
<div class="product-detailscar">
<div class="image-video-linksidebar">
<img alt="#" src="http://lorempixel.com/200/200">
<div class="read-more"><a href="#overlay" class="button"><i class="fa fa-file-text-o fa-3x" aria-hidden="true"></i></a>
</div>
</div>
<div id="overlay">
<div class="intro">
Intro description car
</div>
<div class="userfield1car">
Userfield-1-car
</div>
<div class="userfield1car">
Userfield-2-car
</div>
<div class="userfield1car">
Userfield-3-car
</div>
</div>
</div>
<!--</div>--></a>
</div>
BTW, it is a good idea to clean up your code ;)
A: You can move the overlay div just beneath the image-video-linkssidebar class like this:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<div>
<a href="#" target="_blank">
<div class="product-detailscar">
<div class="image-video-linksidebar">
<div id="overlay">
<div class="intro">
Intro description car
</div>
<div class="userfield1car">
Userfield-1-car
</div>
<div class="userfield1car">
Userfield-2-car
</div>
<div class="userfield1car">
Userfield-3-car
</div>
</div>
<img alt="#" src="http://lorempixel.com/200/200">
<div class="read-more"><a href="#overlay" class="button"><i class="fa fa-file-text-o fa-3x" aria-hidden="true"></i></a>
</div>
</div>
</div>
<!--</div>--></a>
</div>
Then add these styles to overlay:
position: absolute;
z-index: 9999;
margin: 0 auto;
width: 100%;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39557492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Way to show texerror in MathJax I'm using cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full
When MathJax tries to render $$2^2^x$$, it shows 2^2^x instead of error "Double exponent: use braces to clarify"
What configuration should I use in order to show the error?
A: Use
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
noErrors: {disabled: true}
}
});
</script>
just before the script that loads MathJax.js itself. That will display the error messages instead of the original TeX code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59215534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: is it possible to search all Redshift procedures for text? I am dropping old tables from Redshift. Is it possible to search through all procedures to make sure a table is not referenced? It would be a lot easier than opening each one to search for text.
Thank you.
A: Consider using the unscanned_table_summary.sql query we provide on GitHub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61922822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Rest API method throws a 404 Not Found after publishing I am hosting my Backend on Google App Engine and the Rest API works well on localhost. The method url is as follows:
http://127.0.0.1:8888/rest/plans/getplans/242353
This works on local host and returns me a JSON response properly. It's a GET method and 242353 is the parameter I pass to the method.
But when I publish it to my Google Cloud, after I attempt to call it on my browser with the following URL:
http://2-dot-MY_APP_DOMAIN.appspot.com/rest/plans/getplans/242353
I get this error on my browser:
Error: Not Found
The requested URL /rest/plans/getplans/242353 was not found on this
server.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.dinukapj.socialapp.api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Why does this happen? Do I need to add any other information to my web.xml?
A: Try hitting /resources/plans/getplans/242353 as defined in your web.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36300374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot Apply toDateString() to Date in JS I am running into a problem I'm trying to understand. I am simply trying to convert a date into a more reader-friendly format by using toDateString(). However, in doing so I am getting a "toDateString() is not a function" error.
I can do this, using toString():
truncateDate() {
if (this.employee && this.employee.dob)
{
let birthDate = this.employee.dob;
console.log(birthDate); // 2011-06-12T05:00:00.000Z Prints to console
console.log(birthDate.toString());
}
}
But I cannot do toDateString():
truncateDate() {
if (this.employee && this.employee.dob)
{
let birthDate = this.employee.dob;
console.log(birthDate); // 2011-06-12T05:00:00.000Z Prints to console
console.log(birthDate.toDateString());
}
}
What am I missing here?
A: Convert the string to Date Object then you will be able to use that function.
Here is MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
this.employee={}
this.employee.dob='1/2/2018'
let birthDate = this.employee.dob;
console.log(birthDate);
console.log(new Date(birthDate).toDateString());
//
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48101949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Morris Donut Chart label is showing undefined error I am using Morris Donut chart to display the progress. I am getting the count of status correctly. But instead of Label it is showing undefined in the donut chart.
Morris Donut Chart Showing Undefined Error as Label
var dtData = _.groupBy(jsonData, "status");
var keys = [];
keys = Object.keys(dtData);
dtArr = [];
for (var n = 0; n < keys.length; n++) {
dtArr.push({
name: '' + keys[n] + '', value: '' + dtData[keys[n]].length + '',
});
}
Morris.Donut({ element: 'dashboard-donut-8',
data: dtArr,
label: 'name',
value: 'value',
colors: ['#33414E', '#E04B4A', '#1caf9a', '#95b75d'],
resize: true });
I am getting the value correctly. But getting as undefined for label.
Please help me on this
Thank You
A: You should use the key label instead of name
label: '' + keys[n] + '', value: '' + dtData[keys[n]].length + '',
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55195777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Shuffling multiple arrays in $.each() I am generating a hyperlink inside a para in the following way:
<p id="category1"></p>
jQuery Code:
$(function () {
var link = [
["category1", "http://www.xyzabcxyz.com/apple", "Apple description comes here"],
["category2", "http://www.xyzabcxyz.com/banana", "Banana description comes here"],
["category3", "http://www.xyzabcxyz.com/apricots", "Apricots description comes here"],
["category4", "http://www.xyzabcxyz.com/peaches", "Peaches description comes here"]
];
$.each(link, function (e) {
if ($("#" + link[e][0])[0]) {
$("#" + link[e][0]).append('<a target="_blank" href="' + link[e][1] +
'">' + link[e][2] + '</a>');
}
});
});
Demo: http://jsfiddle.net/j2g411yk/
So far so good. Everything works.
I was wondering how to change my code so that it randomnly shuffles multiple products inside a category. Something like this:
$(function () {
var link = [
[["category1", "http://www.xyzabcxyz.com/apple", "Apple description comes here"],
"http://www.xyzabcxyz.com/pineapple", "Pineapple description comes here"],
"http://www.xyzabcxyz.com/lemon", "Lemon description comes here"]],
["category2", "http://www.xyzabcxyz.com/banana", "Banana description comes here"],
[["category3", "http://www.xyzabcxyz.com/apricots", "Apricots description comes here"],
"http://www.xyzabcxyz.com/Berries", "Berries description comes here"]]
["category4", "http://www.xyzabcxyz.com/peaches", "Peaches description comes here"]
];
$.each(link, function (e) {
if ($("#" + link[e][0])[0]) {
$("#" + link[e][0]).append('<a target="_blank" href="' + link[e][1] +
'">' + link[e][2] + '</a>');
}
});
});
So for one user it may show a hyperlink about Apple and for the other, it may be a hyperlink for Lemon. If the same visitor refreshes the page, a new product for the same cateogory should get displayed.
P.S: I want a random link but not to the extent where I have to use a cookie to keep a track if Visitor A has seen that link. It can be possible that the same user sees the same product twice on refresh and that's perfectly ok.
A: You can use math.random() to get a random link from the category array, and use a cookie or localStorage to keep track of which links have already been seen.
A: Try this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type='text/javascript' src='js/jquery.min.js'></script>
</head>
<body>
<p id="category1"></p>
<p id="category4"></p>
<script>
function getRandomInt (min, max) {
if (max == 0) return 0;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(function () {
var link = [
["category1", [[ "http://www.xyzabcxyz.com/apple", "Apple description comes here"],
["http://www.xyzabcxyz.com/pineapple", "Pineapple description comes here"],
["http://www.xyzabcxyz.com/lemon", "Lemon description comes here"]]],
["category2", [["http://www.xyzabcxyz.com/banana", "Banana description comes here"]]],
["category3", [["http://www.xyzabcxyz.com/apricots", "Apricots description comes here"],
["http://www.xyzabcxyz.com/Berries", "Berries description comes here"]]],
["category4", [["http://www.xyzabcxyz.com/peaches", "Peaches description comes here"]]]
];
$.each(link, function (e,v) {
if ($("#" + v[0]).length) {
var min = 0;
var max = (v[1].length)-1;
var i = getRandomInt(min,max);
$("#" + v[0]).append('<a target="_blank" href="' + v[1][i][0] +'">' + v[1][i][1] + '</a>');
}
});
});
</script>
</body>
For the random function tks. to
Javascript: Generate a random number within a range using crypto.getRandomValues
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32586402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is the python "elif" compiled differently from else: if? I know in languages such as C, C++, Java and C#, (C# example)the else if statement is syntactic sugar, in that it's really just a one else statement followed by an if statement.
else if (conition(s)) { ...
is equal to
else {
if (condition(s)) { ...
}
However, in python, there is a special elif statement. I've been wondering if this is just shorthand for developers or if there is some hidden optimization python can do because of this, such as be interpreted faster? But this wouldn't make sense to me, as other languages would be doing it too then (such as JavaScript). So, my question is, in python is the elif statement just shorthand for the developers to use or is there something hidden that it gains through doing so?
A: The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation.Source
A: When you really want to know what is going on behind the scenes in the interpreter, you can use the dis module. In this case:
>>> def f1():
... if a:
... b = 1
... elif aa:
... b = 2
...
>>> def f2():
... if a:
... b = 1
... else:
... if aa:
... b = 2
...
>>> dis.dis(f1)
2 0 LOAD_GLOBAL 0 (a)
3 POP_JUMP_IF_FALSE 15
3 6 LOAD_CONST 1 (1)
9 STORE_FAST 0 (b)
12 JUMP_FORWARD 15 (to 30)
4 >> 15 LOAD_GLOBAL 1 (aa)
18 POP_JUMP_IF_FALSE 30
5 21 LOAD_CONST 2 (2)
24 STORE_FAST 0 (b)
27 JUMP_FORWARD 0 (to 30)
>> 30 LOAD_CONST 0 (None)
33 RETURN_VALUE
>>> dis.dis(f2)
2 0 LOAD_GLOBAL 0 (a)
3 POP_JUMP_IF_FALSE 15
3 6 LOAD_CONST 1 (1)
9 STORE_FAST 0 (b)
12 JUMP_FORWARD 15 (to 30)
5 >> 15 LOAD_GLOBAL 1 (aa)
18 POP_JUMP_IF_FALSE 30
6 21 LOAD_CONST 2 (2)
24 STORE_FAST 0 (b)
27 JUMP_FORWARD 0 (to 30)
>> 30 LOAD_CONST 0 (None)
33 RETURN_VALUE
It looks like our two functions are using the same bytecode -- So apparently they're equivalent.
Careful though, bytecode is an implementation detail of CPython -- There's no telling that all python implementations do the same thing behind the scenes -- All that matters is that they have the same behavior. Working through the logic, you can convince yourself that f1 and f2 should do the same thing regardless of whether the underlying implementation treats it as "syntatic sugar" or if there is something more sophisticated going on.
A: elif in Python is syntactic sugar for else if seen in many other languages. That's all.
A: The three following code snippets would all execute using the same logic however all use different syntax.
elif condition: ...
else if conition { ...
else {
if conition { ...
}
Python's elif is just syntactic sugar for the common else if statement
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34304936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: UIButton with UIImageView subview to show animated images I'm trying to create a button which displays animated images. I read in this post the suggestion that I add an UIImageView (with an array of animationImages) as a subview of the UIButton. I tried to do this like so:
(animation1 is a UIImageView object declared in the header)
- (void)viewDidLoad {
UIImage *image1 = [UIImage imageNamed:@"Good1.png"];
UIImage *image2 = [UIImage imageNamed:@"Good2.png"];
UIImage *image3 = [UIImage imageNamed:@"Bad1.png"];
NSArray *images = [[NSArray alloc] initWithObjects:image1, image2, image3, nil];
animation1.animationImages = images;
[images release];
[self.button1 addSubview:animation1];
[self.button1 bringSubviewToFront:animation1];
[button1 setNeedsDisplay];
animation1.animationDuration = 1;
animation1.animationRepeatCount = 3;
[animation1 startAnimating];
[super viewDidLoad];
}
But nothing appears within the button. Any ideas where I might be going wrong?
Also, I would like it so that different methods are called depending on which image is showing when the user presses the button. I achieved this previously but creating an array of images, using an NSTimer to set the background image of the UIButton to cycle to through these images, and then comparing the image data of the button when pressed to the images in the array, calling a different method for each. This really doesn't seem very efficient! Hence why I'm trying to cycle the images in a subview. Any suggestions of how I might extract imagedata from the UIImageView subview of the UIButton when the button is pressed would be most appreciated :)
Thanks!
Michael
A: This is pure speculation, but sometimes you need to set a frame explicitly. (e.g. when adding a custom button to a UIBarButtonItem) Try adding a line
animation1.frame = CGRectMake(0,0,50,50);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3371932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AUC and Cross validation I have a question regarding AUC and cross validation accuracy.
Is that possible to have higher accuracy for AUC than cross validation?
My cross validation accuracy with random forest estimator is 80% but the AUC is 98%.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49909480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check attribute in SQL Server 2012 using regular expressions? I need to insert an equipment model code, is a string formatted as:
AAA-0123456
It has to be, 3 uppercase letters, the "-" in the middle and 6 numbers,
I need to have a constraint check (model code like regular expression) I think.
How can I do this?
A: You would do this via a check constraint, see here: http://www.w3schools.com/sql/sql_check.asp
Yes you can put regex in a check constraint, here is an example:
CREATE TABLE dbo.PEOPLE (
name VARCHAR(25) NOT NULL
, emailaddress VARCHAR(255) NOT NULL
, CONSTRAINT PEOPLE_ck_validemailaddress CHECK ( dbo.RegExValidate( emailaddress, N'^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$' ) = 1 )
)
Your regular expression would be: [A-Z][A-Z][A-Z][-][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
Here is a great tool to build and test reg expr http://www.regexr.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30667196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deploy Neo4j on Rails I've been developing my rails application using the gem neo4j.
When I run the server it executes an embedded neo4j server.
In production, is it ok to use this embedded server?
How can I can connect my rails application with with the standalone neo4j server?
A: It seems like you can use the gem neography to achieve this. Just set it up with the ip of your standalone server and you should be good to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13951641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Testing Java class using JUnit public void printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
}
My method to test:
@Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
//Patient Patient_child=new Patient("Kate",4,1.90,70.0,"Leicester");
// Patient Patient_elderly=new Patient("Bill",124,1.90,70.0,"Leicester");
surgery_N.findPatient("Ted");
patient_adult.printPatientSummary();
assertEquals("Ted", patient_adult.getName());
assertEquals("-----------PATIENT SUMMARY: ---------"+"\n"+"NAME: "+patient_adult.name+"\n"+"Age: "+patient_adult.getAge()+"\n"+"Address: "+patient_adult.getAddress()+"\n"+"Height: "+patient_adult.getHeight()+"\n"+"Weight: "+patient_adult.getWeight()+"\n"+"------------------------------"+separator,ans.toString());
patient_adult.computeBMI();
assertEquals(19.390581717451525, patient_adult.computeBMI(), 0.0);
}`
The problem is that the way I use to test doesn't cover the original file at all. Hope I can get some help from you guys.
A: You could assign a different writer to System.out (assuming that's where your output goes) and inspect what gets written there. In general, you probably want to make the writer a parameter of printSummary or inject it into the class somehow.
A: So basically you want to do this:
@Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
surgery_N.printSummaryForPatient("Ted");
}
But can't do any asserts, because the Patient is not returned.
Do you want to return the patient?:
public Patient printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
return p;
}
After that you could use your assertions. It seems more like a conceptual problem of how you organize your methods.
You have methods in printSummaryForPatient, that don't seem to do anything. Their return value is not returned or saved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8183072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Php imploding array then making separated strings Fairly new to php scene and this is giving me headache.
So I am doing api call (twitch.tv) and I want to get preview links, there are 3 different links, that end with .jpg. Now problem is its stored as array and I need to break it into strings.
I have tried
$preview = $json_array['stream']['preview'];
$foo = implode(",",$preview);
echo $foo;
$foo prints out http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-80x50.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-320x200.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-640x400.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-{width}x{height}.jpg
now, how do I go about joining those characters into string, so I can be able to display image.
A: You should not join your array at all. In your example $json_array['stream']['preview']; is the following:
array(
'small' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-80x50.jpg',
'medium' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-320x200.jpg',
'large' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-640x400.jpg',
'template' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-{width}x{height}.jpg'
);
So you can use either one of the provided images:
*
*$json_array['stream']['preview']['small']
*$json_array['stream']['preview']['medium']
*$json_array['stream']['preview']['large']
If none of the images fit your desired resolution you can use the template:
echo str_replace("{width}", $width, str_replace("{height}", $height,"Hello world!"));
A: In joining the array in to a string you wont have a link for an image, you will have 3 links joined together. Use;
$json_array['stream']['preview'][0]
and change the 0 for which of the images you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25388337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: There is a Cell bothering me in a LibGDX Window I think I might have found an issue in LibGDX, but before opening an issue in their GitHub, I thought it would be better to discuss it here because maybe I am wrong.
This is what is happening to me:
I have a class named Information extending Window, where I show the information about the characters of my game. Since I need to update the labels dynamically, I thought it would be better to simply remove all the actors inside the Window each time I call setVisible(false). It worked before. So this is my code:
public class Information extends Window {
private final static String TAG = Information.class.getName();
private Unit calledBy; //Variable to know who is calling
public Information (Skin skin) {
//Setting the attributes
super("Information", skin);
this.setPosition(0, 0);
this.setBounds(this.getX(), this.getY(), Constants.INFORMATION_WIDTH, Constants.INFORMATION_HEIGHT);
this.setVisible(false);
}
@Override
public void setVisible(boolean visible) {
if (!visible){
SnapshotArray<Actor> actors = this.getChildren();
while (actors.size > 0){
actors.get(0).remove();
}
} else {
this.add(new Label("Name: " + getCalledBy().getName(), getSkin()));
this.row();
this.add(new Label("Attack: " + getCalledBy().getAttack(), getSkin()));
this.row();
this.add(new Label("Defense: " + getCalledBy().getDefense(), getSkin()));
this.row();
this.add(new Label("Health: " + getCalledBy().getHealth(), getSkin()));
}
super.setVisible(visible);
}
So, every time I call setVisible, I create or erase the actors. The thing is that the first time I call the method, it is working perfectly, but the second and successive times, it appears a Cell with no info besides the Name of the character.
I debugged the creation of the Actors and the deletion of the same and all seems to be working perfectly.
So I was about to open an issue in LibGDX's GitHub, but if someone knows why this is happening to me, I will prefer it.
Thanks in advance!
A: Ok! So I am responding my own question in case someone needs it.
Thanks to Tenfour04 for his comment, since it helped me to find it.
The correct method to call was clearChildren(). This is my new code:
public void setVisible(boolean visible) {
if (!visible){
this.clearChildren();
} else {
this.add(new Label("Name: " + getCalledBy().getName(), getSkin()));
this.row();
this.add(new Label("Attack: " + getCalledBy().getAttack(), getSkin()));
this.row();
this.add(new Label("Defense: " + getCalledBy().getDefense(), getSkin()));
this.row();
this.add(new Label("Health: " + getCalledBy().getHealth(), getSkin()));
}
super.setVisible(visible);
}
Hope this helps someone else in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49475113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: httpie TLS version error On Mac, I'm using httpie for testing REST API. After enabling HTTPs on my server, which only supports TLS 1.2, I started to have the following error:
http: error: SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)
If I'm to guess, I'd say httpie is trying to use an older version of TLS. Anybody seen this one before? How to resolve it?
On my PC running Ubuntu MATE, it works without hassle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34069673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Passing a jQuery load() function variable to codeigniter controller is there a way to pass a variable to a codeigniter controller using jquery's load() function?
currently this is my non working code
main.php
<input type="hidden" id="url" name="url" value="<?php echo base_url();?>site/pax_dropdown/" />
<input type="hidden" val="2" id="value">
<ul id="result" class="dropdown-menu">
<?php $this->load->view("site/pax_dropdown"); ?>
</ul>
pax_dropdown.php
<li><a href="">3</a></li>
<li><a href="">4</a></li>
<li><a href="">5</a></li>
<li><a href="">6</a></li>
<li><a href="">7</a></li>
<li><a href="">8</a></li>
<li><a href="">9</a></li>
<?php
echo $id;
?>
script.js
var url = $("#url").val();
var val = $("#value").val();
$('#result').load(url,val);
controller
public function pax_dropdown($id)
{
$data['id'] = $id;
$this->load->vars($data);
$this->load->view("site/pax_dropdown");
}
with this code the pax_dropdown.php successfully loads inside the
<ul id="result">
in my main.php however my test variable $id cannot be found and says Message: Undefined variable: id
am i doing something wrong?
by the way i also tried sending the variable to the controller this way:
main
<input type="hidden" id="url" name="url" value="<?php echo base_url();?>site/pax_dropdown/2" />
i placed the variable to be passed at the end of the url, which in this case is "2"
and it still did not work
A: Look at this example to pass a variable using jQuery.load() :
var siteName='example.com';
$("#result").load(sitename+"/site/pax_dropdown/2", {"variableName": variable});
A: Try this:
$(function(){
var url = $("#url").val();
var val = $("#value").val();
$("#result").load(url, {id: val});
});
function pax_dropdown()
{
$data['id'] = $this->input->post('id');
$this->load->vars($data);
$this->load->view("site/pax_dropdown");
}
And
<ul id="result" class="dropdown-menu">
<?php //$this->load->view("site/pax_dropdown"); comment out this line ?>
</ul>
A: Don't you have a default ID? If so, set this to the $id. If you don't want any default number, just wrap it into an if statement (if (isset($id)) and don't use the $id if it isn't set and logically shouldn't be set.
Maybe the logic behind the code would help as well for finding a solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18717435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is My jQuery Plugin Template Faulty i fetched a jQuery template and did some trimming. But on init function -as you can see- on line 46, element's CSS should be changed. But nothing happens. Here is my plugin code; http://pastebin.com/raw.php?i=7gQ9jS03
Thanks in advance.
Edit: index.js of the page is;
$(function() {
$("#asd").Loading();
});
and the html is;
<html>
<head>
...
</head>
<body>
...
<div id="asd"></div>
...
</body>
</html>
A: It should be $(this.element).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16921469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Manually sign SOAP message Java I have to sign a Soap message using java, but I can't use WSS4J, SAAJ, AXIS2 or CXF for classpath problems on my websphere server.
I have to sign the body message of the SOAP call.
I generate a XML with body inside body data correctly for the soap message and look like this:
<SERVICE_DISPATCHER_REQUEST xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN"><ns2:SERVICIO_CONSIGNACION_NOTARIAL><ns2:REQUEST><ns2:CABECERA><ns2:ID_COMUNICACION>2147483647</ns2:ID_COMUNICACION><ns2:FECHA>2016-03-22</ns2:FECHA><ns2:HORA>10:55:00</ns2:HORA><ns2:TIPO_OPERACION>TRANSFERENCIA</ns2:TIPO_OPERACION></ns2:CABECERA><ns2:MENSAJE><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>1.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>2.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA></ns2:MENSAJE></ns2:REQUEST>
Formated for best view:
<SERVICE_DISPATCHER_REQUEST xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN">
<ns2:SERVICIO_CONSIGNACION_NOTARIAL>
<ns2:REQUEST>
<ns2:CABECERA>
<ns2:ID_COMUNICACION>2147483647</ns2:ID_COMUNICACION>
<ns2:FECHA>2016-03-22</ns2:FECHA>
<ns2:HORA>10:55:00</ns2:HORA>
<ns2:TIPO_OPERACION>TRANSFERENCIA</ns2:TIPO_OPERACION>
</ns2:CABECERA>
<ns2:MENSAJE>
<ns2:TRANSFERENCIA>
<ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO>
<ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA>
<ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION>
<ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR>
<ns2:NOTARIO>
<ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES>
<ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION>
<ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION>
</ns2:NOTARIO><ns2:IMPORTE>1.00</ns2:IMPORTE>
<ns2:MONEDA>EUR</ns2:MONEDA>
<ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE>
<ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO>
</ns2:TRANSFERENCIA>
<ns2:TRANSFERENCIA>
<ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO>
<ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA>
<ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION>
<ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR>
<ns2:NOTARIO>
<ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES>
<ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION>
<ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION>
</ns2:NOTARIO>
<ns2:IMPORTE>2.00</ns2:IMPORTE>
<ns2:MONEDA>EUR</ns2:MONEDA>
<ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE>
<ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO>
</ns2:TRANSFERENCIA>
</ns2:MENSAJE>
</ns2:REQUEST>
</ns2:SERVICIO_CONSIGNACION_NOTARIAL>
Then I do the Hash value to create the digest value using the previous XML with body start and end tag:
// Change value if there is any problem on websphere
// wsuId = "\"#MsgBody\"";
wsuId = "\"#id-" + UUIDGenerator.getUUID() + "\"";
// Create XML data for body SOAP
String dataXMLSoap = generateBodySoap(doc);
String startBodyHash = "<soapenv:Body xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" wsu:Id=" + wsuId+ ">";
String endBodyHash = "</soapenv:Body>";
MessageDigest messageDigestFromBody= MessageDigest.getInstance("SHA-1");
String xmlHash = startBodyHash + dataXMLSoap + endBodyHash;
byte[] hashSoapBody = messageDigestFromBody.digest(xmlHash.getBytes());
String digestValueFromBody = new BASE64Encoder().encode(hashSoapBody);
Example of XML hash:
<soapenv:Body xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" wsu:Id="#id-D1DD0227ECDC46640D147197713960845"><SERVICE_DISPATCHER_REQUEST xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN"><ns2:SERVICIO_CONSIGNACION_NOTARIAL><ns2:REQUEST><ns2:CABECERA><ns2:ID_COMUNICACION>2147483647</ns2:ID_COMUNICACION><ns2:FECHA>2016-03-22</ns2:FECHA><ns2:HORA>10:55:00</ns2:HORA><ns2:TIPO_OPERACION>TRANSFERENCIA</ns2:TIPO_OPERACION></ns2:CABECERA><ns2:MENSAJE><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>1.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>2.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA></ns2:MENSAJE></ns2:REQUEST></ns2:SERVICIO_CONSIGNACION_NOTARIAL></SERVICE_DISPATCHER_REQUEST></soapenv:Body>
With teh digest value generated I create a SignedInfo node:
String xmlDigestFromBody =
"<ds:SignedInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments\"></ds:CanonicalizationMethod>"
+ "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>"
+ "<ds:Reference URI=" + wsuId + ">"
+ "<ds:Transforms>"
+ "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\">"
+ "</ds:Transform>"
+ "</ds:Transforms>"
+ "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\">"
+ "</ds:DigestMethod>"
+ "<ds:DigestValue>"
+ digestValueFromBody
+ "</ds:DigestValue>"
+ "</ds:Reference>"
+ "</ds:SignedInfo>";
The xml for signature looks like this:
<ds:SignedInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><ds:Reference URI="#id-D1DD0227ECDC46640D147197713960845"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>Dd7cqOPVujwavDwKWwWqI8NHfYw=</ds:DigestValue></ds:Reference></ds:SignedInfo>
With this XML and my X509 Certificate info I use this method to get the sign value:
byte[] signDigest = sign(privateKey, xmlDigestFromBody, algorithm);
String signValueDigest = new BASE64Encoder().encode(signDigest);
// privateKey-> private key from X509 Certificate
// data -> Data to get signed
// algorith -> algorith for sign, in this case with value -> SHA1withRSA
private static byte[] sign(PrivateKey privateKey, String data, String algorithm) throws GeneralSecurityException
{
Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
signature.update(data.getBytes());
return signature.sign();
}
With all information generated I form the complete Soap message.
String signedSoap = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Header>"
+ "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" soap:mustUnderstand=\"1\">"
+ "<ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
+ xmlDigestCXFSoap
+ "<ds:SignatureValue>"
+ signValueDigest
+ "</ds:SignatureValue>"
+ "<ds:KeyInfo>" + "<wsse:SecurityTokenReference>"
+ "<wsse:KeyIdentifier EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\">"
+ wsseKeyIdentifier
+ "</wsse:KeyIdentifier>"
+ "</wsse:SecurityTokenReference>"
+ "</ds:KeyInfo>"
+ "</ds:Signature>"
+ "</wsse:Security>"
+ serviceDispatcher
+ "</soap:Header>"
+ "<soap:Body xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" wsu:Id=" + wsuId+ ">"
+ dataXMLSoap
+ "</soap:Body>"
+ "</soap:Envelope>";
Finally I get this Soap message:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1"><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#id-D1DD0227ECDC46640D147197713960845"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>Dd7cqOPVujwavDwKWwWqI8NHfYw=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>U4I0IFFDfpy32vTfpjLQkV10tGOG4XloOaPJPjymFIaV5tzxqd3bAiigghWgELA5WByZ/IqvCL08//BAq+G+ybYn0dwOS+JYZP5ftDow3ZCf5pQNp2DtSnLbLPjswAzcUvR1MfZHbkIhPWOd5fDIs+hPuRs0cq1owfrmXrik0uB48tq6X8bkrl68QMYOXtvi/MGmAIpyjUvXm91ex7YiHpvZG7Jfqn67sL1ca3mWt+14lHeidWZU7qVGCmL0OskIv4uzJO90BthUSlC2B2v+QBRfnL5mTZ+msSK6yI9jRhFazFNe/NG+obRLhns+1Fz/ETtcbdBs4WrLs78tZmcDnA==</ds:SignatureValue><ds:KeyInfo><wsse:SecurityTokenReference><wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">MIIHdDCCBVygAwIBAgIQDT8ExvuNzblitEznqcBn7jANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCRVMxQTA/BgNVBAoTOEFnZW5jaWEgTm90YXJpYWwgZGUgQ2VydGlmaWNhY2lvbiBTLkwuVS4gLSBDSUYgQjgzMzk1OTg4MS8wLQYDVQQDEyZBTkNFUlQgQ29ycG9yYXRpdm9zIGRlIFNpc3RlbWFzIFYyIFBSRTAeFw0xNjA1MjQxNzA2MzVaFw0xOTA1MjQxNzA2MzZaMIGuMQswCQYDVQQGEwJFUzEdMBsGA1UEChMUQkFOQ08gU0FOVEFOREVSIFMuQS4xNjA0BgNVBAsMLUNlcnRpZmljYWRvIENvcnBvcmF0aXZvIGRlIEFwbGljYWNpw7NuIFNlZ3VyYTESMBAGA1UEBRMJQTM5MDAwMDEzMTQwMgYDVQQDDCtTRVJWSUNJT1MgREUgQ09OVFJBVEFDScOTTiBFTEVDVFLDk05JQ0EgSU5UMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqk5ukS81dw4aya31tHYrnLoA0q9aS4MaIefUfkR/LLSidWPD1bRRWp4FplSK5xobJKaNkMuqUAKgE6RwSVmC3d7czLM3nVrqt763/BnPk1trxj+7WX82smEOOdS9q5FhyQOXZL0qAJeVuvfxCcnUvjNKxm0J+Hs3aV7aNB8J9AqdBszTI6dc/ScRZ6qNhJ1XHIh6NvGjpe6cDoAibngAgqQ4KqmG+gGXQFzWMCE5DC7DORi6/hoV2mw1gKgsO9sksEostVx4X70/H8avpQUAmak6dgMF20rQvaDGMlSlRHMnfqzRrDZuMDfPVbNisRLT2h4Dq2JRqyxwIX5cZK4aQQIDAQABo4ICtzCCArMwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIEsDCBhAYIKwYBBQUHAQEEeDB2MDMGCCsGAQUFBzABhidodHRwOi8vcHJlLm9jc3AuYWMuYW5jZXJ0LmNvbS9vY3NwLnh1ZGEwPwYIKwYBBQUHMAKGM2h0dHA6Ly9wcmUuYW5jZXJ0LmNvbS9wa2kvdjIvY2VydHMvQU5DRVJUQ0NTX1YyLmNydDAfBgNVHSMEGDAWgBQw3KSyh1/zuPOBpq2LBN6tfexXaDAMBgNVHRMBAf8EAjAAMIHqBgNVHSAEgeIwgd8wgdwGDSsGAQQBgZNoAgIBAQIwgcowNwYIKwYBBQUHAgEWK2h0dHBzOi8vcHJlLmFuY2VydC5jb20vY29uZGljaW9uZXMvQ0NBU1NvZnQwgY4GCCsGAQUFBwICMIGBMA0WBkFOQ0VSVDADAgEBDHBFc3RlIGNlcnRpZmljYWRvIHNlIGV4cGlkZSBkZSBhY3VlcmRvIGNvbiBsYXMgY29uZGljaW9uZXMgZGUgdXNvIGVuICBodHRwczovL3ByZS5hbmNlcnQuY29tL2NvbmRpY2lvbmVzL0NDQVNTb2Z0MIGaBgNVHR8EgZIwgY8wgYyggYmggYaGKmh0dHA6Ly9wcmUuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybIYraHR0cDovL3ByZTIuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybIYraHR0cDovL3ByZTMuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybDAdBgNVHQ4EFgQU3sCjLM8MU8nbkkIxXigdcct5nSgwIwYDVR0RBBwwGoEYbm8tcmVwbHlAbm90YXJpYWRvLWkub3JnMA0GCSqGSIb3DQEBCwUAA4ICAQARttm9ma2kkpoxdRT/UAoVPMKQtjXBOUKtNoaF6pVq8gGb8xOQ/DfiuD5H47JTwnxXMhkheJPM1CcnMprvS18QlEvG+id/1wyN+SkqiHd2ZLWHwznzJAE+rQixX+bIfVtXBmTGi9K98VE+0GPRwTeQ36ore0XUMPq5P0RCjSYoGlO6uvnLIpYw8b+PAoCKSHEv9/w1C6PWRKUMsDegX9gRo+RMulA9c5Ns+k84lVbsKyvPV8s96NltxPgxGu3Tc8IZq6I+H/IFDFjcZK4nbS3D2mRll/Hi4EH61VLgJPWfpUo8coKyUz+VajnOGVwkHysutevCRvMV1eh7GZCyI3uiCSfZX5bvA70mZMz2VBg89BdFsyDPih1ZxpxEGdytgdFMI2b2Oq6oanvr5IbmG3JdudnvNtT+PMUvWf+ibmsHn6YQhnJAhdBS+ak2eVTTr8wd0up2zn9zqGMUOyo/P5vVsyeM8Fecf1v5m0p35KnJlDIcLw+9V2k6WZtROyCbhuNSnPnmgaSdRZDfxtErmUuQ9OaPo42THW4TEk6CJpMi1Xa1PlmigTG9AoJc9w4FkS3tlWEKERSByfUrvltqH9iis4LaZBfn47g9RND3rvNOjxdxqSqowRUU6PhBQ0GYATRKxux2/QpQrh9OIUpxAV2AspeojzpPjy5oAZOWMkFSyw==</wsse:KeyIdentifier></wsse:SecurityTokenReference></ds:KeyInfo></ds:Signature></wsse:Security><SERVICE_DISPATCHER xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN"><TIMESTAMP>2016-08-23T20:32:15.294+02:00</TIMESTAMP><TIPO_MSJ>1</TIPO_MSJ><EMISOR>TEST</EMISOR><RECEP>CGN</RECEP><SERVICIO>CN0001</SERVICIO></SERVICE_DISPATCHER></soap:Header><soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="#id-D1DD0227ECDC46640D147197713960845"><SERVICE_DISPATCHER_REQUEST xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN"><ns2:SERVICIO_CONSIGNACION_NOTARIAL><ns2:REQUEST><ns2:CABECERA><ns2:ID_COMUNICACION>2147483647</ns2:ID_COMUNICACION><ns2:FECHA>2016-03-22</ns2:FECHA><ns2:HORA>10:55:00</ns2:HORA><ns2:TIPO_OPERACION>TRANSFERENCIA</ns2:TIPO_OPERACION></ns2:CABECERA><ns2:MENSAJE><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>1.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>2.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA></ns2:MENSAJE></ns2:REQUEST></ns2:SERVICIO_CONSIGNACION_NOTARIAL></SERVICE_DISPATCHER_REQUEST></soap:Body></soap:Envelope>
When I use this soap message using SoapUI over my endpoint (https://test...)
Always received this response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server.generalException</faultcode>
<faultstring>WSDoAllReceiver: security processing failed; nested exception is:
org.apache.ws.security.WSSecurityException: The signature verification failed</faultstring>
<detail>
<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">hermes4</ns1:hostname>
</detail>
</soapenv:Fault>
I have a OK Soap message that I use to generate my Soap message on java a I don't find the structure difference over the XML that I generated.
Correctly signed Soap:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1">
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#id-4A1E576857255EBB5114717876404904"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>K2IpilH1NxMSOTeA4yRZukLC2vk=</ds:DigestValue></ds:Reference></ds:SignedInfo>
<ds:SignatureValue>Yua1G4f8OV3M2xJDZZb3b6zr+9Bx4aufbIkzynYiZeHZhzPHwm4vumN7bmdcU0TC9mF7qpC7CkrcbvlIbnG0Wz/PPcJ7iQ0KLyMMqWhc2u56oMwZjJK4FPX6Pc8wFzSoPACP9c9bC0DDX0ZVBMxXkP2/yWVGIxHSL0oqTHK6vfGBRRYGw7mvzqGXtdKxnENE6akYJU8Xqf/QbP1Oh9sJwRBtbhrJfMWomyDn4FoftNQl2pwMf5PCNmsR7Ecc7iIzFpP141MGgYIecZzA0mxOeF4jqJg3Co/VM4etAFpIFT4GMDDj4JD8nKKfVdZ8+9qOCiZsP2MbSon9tPny2xxPDg==</ds:SignatureValue>
<ds:KeyInfo>
<wsse:SecurityTokenReference>
<wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">MIIHdDCCBVygAwIBAgIQDT8ExvuNzblitEznqcBn7jANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCRVMxQTA/BgNVBAoTOEFnZW5jaWEgTm90YXJpYWwgZGUgQ2VydGlmaWNhY2lvbiBTLkwuVS4gLSBDSUYgQjgzMzk1OTg4MS8wLQYDVQQDEyZBTkNFUlQgQ29ycG9yYXRpdm9zIGRlIFNpc3RlbWFzIFYyIFBSRTAeFw0xNjA1MjQxNzA2MzVaFw0xOTA1MjQxNzA2MzZaMIGuMQswCQYDVQQGEwJFUzEdMBsGA1UEChMUQkFOQ08gU0FOVEFOREVSIFMuQS4xNjA0BgNVBAsMLUNlcnRpZmljYWRvIENvcnBvcmF0aXZvIGRlIEFwbGljYWNpw7NuIFNlZ3VyYTESMBAGA1UEBRMJQTM5MDAwMDEzMTQwMgYDVQQDDCtTRVJWSUNJT1MgREUgQ09OVFJBVEFDScOTTiBFTEVDVFLDk05JQ0EgSU5UMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqk5ukS81dw4aya31tHYrnLoA0q9aS4MaIefUfkR/LLSidWPD1bRRWp4FplSK5xobJKaNkMuqUAKgE6RwSVmC3d7czLM3nVrqt763/BnPk1trxj+7WX82smEOOdS9q5FhyQOXZL0qAJeVuvfxCcnUvjNKxm0J+Hs3aV7aNB8J9AqdBszTI6dc/ScRZ6qNhJ1XHIh6NvGjpe6cDoAibngAgqQ4KqmG+gGXQFzWMCE5DC7DORi6/hoV2mw1gKgsO9sksEostVx4X70/H8avpQUAmak6dgMF20rQvaDGMlSlRHMnfqzRrDZuMDfPVbNisRLT2h4Dq2JRqyxwIX5cZK4aQQIDAQABo4ICtzCCArMwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIEsDCBhAYIKwYBBQUHAQEEeDB2MDMGCCsGAQUFBzABhidodHRwOi8vcHJlLm9jc3AuYWMuYW5jZXJ0LmNvbS9vY3NwLnh1ZGEwPwYIKwYBBQUHMAKGM2h0dHA6Ly9wcmUuYW5jZXJ0LmNvbS9wa2kvdjIvY2VydHMvQU5DRVJUQ0NTX1YyLmNydDAfBgNVHSMEGDAWgBQw3KSyh1/zuPOBpq2LBN6tfexXaDAMBgNVHRMBAf8EAjAAMIHqBgNVHSAEgeIwgd8wgdwGDSsGAQQBgZNoAgIBAQIwgcowNwYIKwYBBQUHAgEWK2h0dHBzOi8vcHJlLmFuY2VydC5jb20vY29uZGljaW9uZXMvQ0NBU1NvZnQwgY4GCCsGAQUFBwICMIGBMA0WBkFOQ0VSVDADAgEBDHBFc3RlIGNlcnRpZmljYWRvIHNlIGV4cGlkZSBkZSBhY3VlcmRvIGNvbiBsYXMgY29uZGljaW9uZXMgZGUgdXNvIGVuICBodHRwczovL3ByZS5hbmNlcnQuY29tL2NvbmRpY2lvbmVzL0NDQVNTb2Z0MIGaBgNVHR8EgZIwgY8wgYyggYmggYaGKmh0dHA6Ly9wcmUuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybIYraHR0cDovL3ByZTIuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybIYraHR0cDovL3ByZTMuYW5jZXJ0LmNvbS9jcmwvQU5DRVJUQ0NTX1YyLmNybDAdBgNVHQ4EFgQU3sCjLM8MU8nbkkIxXigdcct5nSgwIwYDVR0RBBwwGoEYbm8tcmVwbHlAbm90YXJpYWRvLWkub3JnMA0GCSqGSIb3DQEBCwUAA4ICAQARttm9ma2kkpoxdRT/UAoVPMKQtjXBOUKtNoaF6pVq8gGb8xOQ/DfiuD5H47JTwnxXMhkheJPM1CcnMprvS18QlEvG+id/1wyN+SkqiHd2ZLWHwznzJAE+rQixX+bIfVtXBmTGi9K98VE+0GPRwTeQ36ore0XUMPq5P0RCjSYoGlO6uvnLIpYw8b+PAoCKSHEv9/w1C6PWRKUMsDegX9gRo+RMulA9c5Ns+k84lVbsKyvPV8s96NltxPgxGu3Tc8IZq6I+H/IFDFjcZK4nbS3D2mRll/Hi4EH61VLgJPWfpUo8coKyUz+VajnOGVwkHysutevCRvMV1eh7GZCyI3uiCSfZX5bvA70mZMz2VBg89BdFsyDPih1ZxpxEGdytgdFMI2b2Oq6oanvr5IbmG3JdudnvNtT+PMUvWf+ibmsHn6YQhnJAhdBS+ak2eVTTr8wd0up2zn9zqGMUOyo/P5vVsyeM8Fecf1v5m0p35KnJlDIcLw+9V2k6WZtROyCbhuNSnPnmgaSdRZDfxtErmUuQ9OaPo42THW4TEk6CJpMi1Xa1PlmigTG9AoJc9w4FkS3tlWEKERSByfUrvltqH9iis4LaZBfn47g9RND3rvNOjxdxqSqowRUU6PhBQ0GYATRKxux2/QpQrh9OIUpxAV2AspeojzpPjy5oAZOWMkFSyw==</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
<SERVICE_DISPATCHER xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN">
<TIMESTAMP>2017-08-21T15:53:58.308+02:00</TIMESTAMP>
<TIPO_MSJ>1</TIPO_MSJ>
<EMISOR>TEST</EMISOR>
<RECEP>CGN</RECEP>
<SERVICIO>CN0001</SERVICIO>
</SERVICE_DISPATCHER>
</soap:Header>
<soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-4A1E576857255EBB5114717876404904"><SERVICE_DISPATCHER_REQUEST xmlns="http://inti.notariado.org/XML" xmlns:ns2="http://ancert.notariado.org/XML/CSN"><ns2:SERVICIO_CONSIGNACION_NOTARIAL><ns2:REQUEST><ns2:CABECERA><ns2:ID_COMUNICACION>2147483647</ns2:ID_COMUNICACION><ns2:FECHA>2016-03-22</ns2:FECHA><ns2:HORA>10:55:00</ns2:HORA><ns2:TIPO_OPERACION>TRANSFERENCIA</ns2:TIPO_OPERACION></ns2:CABECERA><ns2:MENSAJE><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>1.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA><ns2:TRANSFERENCIA><ns2:CODIGO_SERVICIO>DEUDAS</ns2:CODIGO_SERVICIO><ns2:REFERENCIA>999988887777666655</ns2:REFERENCIA><ns2:FECHA_EMISION>2016-03-24</ns2:FECHA_EMISION><ns2:FECHA_VALOR>2016-03-25</ns2:FECHA_VALOR><ns2:NOTARIO><ns2:CODIGO_ULTIMAS_VOLUNTADES>9900005</ns2:CODIGO_ULTIMAS_VOLUNTADES><ns2:TIP_DOC_IDENTIFICACION>1</ns2:TIP_DOC_IDENTIFICACION><ns2:NUM_DOC_IDENTIFICACION>11711111H</ns2:NUM_DOC_IDENTIFICACION></ns2:NOTARIO><ns2:IMPORTE>2.00</ns2:IMPORTE><ns2:MONEDA>EUR</ns2:MONEDA><ns2:ORDENANTE>JUAN PEREZ SANCHEZ</ns2:ORDENANTE><ns2:CONCEPTO>Pago deuda inmueble Santurze</ns2:CONCEPTO></ns2:TRANSFERENCIA></ns2:MENSAJE></ns2:REQUEST></ns2:SERVICIO_CONSIGNACION_NOTARIAL></SERVICE_DISPATCHER_REQUEST></soap:Body>
</soap:Envelope>
Please can anybody help me telling me what Im doing wrong.
Thanks everyone for your time reading my ask :)
A cordial greeting.
A: I answer to my question with my solution. @pedrofb tell a better way to fix my problem but I couldn't use on my WAS server.
I use a private method to canonicalized my XML to create the digest and later to create the signature:
private String canonicalize(String xml)
{
try
{
String CHARSET = "UTF-8";
Init.init();
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);
String canoninalizacion = new String(canon.canonicalize(xml.getBytes(CHARSET)), CHARSET);
return canoninalizacion;
}
catch (Exception e)
{
e.printStackTrace();
return xml;
}
}
Then we transform the XML correctly to set the namespaces and prefix in the right place. For my needed I use:
private String createBodyXML(String dataXML)
{
String docXML = canonicalize(dataXML);
// Manual introduction of prefixes
docXML = docXML.replaceAll("</", "</ns2:").replaceAll("<", "<ns2:").replaceAll("<ns2:/ns2:", "</ns2:");
String startBodyHash = "<soap:Body xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" Id=\"MsgBody\">";
String endBodyHash = "</soap:Body>";
String dataXMLSoap = "<SERVICE_DISPATCHER_REQUEST xmlns=\"http://inti.notariado.org/XML\">"
+ "<ns2:SERVICIO_CONSIGNACION_NOTARIAL xmlns:ns2=\"http://ancert.notariado.org/XML/CSN\">"
+ docXML
+ "</ns2:SERVICIO_CONSIGNACION_NOTARIAL>"
+ "</SERVICE_DISPATCHER_REQUEST>";
String xmlHash = startBodyHash + dataXMLSoap + endBodyHash;
// this xmlHash is the same body of the SOAP call
return xmlHash;
}
We do at the time of the creation of the XML of body and XML of signedInfo. Is not the best way to make it:
String xmlDigest = "<ds:SignedInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\">"
+ "<ec:InclusiveNamespaces xmlns:ec=\"http://www.w3.org/2001/10/xml-exc-c14n#\" PrefixList=\"soap\"></ec:InclusiveNamespaces>"
+ "</ds:CanonicalizationMethod>"
+ "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>"
+ "<ds:Reference URI=\"#MsgBody\">"
+ "<ds:Transforms>"
+ "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\">"
+ "<ec:InclusiveNamespaces xmlns:ec=\"http://www.w3.org/2001/10/xml-exc-c14n#\" PrefixList=\"\"></ec:InclusiveNamespaces>"
+ "</ds:Transform>"
+ "</ds:Transforms>"
+ "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>"
+ "<ds:DigestValue>"
+ digestValue
+ "</ds:DigestValue>"
+ "</ds:Reference>"
+ "</ds:SignedInfo>";
I want to share how I call my web service with the SOAP message well signed, It is not in relation with this question , but maybe wil be usefull for someone:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
...
private String sendMessage(String xmlAEnviar) throws Exception
{
try
{
// Metodo envio
String POST = "POST";
String urlEndpoint = "https://test.dominio.org/servicedispatcher/services/ServiceDispatcherSigned";
final String httpsProxyHost = "180.100.14.70";
final String httpsProxyPort = "8080";
final String userProxy = "user";
final String passProxy = "password";
URL httpsURL = new URL(urlEndpoint);
HttpsURLConnection httpsURLConnection = null;
if (httpsProxyHost.length() > 0 && httpsProxyPort.length() > 0)
{
Proxy miProxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(httpsProxyHost, Integer.parseInt(httpsProxyPort)));
httpsURLConnection = (HttpsURLConnection) httpsURL.openConnection(miProxy);
if (userProxy.length() > 0 && passProxy.length() > 0)
{
String userPassword = userProxy + ":" + passProxy;
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedLogin = encoder.encode(userPassword.getBytes());
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userProxy, passProxy.toCharArray());
}
});
httpsURLConnection.setRequestProperty("Proxy-Authorization", (new StringBuilder("Basic ")).append(encodedLogin).toString());
}
}
else
{
httpsURLConnection = (HttpsURLConnection) httpsURL.openConnection();
}
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setRequestMethod(POST);
httpsURLConnection.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
httpsURLConnection.setRequestProperty("SOAPAction", "");
OutputStream outputStream = httpsURLConnection.getOutputStream();
outputStream.write(xmlAEnviar.getBytes());
outputStream.flush();
InputStream httpsInputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((httpsInputStream)));
String lineanext = "";
String outputnext = "";
while ((lineanext = bufferedReader.readLine()) != null)
{
outputnext = outputnext.concat(lineanext);
}
httpsURLConnection.disconnect();
return outputnext;
}
catch (NumberFormatException e)
{
e.printStackTrace();
throw new Exception(e);
}
catch (MalformedURLException e)
{
e.printStackTrace();
throw new Exception(e);
}
catch (ProtocolException e)
{
e.printStackTrace();
throw new Exception(e);
}
catch (IOException e)
{
e.printStackTrace();
throw new Exception(e);
}
}
Thanks for everyone, especially to @pedrofb.
A cordial greeting.
A:
SOAP Enveloped signature: Signing XML Document with the qualified certificate.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<!-- <env:Header /> -->
<env:Body>
<product version="11.1.2.4.0"> <!-- Data XML -->
<name>API Gateway</name>
<company>Oracle</company>
<description>SOA Security and Management</description>
</product>
</env:Body>
</env:Envelope>
By using the following function you can digitally Sign the XML using Certificate And Private Key Baeldung.cer, Baeldung.p12 (password = “password”)
public static Document getDigitalSignDoc(String sourceFile) throws Exception {
Document doc = SOAP_Security_Signature.getDocument(sourceFile, false);
String signatureID = "123", keyInfoID = "456", referenceID = "Id-0000011a101b167c-0000000000000012";
//optional, but better
Element signElementEnvelope = doc.getDocumentElement();
//signElement.normalize();
String nameSpace = "env"; //soap
Node itemBody = signElementEnvelope.getElementsByTagName(nameSpace+":Body").item(0);
Node itemHead = signElementEnvelope.getElementsByTagName(nameSpace+":Header").item(0);
if (itemHead == null) {
System.out.println("Provided SOAP XML does not contains any Header part. So creating it.");
Element createElement = doc.createElement(nameSpace+":Header");
signElementEnvelope.insertBefore(createElement, itemBody);
itemHead = signElementEnvelope.getElementsByTagName(nameSpace+":Header").item(0);
}
((Element)itemBody).setAttribute("Id", referenceID);
String elementRefId = "#" + referenceID;
Node firstChild = itemBody.getFirstChild();
Document dataDoc = firstChild.getOwnerDocument(); // Total Entire XML
System.out.println("Document: "+dataDoc.getDocumentElement());
org.apache.xml.security.Init.init();
org.apache.xml.security.signature.XMLSignature signature = new XMLSignature(dataDoc, elementRefId, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
//XMLSignature signature = new XMLSignature(dataDoc, elementRefId, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
itemHead.appendChild(signature.getElement());
// Below code adds Sign element after Body tag: </soap:Body><ds:Signature> ... </ds:Signature></soap:Envelope>
//signElement.appendChild(signature.getElement());
Transforms transforms = new Transforms(signElementEnvelope.getOwnerDocument()); // doc | signElement.getOwnerDocument()
// <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); // TRANSFORM_C14N_OMIT_COMMENTS
//transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
//Sign the content of SOAP Envelope
signature.addDocument(elementRefId, transforms, Constants.ALGO_ID_DIGEST_SHA1);
//Signing procedure
signature.setId(signatureID);
signature.addKeyInfo(loadPublicKeyX509);
signature.addKeyInfo(loadPublicKeyX509.getPublicKey());
KeyInfo keyInfo = signature.getKeyInfo();
keyInfo.setId(keyInfoID);
System.out.println("Start signing");
signature.sign(privateKey);
System.out.println("Finished signing : "+signature.getId());
return doc;
}
Generated SOAP Signed XML file:
<env:Envelope
xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header>
<ds:Signature
xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="123">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="#Id-0000011a101b167c-0000000000000012">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>Fk4qf2xFlZoM2jo9NA+6GkCwKfU=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
VecBSDUFpBBcjLS1AK41NDwUvFl9mHktx2TqqcBtGQpNxMiJv/eRvApeKiHLp8iyVKqbcog4akxp
N6qBGEwOgThYlWdgVSPDct8l42+4XHLxUee5YcUVeW71r4mIuvoT0o9aLtNcjE7xzDeke3rzbOyz
7UORAqyuEe1rVk7QHNEZrW1nZRI9JadAuSboa1ZLI8BK0JqUZD/0UhswLXUtftYAA+2qeWQGRMAk
1RZsC4sfXqmp2oni/wihR+8HkEaiUfpTMq2Gcpnf3a59v67h4fxDtnYlAdN8LX53YHgB+0ONcIxO
vHt88hCLwKiaIeM4Wz7qzMMSmq9/dGBlqFU8Dw==
</ds:SignatureValue>
<ds:KeyInfo Id="456">
<ds:X509Data>
<ds:X509Certificate>
MIIDPjCCAiagAwIBAgIJAPvd1gx14C3CMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNVBAYTAk1BMRAw
DgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzAe
Fw0xNzEwMTIxMDQzMTRaFw0yNzEwMTMxMDQzMTRaMEcxCzAJBgNVBAYTAk1BMRAwDgYDVQQIEwdN
b3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAMyi5GmOeN4QaH/CP5gSOyHX8znb5TDHWV8wc+ZT7kNU8zt5
tGMhjozK6hax155/6tOsBDR0rSYBhL+Dm/+uCVS7qOlRHhf6cNGtzGF1gnNJB2WjI8oMAYm24xpL
j1WphKUwKrn3nTMPnQup5OoNAMYl99flANrRYVjjxrLQvDZDUio6IujrCZ2TtXGM0g/gP++28KT7
g1KlUui3xtB0u33wx7UN8Fix3JmjOaPHGwxGpwP3VGSjfs8cuhqVwRQaZpCOoHU/P8wpXKw80sSd
hz+SRueMPtVYqK0CiLL5/O0h0Y3le4IVwhgg3KG1iTGOWn60UMFn1EYmQ18k5Nsma6UCAwEAAaMt
MCswCQYDVR0TBAIwADARBglghkgBhvhCAQEEBAMCBPAwCwYDVR0PBAQDAgUgMA0GCSqGSIb3DQEB
BQUAA4IBAQC8DDBmJ3p4xytxBiE0s4p1715WT6Dm/QJHp0XC0hkSoyZKDh+XVmrzm+J3SiW1vpsw
b5hLgPo040YX9jnDmgOD+TpleTuKHxZRYj92UYWmdjkWLVtFMcvOh+gxBiAPpHIqZsqo8lfcyAuh
8Jx834IXbknfCUtERDLG/rU9P/3XJhrM2GC5qPQznrW4EYhUCGPyIJXmvATMVvXMWCtfogAL+n42
vjYXQXZoAWomHhLHoNbSJUErnNdWDOh4WoJtXJCxA6U5LSBplqb3wB2hUTqw+0admKltvmy+KA1P
D7OxoGiY7V544zeGqJam1qxUia7y5BL6uOa/4ShSV8pcJDYz
</ds:X509Certificate>
</ds:X509Data>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus>
zKLkaY543hBof8I/mBI7IdfzOdvlMMdZXzBz5lPuQ1TzO3m0YyGOjMrqFrHXnn/q06wENHStJgGE
v4Ob/64JVLuo6VEeF/pw0a3MYXWCc0kHZaMjygwBibbjGkuPVamEpTAqufedMw+dC6nk6g0AxiX3
1+UA2tFhWOPGstC8NkNSKjoi6OsJnZO1cYzSD+A/77bwpPuDUqVS6LfG0HS7ffDHtQ3wWLHcmaM5
o8cbDEanA/dUZKN+zxy6GpXBFBpmkI6gdT8/zClcrDzSxJ2HP5JG54w+1ViorQKIsvn87SHRjeV7
ghXCGCDcobWJMY5afrRQwWfURiZDXyTk2yZrpQ==
</ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature>
</env:Header>
<env:Body Id="Id-0000011a101b167c-0000000000000012">
<product version="11.1.2.4.0">
<name>API Gateway</name>
<company>Oracle</company>
<description>SOA Security and Management</description>
</product>
</env:Body>
</env:Envelope>
Verify the Signature of the XML with the puclic certificate
public static boolean isSOAPXmlDigitalSignatureValid(String signedXmlFilePath, PublicKey publicKey) throws Exception {
String xmlContent = SOAP_Security_Signature.getFileString(signedXmlFilePath);
Document doc = SOAP_Security_Signature.getDocument(xmlContent.trim(), true);
System.out.println("Document: "+doc.getDocumentElement());
// namespaceURI=http://www.w3.org/2000/09/xmldsig#", localName=Signature
String localName = "Signature";
String qualifiedName = "ds";
doc.createElementNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, qualifiedName);
NodeList nl = doc.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, localName); // "Signature"
if (nl.getLength() == 0) {
throw new Exception("No XML Digital Signature Found, document is discarded");
}
Node sigElement = nl.item(0);
org.apache.xml.security.Init.init();
org.apache.xml.security.signature.XMLSignature signature = new XMLSignature((Element) sigElement, "");
return signature.checkSignatureValue(publicKey);
}
Full Example: Some of the functions used form this class SOAP_Security_Signature
//dependency: groupId:xml-security, artifactId:xmlsec, version:1.3.0
//dependency: groupId:xalan, artifactId:xalan, version:2.7.1
public class SOAP_XML_Signature {
static PrivateKey privateKey;
static X509Certificate loadPublicKeyX509;
static String path = "C:/Yash/SOAP/", privateKeyFilePath = path+"Baeldung.p12", publicKeyFilePath = path+"Baeldung.cer",
inputFile= path+"Soap1.xml", outputFile = path+"output.xml";
public static void main(String unused[]) throws Exception {
InputStream pkcs_FileStream = new FileInputStream(privateKeyFilePath);
privateKey = SOAP_Security_Signature.loadPrivateKeyforSigning(pkcs_FileStream, "password");
System.out.println("privateKey : "+privateKey);
InputStream cerFileStream = new FileInputStream(publicKeyFilePath);
loadPublicKeyX509 = SOAP_Security_Signature.loadPublicKeyX509(cerFileStream);
PublicKey publicKey = loadPublicKeyX509.getPublicKey();
System.out.println("loadPublicKey : "+ publicKey);
//SOAP envelope to be signed
Document digitalSignDoc = getDigitalSignDoc(inputFile);
File signatureFile = new File(outputFile);
String BaseURI = signatureFile.toURI().toURL().toString();
//write signature to file
FileOutputStream f = new FileOutputStream(signatureFile);
XMLUtils.outputDOMc14nWithComments(digitalSignDoc, f);
f.close();
System.out.println("Wrote signature to " + BaseURI);
boolean soapXmlDigitalSignatureValid = isSOAPXmlDigitalSignatureValid(outputFile, publicKey);
System.out.println("isSOAPXmlDigitalSignatureValid :"+soapXmlDigitalSignatureValid);
}
}
A: You need to perform a compliant ws-security SOAP message which includes a XML DSig Signature
You are not building the message digest correctly and you do not apply the canonicalization methods neither transforms. Java has native support for XML signatures. You do not need to build them from scratch.
In this post you will find an example using standard Java code and a link to the utilities of your application server(recommended)
A: I'm enhancing https://stackoverflow.com/a/63617195/5845739 Yash's Answer.
Thank You for the excellent answer.
Also, I'm directly calling the SOAP Message, instead of using the File Call in the
callTheWebServiceFromFile()
Maven Dependencies
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>xml-security</groupId>
<artifactId>xmlsec</artifactId>
<version>1.3.0</version>
</dependency>
Java Complete Code
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Scanner;
import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.Constants;
import org.springframework.http.HttpHeaders;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class SOAP_Security_Signature {
static final String
WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
WSU_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
DSIG_NS = "http://www.w3.org/2000/09/xmldsig#", // javax.xml.crypto.dsig.XMLSignature.XMLNS, Constants.SignatureSpecNS
binarySecurityToken_Encoding = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary",
binarySecurityToken_Value = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3",
signatureMethodAlog_SHA1 = DSIG_NS + "rsa-sha1", // XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1
digestMethodAlog_SHA1 = Constants.ALGO_ID_DIGEST_SHA1, // DSIG_NS + "sha1", // Constants.ALGO_ID_DIGEST_SHA1
transformAlog = Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, //"http://www.w3.org/2001/10/xml-exc-c14n#";
canonicalizerAlog = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; //"http://www.w3.org/2001/10/xml-exc-c14n#"; CanonicalizationMethod.EXCLUSIVE
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public static X509Certificate loadPublicKeyX509(InputStream cerFileStream) throws CertificateException, NoSuchProviderException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerFileStream);
return x509Certificate;
}
public static PrivateKey loadPrivateKeyforSigning(InputStream cerFileStream, String password) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {
KeyStore keyStore = KeyStore.getInstance("PKCS12"); //, "BC");
keyStore.load(cerFileStream, password.toCharArray());
Enumeration<String> keyStoreAliasEnum = keyStore.aliases();
PrivateKey privateKey = null;
String alias = null;
if ( keyStoreAliasEnum.hasMoreElements() ) {
alias = keyStoreAliasEnum.nextElement();
if (password != null) {
privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
}
}
return privateKey;
}
static X509Certificate loadPublicKeyX509;
static PrivateKey privateKey;
static String privateKeyFilePath = "pfxFileLocation/Ibtsam.pfx", publicKeyFilePath = "crtFileLocation/Ibtsam.crt",
inputFile= "sourceFileLocation/x.xml", outputFile = "destinationFileLocation/output.xml";
public static void main(String[] args) throws Exception {
InputStream pkcs_FileStream = new FileInputStream(privateKeyFilePath);
privateKey = loadPrivateKeyforSigning(pkcs_FileStream, "password");//Password of PFX file
System.out.println("privateKey : "+privateKey);
InputStream cerFileStream = new FileInputStream(publicKeyFilePath);
loadPublicKeyX509 = loadPublicKeyX509(cerFileStream);
PublicKey publicKey = loadPublicKeyX509.getPublicKey();
System.out.println("loadPublicKey : "+ publicKey);
System.setProperty("javax.xml.soap.MessageFactory", "com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl");
System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");
SOAPMessage soapMsg = WS_Security_signature(inputFile, false);
outputSOAPMessageToFile(soapMsg);
/*ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMsg.writeTo(out);
String strMsg = new String(out.toByteArray());
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println(strMsg);
System.out.println("+++++++++++++++++++++++++++++++++++");*/
new SOAP_Security_Signature().callTheWebServiceFromFile(soapMsg);
//System.out.println("Signature Succesfull. Verify the Signature");
// boolean soapXmlWSSEDigitalSignatureValid = isSOAPXmlWSSEDigitalSignatureValid(outputFile, publicKey);
// System.out.println("isSOAPXmlDigitalSignatureValid :"+soapXmlWSSEDigitalSignatureValid);
}
public static void outputSOAPMessageToFile(SOAPMessage soapMessage) throws SOAPException, IOException {
File outputFileNew = new File(outputFile);
java.io.FileOutputStream fos = new java.io.FileOutputStream(outputFileNew);
soapMessage.writeTo(fos);
fos.close();
}
public static String toStringDocument(Document doc) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
}
public static String getFileString(String xmlFilePath) throws FileNotFoundException {
File file = new File(xmlFilePath);
//FileInputStream parseXMLStream = new FileInputStream(file.getAbsolutePath());
Scanner scanner = new Scanner( file, "UTF-8" );
String xmlContent = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block
System.out.println("Str:"+xmlContent);
return xmlContent;
}
public static Document getDocument(String xmlData, boolean isXMLData) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc;
if (isXMLData) {
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
doc = dBuilder.parse(ips);
} else {
doc = dBuilder.parse( new File(xmlData) );
}
return doc;
}
private void callTheWebServiceFromFile(SOAPMessage msg) throws IOException, SOAPException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
// Set the soapPart Content with the stream source
//soapPart.setContent(ss);
SOAPPart soapPart = msg.getSOAPPart();
// Create a webService connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Invoke the webService.
String soapEndpointUrl = "https://mirsal2gwytest.dubaitrade.ae/customsb2g/oilfields";
SOAPMessage resp = soapConnection.call(msg, soapEndpointUrl);
// Reading result
resp.writeTo(System.out);
//fis.close();
soapConnection.close();
}
public static SOAPMessage WS_Security_signature(String inputFile, boolean isDataXML) throws Exception {
SOAPMessage soapMsg;
Document docBody;
if (isDataXML) {
System.out.println("Sample DATA xml - Create SOAP Message");
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
soapMsg = soapMessage;
String xmlContent = getFileString(inputFile);
docBody = getDocument(xmlContent.trim(), true);
System.out.println("Data Document: "+docBody.getDocumentElement());
} else {
System.out.println("SOAP XML with Envelope");
Document doc = getDocument(inputFile, false); // SOAP MSG removing comment elements
String docStr = toStringDocument(doc); // https://stackoverflow.com/a/2567443/5081877
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(docStr.getBytes());
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.removeHeader("Content-Type");
mimeHeaders.addHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=utf-8");
mimeHeaders.addHeader("SOAPAction", "process");
SOAPMessage message = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(mimeHeaders, byteArrayInputStream);
soapMsg = message;
docBody = soapMsg.getSOAPBody().extractContentAsDocument();
System.out.println("SOAP DATA Document: "+docBody.getDocumentElement());
}
// A new SOAPMessage object contains: •SOAPPart object •SOAPEnvelope object •SOAPBody object •SOAPHeader object
SOAPPart soapPart = soapMsg.getSOAPPart();
soapPart.setMimeHeader("Content-Type", "text/xml;charset=UTF-8");
SOAPEnvelope soapEnv = soapPart.getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader(); // soapMessage.getSOAPHeader();
SOAPBody soapBody = soapEnv.getBody(); // soapMessage.getSOAPBody()
soapBody.addDocument(docBody);
soapBody.addAttribute(soapEnv.createName("Id", "wsu", WSU_NS), "Body");
if (soapHeader == null) {
soapHeader = soapEnv.addHeader();
System.out.println("Provided SOAP XML does not contains any Header part. So creating it.");
}
// <wsse:Security> element adding to Header Part
SOAPElement securityElement = soapHeader.addChildElement("Security", "wsse", WSSE_NS);
securityElement.addNamespaceDeclaration("wsu", WSU_NS);
String certEncodedID = "X509Token", timeStampID = "TS", signedBodyID = "Body";
// (ii) Add Binary Security Token.
// <wsse:BinarySecurityToken EncodingType="...#Base64Binary" ValueType="...#X509v3" wsu:Id="X509Token">The base64 encoded value of the ROS digital certificate.</wsse:BinarySecurityToken>
SOAPElement binarySecurityToken = securityElement.addChildElement("BinarySecurityToken", "wsse");
binarySecurityToken.setAttribute("ValueType", binarySecurityToken_Value);
binarySecurityToken.setAttribute("EncodingType", binarySecurityToken_Encoding);
binarySecurityToken.setAttribute("wsu:Id", certEncodedID);
byte[] certByte = loadPublicKeyX509.getEncoded();
String encodeToString = Base64.getEncoder().encodeToString(certByte);
binarySecurityToken.addTextNode(encodeToString);
//(iii) Add TimeStamp element - <wsu:Timestamp wsu:Id="TS">
SOAPElement timestamp = securityElement.addChildElement("Timestamp", "wsu");
timestamp.addAttribute(soapEnv.createName("Id", "wsu", WSU_NS), timeStampID);
String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
DateTimeFormatter timeStampFormatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
timestamp.addChildElement("Created", "wsu").setValue(timeStampFormatter.format(ZonedDateTime.now().toInstant().atZone(ZoneId.of("UTC"))));
timestamp.addChildElement("Expires", "wsu").setValue(timeStampFormatter.format(ZonedDateTime.now().plusSeconds(30).toInstant().atZone(ZoneId.of("UTC"))));
// (iv) Add signature element
// <wsse:Security> <ds:Signature> <ds:KeyInfo> <wsse:SecurityTokenReference>
SOAPElement securityTokenReference = securityElement.addChildElement("SecurityTokenReference", "wsse");
SOAPElement reference = securityTokenReference.addChildElement("Reference", "wsse");
reference.setAttribute("URI", "#"+certEncodedID); // <wsse:BinarySecurityToken wsu:Id="X509Token"
// <ds:SignedInfo>
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", (java.security.Provider) Class.forName(providerName).newInstance());
//Digest method - <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
javax.xml.crypto.dsig.DigestMethod digestMethod = xmlSignatureFactory.newDigestMethod(digestMethodAlog_SHA1, null);
ArrayList<Transform> transformList = new ArrayList<Transform>();
//Transform - <ds:Reference URI="#Body">
Transform envTransform = xmlSignatureFactory.newTransform(transformAlog, (TransformParameterSpec) null);
transformList.add(envTransform);
//References <ds:Reference URI="#Body">
ArrayList<Reference> refList = new ArrayList<Reference>();
Reference refTS = xmlSignatureFactory.newReference("#"+timeStampID, digestMethod, transformList, null, null);
Reference refBody = xmlSignatureFactory.newReference("#"+signedBodyID, digestMethod, transformList, null, null);
refList.add(refBody);
refList.add(refTS);
javax.xml.crypto.dsig.CanonicalizationMethod cm = xmlSignatureFactory.newCanonicalizationMethod(canonicalizerAlog, (C14NMethodParameterSpec) null);
javax.xml.crypto.dsig.SignatureMethod sm = xmlSignatureFactory.newSignatureMethod(signatureMethodAlog_SHA1, null);
SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(cm, sm, refList);
DOMSignContext signContext = new DOMSignContext(privateKey, securityElement);
signContext.setDefaultNamespacePrefix("ds");
signContext.putNamespacePrefix(DSIG_NS, "ds");
signContext.putNamespacePrefix(WSU_NS, "wsu");
signContext.setIdAttributeNS(soapBody, WSU_NS, "Id");
signContext.setIdAttributeNS(timestamp, WSU_NS, "Id");
KeyInfoFactory keyFactory = KeyInfoFactory.getInstance();
DOMStructure domKeyInfo = new DOMStructure(securityTokenReference);
javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyFactory.newKeyInfo(java.util.Collections.singletonList(domKeyInfo));
javax.xml.crypto.dsig.XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
signContext.setBaseURI("");
signature.sign(signContext);
return soapMsg;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39109111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I get data of my table to process in a popup im currently working on a table that shows selected values out of my database. For that I made the rows clickable to open a Popup as shown. I want to get the values out of my selected row into the popup to process them. It doesnt work for me, can someone show me for my code? Im new to coding and this is my first project so please be nice.
For Example I want the ID ($row["ID"]) out of my database shown in the Popup on $row["Titel"]. At the moment its called "Abstelone" in the picture
Table
Popup
<?php
require 'config.php';
session_start();
$prüfer_id = $_SESSION['prüfer_id'];
if (!isset($prüfer_id)){
header('location:logout.php');
}
$select = $conn->prepare("SELECT * FROM `projektantrag` WHERE pruefer_ID =? OR pruefer2_ID = ?");
$select->execute([$prüfer_id, $prüfer_id]);
$Ausgabe = $select->fetchAll();
$select = $conn->prepare("SELECT * FROM `projektantrag` WHERE pruefer_ID =? OR pruefer2_ID = ?");
$select->execute([$prüfer_id, $prüfer_id]);
$row = $select->fetch(PDO::FETCH_ASSOC);
$OriginalBeschreibung = $row['Beschreibung'];
$FileDownload = explode('/', $OriginalBeschreibung);
$FileActualName = strtolower (end($FileDownload));
$select_profile = $conn->prepare("SELECT * FROM `user` WHERE ID = ?");
$select_profile->execute([$prüfer_id]);
$fetch_profile = $select_profile->fetch(PDO::FETCH_ASSOC);
$email = $fetch_profile['email'];
if(isset($_POST['submit'])){
$select = $conn->prepare("SELECT * FROM `projektantrag` WHERE ID = ?");
$select->execute($ID);
$Ausgabe = $select->fetchAll();
$Titel = $Ausgabe['Titel'];
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Anträge anzeigen</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<link rel="stylesheet" href="css/style1.css">
<link rel="stylesheet" href="css/dialoge.css">
</head>
<body>
<nav>
<a href=""><img src="css/logo.png"></a>
<ul>
<li><a href="prüfer_page.php">Benutzerprofil</a></li>
<li><a class="active" href="Anträge_anzeigen.php">Anträge anzeigen</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</nav>
<?php
//Error Message
if(isset($message)){
foreach($message as $message){
echo '
<div class="message">
<span>'.$message.'</span>
<i class="fas fa-times" onclick="this.parentElement.remove();"></i>
</div>
';
}
}
?>
<table id="meineTabelle" data-role="table" class="content"
data-mode="columntoggle" data-column-btn-text="Spalten">
<thead>
<div class="tablehead">
<tr>
<th class="thblackborder" data-priority=""></th>
<th class="thblackborder" data-priority="">1.Projektant</th>
<th class="thblackborder" data-priority=""></th>
<th class="thblackborder" data-priority="">2.Projektant</th>
<th class="thblackborder" data-priority=""></th>
<th class="thblackborder" data-priority="">3.Projektant</th>
<th class="thblackborder" data-priority=""></th>
<th class="thblackborder" data-priority="">4.Projektant</th>
<th class="thblackborder" data-priority=""></th>
<tr>
<th class="">ID</th>
<th class="">Vorname</th>
<th class="">Nachname</th>
<th class="">Vorname</th>
<th class="">Nachname</th>
<th class="">Vorname</th>
<th class="">Nachname</th>
<th class="">Vorname</th>
<th class="">Nachname</th>
<th class="">Titel</th>
<th class="">Standort</th>
<th class="">Klasse</th>
<th class="">Beginn</th>
<th class="">Abgabe</th>
<th class="">Beschreibung</th>
<th class="">Status</th>
<th class="">Erstellt</th>
</tr>
</tr>
</div>
</thead>
<tbody>
<?php
foreach ($Ausgabe as $row) {
?>
<form>
<tr onclick="dialogOeffnen('loslegen-dialog')">
<td>
<?php echo $row["ID"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Vorname"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Nachname"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Vorname2"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Nachname2"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Vorname3"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Nachname3"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Vorname4"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Nachname4"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Titel"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Standort"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Klasse"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Beginn"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Abgabe"] . "<br>"; ?>
</td>
<td>
<center><a href=<?php echo "uploads/" . $FileActualName?>">Link</a></center>
</td>
<td>
<?php echo $row["Genehmigt"] . "<br>"; ?>
</td>
<td>
<?php echo $row["Erstellt"] . "<br>"; ?>
</td>
</tr>
</form>
<?php
}
?>
</tbody>
</table>
<div id="body-overlay"></div>
<div class="dialog" id="loslegen-dialog">
<a href="#" role="button" class="dialog-schließen-button" onclick="dialogSchliessen('loslegen-dialog')">
<i class="fas fa-times"></i>
</a>
<div class="textarea">
<h1><?php echo $row["Titel"] ?></h1>
<textarea placeholder="Platz für Bemerkungen" name="Bemerkungen" id="" cols="30" rows="10"></textarea>
</div>
<form classaction="">
<div class="txt_field">
<input type="text" name="email" value="<?= $fetch_profile['email'];?>" required>
<span></span>
<label>E-Mail</label>
</div>
<div class="txt_field">
<input type="text" name="password" required>
<span></span>
<label>Passwort</label>
</div>
<input type="submit" value="Bestätigen" name="submit">
<div class="signup_link"></div>
</form>
</div>
<script src="dialoge.js"></script>
</body>
</html>
</body>
A: This reason that this hasn't been answered is because you're actually asking for quite a lot of work to be done to make this happen.
In essence, you're looking to pass data from your table into a modal dialog <div class="dialog" id="loslegen-dialog">. Most likely onclick.
There are many ways to do this, the way I would personally do it would be to use the dialogOeffnen function which causes the dialog (popup) to open.
Create span elements around the data you want to use in your dialog i.e.
<td>
<span id="id_element"><?php echo $row["ID"];?></span><br>
</td>
and
<td>
<span id="title_element"><?php echo $row["Titel"];?></span><br>
</td>
Then ensure you have elements with specific ID attributes where you'd like to display this data i.e.
<h1 id="dialog_title"><?php //echo $row["Titel"]; //You can remove this ?></h1>
Then inside dialogOeffnen before you display the modal/popup:
document.getElementById("dialog_title").innerText = document.getElementById("title_element").innerText;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74790988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to localize page title with Spring and Tiles2? I have a Spring application which uses Tiles for the view tier. So all my pages definitions look like this:
<definition name="main.page" template="/tiles/layout.jsp">
<put-attribute name="title" value="Page Title"/>
<put-attribute name="header" value="/tiles/header.jsp"/>
<put-attribute name="body" value=""/>
<put-attribute name="footer" value="/tiles/footer.jsp"/>
</definition>
<definition name="welcome.page" extends="main.page">
<put-attribute name="title" value="Main Page"/>
<put-attribute name="body" value="/pages/welcome.jsp"/>
</definition>
The code which sets page title is:
<title><tiles:getAsString name="title"/></title>
I would like to localize with Spring tag:
<spring:message>
Are there any "best practices" how to do that?
A: The previous answer contains several little mistakes
tiles.xml
<definition name="main" template="/WEB-INF/jsp/template.jsp">
<put-attribute name="titleKey" value="main.title" />
<put-attribute name="body" value="/WEB-INF/jsp/main.jsp" />
</definition>
jsp (/WEB-INF/jsp/template.jsp)
<c:set var="titleKey"><tiles:getAsString name="titleKey"/></c:set>
<title><spring:message code="${titleKey}"></spring:message> </title>
A: Did you ever tried to put the message key in you tiles variable and use it as key for the spring message tag.
Something like that:
<definition name="welcome.page" extends="main.page">
<put-attribute name="titleKey" value="page.main.title"/>
<put-attribute name="body" value="/pages/welcome.jsp"/>
</definition>
jsp:
<set var"titleKey"><tiles:getAsString name="titleKey"/></set>
<title><spring:message code=${titleKey} /></title>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4448342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: PHP Method to Concatenate Array and String I am building a PHP class to handle database management, and I wondered if it was possible to build a method which could receive a string with a concatenated array as one variable.
For example, take a look at this simplified code:
class Database {
function __construct() {
// Connect to the database, code not shown
}
public function query($input) {
// Do something with the input so the string values are recognized ...
// and the array and its keys are converted into an SQL string.
// Code not shown...
mysql_query($processedInput);
return true;
}
}
So, ideally, if I run something like this ...
$db = new Database();
$db->query("UPDATE `table` SET " .
array("id" = "2",
"position" = "1",
"visible" = "1",
"name" = "My Name's John",
"description" = "This is neat!"
) . " WHERE `id` = '1'");
... PHP would generate, then run this SQL ...
mysql_query("UPDATE `table` SET `id` = '2', `position` = '1', `visible` = '1',
`name` = 'My Name\'s John', `description` = 'This is neat!' WHERE `id` = '1'");
I can do all of the nitty-gritty array conversion, but, for now, all I need is a way for PHP to break the input up into strings and arrays, then evaluate each one separately.
I would like to avoid passing multiple values into the method.
A: In Ruby you could do this, but you're out of luck in PHP. The good news is, you can modify what you're doing slightly to pass the query and the parameters separately as arguments to the query method:
$db->query("UPDATE `table` SET ? WHERE `id` = '1'", array(
"id" = "2",
"position" = "1",
"visible" = "1",
"name" = "My Name's John",
"description" = "This is neat!"
);
And then handle the interpolation and concatenation in your Database object:
class Database {
function __construct() {
// Connect to the database, code not shown
}
public function query($query, $input) {
$sql = $this->_normalize_query($query, $input)
mysql_query($sql);
return true;
}
protected function _normalize_query($query, $input) {
$params = "";
foreach($input as $k => $v) {
// escape and assemble the input into SQL
}
return preg_replace('/\?/', $params, $query, 1);
}
}
However
There are already a lot of ORMs out there that are very capable. If you are looking for something to only assemble queries and not manage results, you can probably find something as well. It seems like you're reinventing the wheel needlessly here.
Good PHP ORM Library?
A: You could write a sort of Helper functions which would work something like:
(inside of class Database { )
public function ArrayValues($array)
{
$string = "";
foreach($array as $Key => $Value)
{
$string .= "`$Key` = '$Value' ,";
}
// Get rid of the trailing ,
// Prevent any weird problems
if(strlen($string) > 1)
{
$string = substr($string, 0, strlen($string) - 2);
}
return $string;
}
Then you'd use it like:
$db->query("UPDATE `table` SET " .
$db->ArrayValues(array("id" = "2",
"position" = "1",
"visible" = "1",
"name" = "My Name's John",
"description" = "This is neat!"
)) . " WHERE `id` = '1'");
I haven't tested this, however it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5394838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fast join for a lot of dataframes Suppose I have around 480 dataframes. Each dataframe is organised as follows:
*
*Each dataframe has around 600*512 rows
*Each dataframe has 6 relevant columns, whose one (timestamp) is unique and can be used as index.
*Each dataframe may miss some rows (i.e., some timestamps), so concatenating them is not possible.
*Before performing the concatenation, I need to concatenate two dataframe index-wise (to extend the timestamps)
My current solution is to incrementally build a dataframe:
# Function to concat index wise the dataframes
def get_joint_dataframe(it, trial_path):
train_path = os.path.join(trial_path, "train_results_iteration_{0}.csv".format(it)) # 1st dataframe
test_path = os.path.join(trial_path, "results_iteration_{0}.csv".format(it)) # 2st dataframe
train_df = pd.read_csv(train_path)
test_df = pd.read_csv(test_path)
train_df = pd.concat([train_df, test_df], axis=0, ignore_index=True)# safe to do as I know index sets are disjoint
train_df = train_df.sort_values(by = 'timestamp').reset_index(drop=True)
return train_df
# Build incremental dataframe
def get_action_df_speedup(trials):
df_action_all = None # Incremental dataframe
policy_count = 0
for trial in trials:
for it in range(1, 11):
df_action = get_joint_dataframe(it, trial)[['timestamp', 'day', 'action']] # In the real case there are 3 additional columns
df_action = df_action.rename(columns={'action':'policy_{0}'.format(policy_count)})
columns_to_join = ['policy_{0}'.format(policy_count)] # I do not need to join 'day', just use the one of the first dataframe
df_action.set_index('timestamp', inplace=True)
if df_action_all is None:
df_action_all = df_action
else:
df_action_all = df_action_all.join(df_action[columns_to_join], how="inner")
policy_count += 1
df_action_all.reset_index(inplace=True, drop=False)
return df_action_all
I actually perform a join as in other overflow posts I saw that it tends to be faster than merge when using the column as index. However, this code takes WAY too much time (for 20 dataframes, about 40 seconds, so 2 hours and half for the whole dataset).
Is there a way to speedup this setup?
EDIT: I am sorry for not posting an example of csv
timestamp day action reward Q Q1 Q2 Q0
0 2.017010e+12 2017/01/03 0.0 0.0 0.008301 0.008301 -1.111009 -0.172822
1 2.017010e+12 2017/01/03 0.0 0.0 0.000000 0.000000 0.000000 0.000000
2 2.017010e+12 2017/01/03 0.0 0.0 0.000000 0.000000 0.000000 0.000000
3 2.017010e+12 2017/01/03 0.0 0.0 0.000000 0.000000 0.000000 0.000000
4 2.017010e+12 2017/01/03 0.0 0.0 0.000000 0.000000 0.000000 0.000000
Note timestamps are unique, even if it does not seem so. Moreover, in a previous version I thought about concatenating all dfs via a list, but I needed to rename all columns and also, in principle, I CANNOT concatenate dfs straight away.
EDIT 2: I developed a solution which in principle takes less time (around 120, which is definitely better)
# Get action dataframe, along with a translator to get the path of a trial
def get_dfs_speedup(trials):
# Logic
def manage_df(iteration, trial, policy_count, translator, columns_Q, columns_pol):
action_df = get_joint_dataframe(iteration, trial)[['timestamp', 'day', 'action', 'Q0', 'Q1', 'Q2']]
translator['policy_{0}'.format(policy_count[0])] = (trial, iteration)
dict_transl_action = {'action':'policy_{0}'.format(policy_count[0])}
dict_transl_Q = {'Q{0}'.format(i):'policy_{1}_Q{0}'.format(i, policy_count[0]) for i in range(3)}
action_df = action_df.rename(columns={'action':'policy_{0}'.format(policy_count[0])})
action_df = action_df.rename(columns={'Q{0}'.format(i):'policy_{1}_Q{0}'.format(i, policy_count[0]) for i in range(3)})
action_df.set_index('timestamp', inplace=True)
# Update translator
# Collect indexes which will be used to index dataframe
columns_Q.extend(list(dict_transl_Q.values()))
columns_pol.extend(list(dict_transl_action.values()))
# We now add the df to list
columns_to_join = list(dict_transl_action.values())
columns_to_join.extend(list(dict_transl_Q.values()))
if policy_count[0] == 0:
columns_to_join.append('day')
policy_count[0] += 1
print("Done policy: {0}".format(policy_count[0]))
return action_df[columns_to_join]
translator = {}
columns_Q = ['day']
columns_pol = ['day']
policy_count = [0]
all_dfs = [manage_df(iteration, trial, policy_count, translator, columns_Q, columns_pol) for iteration, trial in it.product(list(range(1, 11)), trials)]
# Now we simply concatenate columns wise
all_dfs = pd.concat(all_dfs, axis=1, ignore_index=False, join='inner')
# We want both action and q dfs, with translator
#print(columns_Q, all_dfs.columns)
Q_df = all_dfs[columns_Q]
actions_df = all_dfs[columns_pol]
# We reset_index to get back our timestamp
Q_df.reset_index(drop=False, inplace=True)
actions_df.reset_index(drop=False, inplace=True)
# End
return Q_df, actions_df, translator
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72747649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Failed to get the output of jenkins pipeline sh step result inside Declarative Pipeline I would like to get an output of my sh result by using this way:
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
result=sh(script:'ls -al', returnStdout: true)
}
}
}
}
Then it prints an error to me:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 8: Expected a step @ line 8, column 13.
result=sh(script:'ls -al', returnStdout: true)
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:129)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:123)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:517)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:480)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:268)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
If an use the traditional script way, it works very well.
node {
stage("Fetch code from git") {
echo 'Hello World'
result = sh(script:'ls -al', returnStdout: true)
echo result
}
}
A: Since you are assigning the return value of the method invocation to a variable, this now becomes scripted, and you will need to encapsulate the step within a script block for declarative DSL:
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
script {
result=sh(script:'ls -al', returnStdout: true)
}
}
}
}
}
A: The shell commands must be run inside a sh block in a declarative pipeline.
eg:
pipeline {
agent any
stages {
stage('Hello') {
steps {
sh 'echo "Hello World"'
result=sh(script:'ls -al', returnStdout: true)
}
}
}
}
You can also refer to https://www.jenkins.io/doc/pipeline/tour/running-multiple-steps/ for more information.
A: do something like this
pipeline {
agent any
stages {
stage('Hello') {
steps {
sh 'echo Hello World'
scripts {
result = sh(script:'ls -al', returnStdout: true)
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62548359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: array should not spit out on a screen php I have made a form where user post data like names product and links. For validation I am using FILTER_VALIDATE_URL. Now what i want is after validation only host insert into database. like https://www.google.com. Only www.google.com insert in database. For doing this i am using
$website = var_dump(parse_url($websitex, PHP_URL_HOST));
$sql = "INSERT INTO test (Name, Contact, Product) Value ($name, $website, $product)
$result = mysqli_query($dbc_conn, $sql);
Now the problem the host data not going into database plus the host array show into the screen. What i want is only host data insert and array not show on the screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47495334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# Instagram private api GetUserTimelineFeedAsync function "Mothod not allowed" I am developing utility application using c# instagram private api.
Almost apis are working greatly but the GetUserTimeLineFeedAsync function returns Method Not Allowed [405] response.
Is there anyone who can help me?
A: I am not sure which library you are using now.
According to my experience, 405 errors are almost about the bad path problem.
So please check the api url is correct or not.
PLEASE PAY ATTENTION TO THE LAST SLASH '/' OF THE API URL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59479328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mysql complex select query for fetching rows as column issue I am trying to write select query for MySQL DB which will give me output like below:
enter image description here
TEACHER_ID
Image1
Image2
Image3
Image4
Image5
341
1.jpeg
2.jpeg
10.jpeg
20.jpeg
30.jpeg
734
3.jpeg
4.jpeg
40.jpeg
50.jpeg
60.jpeg
Following are the screen shots of the two tables from which I am trying to fetch records-
Table-1
Table-2
I have written following sql query for particular teacher_id:
SELECT R.SCHOOL_ID,R.TEACHER_ID,R.IMAGE_NAME REG_IMAGE_NAME,A.IMAGE_NAME
ATT_IMAGE_NAME,A.ATTENDANCE_DT,A.ATTENDANCE_TYPE
FROM TABLE1 R (NOLOCK)
JOIN
TABLE2 A (NOLOCK)
ON R.TEACHER_ID = A.TEACHER_ID
WHERE A.TEACHER_ID = '341'
AND A.ATTENDANCE_DT = '2022-02-21'
ORDER BY A.ATTENDANCE_TYPE;
But I am struggling to write one which will give me required output not only for a particular teacher_id but for all.
Since I cannot add excel file here, I am attaching here table1, table2 xlsx files dummy data.
Table1
Table2
Please have a look and let me know in case I have missed here to add.
Adding dummy data in form of text as asked by others-
Table1:
SCHOOL_ID
TEACHER_ID
IS_HEAD_MASTER
TAGGED_CLASS
IMAGE_NAME
LATITUDE
LONGITUDE
ACCURACY
CREATED_DATE
CREATED_BY
AI_IMAGE_NAME
AI_STATUS
IS_DOWNLOADED
DOWNLOADED_DATE
IS_PROCESSEED
204
341
Y
10.jpeg
1.1
2.1
80
49:33.0
28110100204
NULL
NULL
NULL
16:54.0
NULL
204
341
Y
20.jpeg
1.1
2.1
80
49:33.0
28110100204
NULL
NULL
NULL
16:54.0
NULL
204
341
Y
30.jpeg
1.1
2.1
80
49:33.0
28110100204
NULL
NULL
NULL
16:54.0
NULL
204
734
N
40.jpeg
1.2
2.2
90
55:59.3
28110100204
NULL
NULL
NULL
16:54.0
NULL
204
734
N
50.jpeg
1.2
2.2
90
55:59.3
28110100204
NULL
NULL
NULL
16:54.0
NULL
204
734
N
60.jpeg
1.2
2.2
90
55:59.3
28110100204
NULL
NULL
NULL
16:54.0
NULL
Table2:
TEACHER_ID
TAGGED_SCHOOL_ID
ATTENDANCE_DT
ATTENDANCE_TYPE
IMAGE_NAME
LATITUDE
LONGITUDE
ACCURACY
CAPTURED_TIME
AI_IMAGE_NAME
AI_STATUS
IS_DOWNLOADED
DOWNLOADED_DATE
IS_PROCESSEED
341
204
21-02-2022
IN
1.jpeg
1.1
2.1
80
37:16.0
NULL
NULL
NULL
NULL
NULL
341
204
21-02-2022
OUT
2.jpeg
1.2
2.2
80
55:45.0
NULL
NULL
NULL
NULL
NULL
734
204
21-02-2022
IN
3.jpeg
1.3
2.3
80
24:24.0
NULL
NULL
NULL
NULL
NULL
734
204
21-02-2022
OUT
4.jpeg
1.4
2.4
80
31:47.0
NULL
NULL
NULL
NULL
NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71217602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to upgrade com.squareup.okhttp(4.6.0) in GRPC OkHttp version (1.29.0)? gRPC-Java with lastest Version of GRPC OkHttp » 1.29.0
dependency - "io.grpc:grpc-okhttp:1.29.0"
link - https://mvnrepository.com/artifact/io.grpc/grpc-okhttp/1.29.0
which is use okhttp(com.squareup.okhttp:2.7.4) but I want to upgrade into in higher(4.6.0).
1
[screenshot from - https://mvnrepository.com]
Because in older version have some security issues in SSL/TLS.
A: The security issues in OkHttp 2.7.4 are in parts of the code not used by gRPC. In particular, none of the TLS code from OkHttp is used. There are no security issues in your configuration unless you also use OkHttp 2.7.4’s APIs directly.
Later releases of OkHttp use a different package name: okhttp3 instead of com.squareup.okhttp, so upgrading OkHttp won't help you anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61813339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do i compare the "EndDate" in my database to the current date of today? I want to execute query depending on if EndDate is < Today's date.Here is what i have so far, i need to know how to compare them Thanks!
//Delete from DB Condition (EndDate)
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
Clear();
this is the stored procedure.
ALTER PROC [dbo].[DeleteByDate]
@AdvID int
AS
BEGIN
UPDATE a SET a.Status = 0
FROM Advertisement a
WHERE a.AdvID = @AdvID
END
A: You can handle it from C# or SQL like this :
C#
if(EndDate < DateTime.Now.Date) // Assuming EndDate is already defined in your class
{
using(SqlConnection sqlCon = new SqlConnection(sqlCon.ConnectionString) )
using(SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon))
{
sqlCon.Open();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("@AdvID", SqlDbType.Int);
sqlCmd.Parameters["@AdvID"].Value = AdvID //Assuming it's already defined;
sqlCmd.ExecuteNonQuery();
}
}
SQL :
ALTER PROC [dbo].[DeleteByDate]
@AdvID int
AS
BEGIN
DECLARE @CurrentDate DATE = GETDATE() -- to get current date
-- Assuming that Advertisement table has the column EndDate
IF EXISTS (SELECT * FROM Advertisement a WHERE a.EndDate < @CurrentDate )
BEGIN
UPDATE a SET a.Status = 0
FROM Advertisement a
WHERE a.AdvID = @AdvID
END
END
If you go with C#, it won't fire the sp until the condition is met, but in SQL, it'll make your C# fires the sp, and the sp will check the condition every time your code runs it.
So, it depends in your application structure, is it application first, or database first, which comes first would be your way to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54476576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hide cursor from objects on the webpage I want to hide my mouse cursor whenever someone goes over the object tag. But cursor:none is not working for objects while it works with rest of the page.
Here is what i am using but i am failing do it.
<object id="obj" class="obj" style="cursor:none;" data='bla-bla.pdf'
type='application/pdf'
width='1000px'
height='640px'>
cursor:none is not working. Please tell me any way to do this.
A: Just use an overlay; <object>s can act funny.
HTML:
<div id="obj_container">
<object id="obj" src="blablabla.pdf"></object>
<div id="obj_overlay"></div>
</div>
CSS:
#obj_container{
position:relative;
}
#obj{
position:absolute;top:0;left:0;
z-index:2;cursor:none;
}
See this JSFiddle demo for more complete code.
A: Yes try using div:
Your HTML:
<div style="cursor:none;">
<object id="obj" class="obj" data='bla-bla.pdf' type='application/pdf'
width='1000px' height='640px'>
</div>
A: How about something like this: http://jsfiddle.net/ZBv22/
It applies a mask over the object element where you specify cursor:none.
The only issue is if you need the object to be clickable/interacted with. Depending on your targeted browsers (modern, IE11+), you could add pointer-events: none to address that.
http://caniuse.com/pointer-events
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21686051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Grabbing selected dropdown list item to add to query string Trying to grab the selected item from the dropdown list, and add to the query string for an ajax call. I can't seem to be able to grab the value of the selected item. I'm trying with $("select#areaCode").filter(":selected").val(), but can't grab the item.
$("#phone").validate({
errorPlacement: function (error, element) {
error.insertAfter($(element).parent('div'));
},
rules: {
phone: {
required: true,
phoneUS: true
}
},
messages: {
phone: {
phoneUS: "Please enter a valid US number",
phoneUK: "Please enter a valid UK number"
}
},
submitHandler: function (form) {
$.ajax({
url: '/textMessage/' + $("select#areaCode").filter(":selected").val() + $('input[name="phone"]').val(),
method: "GET",
success: function () {
console.log(form);
}
});
return false;
}
});
<form id="phone">
<div class="col-md-10">
<div class="modal-header" style="text-align: center;">
<h5>Get a link on your phone</h5>
<div class="input-group">
<div class="input-group-btn">
<button id="label" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span id="areaCode">+1</span><span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="1">US: +1</a>
</li>
<li><a href="#" id="44">UK: +44</a>
</li>
</ul>
</div>
<input class="form-control phone" name="phone" aria-label="..." placeholder="Your phone number" type="text"> <span class="input-group-btn">
<input class="btn btn-default" type="submit">SUBMIT</input>
</span>
</div>
</div>
</div>
</form>
A: using $("select#areaCode").find(":selected").val() should work.
EDIT
You should change:
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="1">US: +1</a>
</li>
<li><a href="#" id="44">UK: +44</a>
</li>
</ul>
to:
<select id="areaCodes">
<option value="1">US: +1</option>
<option value="44">UK: +44</option>
</select>
now using:
$("#areaCodes").find(":selected").val();
Will return the selected option value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28196280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery ajax not worked on my pc I try to use AJAX get method on my PC .
My jquery version is 1.10 , and my problem detected when i move files from other system's localhost to my desktop .
I'm see the code do correct in other system localhost but when moved on my desktop not worked and show this error on google chrome :
OPTIONS file:///C:/Users/Ab3/Desktop/od/file3.htm Origin null is not allowed by Access-Control-Allow-Origin. jquery.min.js:6
XMLHttpRequest cannot load file:///C:/Users/Ab3/Desktop/od/file3.htm. Origin null is not allowed by Access-Control-Allow-Origin. index.html:1
and in firefox not worked ,but don't show any error in fire bug.
my html code is :
<button class="tt" title="1" > btn1 </button>
<button class="tt" title="2" > btn2 </button>
<button class="tt" title="3" > btn3 </button>
<div class="pop" id="popup">
<div class="popup_close" id="pclose"></div>
</div>
and my jquery code :
$(document).ready(function (){
$(".tt").click(function () {
var val = $(this).attr('title') ;
//alert(val);
$.get("file"+val+".htm",function (inp) {
alert(1);
$(".pop").html(inp);
});
$('#popup').show(300);
});
$('#pclose').click(function (){
$('#popup').hide(300);
});
});
and I'm sure file's file1.htm file2.htm file3.htm exists.
how can i solve my pb.
A: Ajax is working on your computer, but not with url begining with file:// because ajax needs to request the server to get a file. So, if you want to use ajax, you have to install a wamp server and move your files in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17769303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A phone number from a large list of phone numbers is a pre-number for another phone number? Example_List=[112,34533344,11234543,98]
In the above list, we can see that 112 is a pre-number of 11234543. How can I check this in python? I think re.match or re.search are one of the solutions ?
A: You can turn your numbers into strings and then sort them.
Afterwards if one number is a pre-number all numbers that start with it will follow and once a number does not start with it anymore you found all.
Example_List=[112,34533344,11234543,98]
list_s = sorted(str(i) for i in Example_List)
result = []
for i in range(len(list_s)):
k=i+1
while k<len(list_s) and list_s[k].startswith(list_s[i]):
result.append((list_s[i],list_s[k]))
k += 1
print(result)
A: If you want to find all numbers, starting with any number from your list you could do something like this:
#Converte your list of ints to list of strings
tmp = map(lambda x : str(x),l)
#Use a set so you duplicate entries are eliminated
result = set()
for x in tmp:
#Insert all numbers starting with the current one
result.update([y for y in filter(lambda z : z.startswith(x) and z != x, l)])
#Convert your set of ints to a list of strings
result = list(map(int, result))
A: A single list comprehension will return all numbers in your list (as integers) which start with a specified "pre-number":
In [1]: Example_List=[112,34533344,11234543,98]
In [2]: [num for num in Example_List if str(num).startswith('112')]
Out[2]: [112, 11234543]
If your pre-number is always the first entry in your list but may be different for different lists then you can still do it in one line, but it's a little longer:
In [3]: [num for num in Example_List[1:] if str(num).startswith(str(Example_List[0]))]
Out[3]: [11234543]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28806467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't Activate Rake (> 0.0.0)? Ok, this is very weird. I'm trying to do a database migration, and all of a sudden, I'm getting these errors:
[C:\source\fe]: rake db:migrate --trace
(in C:/source/fe)
** Invoke db:migrate (first_time)
** Invoke setup (first_time)
** Invoke gems:install (first_time)
** Invoke gems:set_gem_status (first_time)
** Execute gems:set_gem_status
** Execute gems:install
rake aborted!
can`'t activate rake (> 0.0.0), already activated rake-0.8.3]
c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:139:in `activate'
c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:155:in `activate'
c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `each'
c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `activate'
c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:49:in `gem'
C:/source/fe/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:36:in `add_load_paths'
C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths'
C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `each'
C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths'
C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `send'
C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `run'
C:/source/fe/config/gems.rb:45:in `init_dependencies'
C:/source/fe/lib/tasks/overridegems.rake:15
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain'
c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain'
c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain'
c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run'
c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31
c:/ruby/bin/rake:19:in `load'
c:/ruby/bin/rake:19
[C:\source\fe]:
Any suggestions? I've tried uninstalling and reinstalling rake, as well as updating rails.
FYI, I'm using Gem 1.1.1.
I've also tried gem update rails, gem update rake and just about anything else.
A: Interestingly, the solution here was that i needed to downgrade my rake version. The local version (in my C:\ruby dir) was overriding the one in the source directory, and couldn't be loaded. I had done gem update and updated all my local gems.
The commands were:
gem uninstall rake
gem install rake -v ('= 1.5.1')
A: I had a problem similar to this, which I ended up working around by hacking my rails version to not initialize active resource (by modifying the components method in /rails/railties/builtin/rails_info/rails/info.rb )
This is clearly a hack, but I didn't have a chance to work out why active_resource specifically was causing the rake conflict, and since I wasn't using active_resource anyway, it got me through the night.
A: rake aborted!
can`'t activate rake
It is mid-Autumn - perhaps too many leaves have fallen and the rake can't be used. Try using the leaf-blower instead.
Next time, keep up with the raking to prevent this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/245334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In an ASP.NET Web Setup Project, can I disable anonymous access in IIS? I have a really simple ASP.NET web application and a web setup project that deploys the project output and content files to a virtual directory in IIS.
What I want is for the MSI to automatically disable Anonymouse Access for that virtual folder in IIS.
I suspect it can probably be done by writing some code in a custom action DLL, that would be acceptable, but is there any way to do it within the the settings of the web setup project?
A: I'm sure you know that you could disallow users who are not authenticated via web.config
<system.web>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
would do it I think.
A: Taken from technet
The property for anonymous access is
unfortunately not available through
Web setup projects. For this reason,
you must:
*
*Write a custom installer to enable or disable anonymous access.
*Pass the necessary parameters from the setup wizard to the installer at
run time.
A: <configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="SignIn.aspx" defaultUrl="Welcome.aspx" protection="All">
<credentials passwordFormat="Clear">
<user name="lee" password="lee12345"/>
<user name="add" password="add12345"/>
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" /> //deny acces to anonymous users
</authorization>
</system.web>
</configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/298432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Exclude part of server name from Get-Snapshot PowerShell Script What I am trying to do is get a list of VM Snapshots but exclude any snapshots that contain the VM naming convention of "ABCDE" and that the snapshots are over 3 days old and output it to a text file.
The script that I have thus far is the following but it is not excluding the servers that begin with "ABCDE".
# Get VM Snapshot Information excluding anything with HEIEPC
Get-VM | Where {$_.Name -ne "ABCDE"} |
Get-Snapshot |
Where-Object { $_.Created -lt (Get-Date).AddDays(-3) } |
Format-List | Out-File $Log -Append
A: You're checking for VMs with the exact name "ABCDE". To check for VMs whose name begins with "ABCDE" use the -like operator and a wildcard:
Get-VM | Where { $_.Name -notlike 'ABCDE*' } | ...
Make the pattern *ABCDE* if you want to exclude VMs with the substring "ABCDE" anywhere in their name (not just the beginning).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40002733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mysql select top n max values How can you select the top n max values from a table?
For a table like this:
column1 column2
1 foo
2 foo
3 foo
4 foo
5 bar
6 bar
7 bar
8 bar
For n=2, the result needs to be:
3
4
7
8
The approach below selects only the max value for each group.
SELECT max(column1) FROM table GROUP BY column2
Returns:
4
8
A: For n=2 you could
SELECT max(column1) m
FROM table t
GROUP BY column2
UNION
SELECT max(column1) m
FROM table t
WHERE column1 NOT IN (SELECT max(column1)
WHERE column2 = t.column2)
for any n you could use approaches described here to simulate rank over partition.
EDIT:
Actually this article will give you exactly what you need.
Basically it is something like this
SELECT t.*
FROM
(SELECT grouper,
(SELECT val
FROM table li
WHERE li.grouper = dlo.grouper
ORDER BY
li.grouper, li.val DESC
LIMIT 2,1) AS mid
FROM
(
SELECT DISTINCT grouper
FROM table
) dlo
) lo, table t
WHERE t.grouper = lo.grouper
AND t.val > lo.mid
Replace grouper with the name of the column you want to group by and val with the name of the column that hold the values.
To work out how exactly it functions go step-by-step from the most inner query and run them.
Also, there is a slight simplification - the subquery that finds the mid can return NULL if certain category does not have enough values so there should be COALESCE of that to some constant that would make sense in the comparison (in your case it would be MIN of domain of the val, in article it is MAX).
EDIT2:
I forgot to mention that it is the LIMIT 2,1 that determines the n (LIMIT n,1).
A: If you are using mySQl, why don't you use the LIMIT functionality?
Sort the records in descending order and limit the top n i.e. :
SELECT yourColumnName FROM yourTableName
ORDER BY Id desc
LIMIT 0,3
A: Starting from MySQL 8.0/MariaDB support window functions which are designed for this kind of operations:
SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY column2 ORDER BY column1 DESC) AS r
FROM tab) s
WHERE r <= 2
ORDER BY column2 DESC, r DESC;
DB-Fiddle.com Demo
A: This is how I'm getting the N max rows per group in MySQL
SELECT co.id, co.person, co.country
FROM person co
WHERE (
SELECT COUNT(*)
FROM person ci
WHERE co.country = ci.country AND co.id < ci.id
) < 1
;
how it works:
*
*self join to the table
*groups are done by co.country = ci.country
*N elements per group are controlled by ) < 1 so for 3 elements - ) < 3
*to get max or min depends on: co.id < ci.id
*
*co.id < ci.id - max
*co.id > ci.id - min
Full example here:
mysql select n max values per group/
mysql select max and return multiple values
Note: Have in mind that additional constraints like gender = 0 should be done in both places. So if you want to get males only, then you should apply constraint on the inner and the outer select
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6056162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: What is gradle version which should be used with 3.6.1 android studio My question is simple, with android studio 3.6.1, my existing project have stopped working, I have tried to update below two files only, but no use.
Please note I am not a developer, So I will really appreciate, if solution can be given in layman terms.
I am getting below errors-
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ':classpath'.
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.android.tools.build:gradle:3.6.0.
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: No cached version of com.android.tools.build:gradle:3.6.0 available for offline mode.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
buildToolsVersion '28.6.0'
defaultConfig {
applicationId "dhritiapps.tulsiramayan"
minSdkVersion 16
targetSdkVersion 28
versionCode 5
versionName "1.04"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
// implementation 'com.firebase:firebase-client-android:2.5.2'
implementation 'com.google.android.gms:play-services-ads:19.0.1'
testImplementation 'junit:junit:4.13'
}
second file
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
A: I think this error is because your dependencies in your second file (version 3.6.0) aren't the same as your Android Studio version (version 3.6.1) .
Try changing your dependencies to:
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61125719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Appending extra toolbar in fragment view In my application on the dashboard, there is an application bar that looks something like the image below.
As shown in the image, I have a toolbar that currently shows the Navigation drawer.
From the navigation drawer, I can navigate to a fragment A that replaces the TAB area under the toolbar as shown in the image below.
Is there any way I can add two toolbars like this where I can show the navigation drawer icon and back button together inside a fragment?
A: There is no best way to achieve what you are looking for, considering it goes against the Android Design Guidelines. Although not explicitly stated, the navigation drawer icon and the back button icon are never displayed together.
The theory behind this design is that navigation should be intuitive and predictable, displaying two navigational icons next to each other detracts from an intuitive user interface. The back button should be displayed if there is something to go back to. Though, the need for persistent navigation can be addressed in two different ways. Take Google's Gmail app for example.
By default the NavigationView supports using a swipe from the left edge of the screen as a gesture to open the navigation drawer. In the Gmail app, the navigation drawer icon is show while you are in any one of your inboxes. As soon as a message is selected, the navigation drawer icon is replaced with the back button. Though, you will notice that you can still access the drawer using the gesture stated previously.
On larger screens, the Gmail app supports a miniature navigation drawer. This drawer can remain in view without the need to display to navigational icons. Though this is a little more difficult to implement with the current support library, if you are looking to, this answer may help.
Finally, to answer your question, there is no built-in way to display a back button and a navigation drawer icon together. If you need to do so, the only way would be to use a "work-around", as you currently are.
Though, the only change I would probably make is to use an ImageButton rather than an ImageView. Then you can set the style of the button using style="?android:attr/actionButtonStyle" to mimic the look of an ActionBar button.
A: Just to update, for the time being, to achieve the above what I have done is.
I added a layout to my fragment file where I draw a custom back button like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark20"
android:orientation="horizontal"
android:padding="15dp"
android:weightSum="3">
<ImageView
android:id="@+id/backButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:layout_weight="0.2"
android:src="@drawable/delete_icon" />
</LinearLayout>
When a person clicks on backImage, I call popBackStack.
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
The above code gives me the desired functionality.
Note, for the above to work you need to make sure you are adding your fragmentTransaction to backstack as below
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_content_layout,NAME_OFYOUR_FRAGMENT,"nameOfYourFragment");
transaction.addToBackStack(null);
transaction.commit();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38436040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update to specific R version on Linux (Red Hat/CentOS), keeping the previous version? Perhaps a more accurate title would be: "How to switch from in-place (EPEL) R to side-by-side (version-specific) R installation on Linux (Red Hat/CentOS)?
A (possibly typical) upgrading R on Linux story...
History:
At some point in the past, I updated the version of R on our RHEL/CentOS 7 server using the default version pulled down by the yum package manager at that time. For example, sudo yum install R to version 3.5.2 at some point in early 2019. By default, this installs R at /usr/lib64/R for all users and completely replaces the 3.4.x version that had previously been installed there. Shiny Server was already installed, configured to run as user shiny, and it picked up the new version of R without a hitch.
Situation:
A year later, it is now time to bite the bullet and update the version of R that is running on the Linux server. Running yum check-upgrade R I find that the version available is 3.6.0. I actually want to install 3.6.3 AND I don't want to break all of my apps that are running on 3.5.2, so I need to use a different method. Following the instructions found at https://docs.rstudio.com/resources/install-r/, I download the 3.6.3 .rpm file and install it. By default, this installs R at /opt/R/3.6.3/, leaving the 3.5.2 version as is. However, as soon as I complete the Create a symlink to R step, none of my shiny apps work:
sudo ln -s /opt/R/3.6.3/bin/R /usr/local/bin/R
sudo ln -s /opt/R/3.6.3/bin/Rscript /usr/local/bin/Rscript
This should not be surprising. My shiny apps all rely upon several R packages that have not yet been installed for this new version of R. I can quickly get my apps working again on the previous version (3.5.2) by removing these symlinks until after I've installed the necessary packages in the new version:
sudo rm /usr/local/bin/R
sudo rm /usr/local/bin/Rscript
Error messages in my shiny app log files (at /var/log/shiny-server/<app name>-<user>-<datetime>.log) confirm that the apps had failed to launch due to missing packages. To update the R packages in the shared library folder, I need to run the new version of R as sudo: sudo -i /opt/R/3.6.3/bin/R and install the necessary packages, e.g., install.packages(c("shiny","devtools","rmarkdown","shinydashboard","tidyverse")) in R.
Now that the R packages are installed, I can re-create the symlinks:
sudo ln -s /opt/R/3.6.3/bin/R /usr/local/bin/R
sudo ln -s /opt/R/3.6.3/bin/Rscript /usr/local/bin/Rscript
I verify that my apps are working with the new version of R.
Now I have some questions:
Question 1: After completing these steps, R --version still returns the old version (3.5.2). But when I logged back in the following day, it opens 3.6.3. Why? Do I need to run a terminal command to get R --version to return the new version immediately or is opening a new terminal window the only way to achieve this?
Question 2: Running sudo R --version always returns the old version (3.5.2). Running sudo which R returns /bin/R. Running more /bin/R reveals contents which state that it is "Shell wrapper for R executable." and has the "/usr/lib64/R" path hard-coded. I don't think I need this wrapper at this point. What is the recommended way to get these sudo commands to point to the new version?
I can make a backup copy of this file in my home directory (e.g., cp /bin/R ~/binR.backup) just in case, and then:
*
*Delete /bin/R?
*Replace /bin/R with a symlink to the new version (e.g., sudo ln -s /opt/R/3.6.3/bin/R /bin/R)?
*Re-install the 'old' version into /opt/R/3.5.2/ using a .rpm the same way I installed 3.6.3, install packages there, and then remove the /usr/lib64/R version (e.g., sudo yum remove R)?
Links to similar questions that I looked at but didn't answer my questions:
*
*How to upgrade R in Linux
*Change path in Linux
*How can I load a specific version of R in Linux
A: Question 1: I'm not sure why, but having multiple versions of R on your PATH can lead to unexpected situations like this. /usr/local/bin is usually ahead of /usr/bin in the PATH, so I would've expected R 3.6.3 to be found. Perhaps it has to do with Question 2.
Question 2: Some distros (like CentOS/RHEL) don't put /usr/local/bin on the PATH by default when using sudo. See https://unix.stackexchange.com/questions/8646/why-are-path-variables-different-when-running-via-sudo-and-su for details. The answers there describe several ways to add /usr/local/bin to the PATH when using sudo -- for example, modifying secure_path in /etc/sudoers to include /usr/local/bin like:
Defaults secure_path = /usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
With R 3.6.3 ahead of the default system R in the PATH, you shouldn't have to delete /bin/R or /usr/bin/R. But eventually, I'd recommend installing multiple side-by-side versions of R the same way, using https://docs.rstudio.com/resources/install-r/, so it's easier to manage. The next time you install a new R version, you can just replace the symlinks in /usr/local/bin. The default system R (from EPEL) is meant to be the only R on a system, with in-place upgrades.
If you want to replace the default R 3.5.2 with a side-by-side R 3.5.2 (or 3.5.3), you could install R 3.5 from https://docs.rstudio.com/resources/install-r/, install all necessary packages, and have Shiny Server use the new R 3.5. Then uninstall the R from EPEL (R-core or R-core-devel) to fully switch over. From there, you could even create symlinks to R in /usr/bin instead of /usr/local/bin, and not worry about adding /usr/local/bin to the sudo PATH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61646933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Detect if "enable system diagnostics" is checked for conditionals in pipeline file and scripts I need to use the "enable system diagnostics" checkbox state in the pipeline run UI. How do I check if it was checked? For both pipeline YAML file and in a bash script.
A:
Detect if “enable system diagnostics” is checked for conditionals in pipeline file and scripts
The answer is yes.
If we enable the checkbox "enable system diagnostics" in the pipeline run UI, we could get following info in the build log:
agent.diagnostic : true
So, we could use this variable for conditionals in pipeline file and scripts.
But, there is a little different from the Boolean variables we usually use. If we do not enable the checkbox enable system diagnostics, Azure devops will not create this variable to overwrite the variable sysytem.debug. So this variable does not exist at this time, we cannot directly determine whether its value is true or false. We could judge whether this value exists to judge its result.
Below is my test bash scripts for this condition:
- bash: |
if [ -z "$(agent.diagnostic)" ]
then
echo "enable system diagnostics is Unchecked"
else
echo "enable system diagnostics is Checked"
fi
displayName: 'enable system diagnostics'
A: This is equivalent to the System.Debug variable. As an environment variable, SYSTEM_DEBUG.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64935381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angularjs ui.routing - add attribute to input elements before rendering HTML into ui-view I am using angular js - ui.router concept for SinglePageApplication Development.
When I click Page 1 and Page 2 link, then its respective html page will be rendered into 'ui-view' div. I want to add 'data-ng-blur' attribute into respective html page(Sample.html, Sample2.html), input controls while click 'ui-sref' link. I have give Document ready events in
that both htmls, But that's not fired. So there is any option for add attributes for input elements in loading html before its respective Controller called by ui-router.
<div data-ng-app="ProjectApp">
<div class="menulist">
<li><a ui-sref="pageone">Page 1</a></li>
<li><a ui-sref="pagetwo">Page 2</a></li>
</div>
<div class="ui-view"></div>
<script>
var loApp = angular.module("ProjectApp", ["ui.router"]);
loApp.config(function ($urlRouterProvider, $stateProvider, $urlMatcherFactoryProvider) {
$urlMatcherFactoryProvider.caseInsenstiveMatch = true;
$stateProvider
.state('pageone', {
url: '/Screen-one',
templateUrl: 'Sample.html',
controller: pageoneCtrler
})
.state('pagetwo', {
url: '/Screen-two',
templateUrl: 'Sample2.html',
controller: pagetwoCtrler
});
});
loApp.controller("pageoneCtrler", function ($scope) {
$scope.myfunction = function(){
}
});
loApp.controller("pagetwoCtrler", function ($scope) {
});
</script>
</div>
A: You can use the concept of interceptor of $httpProvider i guess
$httpProvider.interceptors
A: JQuery reference must be added before the angular js reference. If we add reference in this order, then document ready events fired of loaded htmls will be fired. Issue solved now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45211127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: excel macro, need an algorithm to compare two lists I need to make a macro to compare two columns looking for duplicate cells.
I'm currently using this simple double for loop algorithm
for i = 0 To ColumnASize
Cell1 = Sheet.getCellByPosition(0,i)
for j = 0 to ColumnBSi
Cell2 = Sheet.getCellByPosition(1,j)
' Comparison happens here
Next j
Next i
However, as I have 1000+ items in each column this algorithm is quite slow and inefficient. Does anyone here know/have an idea for a more efficient way to do this?
A: If you want to ensure that no string in col A is equal to any string in col B, then your existing algorithm is order n^2. You may be able to improve that by the following:
1) Sort col A or a copy of it (order nlogn)
2)Sort col B or a copy of it (order nlogn)
3) Look for duplicates by list traversal, see this previous answer (order n).
That should give you an order nlogn solution and I don't think you can do much better than that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25715386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Tensorflow: How to make the model train using `tfrecords` but test using `feed_dict` I recently completed training a Linear Regression model using a csv data.
The result of the trained data shown here:
However, I'm still dumbfounded as to how to use the model.
How do i give the model an "x" value such that it returns me a "y" value?
Code:
with tf.Session() as sess:
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
sess.run(init)
# Fit all training data
for epoch in range(training_epochs):
_, cost_value = sess.run([optimizer,cost])
#Display logs per epoch step
if (epoch+1) % display_step == 0:
c = sess.run(cost)
print( "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))
print("Optimization Finished!")
training_cost = sess.run(cost)
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
#Plot data after completing training
train_X = []
train_Y = []
for i in range(n_samples): #Your input data size to loop through once
X, Y = sess.run([col1, pred]) # Call pred, to get the prediction with the updated weights
train_X.append(X)
train_Y.append(Y)
#Graphic display
df = pd.read_csv("battdata2.csv", header=None)
X = df[0]
Y = df[1]
plt.plot(train_X, train_Y, linewidth=1.0, label='Predicted data')
plt.plot(X, Y, 'ro', label='Input data')
plt.legend()
plt.show()
print("train_X -- -")
print(train_X)
print("X -- -")
print(X)
print("train_Y -- -")
print(train_Y)
print("Y -- -")
print(Y)
save_path = saver.save(sess, "C://Users//Shiina//model.ckpt",global_step=1000)
print("Model saved in file: %s" % save_path)
coord.request_stop()
coord.join(threads)
Link to ipynb and csv files here.
A: You basically want the inputs to be fed to the network using queue runners during training, but then during inference you want to input it through feed_dict. This can be done by using tf.placeholder_with_default(). So when the inputs are not fed through feed_dict, it will read from the queues, otherwise it takes from 'feed_dict'. Your code should be like:
col1_batch, col2_batch = tf.train.shuffle_batch([col1, col2], ...
# if data is not feed through `feed_dict` it will pull from `col*_batch`
_X = tf.placeholder_with_default(col1_batch, shape=[None], name='X')
_y = tf.placeholder_with_default(col2_batch, shape=[None], name='y')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44871765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ : error : taking address of temporary [-fpermissive] So basically I'm having the error : taking address of temporary and I didn't exactly know why.
I tried to simplify the code to just focus on the issue itself . The error occurs on the adress array.
main.cpp has these lines below :
CPerson Student1("Test1", "street1.", "15a", 12045, "Berlin", 15, 9, 1989);
CPerson Student2("Test2", "street2", "27", 29031, "Milan", 27, 5, 1991);
CPerson Student3("Test3", "street3", "3-5", 12345, "Paris", 3, 11, 1987);
CPerson Student4("Test4", "street4", "23", 19885, "Tokyo", 19, 7, 1985);
CPerson *Studenten[4] = { &Student1, &Student2, &Student3, &Student4 };
CAddress *Adressen[4] = { &(Student1.getAddress()), &(Student2.getAddress()),
&(Student3.getAddress()), &(Student4.getAddress()) }; //Error occurs here
caddress.hpp :
class CAddress
{
public:
CAddress() = default;
void print() const;
friend class CPerson;
~CAddress(){};
private:
std::string Street;
std::string HouseNr;
unsigned Zipcode;
std::string City;
};
CPerson.hpp
class CPerson
{
public:
CPerson() = default;
CPerson(std::string m_Name, std::string m_Street,
std::string m_HouseNr, unsigned m_Zipcode,
std::string m_City, int m_Day, int m_Month, int m_Year);
CAddress getAddress();
void print() const;
~CPerson(){};
private:
unsigned ID;
std::string Name;
CAddress Address;
CDate Birthday;
};
CPerson.cpp
CPerson::CPerson(
string m_Name,
string m_Street,
string m_HouseNr,
unsigned m_Zipcode,
string m_City,
int m_Day, int m_Month, int m_Year)
{
Name = m_Name;
Address.Street = m_Street;
Address.HouseNr = m_HouseNr;
Address.Zipcode = m_Zipcode;
Address.City = m_City;
Birthday.Day = m_Day;
Birthday.Month = m_Month;
Birthday.Year = m_Year;
}
CAddress CPerson::getAddress()
{
return this->Address;
}
I tried to delete the pointer on the array and the address on the elements of the array and it worked correctly but what I actually want is to work around it and leave the main as it is .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64381173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Landing Page Built with Bootstrap 4 I have had a landing page built for me which is fairly simple layout. But the problem is the Banner Photo is swamping the page and I have to scroll to see completed page. Is there an adjustment I can make to HTML and/or CSS to reduce the height of the banner photo by about a third?
A: There are a lot of different approaches of doing this. I'll just show you one, that should perfectly fit your current page and needs.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 d-flex align-items-end overflow-hidden banner-image-container">
<img class="img-responsive" src="img/top-banner.jpg" width="100%">
</div>
(Inside your <style tag:)
.overflow-hidden {
overflow: hidden;
}
.banner-image-container {
max-height: 400px;
}
What I did is to limit the container around your image to a maximum height of 400px. Because your image is bigger then that, I added overflow: hidden; to the container, so it will cut the rest of the image off. Now your main focus in the image will be the building I guess. So I did move it all the way to the top with d-flex align-items-end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50200509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: OCaml: How to construct a formatted string in pythonic way? All of these start from a simple idea: How to write python-style formatted string in ocaml.
pythoners could init a string as:
str = "this var: %s" % this_var
str2 = "this: %s; that: %s" % (this_var, that_var)
but ocaml's formatted string code as :
let str = Printf.sprintf "this var: %s" this_var
let str2 = Printf.sprintf "this: %s; that: %s" this_var that_var
I believed I can do sth to make the ocaml string formating code python-like
At first, I defined a function as below:
let (%) s x = Printf.sprintf s x
then, I can write directly as:
let str = "this: %s" % "sth"
but the simple function cannot handle more complex situations as two or more variables.
so I wanted to write a little complex function to make it perfectly simulate the python way.
I wrote it as below :
let (%) s li =
let split_list = Str.full_split (regexp "%[a-z]") s in
let rec fmt result_str s_list x_list = match s_list with
| [] -> result_str
| shd::stl -> match shd with
| Text t -> fmt (result_str^t) stl x_list
| Delim d -> match x_list with
| [] -> fmt result_str stl []
| xhd::xtl -> fmt (result_str^(Printf.sprintf d xhd)) stl xtl
in
fmt "" split_list li
But the function just CANNOT work, because the type error and also ocaml's list cannot contains multiple types.
if you write sth like: "name: %s; age: %d" % ["John"; 20] the ocaml compiler world laugh at the code and tell you some type ERROR.
Obviously, I must use Tuple to replace List. but I just do NOT konw how to tail-recursive a variable-length tuple.
any suggestion is welcomed. I have two question indeed.
*
*how to write a pythonic ocaml code to format string.
*If Ocaml cannot dynamically generate some string as format6 str and
pass it to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"
would generate ERROR info as:
Error: This expression has type string
but an expression was expected of type
('a -> 'b, unit, string) format =
('a -> 'b, unit, string, string, string, string) format6
A: This is actually doable if your operator starts with a # character, since that character has a higher precedence than function application.
let (#%) = Printf.sprintf;;
val ( #% ) : ('a, unit, string) format -> 'a = <fun>
"Hello %s! Today's number is %d." #% "Pat" 42;;
- : string = "Hello Pat! Today's number is 42."
A: (1) I don't think there's a good way to do it that is going to be nicer than using Printf.sprintf directly. I mean, you can extend what you've already come up with:
let (%) = Printf.sprintf
let str3 = ("this: %s; that: %s; other: %s" % this_var) that_var other_var
which works, but is ugly because of the parentheses that are necessary for precedence.
(2) It's really hard to generate a format string at runtime because format strings are parsed at compile time. They may look like string literals, but they are actually a different type, which is "something format6". (it figures out whether you want a string or format string based on the inferred type) In fact, the exact type of a format string depends on what placeholders are in the format; that's the only way that it is able to type-check the number and types of format arguments. It's best not to mess with format strings because they are tied very heavily into the type system.
A: Why would one want to replace statically checked sprintf with some dynamic formatting? OCaml's Printf is both compact in usage and safe at runtime. Compare that to C printf which is compact but unsafe and C++ streams which are safe but verbose. Python's format is no way better than C printf (except that you get exception instead of crashdump).
The only imaginable use-case is format string coming from external source. And it is usually better to move it to compile-time. If it is not possible, then only one needs to fallback to manual dynamic formatting with error-handling (as already said you cannot use Printf with dynamic format string). BTW one such case - internationalization - is covered with existing libraries. Generally, if one wants to dynamically combine multiple values of different types, then one has to wrap them with variants (like ['S "hello"; 'I 20]) and pattern-match at printing side.
A: You should check out OCaml Batteries Included's extended/extensible printf. I have the feeling that you can do what you want with it.
A:
If Ocaml cannot dynamically generate
some string as format6 str and pass it
to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"
What if we bypass the typing system...
external string_to_format :
string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
let s = string_to_format "%s" in (Printf.sprintf s "hello" : string);;
I don't claim this to be the ultimate solution, but that's as far as I got after looking at the mailing list, http://pauillac.inria.fr/caml/FAQ/FAQ_EXPERT-eng.html#printf and ocaml's src.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1662853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: preventing users to create duplicate primary keys How would you prevent users to create duplicate primary keys?
My question is worded quite poorly so ill give an example to make it more clear (not sure how to put this in better words).
Let's say there are two users who are both trying to insert an item into our db. Now the ID (primary key) for this item is auto-incremented by 1 whenever a new item is inserted.
When two users try to insert an item into the db at the same time, the moment they insert the item, both items would be assigned with same ID but with different details and hence would cause a problem later when we look up that item b/c now there are two items with same ID.
How would you prevent this from Oracle?
Please comment if my question is not clear!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37840656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Object binding for RESTful service using apache-cxf How to bind an object for RESTful service using Apache CXF?
I want to bind variables to an object from url params.
A: You could use @QueryParam. Take a look here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17941359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I convert list of strings to list of doubles in closure? How can I convert the values of 'mymap' to a list of Doubles instead of a list of Strings, at the same time as mymap is created?
(use '[clojure.string :only (join split)])
;(def raw-data (slurp "http://ichart.finance.yahoo.com/table.csv?s=INTC"))
;Downloaded and removed the first line
(def raw-data (slurp "table-INTC.csv"))
(def raw-vector-list
(map
#(split % #",") ; anonymous map function to split by comma
(split raw-data #"\n"))) ; split raw data by new line
(pr (take 1 raw-vector-list))
(def mymap
(zipmap
;construct composite key out of symbol and date which is head of the list
(map #(str "INTC-" %) (map first raw-vector-list))
;How do i convert these values to Double instead of Strings?
(map rest raw-vector-list)))
(pr (take 1 mymap))
A: (def mymap
(zipmap
(map #(str "NAT-" %) (map first raw-vector-list))
(map #(map (fn [v] (Double/parseDouble v)) %)
(map rest raw-vector-list))))
(pprint (take 1 mymap))
-> (["NAT-1991-09-30" (41.75 42.25 41.25 42.25 3.62112E7 1.03)])
Another version
(def mymap
(map (fn [[date & values]]
[(str "NAT-" date)
(map #(Double/parseDouble %) values)])
;; Drop first non-parsable element in raw-vector-list
;; ["Date" "Open" "High" "Low" "Close" "Volume" "Adj Close"]
(drop 1 raw-vector-list)))
A: So for the tail/rest portion of this data. You are mapping an anonymous, map function, to a list of strings, and then mapping the type conversion to the elements in each sublist.
(def mymap
(zipmap
(map #(str "NAT-" %) (map first raw-vector-list))
(map #(map (fn [v] (Double/parseDouble v)) %)
(map rest raw-vector-list))))
How can I pull out the type conversion into a function like below...And then utilize my custom method?
(defn str-to-dbl [n] (Double/parseDouble n))
This code complains about nested #'s.
(def mymap
(zipmap
(map #(str "NAT-" %) (map first raw-vector-list))
(map #(map #(str-to-double %)
(map rest raw-vector-list))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13871883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Determining the memory size of a Heroku Dyno Worker from Ruby code? Is it possible to at lease estimate the total RAM of a Heroku Worker Dyno from Ruby code starting in it? I need this to use just the right number of processes via the https://github.com/salsify/delayed_job_worker_pool gem, so that the processes don't run out of memory.
I have noticed the following Environment variable provided for a Dyno: ENV[“HEROKU_RAM_LIMIT_MB”], and it appears to return correct values, but I'm not sure if it's "official" enough to rely on it. Does anybody know?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63134378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Searching for keywords irrespective of special characters in dataframe I have a dataframe df with a column of some texts:
texts
This is really important(actually) because it has really some value
This is not at all necessary for it @ to get that
I want to perform a search and obtain the texts with keywords like "important(actually)", and it doesn't seem to work.
How do I to get that information?
I have used the following code:
df_filter=df[df.apply(lambda x: x.astype(str).str.contains(keyword, flags=re.I)).any(axis=1)]
But I am unable to get such information.
A: Just escape the special characters in regex
df = pd.DataFrame({'texts': [
'This is really important(actually) because it has really some value',
'This is not at all necessary for it @ to get that']})
keyword = 'important(actually)'
df[df.apply(lambda x:
x.astype(str).str.contains(
re.escape(keyword), flags=re.I)).any(axis=1)]
Output:
texts
0 This is really important(actually) because it ...
A: contains use regex and brackets are special chapter in regex
You can disable the regex by add regex=False:
df_filter=df[df.apply(lambda x: x.astype(str).str.contains(keyword, regex=False)).any(axis=1)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63011806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set the cell color in jqGrid using attributes from the XML file? If have an XML file that jqGrid is reading. I want to set attributes in the class using attributes in the XML file. For example, given a file such as this:
<row id='0'>
<cell class='type1'>2</cell>
<cell class='type2'>2</cell>
</row>
I'd like the CSS to be such that the first cell has 'class="type1"' and the second cell to have 'class="type2"'.
I have been using cellattr_func to try and set these values, but it is only passed in the value of the cell, which isn't enough to determine the CSS class to be used in my use case. I've been inspecting the 'rawObject' parameter, which seems like it might have the information from the XML data attributes, but I don't know how to walk through the rawObject data structure successfully in Javascript to determine if what I want to do is possible or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22822602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NullPointerException: Attempt to read from field StoreData.store_id on a null object reference Please help me where is the problem here and how to fix it. So I wont get null object. In my case, I'm sorry before I try to read other post too but make me little bit confused.
Here is my StoreHelper :
public StoreData getStore(String storeid) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where "
+ COL_STORE_ID + "=?", new String[]{storeid});
StoreData data = null;
System.out.println("This is the problem ");
if (c.moveToFirst()) {
data = new StoreData(
c.getString(c.getColumnIndex(COL_STORE_ID)),
c.getString(c.getColumnIndex(COL_ACCOUNT_ID)),
c.getString(c.getColumnIndex(COL_KOTA_ID)),
c.getString(c.getColumnIndex(COL_STORE_NAME)),
c.getString(c.getColumnIndex(COL_STORE_MANAGER)),
c.getString(c.getColumnIndex(COL_STORE_ADDRESS)),
c.getString(c.getColumnIndex(COL_STORE_TELEPHONE)),
c.getString(c.getColumnIndex(COL_STORE_GEO_LAT)),
c.getString(c.getColumnIndex(COL_STORE_GEO_LONG)),
c.getString(c.getColumnIndex(COL_STORE_LEADTIME)),
c.getString(c.getColumnIndex(COL_STORE_MD)));
db.close();
c.close();
}
return data;
}
This is the StoreData:
public class StoreData {
public int img;
public String store_id;
public String account_id;
public String kota_id;
public String store_name;
public String store_manager;
public String store_address;
public String store_telephone;
public String store_geo_lat;
public String store_geo_long;
public String store_leadtime;
public String store_md;
public StoreData(String storeid, String accountid, String kotaid, String storename, String storemanager,
String storeaddress, String storetelephone, String storegeolat, String storegeolong,
String storeleadtime, String storemd) {
super();
this.store_id = storeid;
this.account_id = accountid;
this.kota_id = kotaid;
this.store_name = storename;
this.store_manager = storemanager;
this.store_address = storeaddress;
this.store_telephone = storetelephone;
this.store_geo_lat = storegeolat;
this.store_geo_long = storegeolong;
this.store_leadtime = storeleadtime;
this.store_md = storemd;
}
}
And this is where the error point is in the Activity
public void inCaseOffline() {
StoreHelper sh = new StoreHelper(ctx);
Log.i("ncdebug", "Store ID(incaseoffline): " + storeid);
StoreData sd = sh.getStore(storeid);
// temporary
StoreInfo.storeid = sd.store_id;
StoreInfo.storename = sd.store_name;
StoreInfo.storeaddress = sd.store_address;
StoreInfo.storetelephone = sd.store_telephone;
StoreInfo.storemanager = sd.store_manager;
Log.i("Data", sd.store_id + "<->" + sd.store_geo_lat + "," + sd.store_geo_long);
TextView tvname = (TextView) findViewById(R.id.tvStoreInfoName);
tvname.setText(sd.store_name);
ProductsHelper helper = new ProductsHelper(ctx);
StoreInfo.storeproducts = helper.getProducts();
StoreInfo.storepromotions = new PromotionListData[0];
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
StoreInfo.storeDisplayCat = helperDisplayCat.getCategories();
PromoCatHelper helperPromoCat = new PromoCatHelper(ctx);
StoreInfo.storePromoCat = helperPromoCat.getCategories();
CompetitorCatHelper helperCompetitorCat = new CompetitorCatHelper(ctx);
StoreInfo.storeCompetitorCat = helperCompetitorCat.getCategories();
add_overlay(StoreInfo.storename, new
LatLng(Double.parseDouble(sd.store_geo_lat),
Double.parseDouble(sd.store_geo_long)));
}
This is my log :
Process: com.apps.userinarts.mobilemerchpre, PID: 5308 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.userinarts.mobilemerchpre/com.apps.userinarts.MobileMerchPre.StoresCheckinActivity}: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.apps.userinarts.MobileMerchPre.data.StoreData.store_id' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.apps.userinarts.MobileMerchPre.data.StoreData.store_id' on a null object reference
at com.apps.userinarts.MobileMerchPre.StoresCheckinActivity.inCaseOffline(StoresCheckinActivity.java:93)
at com.apps.userinarts.MobileMerchPre.StoresCheckinActivity.onCreate(StoresCheckinActivity.java:83)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
A: Simply because your query is returning a null cursor object.
So I would suggest two modification in your getStore function to avoid any crash issue.
This is a query to find a String object. So the query should look like this.
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where "
+ COL_STORE_ID + "='" + new String[]{storeid} + "'", null);
Look closely at the ' before and after the storeid you've provided as a parameter to the query.
And the other thing is you need to check for null value before you do any operation on your Cursor
// Check for null here and return if null
if(c == null) return null;
if (c.moveToFirst()) {
//.. Your code
}
Add a check here too
public void inCaseOffline() {
StoreHelper sh = new StoreHelper(ctx);
Log.i("ncdebug", "Store ID(incaseoffline): " + storeid);
StoreData sd = sh.getStore(storeid);
// Add the null checking
if(sd == null) {
Toast.makeText(YourActivity.this, "Could not fetch information", Toast.LENGTH_LONG).show();
return;
}
// .. Your code
}
Edit
You might consider having the getStore function to be modified like this
public StoreData getStore(String storeid) {
// ... Database operation.
// Initialize the StoreData here
StoreData data = new StoreData();
// ... Your code
return data;
}
To achieve the initialization, add an empty constructor too in your StoreData class
public class StoreData {
public int img;
public String store_id;
public String account_id;
public String kota_id;
public String store_name;
public String store_manager;
public String store_address;
public String store_telephone;
public String store_geo_lat;
public String store_geo_long;
public String store_leadtime;
public String store_md;
public StoreData() {
// Empty constructor
}
// ... The other constructer
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39323616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bold text on webpages when "Bold Text" iOS settings enabled I would like to increase the font weight of the text content in the webpage when the iOS "Bold Text" settings is enabled. But, I'm not able to find any documentation about it online.
A: I believe this has to do with the system-ui font. I've made a quick Codepen to check it out. If you enable the "Bold Text" option on iOS it will change the font weight for the p that uses the system-ui as its font-family. And you can see that the p with the custom font, Poppins, isn't bold.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74100048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mac OSX - Get all running application list with memory usage I am very new to develop mac osx application using xcode. I am trying to get all running application list with their memory usage.
Can any body help me in this case.
Please help me.
Thanks in advance.
A: It will help you to get list of running application :
for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) {
NSLog(@"%@",[app localizedName]);
}
A: You may get the cpu usage as:
- (NSString*) get_process_usage:(int) pid
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/ps"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-O",@"%cpu",@"-p",[NSString stringWithFormat:@"%d",pid], nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSString* temp = [string stringByReplacingOccurrencesOfString:@"PID %CPU TT STAT TIME COMMAND" withString:@""];
NSMutableArray* arr =(NSMutableArray*) [temp componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[arr removeObject:@""];
[string release];
[task release];
if([arr count]>=2)
return [arr objectAtIndex:1];
else
return @"unknown";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21135410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Detecting Available Network Adapters With Python I want to detect the available network interfaces that is connected to a DHCP and got an IP from it. I am using following script to generate the list of available adapters.
import psutil
addrs = psutil.net_if_addrs()
all_network_interfaces = addrs.keys()
available_networks = []
for value in all_network_interfaces:
if addrs[value][1][1].startswith("169.254"):
continue
else:
available_networks.append(value)
print(available_networks)
The ones that starts with 169.254 are the adapters that is using Automatic Private IP Addressing (APIPA) so I want to filter them out. When I connect with an Ethernet cable, this script shows the related adapter, if I also connect over WiFi while ethernet is still connected, it adds the WiFi to the list. However, after disconnecting from the WiFi, WiFi adapters still holds the IP and still exists in the list. I think that it is a problem( maybe feature) with my adapter card. What is the best way to bypass this and obtain only the adapters with DHCP connection?
A: With psutil.net_if_stats() to get only up and running network interfaces:
import psutil
addresses = psutil.net_if_addrs()
stats = psutil.net_if_stats()
available_networks = []
for intface, addr_list in addresses.items():
if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list):
continue
elif intface in stats and getattr(stats[intface], "isup"):
available_networks.append(intface)
print(available_networks)
Sample output:
['lo0', 'en0', 'en1', 'en2', 'en3', 'bridge0', 'utun0']
A: There is a python package get-nic which gives NIC status, up\down, ip addr, mac addr etc
pip install get-nic
from get_nic import getnic
getnic.interfaces()
Output: ["eth0", "wlo1"]
interfaces = getnic.interfaces()
getnic.ipaddr(interfaces)
Output:
{'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}}
Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57093853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fix mismatch processor architecture, unexpected e_machine, due to a .so file I have a Xamarin android project and am currently using Visual Studio 2015.
Inside of my MainActivity.cs, I have the following code:
Com.Alk.Sdk.SharedLibraryLoader.LoadLibrary("alksdk", this);
which then goes into:
// Metadata.xml XPath method reference: path="/api/package[@name='com.alk.sdk']/class[@name='SharedLibraryLoader']/method[@name='loadLibrary' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='android.content.Context']]"
[Register ("loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z", "")]
public static unsafe bool LoadLibrary (string p0, global::Android.Content.Context p1)
{
if (id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ == IntPtr.Zero)
id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
bool __ret = JNIEnv.CallStaticBooleanMethod (class_ref, id_loadLibrary_Ljava_lang_String_Landroid_content_Context_, __args);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
The problem I am having is that when it calls the JNIEnv.CallStaticBooleanMethod, it throws this exception:
[ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
--- End of managed Java.Lang.UnsatisfiedLinkError stack trace ---
java.lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
at java.lang.Runtime.load0(Runtime.java:908)
at java.lang.System.load(System.java:1542)
at com.alk.sdk.SharedLibraryLoader.loadLibrary(SharedLibraryLoader.java:44)
at com.pai.rp.MainActivity.n_onCreate(Native Method)
at com.pai.rp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6973)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3064)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1659)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
From what I've been able to research I've found that
*
*e_machine: 3 indicates the expected arch is Intel 80386 (ELF Headers).
*When using a Google Nexus 10 emulator it seems to work, however when
I use the Galaxy Tab E (ARM) through USB debugging, it crashes and gives me
this error.
So the question is, how do I correct this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50806019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Combine 2 functions into 1 How can i combine this functions. Basically, when if the checkbox is clicked, something happens and if the page loads and if the checkbox is already clicked, the same thing happens as the second function.
$(document).on("click", ".dimensions", function() {
var size = $('.td-hide');
if ($('input#dimensions').is(':checked')) {
size.show();
$('.single-select-sm').css('width','148px')
} else {
size.hide();
$('.single-select-sm').css('width','230px')
}
});
$(function() {
var size = $('.td-hide');
if ($('input#dimensions').is(':checked')) {
size.show();
$('.single-select-sm').css('width','148px')
} else {
size.hide();
$('.single-select-sm').css('width','230px')
}
});
A: var myFunc = function()
{
var size = $('.td-hide');
if ($('input#dimensions').is(':checked')) {
size.show();
$('.single-select-sm').css('width','148px')
} else {
size.hide();
$('.single-select-sm').css('width','230px')
}
}
$(document).on("click", ".dimensions", function() {
myFunc();
}
$(function() {
myFunc();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26263275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Letter to word assignment I'm practicing programming in C sharp and i'm trying to write a program that will ask for a letter value from the user and output a word value eg. the user inputs the letter "a" and gets the word "apple". What would be the best code for this? Cheers.
A: Hint: use a Dictionary.
var dict = new Dictionary<char, string>() {
{'a', "apple"},
{'b', "box"},
// ......
{'z', "zebra"}
};
dict['a']; // apple
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19719744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: TimerTask runs one more time after I call timer.cancel() method TimerTask runs one more time after I call timer.cancel() method.
I don't need TimerMethod to be executed after I call stopBusTimer() method.
Can somebody explain why is it happening?
busTimer = new Timer();
busTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod(mSelectedRoute);
}
}, 0, Consts.BUS_TIMER_INTERVAL);
private void stopBusTimer() {
if (busTimer != null) {
busTimer.cancel();
busTimer.purge();
busTimer = null;
Log.v(LOG_TAG, "stop BusTimer");
}
}
A: The cancel method will stop all following executions, but not the current one. It your method execution takes a long time, then it is possible by the time you call cancel, the method has already begun executing.
The best way to make sure the method does not execute is to call cancel from within the run() function itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38651832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting a Mod_Security error When i install captcha plugin on my website and try to login, m getting Error:
An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18779382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ML assignment operation everyone, what is difference between the following assignments in ML,
val n = 5;
and
n := 1;
A: The former is a declaration of a new, immutable variable. The latter is how you re-assign the value of a reference cell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5168889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scheduling playback of AudioWorkletNode I'm working with soundtouchjs-audio-worklet in order to change the tempo/pitch of audio files that have been read into a buffer. The library creates a worklet that can process these buffers, and gives me an AudioWorkletNode to control it. What I need to do is schedule the playback of multiple AudioWorkletNodes so that different audio files can be on a "timeline" of sorts.
I know the AudioBufferSourceNode has a when parameter in it's start() function that you can use to schedule the playback of the node. But AudioWorkletNode doesn't seem to be scheduleable; it just immediately begins playback upon connect()ing it.
I could use setTimeout() to delay calling connect(), but I don't think the timing will be accurate enough. Does anyone know of a way to schedule playback of an AudioWorkletNode? Or an accurate way to connect it at the exact right time?
A: There is no built-in way to schedule an AudioWorkletProcessor but it's possible to use the global currentTime variable to build it yourself. The processor would then look a bit like this.
class ScheduledProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.port.onmessage = (event) => this.startTime = event.data;
this.startTime = Number.POSITIVE_INFINITY;
}
process() {
if (currentTime < this.startTime) {
return true;
}
// Now it's time to start the processing.
}
}
registerProcessor('scheduled-processor', ScheduledProcessor);
It can then be "scheduled" to start when currentTime is 15 like this:
const scheduledAudioNode = new AudioWorkletNode(
audioContext,
'scheduled-processor'
);
scheduledAudioNode.port.postMessage(15);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73809315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Upgrade Hibernate 3.6 to hibernate 4.3.6 on jboss 6.0.0 AS getting java.lang.NoClassDefFoundError: org/hibernate/classic/Session We are upgrading hibernate 3.6 to hibernate 4.3.6 in our application and we are using hibernate JPA 2.0 in Jboss 6.0.0. We have excluded jpa components and other JBoss components and bundled our own libs (i.e jpa hibernate etc) after deploying and starting the Jboss.
We get :
17:50:31,788 ERROR [AbstractKernelController] Error installing to Real: name=vfs:///C:/Jboss/jboss-6.0.0.Final/server/XXXXXX/deploy/XXXXXX-6.4.1.ear state=PreReal mode=Manual requiredState=Real: org.jboss.deployers.spi.DeploymentException: Error deploying XXXXXXEJB3.jar: org/hibernate/classic/Session
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:194) [:6.0.0.Final]
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:60) [:6.0.0.Final]
at org.jboss.deployers.vfs.spi.deployer.AbstractSimpleVFSRealDeployer.deploy(AbstractSimpleVFSRealDeployer.java:56) [:2.2.0.GA]
at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) [:2.2.0.GA]
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1832) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1550) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1603) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1491) [:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.change(DeployersImpl.java:1983) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:1076) [:2.2.0.GA]
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:679) [:2.2.0.GA]
at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.process(MainDeployerPlugin.java:106) [:6.0.0.Final]
at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.process(ProfileControllerContext.java:143) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:151) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.GA]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.GA]
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2]
at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.0.0.Final]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.0.0.Final]
at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
at java.lang.Thread.run(Unknown Source) [:1.6.0_31]
Caused by: java.lang.NoClassDefFoundError: org/hibernate/classic/Session
at org.jboss.injection.PcEncInjector.<clinit>(PcEncInjector.java:48) [:1.7.17]
at org.jboss.injection.PersistenceContextHandler.loadXml(PersistenceContextHandler.java:73) [:1.7.17]
at org.jboss.ejb3.EJBContainer.processMetadata(EJBContainer.java:779) [:1.7.17]
at org.jboss.ejb3.Ejb3Deployment.processEJBContainerMetadata(Ejb3Deployment.java:471) [:1.7.17]
at org.jboss.ejb3.Ejb3Deployment.create(Ejb3Deployment.java:553) [:1.7.17]
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:177) [:6.0.0.Final]
... 49 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.classic.Session from BaseClassLoader@5b3ba312{vfs:///C:/Jboss/jboss-6.0.0.Final/server/XXXXXX/conf/jboss-service.xml}
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:480) [jboss-classloader.jar:2.2.0.GA]
at java.lang.ClassLoader.loadClass(Unknown Source) [:1.6.0_31]
... 55 more
Removed all the reference somewhere jboss bootstrap class loader looks for org/hibernate/classic/Session We couldn't find the reference . Please help me out.
A: This looks like the JBoss 6.0 EJB3 implementation is dependent upon the version of Hibernate that you have removed.
Why don't you upgrade to JBossAS 7.x for JPA 2.0 support?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26750342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python 2: insert existing list inside of new explicit list definition This may not be possible, but if it is, it'd be convenient for some code I'm writing:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']
If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo.
But instead, I want to expand ListOne into ListTwo, but I don't want to have to do something like:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox']
ListTwo.extend(ListOne)
ListTwo.extend(['lazy', 'dog!']
This will work but it's not as readable as the above code.
Is this possible?
A: You can just use the + operator to concatenate lists:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']
ListTwo will be:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
A: Another alternative is to use slicing assignment:
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!']
>>> ListTwo[4:4] = ListOne
>>> ListTwo
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
A: >>> ListOne = ['jumps', 'over', 'the']
>>> from itertools import chain
>>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])]
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
A: Why not concatenate?
>>> ListTwo = ['The', 'quick', 'brown', 'fox']
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo + ListOne
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the']
>>> ListTwo + ListOne + ['lazy', 'dog!']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17670457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Laravel group by not working if only one key exists? I have this following code:
$groupedRates = $result->rates->groupBy('minimum_age');
when I try to return it, I get this:
"rates": [
[
{
"id": 1,
"cpf_scheme_id": 1,
"minimum_age": 0,
"minimum_wage": 0,
},
{
"id": 2,
"cpf_scheme_id": 1,
"minimum_age": 0,
"minimum_wage": 750,
}
]
]
however, if I were to add one more key, it returns an associative array as expected.
"rates": {
"0": [
{
"id": 1,
"cpf_scheme_id": 1,
"minimum_age": 0,
"minimum_wage": 0,
},
{
"id": 2,
"cpf_scheme_id": 1,
"minimum_age": 0,
"minimum_wage": 750,
}
],
"50": [
{
"id": 4,
"cpf_scheme_id": 1,
"minimum_age": 50,
"minimum_wage": 100,
}
]
}
How do I fix this? It will break apis if it returns an associative array sometimes and a normal array other times!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70377506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can NSNotificationCenter be used between different frameworks to communicate? An app can make internal use of NSNotificationCenter for different parts to communicate with each other, but can this be extended such that different frameworks can use it to communicate on iOS?
A: In the same app, frameworks all get executed on the same process. They just locate at different places in memory allocated by the app.
On the same running process, NSNofitcationCenter can communicate with each other no matter which framework the sender or receiver locates at.
If you are talking about app and its extension, they run on different process and thus NSNofitcationCenter can not send notification to each other. You have to use CFNotificationCenter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58657816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I edit and transfer output tables from R? I am working with R for analyzing data for my research paper. I have run some regressions and marginal effects and would like to get the output in a format that I can include in my research paper (best would be tables as images). How can I do this?
I have tried using the sumtable() command, but it only provides a table that summarizes the overall data that I am using and not the specific regressions or the marginal effect output.
I have also used htmlreg() but as far as I know it is only for regressions, and I do not know how to transfer the html output into my word document where I am writing the paper.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74843193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.