_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d13401
train
The command git cherry-pick --abort will only abort the last cherry pick you started. Previous complete cherry-pick operations are already committed, so they will not be affected. So that's all you need to do at this point.
unknown
d13402
train
* *Server side is needed for foolproofing this. On the server, when assessment is started, you should first have start screen URL. You must program it so that once assessment is started (after clicking start), it goes to the exam URL, and your assessment is always saved - when user goes back, using server side tricks have it so that instead of showing the start screen, it redirects back to the correct page (in a way that still maintains history), shows the exam with the data still in it, and pops up the warning not to click back button. Then, if user does it again, it does the same thing, again. *You have to have it so the exam is saved all the time. unload javascript event can be used to notify via alert() that they shouldn't be leaving the exam, and thats about all. onbeforeunload event can be used to try to give them the choice to stay, but shouldn't be depended on as it doesn't work on every browser. A: Use onbeforeunload as suggested in a comment. There are various example, like this one: https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm If you want to call out the buttons that the user must click, you will need to do some browser detection, as most browsers have OK/Cancel buttons on the window that they display, but Chrome has "Leave this page" and "Stay on this page".
unknown
d13403
train
This took me hours to work out - so worth sharing I feel. In order to terminate this service as a TLS, a Destination Rule is required. My final config: apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 443 name: https protocol: HTTPS resolution: DNS location: MESH_EXTERNAL --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: httpbin spec: hosts: - httpbin.domain.co gateways: - public-gateway.istio-system.svc.cluster.local - mesh http: - match: - gateways: - public-gateway.istio-system.svc.cluster.local port: 443 host: httpbin.domain.co - gateways: - public-gateway.istio-system.svc.cluster.local port: 80 host: httpbin.domain.co route: - destination: host: httpbin.org port: number: 443 --- apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: httpbin-org spec: host: httpbin.org trafficPolicy: loadBalancer: simple: ROUND_ROBIN portLevelSettings: - port: number: 443 tls: mode: SIMPLE
unknown
d13404
train
You don't need any JavaScript for this. You can have a completely different display than the stored value. <div class="radiobutton"> <input type="radio" id="morn_before" name="morn_time" value="2"> <label for="morn_before">Before Food</label><br> <input type="radio" id="morn_after" name="morn_time" value="1"> <label for="morn_after">After Food</label><br><br> </div> Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you. ADDITIONAL INFO: You are not supposed to read a radio button group that way. You should go over some basics of HTML INPUT tag such as https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/
unknown
d13405
train
Instead of using $.unload() why not use a page pre-loader? This is a common design pattern for web pages that have to load large static assets(like videos or large images). You can setup your page pre-loader like this: //example js //Show your web page once all the assets are fully loaded $(window).load(function() { $('#preLoader').hide(); //Or whatever animation you want to remove the preloader $('#pageWrapper').show(); //Or whatever animation you want to show the page }); <!-- Example HTML --> <div id="preLoader"> <h1>Loading.....</h1> </div> <div id="pageWrapper" style="display:none;"> [page content goes here] </div>
unknown
d13406
train
It is supported for one job. But for all jobs, the Global Build Stats Plugin will be able to do that. However, it is not there yet. Meaning you need to develop your own plugin, based on the Plot Plugin, to vizualise that kind of trend (build times) alt text http://wiki.hudson-ci.org/download/attachments/2752526/examplePlot.png?version=1&modificationDate=1184536762000
unknown
d13407
train
If you have getter defined for the fields of Person, you can map the names: List<String> personNames = list.stream().map(Person::getName).collect(Collectors.toList()); A: Use .filter, like the webiste explains you, instead of .map A: To filter say on the name, do it like this. Person{id=4, name=E, color=red}] [Person{id=0, name=A, color=blue} Person{id=1, name=B, color=green} Person{id=2, name=D, color=pink} Person{id=0, name=C, color=yellow Assuming a List<Person> To get all the Person objects with a specific name List<Person> specific = list .stream() .filter(person->person.name.equals("E")) .collect(Collectors.toList()); To get just the names List<String> names = list .stream() .map(person->person.name) .collect(Collectors.toList()); A: Here is a generic code, that uses filter: import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; class Person { int id; String name; String color; @Override public String toString() { // TODO Auto-generated method stub return id + ":" + name + ":" + color; } public Person(int id, String name, String color) { super(); this.id = id; this.name = name; this.color = color; } public int getId() {return id;} public void setId(int id) {this.id = id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getColor() {return color;} public void setColor(String color) {this.color = color;} } public class Test { public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); list.add(new Person(1,"Ana","red")); list.add(new Person(2,"tna","orange")); list.add(new Person(3,"Hna","green")); list.add(new Person(4,"Ana","blue")); List<Person> t = list.stream().filter(p->p.getName().equals("Ana")).collect(Collectors.toList()); System.out.println(t); } } For this particular question it is suggestible to use filter instead of map. Because we are only interested in filtering the stream to get the desired output. On the other hand, map operation is used on the stream if we have the requirement to manipulate the data further in which condition we can apply more functions before the terminal operation (example is provided). By using map, you transform the object values. The map operation allows us to apply a function, that takes in a parameter of one type, and returns something else. For an example: Stream students = persons.stream() .filter(p -> p.getAge() > 18) .map(new Function<Person, Customer>() { @Override public Customer apply(Person person) { return new Customer(person); } }); Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out. For in-depth understanding follow the documentation link
unknown
d13408
train
You are using ms instead of s. Your animation is working, but it finishes so fast that you just can't see it. Therefore, you should give it a longer duration.
unknown
d13409
train
EF Core Interceptors allow you to do just that: public class QueryCommandInterceptor : DbCommandInterceptor { public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync( DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default) { var resultReader = await SendCommandToAnotherAppAsync(command); return InterceptionResult<DbDataReader>.SuppressWithResult(resultReader); } private Task<DbDataReader> SendCommandToAnotherAppAsync(DbCommand command) { // TODO: Actual logic. Console.WriteLine(command.CommandText); return Task.FromResult<DbDataReader>(null!); } } Make sure to override other methods like ScalarExecuting, NonQueryExecuting, sync and async variants. A: Multitenancy is already supported in EF Core. The options are described in the Multi-tenancy page in the docs. In this case, it appears a different database per tenant is used. Assuming there's a way/service that can return who the tenant is, a DbContext can use a different connection string for each tenant. Assuming there's a way/service to retrieve the current tenant name, eg ITenantService, the DbContext constructor can use it to load a different connection string per tenant. The entire process could be abstracted behind eg an ITenantConnectionService, but the docs show how this is done explicitly. The context constructor will need the tenant name and access to configuration : public ContactContext( DbContextOptions<ContactContext> opts, IConfiguration config, ITenantService service) : base(opts) { _tenantService = service; _configuration = config; } Each time a new DbContext instance is created, the connection string is loaded from configuration based on the tenant's name: protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var tenant = _tenantService.Tenant; var connectionStr = _configuration.GetConnectionString(tenant); optionsBuilder.UseSqlite(connectionStr); } This is enough to use a different database per tenant. Scope and lifecycle These aren't a concern when a DbContext is used as a Scoped or Transient service. By default AddDbContext registers DbContexts as scoped services. The scope in a web application is a single request. Once a request is processed, any DbContext instances created are disposed. Connection Pooling Connection pooling isn't a concern either. First of all, a DbContext doesn't represent a database connection. It's a disconnected Unit-of-Work. A connection is only opened when the context needs to load data from the database or persist changes when SaveChanges is called. If SaveChanges isn't called, nothing gets persisted. No connections remain open between loading and saving. Consistency is maintained using optimistic concurrency. When the data is saved EF Core checks to see if the rows being stored have changed since the time they were loaded. In the rare case that some other application/request changed the data, EF Core throws a DbConcurrencyException and the application has to decide what to do with the changed data. This way, there's no need for a database transaction and thus no need for an open connection. When optimistic concurrency was introduced in ... the late 1990s, application scalability increased by several (as in more than 100, if not 1000) orders of magnitude. Connection pooling is used to eliminate the cost of opening and closing connections. When DbConnection.Close() is called, the actual network connection isn't terminated. The connection is reset and placed in a pool of connections that can be reused. That's a driver-level feature, not something controlled by EF Core. Connections are pooled by connection string and in the case of Windows Authentication, per user. This eliminates the chance of a connection meant for one user getting used by another one. Connection pooling is controlled by ADO.NET and the database provider. Some drivers allow connection pooling while others don't. In those that do support it, it can be turned off using keywords in the connection string or driver settings.
unknown
d13410
train
Controller has nothing to do with a link being displayed or not. However you can disable the deletion in the controller by checking the same condition. Anyways, you should create at least a model property for this. This id hardcode thingy is not nice, so hide it at least and make it not being repeated. model User ... def can_delete_account? id != 223 # ugly hack end end
unknown
d13411
train
How about using server side validation? I answered to similar issue here: extjs4 rails 3 model validation for uniqueness Obviously you can change it to use "ajax" instead of "rest" proxy.
unknown
d13412
train
If you load your KML through the API, with GGeoXml(), (V2), or KmlLayer(), (V3), then your data needs to be in a public server because it is parsed by Google's servers and they need to be able to get to it. If you load it with a third party extension then you can keep it private. Third party extensions that can load and parse KML data are EGeoXml() by Mike Williams http://econym.org.uk/gmap/extensions.htm#EGeoXml and GeoXml() by Lance Dyas http://www.dyasdesigns.com/geoxml/ but I believe that both of those are only available for the API V2 for now. A: I just upgraded my Google Maps JavaScript API Application from v2 to v3, following these instructions. My v2 application was using the EGeoXml extension referred to by @Marcelo in the accepted answer to locally parse KML data. A substitution of geoxml3 in its place, as suggested by @geocodezip (a contributor to the project) in a comment, functioned immediately in my v3 application. A: No, the data will not be public. I'm not sure about your other question though.
unknown
d13413
train
You can simply do: SELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber FROM tbl1 AS [SO] GROUP BY P.LegacyKey HAVING COUNT(DISTINCT D.DesignNumber) = 1; ORDER BY LegacyKey; No subquery is necessary. A: You need something like this: select t2.LegacyKey, t2.DesignNumber from ( select t.LegacyKey from tbl1 t group by t.LegacyKey having count(t.LegacyKey ) = 1 )x join tbl1 t2 on x.LegacyKey = t2.LegacyKey or select t2.LegacyKey, t2.DesignNumber from tbl1 t2 where t2.LegacyKey in ( select t.LegacyKey from tbl1 t group by t.LegacyKey having count(t.LegacyKey ) = 1 ) A: You could try this NB - This is untested SELECT * FROM ( SELECT P.LegacyKey AS LegacyKey, D.DesignNumber AS DesignNumber, COUNT([P].[LegacyKey]) AS cnt FROM tbl1 AS [SO] GROUP BY D.DesignNumber,P.LegacyKey HAVING COUNT([P].[LegacyKey]) = 1 ) a WHERE COUNT() OVER (PARTITION BY LegacyKey) = 1
unknown
d13414
train
The easiest way to do it is using a library like Picasso or Glide. If you want to do it on your own you will have to decode the image yourself then transform it into a object that is accepted by an ImageView, you can refer to this other question https://stackoverflow.com/a/25463200/4632435
unknown
d13415
train
All Lucene does is provide a way for "Documents" to be added into a structured index and for queries to be executed against that index. The Nutch crawler (I assume that's what you mean by nutch) just provides an easy way to get unstructured data (ie a website) to get pushed into the index. Just like you can use Solr to easily push xml data into a lucene index. Nutch plugins simply provide a hook were you can put customer logic. For instance the "parse-pdf" can convert a binary PDF file into one of these "lucene Documents". Basically all it does is use an API that can read PDF documents (pdfbox) to extract the text (this is similar to what "parse-html" does since html has a lot of parts that isn't text, for example all html tags). So regarding your concern about binary formats, its not difficult to parse, just difficult to get something useful. For instance we can write a "parse-image" plugin that could extract a lot of info about the image (ie name, format, size), it's just that parsing the "face" or the "dog" in the picture is difficult.
unknown
d13416
train
As long as you can fit all of the data in memory you're better off holding onto it all and sorting it in memory rather than writing it to a file. The concept of sorting data in a file is generally solved by "read it into memory, sort it, and write it back out again". As for writing a CSV file, it's not really that hard. I like to use a StringBuilder to add on each of the fields for each line, and then once I have a line I append that line to the file. For the headers, you either hard code them if appropriate, or get them from whatever source you have if it's dynamic. Do you not know how to write to a file? My guess is the File.WriteAllText() and File.AppendText() methods will be all you should need for that. Just a general tip, since you asked, is that rather than adding the items to the list, since you'll eventually sort them all, is to add them to a SortedList, so that they're sorted as you go. Then when you're done, you just get them one at a time and they are already in order. A: You can use LINQ for the sorting and a StreamWriter for the file creation. using (var writer = new StreamWriter(@"C:\files.csv")) { writer.WriteLine("Name,Size"); // Header var query = fileList.OrderBy(r => r.fileName); foreach (Record record in query) { writer.WriteLine("\"{0}\",{1}", record.fileName, record.fileSize); } } Note that I enclosed the file name in double quotes ("), in the case that a comma (,) is part of the file name. The double quote itself is not a valid character for file names in Windows, so that it should not be a problem.
unknown
d13417
train
I've tried putting in the following config for my WCF service, and hit the service with valid and invalid credentials. Only the requests with invalid credentials caused anything to appear in the service trace file. My service uses a custom UserNamePasswordValidator class, and this was present in the stack trace. The important parts are the switchValue="Error" and propagateActivity="false" in the <source> element. Not sure if this is exactly what you want, but it at least seems close... <system.diagnostics> <sources> <source name="System.ServiceModel" switchValue="Error" propagateActivity="false"> <listeners> <add type="System.Diagnostics.DefaultTraceListener" name="Default"> <filter type="" /> </add> <add name="ServiceModelTraceListener"> <filter type="" /> </add> </listeners> </source> </sources> <sharedListeners> <add initializeData="C:\Path-to-log-file\Web_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="DateTime, Timestamp, Callstack"> <filter type="" /> </add> </sharedListeners> <trace autoflush="true" /> </system.diagnostics> A: Alternatively it's possible to specify EventTypeFilter as listener's filter <listeners> <add name="console" type="System.Diagnostics.ConsoleTraceListener" > <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error" /> </add> </listeners>
unknown
d13418
train
In a Flex rule file, you'd use \\ to match a single backslash '\' character. This is because the \ is used as an escape character in Flex. BACKSLASH \\ LITERAL_BACKSLASH \\\\ LITERAL_LESSTHAN \\\\< LITERAL_GREATERTHAN \\\\> LITERAL_VERTICALBAR \\\\| If I follow you correctly, in your case you want "\>" to be treated as literal '>' but "\\>" to be treated as literal '\' followed by special redirect. You don't need negative look behind or anything particularly special to accomplish this as you can build one rule that would accept both your regular argument characters and also the literal versions of your special characters. For purposes of discussion, let's assume that your argument/parameter can contain any character but ' ', '\t', and the special forms of '>', '<', '|'. The rule for the argument would then be something like: ARGUMENT ([^ \t\\><|]|\\\\|\\>|\\<|\\\|)+ Where: [^ \t\\><|] matches any single character but ' ', '\t', and your special characters \\\\ matches any instance of "\" (i.e. a literal backslash) \\> matches any instance of ">" (i.e. a literal greater than) \\< matches any instance of "\<" (i.e. a literal less than) \\\| matches any instance of "\|" (i.e. a literal vertical bar/pipe) Actually... You can probably just shorten that rule to: ARGUMENT ([^ \t\\><|]|\\[^ \t\r\n])+ Where: [^ \t\\><|] matches any single character but ' ', '\t', and your special characters \\[^ \t\r\n] matches any character preceded by a '\' in your input except for whitespace (which will handle all of your special characters and allow for literal forms of all other characters) If you want to allow for literal whitespace in your arguments/parameters then you could shorten the rule even further but be careful with using \\. for the second half of the rule alternation as it may or may not match " \n" (i.e. eat your trailing command terminator character!). Hope that helps! A: You cannot easily extract single escaped characters from a command-line, since you will not know the context of the character. In the simplest case, consider the following: LessThan:\< BackslashFrom:\\< In the first one, < is an escaped character; in the second one, it is not. If your language includes quotes (as most shells do), things become even more complicated. It's a lot better to parse the string left to right, one entity at a time. (I'd use flex myself, because I've stopped wasting my time writing and testing lexers, but you might have some pedagogical reason to do so.) If you really need to find a special character which shouldn't be special, just search for it (in C++98, where you don't have raw literals, you'll have to escape all of the backslashes): regex: (\\\\)*\\[<>|] (An even number -- possibly 0 -- of \, then a \ and a <, > or |) as a C string => "(\\\\\\\\)*\\\\[<>|]"
unknown
d13419
train
You can use tabBarVisible(boolean) prop for this purpose. <AppStack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} navigationOptions:()=>{ return { tabBarVisible:false, } } />
unknown
d13420
train
The closest I've come to this is using an ArraySubquery. The only downside being that lines is a list of dictionaries rather than model instances. Category.objects.annotate( lines=ArraySubquery( OrderLine.objects .filter(category=OuterRef('id')) .values(json=JSONObject( id='id', product_name='product__name', quantity='quantity', )) ) )
unknown
d13421
train
If you have a Column of TicketProxy, you can get the UserProxy from the TicketProxy ? ColumnConfig<TicketProxy, String> userRoomColumn = new ColumnConfig<TicketProxy, String>( new ValueProvider<TicketProxy, String>() { public String getValue(TicketProxy object) { String userRoom = object.getUser().getUserRoom(); String room = ""; if (userRoom != null) { room = userRoom; } return room; } public void setValue(TicketProxy object, String userRoom) { object.getUser().setUserRoom(userRoom); } public String getPath() { return "user.userRoom"; } }, 70, "User's Room"); columnsChamado.add(userRoomColumn); A: An gxt grid is able to show the data only of one data type. If you put a single TicketProxy row, how do you expect to access a user object? If you want to display both Tickets and Users independently (so a row is either a Ticket OR a User), you have to use BaseEntityProxy in your Grid: Grid<BaseEntityProxy>. Then you can define your columns as ColumnConfig<BaseEntityProxy, ?> and check the type within your getters and setter: List<ColumnConfig<BaseEntityProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<BaseEntityProxy, ?>>(); ColumnConfig<BaseEntityProxy, String> dateColumn = new ColumnConfig<BaseEntityProxy, String>( new ValueProvider<BaseEntityProxy, String>() { private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL); public String getValue(BaseEntityProxy object) { Date initialDate = ((TicketProxy) object).getInitialDate(); String date = ""; if (initialDate != null) { date = dtFormat.format(initialDate); } return date; } public void setValue(BaseEntityProxy object, String initialDate) { if (object instanceof TicketProxy) { ((TicketProxy) object).setInitialDate(dtFormat.parse(initialDate)); } } public String getPath() { return "initialDate"; } }, 70, "Date"); columnsChamado.add(dateColumn); ColumnConfig<BaseEntityProxy, String> userRoomColumn = new ColumnConfig<BaseEntityProxy, String>( new ValueProvider<BaseEntityProxy, String>() { public String getValue(BaseEntityProxy object) { String userRoom = ((UserProxy)object).getUserRoom(); String room = ""; if (userRoom != null) { room = userRoom; } return room; } public void setValue(BaseEntityProxy object, String userRoom) { if (object instanceof UserProxy) { ((UserProxy)object).setUserRoom(userRoom); } } public String getPath() { return "userRoom"; } }, 70, "User's Room"); columnsChamado.add(userRoomColumn); ColumnModel<BaseEntityProxy> cm = new ColumnModel<BaseEntityProxy>(columnsChamado); If, on the other hand, you want one grid row to display a User AND a Ticket, you have to use a wrapper class: class TicketWithUserProxy extends BaseEntityProxy{ private UserProxy userProxy; private TicketProxy ticketProxy; public UserProxy getUserProxy() { return userProxy; } public void setUserProxy(UserProxy userProxy) { this.userProxy = userProxy; } public TicketProxy getTicketProxy() { return ticketProxy; } public void setTicketProxy(TicketProxy ticketProxy) { this.ticketProxy = ticketProxy; } } and setup your grid (Grid<TicketWithUserProxy>) accordingly: List<ColumnConfig<TicketWithUserProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<TicketWithUserProxy, ?>>(); ColumnConfig<TicketWithUserProxy, String> dateColumn = new ColumnConfig<TicketWithUserProxy, String>( new ValueProvider<TicketWithUserProxy, String>() { private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL); public String getValue(TicketWithUserProxy object) { Date initialDate = object.getTicketProxy().getInitialDate(); String date = ""; if (initialDate != null) { date = dtFormat.format(initialDate); } return date; } public void setValue(TicketWithUserProxy object, String initialDate) { object.getTicketProxy().setInitialDate(dtFormat.parse(initialDate)); } public String getPath() { return "initialDate"; } }, 70, "Date"); columnsChamado.add(dateColumn); ColumnConfig<TicketWithUserProxy, String> userRoomColumn = new ColumnConfig<TicketWithUserProxy, String>( new ValueProvider<TicketWithUserProxy, String>() { public String getValue(TicketWithUserProxy object) { String userRoom = object.getUserProxy().getUserRoom(); String room = ""; if (userRoom != null) { room = userRoom; } return room; } public void setValue(TicketWithUserProxy object, String userRoom) { object.getUserProxy().setUserRoom(userRoom); } public String getPath() { return "userRoom"; } }, 70, "User's Room"); columnsChamado.add(userRoomColumn); ColumnModel<TicketWithUserProxy> cm = new ColumnModel<TicketWithUserProxy>(columnsChamado);
unknown
d13422
train
You need to insert a copy of your descriptions list into the map, currently you manipulate 1 instance of the list. So instead of: block.fields.put(title, descriptions); create a new list, e.g.: block.fields.put(title, new ArrayList<>(descriptions));
unknown
d13423
train
found this url for managing branch permissions using API: https://developer.atlassian.com/static/rest/stash/2.12.1/stash-branch-permissions-rest.html
unknown
d13424
train
There are multiple ways: Using NOT EXISTS INSERT INTO SCHEMA_ABC.TBL_DATA (username, data_id, version) SELECT username, 12345, '1.0' FROM SCHEMA_ABC.TBL_USER A WHERE NOT EXISTS (SELECT 1 FROM SCHEMA_ABC.TBL_DATA NE WHERE NE.username = A.username And ne.data_id = 12345); Using merge: -- updated MERGE INTO SCHEMA_ABC.TBL_DATA T USING (SELECT username, 12345 data_id, '1.0' version FROM SCHEMA_ABC.TBL_USER) D ON (T.USERNAME = D.USERNAME AND T.DATA_ID = D.DATA_ID) WHEN MATCHED THEN UPDATE SET VERSION = VERSION + 1 WHEN NOT MATCHED THEN INSERT(username, data_id, version) Values (D.USERNAME, D.DATA_ID, D.VERSION); Cheers!!
unknown
d13425
train
Resolution: It seems that this embed way had nothing to do with the problem. Comment: This question didn't get an answer for a quite a long time. Anyway I hope IE6 mixed with flash is not a problem nowadays.
unknown
d13426
train
&array_month_count is a macro variable. In SAS, this is a string that is substituted at compile time. Macros "write" code. It looks like all the errors you are getting are because that variable does not have a value. So somewhere in the code, there should be something that sets the value of array_month_count. Find that, fix it, and this step should work. A: A bit more detail than Dom's answer may be helpful, though his answer is certainly the crux of the issue. &array_month_count needs to be defined, but you also probably have a few other issues. array array1 [&array_month_count] $ 1 membsdemo_flag_&start_yrmo membsdemo_flag_&end_yrmo; This is probably wrong, or else this code is perhaps doing something different from what it used to: I suspect it is intended to be array array1 [&array_month_count] $ 1 membsdemo_flag_&start_yrmo - membsdemo_flag_&end_yrmo; In other words, it's probably supposed to expand to something like this. array array1 [6] $ 1 membsdemo_flag_1701 membsdemo_flag_1702 membsdemo_flag_1703 membsdemo_flag_1704 membsdemo_flag_1705 membsdemo_flag_1706; The 6 there isn't actually needed since the variables are listed out (in a condensed form). The dash tells SAS to expand numerically with consecutive numbers from the start to the end; it would only work if your yrmo never crosses a year boundary. It's possible -- is appropriate instead - it tells SAS to expand in variable number order, which works fine if you have consecutively appearing variables (in other words, they're adjacent when you open the dataset). The 6 is however needed for the second bit. do i=1 to &array_month_count; Unless you rewrite it to this: do i = 1 to dim(array1); *dim = dimension, or count of variables in that array; In which case you really don't even need that value. -- If it's actually intended to be the code as above, and only have 2 variables, then you don't need &array_month_count since it's known to be only 2 variables.
unknown
d13427
train
Use a getBroadcast() PendingIntent, where the BroadcastReceiver calls stopService(). Or, use a getService() PendingIntent, where you send a command to your service that has the service call stopSelf(). Or, switch the service to an IntentService, so it shuts down automatically, if that is a better service implementation for your scenario.
unknown
d13428
train
Gatsby comes with reach router, so you can use it to get location.pathname and then render something conditionally. import React from 'react' import { Location } from '@reach/router' const HomepageOnly = () => ( <Location> {({ location }) => location.pathname === '/' ? ( <p>This is the homepage</p> ) : ( <p>This is not</p> ) } </Location> ) export default HomepageOnly Codesandbox
unknown
d13429
train
If you have a keytab file to authenticate to the cluster, this is one way I've done it: val conf: Configuration: = new Configuration() conf.set("hadoop.security.authentication", "Kerberos") UserGroupInformation.setConfiguration(conf) UserGroupInformation.loginUserFromKeytab("user-name", "path/to/keytab/on/local/machine") FileSystem.get(conf) I believe to do this, you might also need some configuration xml docs. Namely core-site.xml, hdfs-site.xml, and mapred-site.xml. These are somewhere usually under /etc/hadoop/conf/. You would put those under a directory in your program and mark it as Resources directory in IntelliJ.
unknown
d13430
train
You check K_UP for second player in KEYUP but it has to be K_w and K_s. Besides you don't have to check player_paddle2.direction if event.type == KEYUP: if event.key == K_UP: player_paddle1.direction = 0 elif event.key == K_DOWN: player_paddle1.direction = 0 elif event.key == K_w: # <-- there was K_UP print("The key is now up!") player_paddle2.direction = 0 elif event.key == K_s: # <-- there was K_UP player_paddle2.direction = 0 it can be shorter elif event.type == KEYUP: if event.key in (K_UP, K_DOWN) player_paddle1.direction = 0 elif event.key in (K_w, K_s): player_paddle2.direction = 0 BTW: you can use elif in some places.
unknown
d13431
train
Why dont you create a function in the user around the lines of: public function autologin() { $this->autoRender = false; if ($this->request->is('post')) { if ($this->Auth->login()) { $cuser = $this->Auth->user(); $this->Session->write('Udata', $udata); $fD = array('loggedIn'=>true,'vdata'=>$udata); } else { $fD = array('loggedIn'=>false,'vdata'=>'Your username/password combination was incorrect'); } echo json_encode($fD); } } and call this page with your ajax. with the JSON run some check;
unknown
d13432
train
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; } }
unknown
d13433
train
You can use functools.reduce for that: from functools import reduce def some_func(df, cond_list): return df[reduce(lambda x,y: x&y, cond_list)] Or, like @AryaMcCarthy says, you can use and_ from the operator package: from functools import reduce from operator import and_ def some_func(df, cond_list): return df[reduce(and_, cond_list)] or with numpy - like @ayhan says - which has also a logical and reduction: from numpy import logical_and def some_func(df, cond_list): return df[logical_and.reduce(cond_list)] All three versions produce - for your sample input - the following output: >>> some_func(df, [cond1, cond2]) Sample DP GQ AB 1 HG_12_34_2 50 45 0.9 2 KD_89_9 76 67 0.7 >>> some_func(df, [cond1, cond2, cond3]) Empty DataFrame Columns: [Sample, DP, GQ, AB] Index: []
unknown
d13434
train
I had the same issue as you are presenting, and after a lot of trial and error, i found some simple steps to fix it. First, add to your Gemfile: gem 'sqlite3', '1.3.5' Then run in your console: bundle install And then you should proceed normally A: Ruby 2.0 has problems with sqlite3 and can't run. If you need to use sqlite3 you'll have to downgrade to 1.9.3. I don't have the link to the documentation about this, but I know if you downgrade to 1.9.3 you'll be fine. I'll see if I can find the link. A: You cannot install activerecord-sqlite3-adapter as a gem, because this adapter is included with ActiveRecord already. The problem is not in activerecord-sqlite3-adapter, but in that you don't have sqlite3 as part of your Gem bundle (the error message tells us this at the end: "sqlite3 is not part of the bundle.") To fix it, add it to your Gemfile first: # in your Gemfile gem 'sqlite3' then run from command line: $ bundle install Ensure that sqlite3 installs correctly and shows up in your Gem bundle, and everything should work.
unknown
d13435
train
You could send Orchestrator as an auxiliary apps when using AWS Device Farm. If you're using the console, this is done during the Specify device state step under Install other apps If you're using the CLI use auxiliaryApps flag https://docs.aws.amazon.com/cli/latest/reference/devicefarm/schedule-run.html A: Short answer: Uploading the orchestrator seems to work, but you dont need it to get the tests run in separate processes. Long answer: As Scott's answer said, you can upload and install the orchestrator to the device. You should upload android test services apk as well (test-services-1.4.0-alpha05.apk for example) Also the Piotr's comment is correct. If you want to use the orchestrator, you should specify your own start command for tests like this: "adb shell "CLASSPATH=$(pm path androidx.test.services) exec app_process / androidx.test.services.shellexecutor.ShellMain am instrument ...". This can be done by using the custom evironment option from the device farm's start test wizard. More info can be found here: https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator If you want to get the tests run separatedly, just use the default environment option, as it seems to isolate the tests by default in the aws farm. There's no need to use the orchestrator. Orchestrator is needed only, if you want to use your own custom test runners, or use custom parameters that needs to be passed to the tests.
unknown
d13436
train
This is a trigger that your admin has set up. Based on the error, I surmise that they want you to set up your client's View to only include one project (they want to keep you from syncing down the entire world when you set up your new client). To create a new client, run: p4 set P4CLIENT=your_workspace_name p4 client and take a look at the form that pops up. The View field defines which part of the depot(s) your client will "see" and operate on. According to the error message, your admin wants you to restrict this to a single "project" -- I don't know what that means in this context (maybe it means just a single depot, or maybe a single folder in a particular depot?) so you might need to talk to your admin about it, or maybe browse around in the GUI and try to glean from context clues (i.e. names of directories) what that message is referring to. Just to use a made-up example, if you have a few different depots your default ("loose") View might look like: //depot_one/... //your_workspace_name/depot_one/... //mumble/... //your_workspace_name/mumble/... //widgets/... //your_workspace_name/widgets/... and if you want to only map the project //mumble/core to your workspace root, you'd change that View to: //mumble/core/... //your_workspace_name/...
unknown
d13437
train
Please try this $dom = new DOMDocument(); $dom->loadHTML($html); $elements = $dom->getElementsByTagName('meta'); foreach ($elements as $child) { echo $child->nodeValue; } A: Do something like this: <?php $nodes = $xml->getElementsByTagName ("meta"); $nodeListLength = $nodes->length; for ($i = 0; $i < $nodeListLength; $i ++) { $node = $nodes->item($i)->getAttribute('content'); } ?>
unknown
d13438
train
You don't want a Comparison(Of String) but a Comparison(Of Class_Post) and you want to compare the Ueberschrift. Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String) Dim comparison As Comparison(Of Class_Post) = Function(x, y) Dim rslt As Integer = StringComparer.Ordinal.Compare(x.Ueberschrift, y.Ueberschrift) Return rslt End Function sorted.Sort(comparison) A ListOf(Of Class_Post) can just be sorted with a Comparison(Of Class_Post). Another approach which is easier to read and to maintain is LINQ: Select Case Suchmoeglichkeit Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String) Return Ergebnisse.OrderBy(Function(x) x.Ueberschrift).ToList() Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date) Return Ergebnisse.OrderBy(Function(x) x.Erstelldatum_dieses_Posts).ToList() Case Else Exit Select End Select
unknown
d13439
train
Sounds like you don't have your dependencies specified properly in your solution. When your build fails look to see what project it is that fails and what project it couldn't find. Then add the dependency.
unknown
d13440
train
Telosys 4 is not yet available as an Eclipse plugin (work in progress). In the meantime, you can use Telosys CLI. NB : since version 4 there is a unique model type : the "DSL model", is you are starting from an existing database the DSL model will be created from the database schema (instead of the previous specific "database model" based on XML)
unknown
d13441
train
Default base for std::stoul is 10. stoul reads 0, x is invalid so the rest of the string is ignored and numeric value 0 is returned. Use similar syntax as in strtoul: unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 16); Or with automatic deduction of numeric base: unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 0); Both of the above versions will throw. See it online!
unknown
d13442
train
Her is the final result of my research based on this question:Changing website favicon dynamically. The final result is as follows: javascript:(function()%7Bvar link %3D document.querySelector("link%5Brel~%3D'icon'%5D")%3Bif (!link) %7Blink %3D document.createElement('link')%3Blink.rel %3D 'icon'%3Bdocument.getElementsByTagName('head')%5B0%5D.appendChild(link)%3B%7Dlink.href %3D prompt('favicon url%3F'%2C 'https%3A%2F%2Fstackoverflow.com%2Ffavicon.ico')%7D)()
unknown
d13443
train
You can use PropertiesPersistingMetadataStore for idempotent receiver: The PropertiesPersistingMetadataStore is backed by a properties file and a PropertiesPersister. By default, it only persists the state when the application context is closed normally. It implements Flushable so you can persist the state at will, be invoking flush(). See more in its JavaDocs.
unknown
d13444
train
std::popcount returns the number of active bits in a value. It is able to call intrinsic functions, if available. constexpr auto get_popcount(auto list) { decltype(list) result; std::transform(list.begin(), list.end(), result.begin(), [](auto x) { return std::popcount(x); }); return result; } int main() { constexpr auto i12 = std::array{ 0b10000010u, 0b00000000u, 0b11000000u, 0b00001010u, 0b00000010u, 0b00000011u, 0b00000000u, 0b00000010u}; static_assert(get_popcount(i12) == std::array{ 2u, 0u, 2u, 2u, 1u, 2u, 0u, 1u }); } A: Can't test this right now but (I1 XOR I2) AND I1 should leave only the bits that you want to count, so: constexpr auto get_popcount(auto i1, auto i2) { std::vector<std::pair(int,int)> res; std::transform (i1.begin(), i1.end(), i2.begin(), res.begin(), [] (auto x, auto y){ return std::tie(std::popcount((x^y)&x),std::popcount((x^y)&y)); }); return res; } Where the first item of the touple is the number of bits on I1 and the second on I2. A: I'm dealing with a similar problem, where I have to count the number of '1' bits from a run-time-determined range. Don't know how long your bit array is, but mine is millions to billions of bits. For a very long bit arrays (say, millions of bits), you could build an auxiliary tree structure for each bit array. The root node counts all bits 0~N in the array, the left child node of root stores the partial sum of bits 0~N/2, the right child node store the partial sum of bits (N/2+1)~N, etc. etc. That way, when you want to count the number of '1' bits from an arbitrary range, you traverse the tree and add the partial sum values stored in appropriate nodes of the tree. The time complexity is O(log(N)). When your array is huge, this is going to be much more efficient than iterating over the entire array (complexity O(N)). If your array is smaller, I would guess SSE/AVX instructions can result in higher throughput? Like Stack Danny has implied, intrinsic functions may already be the underlying implementation of popcount. If you just use a for loop, GCC is able to vectorize your loop into SSE/AVX (e.g. if you got AVX2 on your CPU, add '-mavx2 -O3' to your compiler command). That works for summing elements of an integer array, but I never examined if looping on a bitarray can also result in vectorized code. https://gcc.gnu.org/projects/tree-ssa/vectorization.html A: Use the AND operator for i1 and i2 to get only the intersecting bits. Then in a loop, SHIFT right checking each bit using the AND operator until the variable is zero. Assuming the arrays are in packs of 4 bytes (unsigned long), this should work: size_t getIntersecting(unsigned long* i1, unsigned long* i2, size_t nPacks) { size_t result = 0; unsigned long bitsec; for (size_t i = 0; i < nPacks; i++) { bitsec = i1[i] & i2[i]; while (bitsec != 0) { if (bitsec & 1) { result++; } bitsec >>= 1; } } return result; } I'm not at my workstation to test it. Generally it should count intersecting bits. EDIT: After reexamination of your question, try something like this. // Define the global vectors vector<unsigned long> vector1; vector<unsigned long> vector2; // Define the function void getIntersecting(unsigned long* pi1, unsigned long* pi2, size_t nPacks) { // Initialize the counters to 0 unsigned long i1cnt = 0; unsigned long i2cnt = 0; // Local storage variables unsigned long i1, i2; // Loop through the pointers using nPacks as the counter for (size_t i = 0; i < nPacks; i++) { // Get values from the pointers i1 = pi1[i]; i2 = pi2[i]; // Perform the bitwise operations unsigned long i4 = i1 & i2; // Loop for each bit in the 4-byte pack for (int ibit = 0; ibit < 32; ibit++) { // Check the highest bit of i4 if (!(i4 & 0x80000000)) { // Check the highest bit of i1 if (i1 & 0x80000000) { i1cnt++; } // Check the highest bit of i2 if (i2 & 0x80000000) { i2cnt++; } } else { // Push the counters to the global vectors vector1.push_back(i1cnt); vector2.push_back(i2cnt); // Reset counters i1cnt = 0; i2cnt = 0; } // Shift i4, i1, and i2 left by 1 bit i4 = i4 << 1; i1 = i1 << 1; i2 = i2 << 1; } } }
unknown
d13445
train
It definitely sounds like you're only listening on localhost, so add your IP address from eth0 (or whichever interface you're using). Your config line: interfaces = 127.0.0.1/8 192.168.0.0/24 is incorrect. 127.0.0.1/8 is a way to express both the IP and the subnet. 192.168.0.0/24 is a subnet declaration. Change the 192.168.0.0/24 to whatever your actual IP address is (/sbin/ifconfig) and restart samba. You may want to read the Networking Options with Samba section to familiarize yourself with the hosts allow and hosts deny options as well
unknown
d13446
train
You can use stylesheets (on runtime or loading the file qss). You could manage to do it very easily: QString str = "bottom-right-radius: 10px; top-right-radius: 0px...."; box->setStylesheet(str); I suppose the box is a pixmap inside a QLabel ( label->setPixmap(...) ) OR Set the object name to something (the label), and then use the QLabel#name { bottom-right-radius: 10px... } In a stylesheet you load. Check this site out. It helps: http://border-radius.com/ A: You can use QPainterPath for that : QPainterPath path; path.setFillRule( Qt::WindingFill ); path.addRoundedRect( QRect(50,50, 200, 100), 20, 20 ); path.addRect( QRect( 200, 50, 50, 50 ) ); // Top right corner not rounded path.addRect( QRect( 50, 100, 50, 50 ) ); // Bottom left corner not rounded painter.drawPath( path.simplified() ); // Only Top left & bottom right corner rounded A: Also you can use arcTo() to create rounded corners. Showcase: Code: // Position of shape qreal x = 100.0; qreal y = 100.0; // Size of shape qreal width = 300.0; qreal height = 200.0; // Radius of corners qreal corner_radius = 30.0; QPainterPath path; path.moveTo(x + corner_radius, y); path.arcTo(x, y, 2 * corner_radius, 2 * corner_radius, 90.0, 90.0); path.lineTo(x, y + (height - 2 * corner_radius)); path.arcTo(x, y + (height - 2 * corner_radius), 2 * corner_radius, 2 * corner_radius, 180.0, 90.0); path.lineTo(x + (width - 2 * corner_radius), y + height); path.lineTo(x + (width - 2 * corner_radius), y); path.lineTo(x + corner_radius, y); painter.drawPath(path); A: You can separately draw polygon and pies to create rectangle with 2 rounded corners Code: // Position of shape qreal x = 100; qreal y = 100; // Radius of corners qreal border_radius = 30; // Size of shape qreal width = 300; qreal height = 200; QPolygonF myPolygon; myPolygon << QPointF(x, y+border_radius) << QPointF(x+border_radius, y+border_radius) << QPointF(x+border_radius, y) << QPointF(x+width, y) << QPointF(x+width, y+height) << QPointF(x+border_radius, y+height) << QPointF(x+border_radius, y+height-border_radius) << QPointF(x, y+height-border_radius) << QPointF(x, y+border_radius); QPainterPath myPath; myPath.addPolygon(myPolygon); QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing); painter.setPen(Qt::NoPen); QBrush myBrush(QColor(0, 0, 0), Qt::SolidPattern); painter.setBrush(myBrush); // Draw base polygon painter.drawPath(myPath); // Add rounded corners painter.drawPie(x, y, 2*border_radius, 2*border_radius, 90*16, 90*16); painter.drawPie(x, y+height-2*border_radius, 2*border_radius, 2*border_radius, 180*16, 90*16); How does it look like: Main polygon: QPolygonF myPolygon; myPolygon << QPointF(x, y+border_radius) << QPointF(x+border_radius, y+border_radius) << QPointF(x+border_radius, y) << QPointF(x+width, y) << QPointF(x+width, y+height) << QPointF(x+border_radius, y+height) << QPointF(x+border_radius, y+height-border_radius) << QPointF(x, y+height-border_radius) << QPointF(x, y+border_radius); QPainterPath myPath; myPath.addPolygon(myPolygon); // Draw base polygon painter.drawPath(myPath); Corners: // Add rounded corners painter.drawPie(x, y, 2*border_radius, 2*border_radius, 90*16, 90*16); painter.drawPie(x, y+height-2*border_radius, 2*border_radius, 2*border_radius, 180*16, 90*16); A: To extend the answer of Romha Korev. Here an example of a box with only rounded top corners (top left, top right). The rectangles in the corners are calculated based on the main rectangle! qreal left = 5; qreal top = 10; qreal width = 100; qreal height = 20; QRectF rect(left, top, width, height); QPainterPath path; path.setFillRule( Qt::WindingFill ); path.addRoundedRect(rect, 5, 5 ); qreal squareSize = height/2; path.addRect( QRect( left, top+height-squareSize, squareSize, squareSize) ); // Bottom left path.addRect( QRect( (left+width)-squareSize, top+height-squareSize, squareSize, squareSize) ); // Bottom right painter->drawPath( path.simplified() ); // Draw box (only rounded at top)
unknown
d13447
train
If you use a InvokeScriptedProcessor using groovy you can use context.procNode.processGroup from the ProcessContext If you want to extract all the parents in a breadcrum way, you can use this: import groovy.json.*; import org.apache.nifi.groups.*; class GroovyProcessor implements Processor { def REL_SUCCESS = new Relationship.Builder() .name("success") .description('FlowFiles that were successfully processed are routed here').build() def ComponentLog log @Override void initialize(ProcessorInitializationContext context) { log = context.logger } @Override Set<Relationship> getRelationships() { return [REL_SUCCESS] as Set } void executeScript(ProcessSession session, ProcessContext context) { def flowFile = session.get() if (!flowFile) { return } def breadcrumb = getBreadCrumb(context.procNode.processGroup) + '->' + context.getName() flowFile = session.putAttribute(flowFile, 'breadcrumb', breadcrumb) // transfer session.transfer(flowFile, this.REL_SUCCESS) } // Recursive funtion that gets the breadcrumb String getBreadCrumb(processGroup) { def breadCrumb = '' if(processGroup.parent != null) breadCrumb = getBreadCrumb(processGroup.parent) + '->' return breadCrumb + processGroup.name } @Override void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException { def session = sessionFactory.createSession() try { executeScript( session, context) session.commit() } catch (final Throwable t) { log.error('{} failed to process due to {}; rolling back session', [this, t] as Object[]) session.rollback(true) throw t } } @Override PropertyDescriptor getPropertyDescriptor(String name) { null } @Override List<PropertyDescriptor> getPropertyDescriptors() { return [] as List } @Override void onPropertyModified(PropertyDescriptor descriptor, String oldValue, String newValue) { } @Override Collection<ValidationResult> validate(ValidationContext context) { null } @Override String getIdentifier() { null } } processor = new GroovyProcessor()
unknown
d13448
train
The DataFrame can be written to an xlsx file with no issues using to_excel and the xlsxwriter engine. Maybe that's good enough. However the same issue as you have experienced occurs after converting the xlsx file to cvs format using Excel. Here is an example of creating the xlsx file: import pandas as pd from pandas import DataFrame data = {'Words': ['+Beverly +Hills', '+Andrea +Johnson', '+Football']} df = DataFrame(data) df Out[2]: Words 0 +Beverly +Hills 1 +Andrea +Johnson 2 +Football writer = pd.ExcelWriter('df.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() # contents of df.xlsx are now # Words # 0 +Beverly +Hills # 1 +Andrea +Johnson # 2 +Football
unknown
d13449
train
You can combine regex and shorten your rules in your .htaccess with QSA flag: RewriteEngine on RewriteBase / # add www in host name RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*?)/?$ http://www.%{HTTP_HOST}/$1 [R=301,NE,L] # Unless directory, remove trailing slash RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ /$1 [NE,R=301,L] RewriteRule ^page/(submit|contact|search|recent|playlist)/?$ $1.php [L,NC] RewriteRule ^page/(videos|watch)/([^/]+)/?$ $1.php?title=$2 [L,QSA,NC]
unknown
d13450
train
Perhaps, the following will solve your case: $isInstalled = (bool) shell_exec('which pdftohtml'); which returns nothing if the program isn't found. But it will only work if it's installed globally (without specifying an absolute path). And returns a full path if it's there
unknown
d13451
train
You can't. Enum value names have to be valid C# identifiers, and that excludes &. I suggest you use DescriptionAttribute or something similar to provide more flexible metadata for the enum values. While you could use a regular expression to perform the mapping, I believe you'll end up with a more flexible result if you use metadata. You can then easily build a Dictionary<string, YourAttributeType> and vice versa.
unknown
d13452
train
Random rand = new Random(); int total = db.UploadTables.Count(); var randomId = db.UploadTables.Skip(rand.Next(total)).First().Id; Random.Next(Int32 maxValue) will get a number between 0 and maxValue-1. IQueryable<TSource>.Skip(this IQueryable<TSource>, int count) will skip count entries. You then take the First() of the remaining entries and tadaa you can access its Id field. Obviously, this is only one way to do it, and as told by others, there are many ways to do that.
unknown
d13453
train
I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective. Global.asax: protected void Application_EndRequest() { if (Context.Response.StatusCode == 302 && Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Context.Response.Clear(); Context.Response.StatusCode = 401; } } Client Side Code: $(function () { $.ajaxSetup({ statusCode: { 401: function () { location.href = '/Logon.aspx?ReturnUrl=' + location.pathname; } } }); }); A: try with cache: false cache option in jquery ajax: $.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } }); ---EDIT Try with this in C# code : protected void Page_Load(object sender, System.EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); ... } A: A similar problem has been encountered before. Is the solution given in this question helpful? A: This is the solution I've used in the past: Server side: When I'm checking to see if a session is still valid, I also keep an eye out for the "X-Requested-With" header, which should be "XMLHttpRequest" if you're using jQuery (NOTE: IE tends to return the header name in lower case, so watch for that as well). If the session has indeed expired and the header is present, instead of using an HTTP redirect, I respond with a simple JSON object like this: { "SESSION": "EXPIRED" } Client side: In my onload code, I use jQuery's ajaxComplete event to check all incoming request payloads for the session expired object. The code looks something like this: $(window).ajaxComplete(function(ev, xmlhr, options){ try { var json = $.parseJSON(xmlhr.responseText); } catch(e) { console.log('Session OK'); return; } if ($.isPlainObject(json) && json.SESSION == 'EXPIRED') { console.log('Session Expired'); //inform the user and window.location them somewhere else return; } console.log('Session OK'); }); A: I'm pretty sure you will never get the 302 in the completed status of the XHR object. If a redirect occurs then the connection is still in process until you see the response from the login page (which should be 200, if it exists). However, why do you need to see the 302? Surely if you are getting a redirect to login.php then simply getting the url (or parsing for content) of the returned response tells you they have been logged out? An alternative, only if you want to know as soon as the session has expired (before they do some action), is to poll the server using setTimeout or similar to get information on the authentication status. Good luck.
unknown
d13454
train
I don't understand the formatting behind this but it seems that converting my edgelist from a tbldf to a regular dataframe did the trick. I did this simply by executing the following before converting to networkDynamic time = time %>% data.frame() time = time %>% networkDynamic(edge.spells = time)
unknown
d13455
train
When you assign values here, while (inventory >> temp.PLU >> temp.name >> temp.salesType >> temp.unitPrice >> temp.inventory) Am I right to assume that the input file is in the format (since you're assigning each line to the variables? line 1: Some string you want assigned to PLU line 2: Some string you want assigned to name line 3: Some Int you want assigned to salestype .......... .......... line n:string PLU
unknown
d13456
train
The problem is solved by puting if smode == 'resize': y += kheight in function Window.update_viewport(), I added the next code to my app in order to workout. DO NOT MUST CHANGE THE KIVY LIBS DIRECTLY def update_viewport(self=Window): from kivy.graphics.opengl import glViewport from kivy.graphics.transformation import Matrix from math import radians w, h = self.system_size if self._density != 1: w, h = self.size smode = self.softinput_mode target = self._system_keyboard.target targettop = max(0, target.to_window(0, target.y)[1]) if target else 0 kheight = self.keyboard_height w2, h2 = w / 2., h / 2. r = radians(self.rotation) x, y = 0, 0 _h = h if smode == 'pan': y = kheight elif smode == 'below_target': y = 0 if kheight < targettop else (kheight - targettop) if smode == 'scale': _h -= kheight if smode == 'resize': y += kheight # prepare the viewport glViewport(x, y, w, _h) # do projection matrix projection_mat = Matrix() projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0) self.render_context['projection_mat'] = projection_mat # do modelview matrix modelview_mat = Matrix().translate(w2, h2, 0) modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1)) w, h = self.size w2, h2 = w / 2., h / 2. modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0)) self.render_context['modelview_mat'] = modelview_mat frag_modelview_mat = Matrix() frag_modelview_mat.set(flat=modelview_mat.get()) self.render_context['frag_modelview_mat'] = frag_modelview_mat # redraw canvas self.canvas.ask_update() # and update childs self.update_childsize() if __name__ == '__main__': app = MainApp() Window.update_viewport = update_viewport Window.softinput_mode = 'resize' app.run() Have in count the import of Window and depending onn the kivy version kheight variable may have a different name.
unknown
d13457
train
The simplest way is to use Activity Recognition API http://developer.android.com/training/location/activity-recognition.html . Or you could read raw data from sensors to recognize patterns. But eventually you'll come the same functionality.
unknown
d13458
train
Since you are trying to edit the array elements and its size, I believe array_map() or array_filter() won't be a solution to this. This is what I could come up with... $jobs = [ 'Director', 'Director of Photography', 'Cinematography', 'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer' ]; $crew = []; foreach($tmdbApi as $key => $member) { if($member['id'] == $id && in_array($member['job'], $jobs)) { if(!isset($crew[$key])) { $crew[$key] = $member; } else { $crew_jobs = explode(', ', $crew[$key]['job']); if(!in_array($member['job'], $crew_jobs)) { $crew_jobs[] = $member['job']; } $crew[$key]['job'] = implode(', ', $crew_jobs); } } } Hope this answers your question :) A: You could nicely use Laravel's Collection in such a situation, which has a great number of methods which will help you in this case. First, turn this array (the one you already filtered on jobs) to a Collection: $collection = collect($crew); Second, group this Collection by it's ids: $collectionById = $collection->groupBy('id'); Now, the results are grouped by the id and transformed to a Collection in which the keys correspond to the id, and the value an array of 'matching' results. More info about it here. Finally, just a easy script that iterates through all the results for each id and combines the job field: $combinedJobCollection = $collectionById->map(function($item) { // get the default object, in which all fields match // all the other fields with same ID, except for 'job' $transformedItem = $item->first(); // set the 'job' field according all the (unique) job // values of this item, and implode with ', ' $transformedItem['job'] = $item->unique('job')->implode('job', ', '); /* or, keep the jobs as an array, so blade can figure out how to output these $transformedItem['job'] = $item->unique('job')->pluck('job'); */ return $transformedItem; })->values(); // values() makes sure keys are reordered (as groupBy sets the id // as the key) At this point, this Collection is returned: Collection {#151 ▼ #items: array:4 [▼ 0 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5e9d" "department" => "Directing" "id" => 139098 "job" => "Director, Story, Screenplay" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] 1 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5edd" "department" => "Writing" "id" => 132973 "job" => "Story, Screenplay" "name" => "Ben Coccio" "profile_path" => null ] 2 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5eef" "department" => "Writing" "id" => 1076793 "job" => "Screenplay" "name" => "Darius Marder" "profile_path" => null ] 3 => array:6 [▼ "credit_id" => "52fe49de9251416c750d5f13" "department" => "Camera" "id" => 54926 "job" => "Director of Photography" "name" => "Sean Bobbitt" "profile_path" => null ] ] } Note: to use this Collection as an array, use: $crew = $combinedJobCollection->toArray(); There are multiple ways to achieve this, for example: search the array for overlapping id's, but I think this is the easiest way to achieve this. Goodluck!
unknown
d13459
train
The version of SSRS (Reporting Services) is 12.0.2000.8 which according to https://sqlserverbuilds.blogspot.com/ is SQL Server 2014. If the version of SSRS is 2014 then it is not possible to deploy an SSRS report created using Visual Studio 2012 BIDS. As an alternatively you can use Visual Studio 2017 which can deploy to SSRS 2008, 2008 R2 2012, 2014, and 2016 upwards. See this answer for a screenshot of where you can make the changes. This is the method I used to deploy SSRS reports to a 2012 and then a 2016 installation of SSRS.
unknown
d13460
train
The expression: make([][]bool, sizeX) will create a slice of []bools of size sizeX. Then you have to go through each element and initialize those to slices of sizeY. If you want a fully initialized array: s := &Struct{ X: sizeX, Y: sizeY, Grid: make([][]bool, sizeX), } // At this point, s.Grid[i] has sizeX elements, all nil for i:=range s.Grid { s.Grid[i]=make([]bool, sizeY) } The expression make([][]bool, sizeX, sizeY) creates a [][]bool slice with initial size sizeX and capacity sizeY.
unknown
d13461
train
you need to change the following line canvas=this.surfaceHolder.lockCanvas(); to canvas=surfaceHolder.lockCanvas(); for simple reason. Scope of the variable
unknown
d13462
train
As written in the documentation for the custom elements interface, you have to "bind" the custom element functionality to the HTML by using the is="" attribute. There seems to be differences between custom elements: 1) The ones that use their own shadow DOM ( "stand alone element", "autonomous element" ), and hence are forced to extend HTMLElement ( so not HTMLFormElement ), can be written in the <my-form> style inside the HTML. 2) For custom elements that do not extend HTMLElement, but try to extend other things, like a HTMLFormElement, it seems you need to use <form is="your-defined-name"></form>, ( "customized builtin element" ) https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Customized_built-in_elements class MyForm extends HTMLFormElement { constructor() { super(); this.addEventListener('submit', this.mySubmit); } mySubmit() { console.log('mySubmit was called'); } connectedCallback() { console.log('Custom form element added to page.'); } } customElements.define('my-form', MyForm, { extends: 'form' }); <!DOCTYPE html> <html lang="de-DE"> <head> <title>My Form</title> <meta charset="utf-8"> <!--<script src="myform.js" async="true"></script>--> </head> <body> <h1>My Form</h1> <form is="my-form"> <p><input type="input" value="Whoa!" /></p> <p><button type="submit">Submit</button></p> </form> </body> </html> A: You could do it without is="" by inheriting HTMLElement by adding your custom mySubmit event, consider the following: 'use strict'; class MyForm extends HTMLElement { constructor() { super(); this.addEventListener('mySubmit', this.mySubmit); debugger; } get action() { return this.getAttribute('action') || window.location.href; } mySubmit() { console.log('mySubmit was called'); window.location = this.action; } connectedCallback() { console.log('Custom form element added to page.'); this.querySelector('[type=mySubmit]').onclick = () => { this.dispatchEvent(new CustomEvent('mySubmit')); //,{type: 'submit'}); } } } customElements.define('my-form', MyForm); //, {extends: 'form'}); <!DOCTYPE html> <html lang="de-DE"> <head> <title>My Form</title> <meta charset="utf-8"> <!--<script src="myform.js" async="true"></script>--> </head> <body> <h1>My Form</h1> <my-form action="https://www.google.com"> <p><input type="input" value="Whoa!" /></p> <p><button type="mySubmit">Submit</button></p> </my-form> <hr> <h1>My Form 2</h1> <my-form> <p><input type="input" value="Whoa2!" /></p> <p><button type="mySubmit">Submit</button></p> </my-form> </body> </html> A: Thanks a lot for your help! There was only a tiny piece of code missing to make it happen... 'action="#"' in the element. Best regards, Oliver Now the code looks like this and works as expected: <!DOCTYPE html> <html lang="de-DE"> <head> <title>My Form</title> <meta charset="utf-8"> <script async="true"> class MyForm extends HTMLFormElement { constructor() { super(); console.log('Custom form element created.'); this.addEventListener('submit', this.mySubmit); } mySubmit(event) { event.preventDefault(); console.log('mySubmit was called'); } connectedCallback() { console.log('Custom form element added to page.'); } } customElements.define('my-form', MyForm, { extends: 'form' }); </script> </head> <body> <h1>My Form</h1> <form is="my-form" action="#"> <p><input type="input" value="Whoa!"></input></p> <p><button type="submit">Submit</button></p> </form> </body> </html>
unknown
d13463
train
Goku, in apex, the best way to learn (you said yourself you're a beginner) is to write a lot of small apps in a dev environment that only perform one thing. That way you can isolate issues and study behavior in detail. I suggest you do the same for this switch item issue to figure out what the problem is. You have not provided enough information for anyone to answer it so users are giving you their best guesses. So this is what I did. Create test table create table so_test_with_switch ( so_test_with_switch_id number generated by default on null as identity constraint so_test_with_switc_id_pk primary key, name varchar2(255), switchval number ); Create a report and form in apex, change the form item for switchval page item (P32_SWITCHVAL) to "Switch" with custom settings: 1 for On and 0 for off. I tested and my form worked fine. The error message indicates that the value apex is getting does not match either 1 or 0 so it must get that value from somewhere else. In my case I added an after submit computation to set the value of P32_SWITCHVAL to 'Y'. Saved my changes, ran the form, clicked "Apply Changes" and I got the same error as you. It is up to you to figure out where your page item is getting the other value from. Go through your page, investigate and debug. The key to finding the solution is in your code. --Koen
unknown
d13464
train
I got my answer in the spring framework reference and that is mention below: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> ... </beans> In general it should be like this. for reference Spring Security 3.0 Reference
unknown
d13465
train
if you have saved some values, then symfony will select the values in the form itself. You don't need to preselect them. You need in your form type the method "configureOptions" like this: public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\MyClass' )); } If it is not working anyway, post more code.
unknown
d13466
train
The flipping is achieved by multiplying with a matrix that is initialized with those parameters: # Flip the page left-right (a = -1). destpage.showPDFpage(r * fitz.Matrix(a=-1), src, sourcepage.number) OR: # Flip the page up-down (d = -1). destpage.showPDFpage(r * fitz.Matrix(d=-1), src, sourcepage.number)
unknown
d13467
train
Just an update on the previous accept answer, this is my main.swift: private func isTestRun() -> Bool { return NSClassFromString("XCTestCase") != nil } if isTestRun() { // This skips setting up the app delegate NSApplication.shared.run() } else { // For some magical reason, the AppDelegate is setup when // initialized this way _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) } A bit more compact! I'm using Swift 4.1 and XCode 9.4.1 A: After days of trying and failing I found an answer on the Apple forums: The problem was that my main.swift file was initializing my AppDelegate before NSApplication had been initialized. The Apple documentation makes it clear that lots of other Cocoa classes rely on NSApplication to be up and running when they are initialized. Apparently, NSObject and NSWindow are two of them. So my final and working code in main.swift looks like this: private func isTestRun() -> Bool { return NSClassFromString("XCTest") != nil } private func runApplication( application: NSApplication = NSApplication.sharedApplication(), delegate: NSObject.Type? = nil, bundle: NSBundle? = nil, nibName: String = "MainMenu") { var topLevelObjects: NSArray? // Actual initialization of the delegate is deferred until here: application.delegate = delegate?.init() as? NSApplicationDelegate guard bundle != nil else { application.run() return } if bundle!.loadNibNamed(nibName, owner: application, topLevelObjects: &topLevelObjects ) { application.run() } else { print("An error was encountered while starting the application.") } } if isTestRun() { let mockDelegateClass = NSClassFromString("MockAppDelegate") as? NSObject.Type runApplication(delegate: mockDelegateClass) } else { runApplication(delegate: AppDelegate.self, bundle: NSBundle.mainBundle()) } So the actual problem before was that the Nib was being loaded during tests. This solution prevents this. It just loads the application with a mocked application delegate whenever it detects a test run (By looking for the XCTest class). I'm sure I will have to tweak this a bit more. Especially when a start with UI Testing. But for the moment it works.
unknown
d13468
train
Use execSQL() for such SQL and not rawQuery(). rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program. execSQL() both compiles and runs the SQL program. There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe. A: To update sqlite query change Cursor c = myDataBase.rawQuery(qry, null); to this myDataBase.execSQL(qry); A: try to use this: ContentValues values = new ContentValues(); values.put("Recieve", str); db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });
unknown
d13469
train
You mean environment variables? See http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable%28v=vs.110%29.aspx and http://msdn.microsoft.com/en-us/library/system.environment.setenvironmentvariable%28v=vs.110%29.aspx You can store strings in it, by I wouldn't store too much data there.
unknown
d13470
train
Sorry for messing the code. It is first time to post for me. Here is the code. require 'rubygems' require 'active_record' require 'logger' ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection(:adapter => "ibm_db", :username => "edwdq", :password => "edw%2dqr", :database => "EDWV2", :schema => "EDWDQ" ) class Eval < ActiveRecord::Base set_table_name "eval" set_primary_key :eval_id TYPE_MAP = { 1 => 'SqlEval' } class << self def find_sti_class(type) puts "#{type}" super(TYPE_MAP[type.to_i]) end def sti_name TYPE_MAP.invert[self.name] end end set_inheritance_column :eval_typ_id end class SqlEval < Eval has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id, :foreign_key=>:eval_id, :include=>true, :dependent=>:delete default_scope :conditions => { :eval_typ_id => 1 } end class SqlEvalDetails < ActiveRecord::Base belongs_to :sql_eval, :class_name=>'SqlEval', :conditions => { :eval_type_id => 1 } set_table_name "sql_eval" set_primary_key :eval_id end se = SqlEval.find(:last) e = Eval.where(:eval_id => 26) require 'pp' pp se pp e pp se.details # Eval.delete(se.eval_id) se.delete
unknown
d13471
train
'label':str(repo_dict['description']) Try str() like above, it seems the data you got before hasn't clarifed the type of value that 'description' storged. A: May be the API didn't match the description, so you can use ifelse to solve it. Just like this. description = repo_dict['description'] if not description: description = 'No description provided' plot_dict = { 'value': repo_dict['stargazers_count'], 'label': description, 'xlink': repo_dict['html_url'], } plot_dicts.append(plot_dict)` If the web API returns the value null, it means there's no result, so you can solve it with if statement. Maybe here, the items shadowsocks didn't return anything, so it maybe something went wrong. A: from requests import get from pygal import Bar, style, Config url = "https://api.github.com/search/repositories?q=language:python&sort=stars" # получение данных по API GitHub get_data = get(url) response_dict = get_data.json() repositories = response_dict['items'] # получение данных для построения визуализации names, stars_labels = [], [] for repository in repositories: names.append(repository['name']) if repository['description']: stars_labels.append({'value': repository['stargazers_count'], 'label': repository['description'], 'xlink': repository['html_url']}) else: stars_labels.append({'value': repository['stargazers_count'], 'label': "нет описания", 'xlink': repository['html_url']}) # задание стилей для диаграммы my_config = Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.truncate_label = 15 # сокращение длинных названий проектов my_config.show_y_guides = False # скроем горизонтальные линии my_config.width = 1300 my_style = style.LightenStyle('#333366', base_style=style.LightColorizedStyle) my_style.label_font_size = 16 my_style.major_label_font_size = 20 # построение визуализации chart = Bar(my_config, style=my_style) chart.title = "Наиболее популярные проекты Python на GitHub" chart.x_labels = names chart.add('', stars_labels) chart.render_to_file("python_projects_with_high_stars.svg")
unknown
d13472
train
get-in is better for nested structures, because many interesting keys are not callable, in particular indexes in a vector (other than first or second) or string keys in hash-maps. user=> (get-in [{:a 0} 1 nil "unknown" {:b {"context info" 42}}] [4 :b "context info"]) 42
unknown
d13473
train
Nothing is quick and easy. Setup First you must make sure that you have the package installed To use mod_rewrite, you need to load the extension. Usually, this is done by inmporting the rewrite.so module in the apache2 global configuration (/etc/apache2/apache2.conf) Usually all mod_rewrite instruction are written in the virtual host definition. (Say: /etc/apache2/site-available/000default) Usage First step To enable rewrite for one site, you have to ask for it with : RewriteEngine On Then you can begin to write rules. The basic you need to write rules is describe by the following diagram : (See also : How does url rewrite works?) To help me understand how it works, always consider it from the server side (not client side). You receive an URL from the client. This URL has a certain format that you had defined. (E.g. http://blog.com/article/myarticle-about-a-certain-topic). But apache can't understand this by himself, so we need to help him. We know that the controller is page.php and can look up article by name. Getting information So now we forge a regex to extract information from the URL. All regex are matched against what is following your domain name (here : article/myarticle-about-a-certain-topic without the first / -- It can be written though on recent version of rewrite) Here we need the article's name: ^article/(.*)$ will do the job of matching URL against article/<something> and capturing <something> into $1. (For characters meaning, I advise you to look a tutorial on regex. Here ^ is beginning of the string, invisible position after the .com/, and $ the end of the URL) So now we need to informe apache that this URL means http://myblog.com/page.php?article=myarticle-about-a-certain-topic This is achieved by using a RewriteRule RewriteRule ^article/(.*)$ page.php?article=$1 Restricting to conditions To go a bit on advance topics, you may want to apply this rule only if the article name is fetch by GET method. To do this, you can include a RewriteCond like RewriteCond %{REQUEST_METHOD} GET It goes BEFORE a RewriteRule in the file but is tested AFTER it. Flags If you are making lot of redirection/rewrite, you will have to understand flags The most used are [L] and [R]. A little explanation on those : * *[R] ask for redirection, it can be tuned like [R=302] where 302 is a redirection status number of the HTTP protocol. This will force the client to make a new request with the rewritten URL. Therefore he will see the rewritten URL in his address bar. *[L] forces apache to stop treating rules. Be advise that it does mean that the current incoming URL will stop being modified, but the rewritten URL WILL go again through the process of rewriting. Keep this in mind if you want to avoid loops. Conclusion So you end up with the following block of instructions RewriteEngine On RewriteCond %{REQUEST_METHOD} GET RewriteRule ^article/(.*)$ page.php?article=$1 See also You can find additional resources here : * *A basic tester http://martinmelin.se/rewrite-rule-tester/ *Cheat sheet : http://www.ranzs.com/?p=43 *Query_String examples : http://statichtml.com/2010/mod-rewrite-baseon-on-query-string.html *Tips : http://www.noupe.com/php/10-mod_rewrite-rules-you-should-know.html and http://www.ranzs.com/?p=35
unknown
d13474
train
In PHP you can use the file_get_contents() function to grab files over the internet. $html = file_get_contents('https://raw.github.com/USER/PROJECT/master/file.html'); echo $html; Your pages will be slower if you do this, though. Setting up a cronjob that downloads the file to your server periodically, and then serving it from your server, is a much better idea. A: $url = "http://www.example.com"; //write your raw.github.com URL $gethtml = file_get_contents($url); echo $gethtml; //output the content in the page A: if you want to show it as code you can use this jquery plugin for that
unknown
d13475
train
Your rules are identical. The only difference is a set of parentheses ( ) that don't actually matter because of order of operations / operator precedence rules.
unknown
d13476
train
onRestart you create a new instance of GPSTracker. try updating your GPSTracker handler in onRefresh. give it a try A: @Override public void onRefresh() { final GPSTracker gpsTracker = new GPSTracker(MainActivity.this); new Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); if (gpsTracker.getIsGPSTrackingEnabled()) { gpsTracker.getLocation(); getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } } }, 3000); } });
unknown
d13477
train
Your _setDomainName usage is correct and sufficient. But its value is never send to Analytics : you must use it BEFORE _trackPageview. Then _addIgnoredRef is not useful anymore. A: Move the _trackPageview calls after the _setDomainName and _addIgnoredRef calls. _setDomainName sets the domain for the GA cookies, which get set during _trackPageview. By having _setDomainName after _trackPageview, the default cookie domain is used, resulting in two different sets of cookies, and the data not transferring between domain/subdomain.
unknown
d13478
train
Assuming the address points to int, you may do: cout << "Value is : " << *reinterpret_cast<int*>(0xfee2200); as literal 0xfee2200 is an interger type whereas you expected a pointer. A: You have to decide as what type of data you want to interpret the memory content and cast it accordingly: const char* tmp = "foofoo"; // Valid ptr for this example const void* address = tmp; // Set to your address const int* i = reinterpret_cast<const int*>(address); const unsigned short* us = reinterpret_cast<const unsigned short*>(address); const char* c = reinterpret_cast<const char*>(address); std::cout << "i: " << (*i) << "\nus: " << (*us) << "\nc: " << (*c); Output: i: 1718579046 us: 28518 c: f
unknown
d13479
train
Not a lot to go on, but I think it should be something like this: /^.*\s+HTTP.*\s+-\s+(\d+)\s+/ A backreference will then hold the value you're after. A: I'd see if you can use the apachelogregex gem... http://rubydoc.info/gems/apachelogregex/0.1.0/frames A: Short answer: /HTTP[^-]*-([\d\s]+)/ then, call split on the result. This regexp translates to: "HTTP", followed by any number of non-hyphen characters, followed by a hyphen, followed by the largest string consisting only of digits and spaces.
unknown
d13480
train
Your problem is one of message framing. The Available property only reports the bytes that have arrived so far - not the complete HTTP request or response. If this is just a learning exercise, then I recommend using another protocol. HTTP has one of the most complex message framing systems of any protocol. If this is intended for production, then you'll have to implement (at least partial) HTTP parsing to handle the message framing, and I also recommend a change to asynchronous socket methods rather than synchronous. A better solution is to just implement a web application that uses WebRequest to handle client requests.
unknown
d13481
train
First you must convert text on textbox to int or any number type Simple way : private void EqualsButton2_Click(object sender, EventArgs e) { int numberA = int.Parse(textBox1.Text.Trim()); int numberB = int.Parse(textBox2.Text.Trim()); var result = numberA + numberB; textBox3.Text = result.ToString(); } Safe way : private void EqualsButton_Click(object sender, EventArgs e) { if (!int.TryParse(textBox1.Text.Trim(), out int numberA)) numberA = 0; if (!int.TryParse(textBox2.Text.Trim(), out int numberB)) numberB = 0; var result = numberA + numberB; textBox3.Text = result.ToString(); } A: private void EqualsButton_Click(object sender, EventArgs e) { var resultA=0; var resultB=0; if(!string.IsNullOrEmpty(InputTextBoxA.Text)) resultA=Convert.ToInt32(InputTextBoxA.Text); if(!string.IsNullOrEmpty(InputTextBoxB.Text)) resultB=Convert.ToInt32(InputTextBoxB.Text); OutputTextBox.Text = resultA+ resultB ; } A: Don't listen to anyone. Do this txtResult.Text = string.Empty; if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1)) { MessageBox.Show("Bad value in txt1"); return; } if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2)) { MessageBox.Show("Bad value in txt2"); return; } txtResult.Text = (v1 + v2).ToString(); A: You can change into this private void EqualsButton_Click(object sender, EventArgs e) { try { OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}"); } catch(exception ex) { MessageBox.Show("Enter Valid number")' } } A: You need to convert text fields to int and after for the answer back to the text. If you did not enter a value, then there "" is considered as 0 when adding. private void EqualsButton_Click(object sender, EventArgs e) { OutputTextBox.Text = Convert.ToString( Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text)); }
unknown
d13482
train
Should be hardware problem. When StageVideo is not available on particular device stage.stageVideos property is empty, so to make sure you should make check like this. var stageVideo:StageVideo; if ( stage.stageVideos.length >= 1 ) { stageVideo = stage.stageVideos[0]; } or register StageVideoAvailabilityEvent on stage stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, stageVideoChange); private function stageVideoChange(e:StageVideoAvailabilityEvent):void { if(e.availability == AVAILABLE) { // (stage.stageVideos.length >= 1) is TRUE so we can use stageVideo[0] } else { // StageVideo become unavailable for example after going from fullscreen // back to wmode=normal, wmode=opaque, or wmode=transparent } } Of course second approach is more acceptable because you are notified every time StageVideo becomes available or negative. Note if stage video is available at the moment of registering Listener on StageVideoAvailabilityEvent then listener function (stageVideoChange) is called immediately. A: Turns out Starling runs on Stage3D on TOP of the actual flash display stage. So in order to do this, you need to hide the Starling Stage3D first: Starling.current.stage3D.visible = false Then you can access and show...etc stageVideos and add to the flash display stage: _stageVideo = Starling.current.nativeStage.stageVideos[0]; So basically, the native flash display stage is on the Starling.current.nativeStage property, however, can not be visible unless you first hide the Starling.current.stage3D FIRST. Thanks for the responses! Hope this helps anyone else with the same problem.
unknown
d13483
train
Calling FormsAuthentication.SignOut should clear the authentication cookie. I suggest capturing the HTTP flow and confirming whether the authentication cookie has been deleted. The default name for the authentication cookie is .ASPXAUTH. Alternatively it will be the name specified in your web.config's section. For example, forms name="mycookie" would rename the cookie to mycookie. You shouldn't have to delete the ASP.NET_SessionId session ID cookie.
unknown
d13484
train
To get the nested menu work make all the li items position:relative and make the ul displayed on hover as position:absolute. Check this fiddle HTML: <div class="nav"> <ul class="main"> <li><a href="">1</a> <ul class="sub"> <li><a href="">1-1</a> <ul class="sub"> <li><a href="">1-1-1</a></li> <li><a href="">1-2-1</a></li> </ul> </li> <li><a href="">1-2</a> <ul class="sub"> <li><a href="">1-2-1</a></li> <li><a href="">1-2-2</a></li> </ul> </li> </ul> </li> <li><a href="">2</a></li> </ul> </div> CSS .main{ list-style: none; padding:0px; margin: 0px; } .main li{ background-color:#f1f1f1; padding: 10px; margin: 5px; float:left; clear:both; position:relative; } .main li:hover{ background-color:#d8d8d8; } .main .sub{ display: none; list-style:none; padding-left:0; width:auto; } .main .sub li{ float:none; } .main > li:hover > .sub{ display:block; position:absolute; top:0; left:100%; } .sub li:hover .sub{ display:block; position:absolute; top:0; left:100%; }
unknown
d13485
train
Try using #!/usr/bin/env coffee as your shebang line. That works for me at least, though I'm not sure why exactly (apart from it having to do with the ENV somehow)
unknown
d13486
train
You need to import it from the turtle module. from turtle import Turtle t1 = Turtle() t1.forward(100) A: Try to check within the library files whether there is a file called turtle in it . I had the same problem and i found the library file and opened it. So check it and see if it will fix your problem. Most probably turtle library file will be in Lib folder. A: Nothing here worked for me. This is what I did: I checked what configuration I had (in the upper right hand corner). I changed it so it was the python version that ran through the project and not just plain python. Then you also have to go to script path (also a setting in the configuation) and set it to the .py that you are working on :) A: hey all of you guys just check importing that module ,you dont get any errors its already in standard libraray
unknown
d13487
train
Just this will do: df_new['pct'] = df_new['spend_sum']/df_raw['spend_sum'] spend_sum pct category month product_list Home 1 A 1 0.100000 B 2 0.100000 C 3 0.100000 2 A 20 0.500000 B 10 0.200000 C 5 0.083333
unknown
d13488
train
U can add icons to tabs using defaultNavigationOptions, here is an example, more information about tabs can be got from https://reactnavigation.org/docs/en/4.x/tab-based-navigation.html export default createBottomTabNavigator( { Home: HomeScreen, Settings: SettingsScreen, }, { defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, horizontal, tintColor }) => { const { routeName } = navigation.state; let IconComponent = Ionicons; let iconName; if (routeName === 'Home') { iconName = focused ? 'ios-information-circle' : 'ios-information-circle-outline'; // Sometimes we want to add badges to some icons. // You can check the implementation below. IconComponent = HomeIconWithBadge; } else if (routeName === 'Settings') { iconName = focused ? 'ios-list-box' : 'ios-list'; } // You can return any component that you like here! return <IconComponent name={iconName} size={25} color={tintColor} />; }, }), tabBarOptions: { activeTintColor: 'tomato', inactiveTintColor: 'gray', }, } );```
unknown
d13489
train
You need to put the python code in quotes so the shell doesn't try to parse it like shell code: mypython -c 'print("Hello Again")' # ..........^....................^ If you get python code that contains both double and single quotes, quoting can be a real pain. That's the point when you use a quoted here-doc: python <<'END_PYTHON' print("Hello") print('World') END_PYTHON
unknown
d13490
train
Seems reasonable to me, I probably put it serverside though, give the client a "session-id" and delete the session when a user logs out. Doing it all client side means there is no way to invalidate the session if it has been stolen except to wait for the timeout.
unknown
d13491
train
var a = "<pre><code><p>This is a <span>test</span></p></code></pre>"; var b = a.replace(/\<(?!\/?(p|li|br|b)[ >])[^>]*\>/ig,""); This regex matches the leading < or </ only if it is not followed by one of the tag names you want to keep p, li, br, b (followed by a space or closing >, so that it doesn't think <pre> is <p>). Then it matches everything up to the closing >. A: See this answer. That said, square brackets [] match on single characters, not words - for more information on what yours is doing, see the bottom of this answer. Instead, you would need to use parentheses (?:p|li|br|b) to match words - the ?: is used to avoid capturing. Also, the parentheses would occur outside of the square brackets. Since you're using a negative match you may wish to look into lookarounds; specifically, the section on Positive and Negative Lookbehind. [^\>,p,li,br,b] translates to not > and not , and not p and not , and not l and not i and not , and not b and not r and not , and not b.
unknown
d13492
train
The cluster reorganizes itself to spread the data evenly. You can read it here For your specific case you cane use kopf, A greate plugin that visualize the location of all shards in each node. I think that there are more similar plugins but this is the only one that i worked with.
unknown
d13493
train
This is because Type.GetProperties only returns properties. What you are searching for is essentially the same code as the CopyPropertiesTo above, but you want to replace GetProperties with GetFields. You also need to specify BindingFlags in the parameters of the method to get private members. Try this out: public static void CopyFieldsTo<T, TU>(this T source, TU dest) { var sourceFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList(); var destFields = typeof(TU).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList(); foreach (var sourceField in sourceFields) { if (destFields.Any(x => x.Name == sourceField.Name)) { var f = destFields.First(x => x.Name == sourceField.Name); f.SetValue(dest, sourceField.GetValue(source)); } } }
unknown
d13494
train
Following the example on this MUI page for useMediaQuery, please see what I have created to assist you: import * as React from "react"; import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles"; import useMediaQuery from "@mui/material/useMediaQuery"; import { Typography } from "@material-ui/core"; function MyComponent() { const theme = useTheme(); const large = useMediaQuery(theme.breakpoints.up("lg")); const medium = useMediaQuery(theme.breakpoints.up("md")); const small = useMediaQuery(theme.breakpoints.up("sm")); return ( <> <div>{`large: ${large}`}</div> <div>{`medium: ${medium}`}</div> <div>{`small: ${small}`}</div> <Typography variant={large ? "h1" : medium ? "h2" : small ? "h3" : "body1"} > Font Size Change </Typography> </> ); } const theme = createTheme(); export default function ThemeHelper() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); } Inspect the page, and change the sizes for the screen. Some will appear true, whilst other's false.
unknown
d13495
train
Assuming it works the same way as VideoCategories do, the IDs should work for and remain consistent across any region that supports it. For example, when I used the API explorer and specified USA, Germany, or Australia for the region, the guideCategory ID for Music (GCTXVzaWM) was available for all three, so that guideCategory is supported in and will work for all three of those regions.
unknown
d13496
train
Just a friendly reminder is that it is generally not recommended to parse html with regex. If you would like to do that anyway you could try like this: $pattern = '~<ul>(.*?)</ul>~s'; So in your code it would look like this: preg_match_all('/(~<ul>(.*?)</ul>~s)/', $content, $ulElements); And then for removing it from the original string: preg_replace('/(~<ul>(.*?)</ul>~s)/', '', $content);
unknown
d13497
train
The ItemsControl you are fetching might be the StackPanel, or the Grid. You should be able to access the Checkbox through the event sender, and navigate up to the TreeViewItem and TreeView and use IndexOf. private void CheckBox_Click(object sender, RoutedEventArgs e) { CheckBox cb = (CheckBox)sender; StackPanel sp = (StackPanel)cb.Parent; Grid g = (Grid)sp.Parent; ContentPresenter cp = (ContentPresenter)VisualTreeHelper.GetParent(g); IList l = (IList)myTreeView.ItemsSource; object o = cp.Content; MessageBox.Show(l.IndexOf(o).ToString()); }
unknown
d13498
train
What you are describing is a basic function in almost all AM software implementing OIDC, there is no such a thing as log in to clientA, the users always log in to the IDP, i.e. Keycloak. Clients dont have sessions by default, keycloak does, and clients use keycloak session in thier OIDC flow. For example if you are already authenticated to keycloak, and you tried to do OIDC flow with ClientA or ClientB, you wont be prompted to enter username/password, keycloak will use the existing session. So if you want to have different session for the same user, then you have to create your own session, for example if your clients are using apache, you can use apache oidc module to create a local session ( which will be your ClientA session), as for keycloak session, you cant have two sessions, but you can have one keycloak session for the two clients and two apache session for each clients.
unknown
d13499
train
@Janusz, I have had the same problem. My solution is based on the extended scroll view behaviour in couple with the correct layout. I have wrote the answer to the same question here. Let me know in case you have implementation problems or questions and, please inform whether it helps :) A: In my case, I have a webview within a scrollview container, and the scrollview and webview are full screen. I was able to fix this by overriding the onTouch event in my webView touchListener. scrollView = (ScrollView)findViewById(R.id.scrollview); webView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { scrollView.requestDisallowInterceptTouchEvent(true); return false; } } A: Use TouchyWebView.java public class TouchyWebView extends WebView { public TouchyWebView(Context context) { super(context); } public TouchyWebView(Context context, AttributeSet attrs) { super(context, attrs); } public TouchyWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event){ requestDisallowInterceptTouchEvent(true); return super.onTouchEvent(event); } } In layout file: <yourclasapath.TouchyWebView android:id="@+id/description_web" android:layout_width="match_parent" android:layout_height="wrap_content" /> A: Our solution uses a Javascript callback through the Javascript Interface. Every time a part of the UI that is scrollable inside the WebView is touched a listener is called through java script and this listener calls requestDisallowInterceptTouchEvent on the WebViews parent. This is not optimal but the nicest solution found at the moment. If the user scrolls very fast the layer in the WebView won't scroll but at a normal scroll rate it works fine.
unknown
d13500
train
Finally I had to resign not to use alert() and confirm() anymore. I just made two simple functions that replace the standard ones: function async_alert(message) { $("body").append("<div class='alert-box'>\ <div class='alert-surface'>\ <h2>Alert</h2></header>\ <p>" + message + "</p>\ <button type='button' class='alert-remove'>OK</button>\ </div>\ <div class='alert-backdrop'></div>\ </div>"); $(".alert-remove").off("click").on("click", function() { $(".alert-box").remove(); }); } function async_confirm(message, onAcceptFunction) { $("body").append("<div class='confirm-box'>\ <div class='confirm-surface'>\ <h2>Confirm</h2>\ <p>" + message + "</p>\ <button type='button' class='confirm-remove'>Cancel</button>\ <button type='button' class='confirm-accept'>OK</button>\ </div>\ <div class='confirm-backdrop'></div>\ </div>"); $(".confirm-remove").off("click").on("click", function() { $(".confirm-box").remove(); }); $(".confirm-accept").off("click").on("click", onAcceptFunction); } You should adjust your styles achieving that .alert-box div covers view-port entirey and .alert-surface div becomes a centered rectangle containing informations. E.g.: .alert-box, .confirm-box { position: fixed; top: 0; left: 0; align-items: center; justify-content: center; width: 100%; height: 100%; z-index: 100000; display: flex; align-items: flex-start; } .alert-surface, .confirm-surface { opacity: 1; visibility: visible; box-shadow: 0 11px 15px -7px rgba(0,0,0,.2), 0 24px 38px 3px rgba(0,0,0,.14), 0 9px 46px 8px rgba(0,0,0,.12); background-color: #fff; display: inline-flex; flex-direction: column; width: calc(100% - 30px); max-width: 865px; transform: translateY(50px) scale(.8); border-radius: 2px; } .alert-backdrop, .confirm-backdrop { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,.87); opacity: .3; z-index: -1; } You can use async_alert() just as the original alert() function, but keep in mind that this newly defined function is just asynchronous while the other is synchronous (so it doesn't stop your runtime javascript execution waiting your click). You can also replace the standard browser alert function: window.alert = async_alert; To use async_confirm() function you should slightly change your code from: if(confirm("Do something?") { console.log("I'm doing something"); } to: async_confirm("Do something?", function() { console.log("I'm doing something"); }); Once again, pay attention that async_confirm() il an asynchronous function compared to the standard confirm().
unknown