text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Separate node js query results into objects?
I have a node query that is returning results. However, the handlebars helpers on my view is treating the entire array as one result:
{{#if donations}}
{{#each donations}}
{{this}} is printing the entire set of donations!
{{/each}}
{{/if}}
The {{this}} prints the entire set of the array instead of just printing one object on the web page:
{ owner: '5a6d4c99d6320c05223e0cdb', _id: 5a930456d5ff0809409d15d8, name: 'test', price: 24, description: 'please donate to our cause', enddate: null, __v: 0 },{ owner: '5a6d4c99d6320c05223e0cdb', _id: 5a9a0b601be9210796083c9b, name: 'please donate again', price: 150, description: 'medical condition', enddate: null, __v: 0 },
Here's the relevant router code:
// GET user by username
router.get('/:username', function(req, res) {
//var id = req.params.id;
var username = req.params.username;
User.getUserByUsername(username,function(err, user){
const vm = user;
var id = vm.id;
Donation.getDonationsByUserId(id, function(err, donations){
const vd = { donations };
//console.log(vd);
res.render('user', {donations: vd, user: vm});
})
});
});
And here's the model function it's referencing:
module.exports.getDonationsByUserId = function(id, callback){
return Donation.find({owner: id}, function(err, donations) {
//ar query = {owner: id};
return callback(err, donations);
});
}
How can I iterate through each individual object result?
Thanks!
A:
Considering your JSON structure as below,
{
"donations": [
{
"owner": "5a6d4c99d6320c05223e0cdb",
"_id": "5a930456d5ff0809409d15d8",
"name": "test",
"price": 24,
"description": "please donate to our cause",
"enddate": null,
"__v": 0
},
{
"owner": "5a6d4c99d6320c05223e0cdb",
"_id": "5a9a0b601be9210796083c9b",
"name": "please donate again",
"price": 150,
"description": "medical condition",
"enddate": null,
"__v": 0
}
]
}
You may use the below template structure.
{{#if donations}
{{#each donations}}
{{#each this}}
{{this}}
{{/each}}
is printing the entire set of donations!
{{/each}}
{{/if}}
Which prints the output as,
5a6d4c99d6320c05223e0cdb
5a930456d5ff0809409d15d8
test
24
please donate to our cause
0
is printing the entire set of donations!
5a6d4c99d6320c05223e0cdb
5a9a0b601be9210796083c9b
please donate again
150
medical condition
0
is printing the entire set of donations!
Tested using http://tryhandlebarsjs.com
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
RowStyles and Rows doesn't match in TableLayoutPanel?
We are hiding controls in a TableLayoutPanel. We have been using the following code for a while for hiding a row that shouldn't be visible.
int controlRow = m_panel.GetPositionFromControl(control).Row;
m_panel.RowStyles[controlRow].SizeType = SizeType.Absolute;
m_panel.RowStyles[controlRow].Height = 0;
Now we have been adding more rows, and all of a sudden we have problems with the indexes.
There are fewer RowStyles than Rows.
Is there something fishy going on, or have I misunderstood how the TableLayoutPanel works?
A:
I've tried digging into the issue. The problem is that you did not add rows in a correct way. To add rows correctly, you have to ensure the value of RowCount and the number of RowStyles to be equal. You can see this right in the Form1.Designer.cs in the autogenerated code for the tableLayoutPanel. So you should do something like this:
//add a new row
tableLayoutPanel.RowCount++;
tableLayoutPanel.RowStyles.Add(newRowStyle);
The mismatching in fact does not cause a very serious problem. When the RowStyles.Count is larger than the actual RowCount, all the top RowStyles (which has count being equal to RowCount) will be used to style the rows, the rest can be seen as reserve. When the RowStyles.Count is smaller than the actual RowCount, there will be some rows not having any style and may be collapsed. Anyway using the code I posted above to add a new row will help you avoid any issue. The point is we have to ensure the number of rows and the number of RowStyles to be equal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Backbone + JQuery Plugin won't work (Written in CoffeeScript)
Ok, I have a simple JQuery plugin that when applied to a div will neatly load all the images within that div using a preloader image. This works fine.
However, in Backbone i'm appending data from JSON to a element after the page has been loaded. Therefore the code below won't work.
$(document).ready( ->
$("#theList").preloader()
)
So I need to put the "$("#theList").preloader()" in my render function, after my list is generated..
class HomeView extends Backbone.View
constructor: ->
super
initialize: ->
@isLoading = false
events: {
"click #nextPage": "nextPage"
"click #prevPage": "prevPage"
}
template: _.template($('#home').html())
theListTemplate: _.template($('#theList').html())
render: ->
$(@el).append(@template)
@loadResults()
$("#theList").preloader() #<----------------- DOESN'T WORK NOW
loadResults: () ->
@isLoading = true
Properties.fetch({
success: (data) =>
#Append properties to list
$('#theList').append(@theListTemplate({data: data.models, _:_})).listview('refresh')
error: ->
@isLoading = false
alert('Unable to load information')
})
However, now the line of code is within a Backbone View/Model/Controller or whatever, it doesn't work..
For reference I load my application like so..
$(document).ready( ->
console.log('document ready')
app.AppRouter = new AppRouter()
Backbone.history.start()
)
Any help would be much appreciated! Thanks.
A:
Assuming the preloader isn't intended to operate on the nodes added in the loadResults#fetch#success (since the fetch has not returned by the time you invoke the preloader), I suspect the issue is that, during the execution of the render() function, the view's el is not part of the DOM yet.
If you invoke HomeView like
myHomeView = new HomeView()
$('some selector').append(myHomeView.render().el)
the HomeView's el has not yet been added to the DOM, its in a detached document.
Therefore the jQuery selector $("#theList") returns an empty result - since its searching the DOM. This is easily verified by either console.log'n the result of that selector, or putting a breakpoint in using a debugger, and testing using the console.
Thankfully, the fix is easy. You need to reference the detached document by scoping the selector to the view, either using the jQuery reference scoped to the view:
@$("#theList").preloader()
or, by doing it yourself
$(@el).find("#theList").preloader()
| {
"pile_set_name": "StackExchange"
} |
Q:
img слайдер в java script
Всем привет!
Пишу код для слайда в определённом диве.
Не получается заменить картину. В чём может быть проблема в данном коде ?
Попробувал 3 варианта и не работают, в чём может быть проблема ? Я не получаю никаких ошибок в консоле и в IDE!
var images = [
"BackgroundSlideImages/italy-1587287.jpg",
"BackgroundSlideImages/stream-1149882_1920.jpg",
"BackgroundSlideImages/thimble-1597514_1920.jpg",
"BackgroundSlideImages/mountain-1543308.jpg",
"BackgroundSlideImages/maligne-river-1485060_1920.jpg",
"BackgroundSlideImages/camping-1289930_1920.jpg",
"BackgroundSlideImages/beach-1092734_1920.jpg",
"BackgroundSlideImages/malaysia-911580.jpg",
"BackgroundSlideImages/night-839807.jpg",
"BackgroundSlideImages/sunset-1373171.jpg",
"BackgroundSlideImages/cycling-1533265_1920.jpg",
"BackgroundSlideImages/swim-422546_1920.jpg",
"BackgroundSlideImages/sea-79606_1920.jpg",
"BackgroundSlideImages/paragliding-1219999_1280.jpg",
"BackgroundSlideImages/ski-247787_1920.jpg",
"BackgroundSlideImages/snowboarder-1261844_1920.jpg",
"BackgroundSlideImages/water-fight-442257_1920.jpg",
"BackgroundSlideImages/family-591581_1920.jpg",
"BackgroundSlideImages/pregnant-422982_1920.jpg"
];
var imageCounter = 0;
var element = $("<img src="+images[imageCounter]>+">");
var image = $(".content");
image.append(element);
setInterval(function () {
var img = imageCounter++;
image.fadeOut(1000,function () {
$("img").attr("src",images[img]);
image.fadeIn(1000);
});
if (img == images.length){
img = 0 ;
$("img").attr("src",images[img]);
}
},10000); // Не работает, что можно сделать по другому ?
=================================================================
var imageCounter = 0;
//var element = $("<img src="+images[imageCounter]>+">");
var image = $("#img-page");
// var image = $(".content");
//image.append(element);
setInterval(function () {
var img = imageCounter++;
image.fadeOut(1000,function () {
image.src = images[img];
image.fadeIn(1000);
});
if (img == images.length){
img = 0 ;
image.src = images[img];
}
},10000); //Этот тоже не работает!
=======================================================================
var imageCounter = 0;
var element = $("<img src="+images[imageCounter]>+">");
var image = $(".content");
image.append(element);
setInterval(function () {
var img = imageCounter++;
image.fadeOut(1000,function () {
element.src = images[img];
image.fadeIn(1000);
});
if (img == images.length){
img = 0 ;
element.src = images[img];
}
},10000); // Этот вариант тоже не работет!
=======================================================================
.content{
border: solid;
color: brown;
min-width: 100%;
max-width: 100%;
}
.content > img {
width: 99%;
max-width: 99%;
min-width: 99%;
min-height: 775px;
max-height: 775px;
}
<div class="content">
тут должна быть картина, элемент создаю динамически
<div class="home-content" id = "home-page">
Home
</div>
</div>
A:
Так делать не правельно, но....
var images = [
"http://www.evilbeetgossip.com/wp-content/uploads/2010/08/ladygaga_i-d.jpg",
"http://www.evilbeetgossip.com/wp-content/uploads/2010/08/gaga_id_11.jpg",
"http://www.evilbeetgossip.com/wp-content/uploads/2010/08/gagaid.jpg",
"http://www.evilbeetgossip.com/wp-content/uploads/2010/08/gaga_id_10.jpg"
];
var imageCounter = 0;
var element = $("<img src=" + images[imageCounter] + ">");
var image = $(".content");
image.append(element);
setInterval(function() {
imageCounter++;
image.fadeOut(500, function() {
$("img").attr("src", images[imageCounter]);
image.fadeIn(500);
});
if (imageCounter == images.length) {
imageCounter = 0;
image.fadeOut(500, function() {
$("img").attr("src", images[imageCounter]);
image.fadeIn(500);
});
}
}, 1500);
.content {
border: solid;
color: brown;
max-width: 300px;
}
img{
max-width: 300px;
max-height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="home-content" id="home-page">
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to programmatically connect to a particular PC of unknown IP from a WiFi network?
I want to connect and transfer data between a PC and an Android device both of which are on the same local WiFi network.
I cannot use the local IP as such in the code to actually get the connection going because it does not remain constant every time. I know I can set the local IP to be constant but I am looking for a more general solution to the problem.
Having a central server is also not what I'm looking for, because I want to transfer data offline.
I am not an expert on networks as you might have already guessed, so if I am missing something out, let me know. Also is there some API in android that could do this?
A:
You should look at broadcasting. This is technique of sending your packets to all devices (IP's) in a subnet. It would look something like that:
Android 192.168.0.101: Send message packet to broadcast address
192.168.0.254
PC 192.168.0.110: Reply to 192.168.0.101's broadcast message
Android now knows PC's IP address and can communicate directly
It's really simple. You can find JAVA sample in this SO question: https://stackoverflow.com/questions/12999425/simple-udp-broadcast-client-and-server-on-different-machines
| {
"pile_set_name": "StackExchange"
} |
Q:
get the margin size of an element with jquery
How can I get the properties of an element with jquery? I want to get the size of the margin of a div in particular.
I have set the style of the div in a .css file, for instance,
.item-form {
margin:0px 0px 10px 0px;
background: blue;
}
the html,
<form>
...
<div class="item-form">
<textarea class="autohide"></textarea>
</div>
...
</form>
I tried with this code, but it fails obviously,
$(".autohide").each(function(){
var $this = $(this);
alert($this.parents("div:.item-form").css("margin"));
});
any ideas? thanks.
A:
The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop'), etc. - note they will have 'px' on the end if you have specified them that way.
Use parseInt() around the result to turn it in to the number value.
NB. As noted by Omaty, the order of the shorthand 'margin' tag is: top right bottom left - the above list was not written in a way intended to be the list order, just a list of that specified in the tag.
A:
You'll want to use...
alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));
A:
Exemple, for :
<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>
In this js code :
var myMarginTop = $("#myBlock").css("marginBottom");
The var becomes "15px", a string.
If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.
The fastest is to use native js method :
var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fire following command from vc++?
I want to change image's exif data. For that I've used Exiv2.exe. Now I want to fire command from my program which is written in vc++ 08. For modify GPS data of image, exive command is
exiv2 -M"set Exif.GPSInfo.GPSLatitude 4/1 15/1 33/1" D:\test\image.jpg
I've placed exiv2.exe into system32 folder. And this command works fine from command prompt. For example,
C:\Users\Me>exiv2 -M"set Exif.GPSInfo.GPSLatitude 4/1 15/1 33/1" D:\test\image.jpg
Now how can I fire this same command from my c++ program?
Thanks in advance...
A:
Finally got it,
const char *change_latitude = "exiv2 -M\"set Exif.GPSInfo.GPSLatitude 14/1 15/1 13/1\" D:\\test\\image.jpg";
system(change_latitude);
In this example assumption is : exiv2.exe in system32 folder.
Thanks...
| {
"pile_set_name": "StackExchange"
} |
Q:
window.close() not working on Windows Mobile 6.5
I'm calling a webpage from a mobile device (a motorola MC55A0).
The browser is IEmobile.
The page has a button on it, a press on that button calls some javascript code ending with the line:
window.close();
The javascript executes fine until that line, where nothing happens.
The browser is expected to close but doesn't.
What could be the cause of that behavior?
EDIT: I would like to add that the same webpage worked on another mobile device, with Windows CE 5.0 (Motorola MC3000 series)
A:
remember that: you can fire window.close() only on windows that have been opened with window.open()
See: Scripts may close only the windows that were opened by it
This method is only allowed to be called for windows that were opened
by a script using the window.open method. If the window was not
opened by a script, the following error appears in the JavaScript
Console: Scripts may not close windows that were not opened by
script.
that's the "nothing happens" you're facing. actually it's not absolutely nothing- a script message has been printed to the console.
hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need help on deploying node js project?
I am very much new to Node JS. I have developed a node js project, in my local machine I am running the command 'node app.js' through command prompt. Now I want to deploy this project in our QA environment. Can someone help me on how I can bundle project and deploy it in QA regions?
Also I need to set up an the environment specific variables out side the project so that other projects can use it. Please help me on this as well.
A:
Its easy make a copy, then zip the copied directory and clone your application to you QA environment. In your QA environment, run:
npm install
Optionally, if you have any tests, you can run :
npm install
Also don't forget to set the environment:
NODE_EN=development
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a name for the center of a line?
Is there a name for the center point for a line?
For example:
---------o---------
If the dashes represent a straight line and the O represents the center of that line, what would the name for that center point be?
A:
A line goes forever in both directions, so it has no center. If you have a line segment - a part of a line with two definite ends - then the name is "midpoint."
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I merge data from several rows in SQL Server
Here is my situation:
TABLE PEOPLE (code, name, + other fields that are identical for records with same code)
1;John Wayne
2;Jack Smith
2;Jill Smith
3;Bill Peyton
3;Gill Peyton
3;Billy Peyton
The result I would like:
VIEW PEOPLE (code, name, + other fields that are identical for records with same code)
1;John Wayne
2;Jack Smith Jill Smith
3;Bill Peyton Jill Peyton Billy Peyton
Can some one please help me create a view that would give me this result?
The point is merging rows with same "code" and merge names in column "name". All the other fields are 100% identical for rows with same "code".
Thank you.
A:
Try this
SELECT Code,
( SELECT Name + ' '
FROM Table1 t2
WHERE t2.Code = t1.Code
ORDER BY Name
FOR XML PATH('') ) AS Name
FROM Table1 t1
GROUP BY Code ;
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Security Oauth - Custom format for OAuth2Exceptions
The error format of spring security oauth conforms with the OAuth spec and looks like this.
{
"error":"insufficient_scope",
"error_description":"Insufficient scope for this resource",
"scope":"do.something"
}
Especially on a resource server I find it a bit strange to get a different error format for authentication issues. So I would like to change the way this exception is rendered.
The documentation says
Error handling in an Authorization Server uses standard Spring MVC
features, namely @ExceptionHandler methods
So I tried something like this to customize the format of the error:
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyErrorHandler {
@ExceptionHandler(value = {InsufficientScopeException.class})
ResponseEntity<MyErrorRepresentation> handle(RuntimeException ex, HttpServletRequest request) {
return errorResponse(HttpStatus.FORBIDDEN,
MyErrorRepresentation.builder()
.errorId("insufficient.scope")
.build(),
request);
}
}
But this does not work.
Looking at the code, all the error rendering seems to be done in DefaultWebResponseExceptionTranslator#handleOAuth2Exception. But implementing a custom WebResponseExceptionTranslator would not allow changing the format.
Any hints?
A:
First of all,some knowledge for Spring Security OAuth2.
OAuth2 has two main parts
AuthorizationServer : /oauth/token, get token
ResourceServer : url resource priviledge management
Spring Security add filter to the filter chains of server container, so the exception of Spring Security will not reach @ControllerAdvice
Then, custom OAuth2Exceptions should consider for AuthorizationServer and ResourceServer.
This is configuration
@Configuration
@EnableAuthorizationServer
public class OAuthSecurityConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//for custom
endpoints.exceptionTranslator(new MyWebResponseExceptionTranslator());
}
}
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
// format message
resources.authenticationEntryPoint(new MyAuthenticationEntryPoint());
resources.accessDeniedHandler(new MyAccessDeniedHandler());
}
}
MyWebResponseExceptionTranslator is translate the exception to ourOAuthException and we custom ourOAuthException serializer by jackson, which way is same by default the OAuth2 use.
@JsonSerialize(using = OAuth2ExceptionJackson1Serializer.class)
public class OAuth2Exception extends RuntimeException {
other custom handle class stuff
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
/**
* @author qianggetaba
* @date 2019/6/21
*/
public class MyWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
@Override
public ResponseEntity<OAuth2Exception> translate(Exception exception) throws Exception {
if (exception instanceof OAuth2Exception) {
OAuth2Exception oAuth2Exception = (OAuth2Exception) exception;
return ResponseEntity
.status(oAuth2Exception.getHttpErrorCode())
.body(new CustomOauthException(oAuth2Exception.getMessage()));
}else if(exception instanceof AuthenticationException){
AuthenticationException authenticationException = (AuthenticationException) exception;
return ResponseEntity
.status(HttpStatus.UNAUTHORIZED)
.body(new CustomOauthException(authenticationException.getMessage()));
}
return ResponseEntity
.status(HttpStatus.OK)
.body(new CustomOauthException(exception.getMessage()));
}
}
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
/**
* @author qianggetaba
* @date 2019/6/21
*/
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {
public CustomOauthException(String msg) {
super(msg);
}
}
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
/**
* @author qianggetaba
* @date 2019/6/21
*/
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
public CustomOauthExceptionSerializer() {
super(CustomOauthException.class);
}
@Override
public void serialize(CustomOauthException value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("code4444", value.getHttpErrorCode());
jsonGenerator.writeBooleanField("status", false);
jsonGenerator.writeObjectField("data", null);
jsonGenerator.writeObjectField("errors", Arrays.asList(value.getOAuth2ErrorCode(),value.getMessage()));
if (value.getAdditionalInformation()!=null) {
for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
String key = entry.getKey();
String add = entry.getValue();
jsonGenerator.writeStringField(key, add);
}
}
jsonGenerator.writeEndObject();
}
}
for custom ResourceServer exception
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author qianggetaba
* @date 2019/6/21
*/
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException)
throws ServletException {
Map map = new HashMap();
map.put("errorentry", "401");
map.put("message", authException.getMessage());
map.put("path", request.getServletPath());
map.put("timestamp", String.valueOf(new Date().getTime()));
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), map);
} catch (Exception e) {
throw new ServletException();
}
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author qianggetaba
* @date 2019/6/21
*/
public class MyAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
Map map = new HashMap();
map.put("errorauth", "400");
map.put("message", accessDeniedException.getMessage());
map.put("path", request.getServletPath());
map.put("timestamp", String.valueOf(new Date().getTime()));
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), map);
} catch (Exception e) {
throw new ServletException();
}
}
}
A:
I found a similar question with answers that really helped my solving this - Handle spring security authentication exceptions with @ExceptionHandler
But my question is specifically about spring-security-oauth2 - so I think it is still worth stating the answer specific to spring-security-oauth2. My solution was picked from different answers to the question mentioned above.
My samples work for spring-security-oauth2 2.0.13
So the solution for me to achieve a different custom error structure for oauth2 errors on resource server resources was to register a custom OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler that I register using a ResourceServerConfigurerAdapter. It is worth mentioning that this is only changing the format for ResourceServer endpoints - and not the AuthorizationServer endpoints like the TokenEndpoint.
class MyCustomOauthErrorConversionConfigurerAdapter extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer configurer) throws Exception {
configurer.authenticationEntryPoint(new MyCustomOauthErrorOAuth2AuthenticationEntryPoint());
configurer.accessDeniedHandler(new MyCustomOauthErrorOAuth2AccessDeniedHandler());
}
}
I could not reuse the functionality in OAuth2AuthenticationEntryPoint and OAuth2AccessDeniedHandler because the relevant methods translate the exception and flush it in the same method. So I needed to copy some code:
public class MyCustomOauthErrorOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {
private final MyCustomOauthErrorOAuth2SecurityExceptionHandler oAuth2SecurityExceptionHandler = new MyCustomOauthErrorOAuth2SecurityExceptionHandler();
/**
* Does exactly what OAuth2AccessDeniedHandler does only that the body is transformed to {@link MyCustomOauthError} before rendering the exception
*/
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access.AccessDeniedException authException)
throws IOException, ServletException {
oAuth2SecurityExceptionHandler.handle(request, response, authException, this::enhanceResponse);
}
}
public class ExceptionMessageOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
private final MyCustomOauthErrorOAuth2SecurityExceptionHandler oAuth2SecurityExceptionHandler = new MyCustomOauthErrorOAuth2SecurityExceptionHandler();
/**
* Does exactly what OAuth2AuthenticationEntryPoint does only that the body is transformed to {@link MyCustomOauthError} before rendering the exception
*/
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
oAuth2SecurityExceptionHandler.handle(request, response, authException, this::enhanceResponse);
}
}
@RequiredArgsConstructor
public class MyCustomOauthErrorOAuth2SecurityExceptionHandler {
private final WebResponseExceptionTranslator exceptionTranslator = new DefaultWebResponseExceptionTranslator();
private final OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();
private final HandlerExceptionResolver handlerExceptionResolver = new DefaultHandlerExceptionResolver();
/**
* This is basically what {@link org.springframework.security.oauth2.provider.error.AbstractOAuth2SecurityExceptionHandler#doHandle(HttpServletRequest, HttpServletResponse, Exception)} does.
*/
public void handle(HttpServletRequest request, HttpServletResponse response, RuntimeException authException,
BiFunction<ResponseEntity<OAuth2Exception>, Exception, ResponseEntity<OAuth2Exception>> oauthExceptionEnhancer)
throws IOException, ServletException {
try {
ResponseEntity<OAuth2Exception> defaultErrorResponse = exceptionTranslator.translate(authException);
defaultErrorResponse = oauthExceptionEnhancer.apply(defaultErrorResponse, authException);
//this is the actual translation of the error
final MyCustomOauthError customErrorPayload =
MyCustomOauthError.builder()
.errorId(defaultErrorResponse.getBody().getOAuth2ErrorCode())
.message(defaultErrorResponse.getBody().getMessage())
.details(defaultErrorResponse.getBody().getAdditionalInformation() == null ? emptyMap() : defaultErrorResponse.getBody().getAdditionalInformation())
.build();
final ResponseEntity<MyCustomOauthError> responseEntity = new ResponseEntity<>(customErrorPayload, defaultErrorResponse.getHeaders(), defaultErrorResponse.getStatusCode());
exceptionRenderer.handleHttpEntityResponse(responseEntity, new ServletWebRequest(request, response));
response.flushBuffer();
} catch (ServletException e) {
// Re-use some of the default Spring dispatcher behaviour - the exception came from the filter chain and
// not from an MVC handler so it won't be caught by the dispatcher (even if there is one)
if (handlerExceptionResolver.resolveException(request, response, this, e) == null) {
throw e;
}
} catch (IOException | RuntimeException e) {
throw e;
} catch (Exception e) {
// Wrap other Exceptions. These are not expected to happen
throw new RuntimeException(e);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
A potentially dangerous Request.Form value was detected from the client in local server
I am getting this error when I click on ASP Button. Error: A potentially dangerous Request.Form value was detected from the client
I have read few question of stack over flow. The point here is the button is working fine when I live the website to our client server. But it is not working if I configure in my local IIS server.
Do I need to change any settings in my local IIS server?
Please suggest.
A:
By default, the application is prevented from processing unencoded HTML content submitted to the server.
If you set the the RequestValidationMode to 2.0 in your web.config, it will solve your issue.
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
If you want to make the smallest change possible, you could define the requestValidationMode inside a location element to have it applied to a specific page (ex: Login page)
<location path="Login.aspx">
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
</location>
Remarks (From MSDN)
The RequestValidationMode property specifies which ASP.NET approach to validation will be used. This can be the algorithm that is used in versions of ASP.NET earlier than version 4, or the version that is used in .NET Framework 4. The property can be set to the following values:
4.5 (the default). In this mode, values are lazily loaded, that is, they are not read until they are requested.
4.0 The HttpRequest object internally sets a flag that indicates that request validation should be triggered whenever any HTTP request data is accessed. This guarantees that the request validation is triggered before data such as cookies and URLs are accessed during the request. The request validation settings of the element (if any) in the configuration file or of the directive in an individual page are ignored.
2.0. Request validation is enabled only for pages, not for all HTTP requests. In addition, the request validation settings of the element (if any) in the configuration file or of the directive in an individual page are used to determine which page requests to validate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Posicionamento de imagem
Estou com um problema no posicionamento de imagens em um site que estou desenvolvendo.
Algumas delas aparentemente não estão se encaixando em uma linha, no caso, posicionei 4 por linha.
Fiz algumas tentativas, criei um div que acomodou todo o conteúdo da imagem, ficando assim:
<div class="posicao">
<div class="produtos-wrapper">
<div class="produtos-conteudo one-fourth">
<a href="detalhes.php?produto=<?php echo $row_rsProdutos['id_produto']; ?>&dep=<?php echo $row_rsProdutos['id_departamento']; ?>&subdep=<?php echo $row_rsProdutos['id_subdepartamento']; ?>"><img class="photo" src="<?php echo $foto; ?>" /></a>
<div class="content">
<h3 class="name"><?php echo $row_rsProdutos['descricao']; ?> </h3>
<span class="job-title"> <?php echo $row_rsProdutos['codigo_msb']; ?> </span> </div>
</div>
</div>
<?php } while ($row_rsProdutos = mysql_fetch_assoc($rsProdutos)); ?>
</div>
E o css, assim:
.posicao {
float: right;
width:auto;
}
Mas as imagens ainda ficam com o espaços.
O site para verificação é esse Site para exibição
A:
Quando você trabalha com div, basicamente você tem vários quadrados de sustentação para inserção de conteúdo, sendo ele texto ou multimídia. No caso, esta havendo uma falta de padronização de altura e por isso as divs não encaixam.
Acrescente isso no CSS:
.produtos-conteudo{
height: 200px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
possible to select multiple options with xpath?
/html/body/form/select/option[@val = '1' and @val = '3']
so that means select the first and third option in a select-multiple form ?
A:
Did you mean or?
/html/body/form/select/option[@val = '1' or @val = '3']
That should select both elements. By using and you're trying to select an element whose val is both 1 and 3, which isn't going to work. :-)
| {
"pile_set_name": "StackExchange"
} |
Q:
X11 Forwarding for user without home directory
I have a privileged user without home folder with ssh access. I try to do X forwarding but I get the message /usr/bin/xauth: error in locking authority file /home/user/.Xauthority
If I don't have home folder logically .Xauthority doesn't exist.
Is there a way to replace the location or tell xauth to use a different file?
A:
You can change the location of this file by setting the XAUTHORITY environment variable.
$ export XAUTHORITY=/tmp/.Xauthority_$USER
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I set up two monitors on two very different graphics cards?
I have two video cards, one running each of two identical monitors. My main card is an Nvidia GeForce 750 Ti, and the secondary is a Radeon HD5500. When I boot from live USB, the monitor attached to the HD5500 displays the desktop, and the other displays a gray screen with a flashing cursor (but doesn't do anything else). After installing, the desktop shows up on the GeForce, and the Radeon monitor is blank.
I followed this guide to attempt to install proprietary Nvidia drivers, but it didn't work. So I tried downloading the package straight from Nvidia. I think that worked, but I'm not sure (I'm completely new to this). I then tried to select a different driver for the Radeon from the list on the Additional Drivers settings tab. Now when I boot Ubuntu, the Radeon monitor gets no signal, and the GeForce monitor displays black.
What did I do wrong, and how do I fix it?
Ubuntu 14.04 dual boot with Windows 8.1 U1
A:
You didn't do anything wrong. What you're trying to do is "impossible". Both graphics cards have their own discrete memory and you need a shared frame buffer between the two to make this work...
The BumbleBee project is doing this for Intel and NVidia cards, but they don't support AMD/ATI cards, so unless you start programming this yourself for AMD, it's "impossible"... (for a certain definition of impossible. Look up Charles De Gaulle)
Sorry to be the harbinger of bad news...
| {
"pile_set_name": "StackExchange"
} |
Q:
What happened to the Future Flash?
In The Flash, the Flash from the future traveled back in time to stop the Reverse-Flash from killing his mother. He failed, but where did he go? The Reverse-Flash was stuck in past, so he killed and took the appearance of Doctor Harrison Wells. In his hidden room we see holograms of newspapers from the year 2024 with article about the Flash gone missing. So he didn't travel back to the future. Where is the future Flash?
A:
We don't know. 2 seasons in, they haven't brought it up.
We don't know the extent of Eobard Thawne's supercomputer Gideon's ability to scan the timelines.
We do know is that while the Reverse-Flash is faster than the Flash most of the time, the Flash does not have his issues with time travel. Eobard, in the multiple times we see him time-travel regardless of how, seems to loose his connection to the Speed-Force. Flash, the multiple times we see him time-travel, can do it without any loss of powers.
And due to the constant inconsistencies in how the show handles time-travel (See Why wasn't the timeline affected any further from the events in the season 1 finale?) we don't really know how the show attempts to handle it.
We do know that comic Barry Allen, prior to the DC Crisis of Infinite Earths, during the "Trial of the Flash" in the 80's, essentially leaves the current time and ends up living in the 30th Century, with a reincarnated Iris.
So possibly, after saving his 10 year old self, Future Barry gets sent forward significantly into the future to the 25th or 30th century, Or he returns in 2024 and Gideon simply doesn't know.
Since we only have Eobard's word that he created the particle accelerator explosion 15 years earlier then it normally happened, turning Barry into the Flash much earlier, or if any of the events that shaped Barry into the future Barry that disappeared in 2024, we don't know if that timeline exists as that Barry knew it. The future Flash could be a Timeline Remnant of some sort that disappeared.
| {
"pile_set_name": "StackExchange"
} |
Q:
Парсинг JSON в shell
Есть JSON такого типа
{"response":{"upload_url":"url"}}
Как мне забрать url средствами только shell? В JSON.awk не разобрался, jq не поддерживается в моем случае
A:
Для разбора JSON в командной строке воспользуйтесь утилитой Jshon, она позволяет легко извлекать поля из объекта произвольной сложности с автоматическим раскодировыванием строк (при необходимости). Программа написана на чистом Си и из зависимостей требует только библиотеку Jansson (не считая стандартной libc).
Для вашего случая вызов будет таким:
echo '{"response":{"upload_url":"url"}}' | jshon -e response -e upload_url -u
Её можно найти в архиве Debian в одноимённом пакете.
| {
"pile_set_name": "StackExchange"
} |
Q:
XSL transform to include css
I'm attempting to duplicate an xml via XSLT and the CSS from the source XML is being placed in the body of the xhtml xml file and the head element appears to be empty. How do I get the CSS reference in the correct place so that it formats the newly created XML file.
Source XML
<?xml version="1.0" encoding="utf-8"?>
<?DOCTYPE album SYSTEM "music_inventory.dtd"?>
<?xml-stylesheet type="text/css" href="music_inventory.css"?>
<music_inventory>
<album id="LEDZEP" type="full_length" albumart="http://upload.wikimedia.org/wikipedia/en/c/cb/Led_Zeppelin_-_Mothership.jpg">
<artist>Led Zepplin</artist>
<name>Mothership</name>
<year>1968</year>
<label>Atlantic</label>
<disc>1</disc>
<totaldiscs>1</totaldiscs>
<tracklist>
<track id="1">Good Times Bad Times</track>
<track id="2">Communication Breakdown</track>
<track id="3">Dazed and Confused</track>
<track id="4">Babe I'm gonna Leave You</track>
<track id="5">Whole Lotta Love</track>
<track id="6">Ramble On</track>
<track id="7">Heartbreaker</track>
<track id="8">Immigrant Song</track>
<track id="9">Since I've Been Loving You</track>
<track id="10">Rock and Roll</track>
<track id="11">Black Dog</track>
<track id="12">When the Levee Breaks</track>
<track id="13">Stairway to Heaven</track>
</tracklist>
</album>
<album id="SUBL" type="full_length" albumart="http://upload.wikimedia.org/wikipedia/en/thumb/9/94/Sublime_Self-Titled.jpg/220px-Sublime_Self-Titled.jpg">
<artist>Sublime</artist>
<name>Sublime</name>
<year>1996</year>
<label>MCA</label>
<disc>1</disc>
<totaldiscs>1</totaldiscs>
<tracklist>
<track id="1">Garden Grove</track>
<track id="2">What I Got</track>
<track id="3">Wrong Way</track>
<track id="4">Same in the End</track>
<track id="5">April 29, 1992 (Miami)</track>
<track id="6">Santeria</track>
<track id="7">Seed</track>
<track id="8">Jailhouse</track>
<track id="9">Pawn Shop</track>
<track id="10">Paddle Out</track>
<track id="11">The Ballad of Johnny Butt</track>
<track id="12">Burritos</track>
<track id="13">Under My Voodoo</track>
<track id="14">Get Ready</track>
<track id="15">Caress Me Down</track>
<track id="16">What I Got (Reprise)</track>
<track id="17">Doin' Time</track>
</tracklist>
</album>
</music_inventory>
XSL
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml"
>
<xsl:output method="xml" />
<xsl:template match="* | @* | processing-instruction()">
<xsl:copy>
<xsl:apply-templates select="* | @* | text() | processing-instruction()"/>
</xsl:copy>
</xsl:template>
<xsl:param name="albumid">SUBL</xsl:param>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="music_inventory">
<xsl:apply-templates select="album[@id=$albumid]"/>
</xsl:template>
<!--creates hyperlink-->
<xsl:template match="album/name">
<id>
<a xmlns="http://www.w3.org/1999/xhtml"
href="{../@id}.xhtml">
<xsl:value-of select="."/>
</a>
</id>
</xsl:template>
</xsl:stylesheet>
Resulting XML (note the placement of the stylesheet reference)
<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml">
<body><?xml-stylesheet type="text/css" href="music_inventory.css"?><album xmlns="" id="SUBL" type="full_length" albumart="http://upload.wikimedia.org/wikipedia/en/thumb/9/94/Sublime_Self-Titled.jpg/220px-Sublime_Self-Titled.jpg">
<artist>Sublime</artist>
<id xmlns="http://www.w3.org/1999/xhtml"><a href="SUBL.xhtml">Sublime</a></id>
<year>1996</year>
<label>MCA</label>
<disc>1</disc>
<totaldiscs>1</totaldiscs>
<tracklist>
<track id="1">Garden Grove</track>
<track id="2">What I Got</track>
<track id="3">Wrong Way</track>
<track id="4">Same in the End</track>
<track id="5">April 29, 1992 (Miami)</track>
<track id="6">Santeria</track>
<track id="7">Seed</track>
<track id="8">Jailhouse</track>
<track id="9">Pawn Shop</track>
<track id="10">Paddle Out</track>
<track id="11">The Ballad of Johnny Butt</track>
<track id="12">Burritos</track>
<track id="13">Under My Voodoo</track>
<track id="14">Get Ready</track>
<track id="15">Caress Me Down</track>
<track id="16">What I Got (Reprise)</track>
<track id="17">Doin' Time</track>
</tracklist>
</album></body></html>
A:
The template matching / has the problem. You may use this stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" >
<xsl:output method="xml" />
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:param name="albumid">SUBL</xsl:param>
<xsl:template match="/">
<xsl:apply-templates select="processing-instruction()"/>
<html>
<body>
<xsl:apply-templates select="*"/>
</body>
</html>
</xsl:template>
<xsl:template match="music_inventory">
<xsl:apply-templates select="album[@id=$albumid]"/>
</xsl:template>
<!--creates hyperlink-->
<xsl:template match="album/name">
<id>
<a xmlns="http://www.w3.org/1999/xhtml" href="{../@id}.xhtml">
<xsl:value-of select="."/>
</a>
</id>
</xsl:template>
</xsl:stylesheet>
| {
"pile_set_name": "StackExchange"
} |
Q:
Bool? not nullable
I have following field in my class:
public bool? EitherObject1OrObject2Exists => ((Object1 != null || Object2 != null) && !(Object1 != null && Object2 != null)) ? true : null;
But in Visual Studio I get an IntelliSense error that there cannot be a conversion between "bool" and "NULL" even though the field is nullable.
What do I do wrong?
And is there a cleaner way to check if either one of two objects is not null but one of them must be null?
A:
try
? (bool?) true : null;
the problem is that default bool (true) is not nullable so the case statement are returning different types as far as the compiler is concerned
And you can remove the redundancy as pointed out by Servy
Object1 != null ^ Object2 != null
| {
"pile_set_name": "StackExchange"
} |
Q:
No. of grid walks not going through four points
Given a $11\times11$ grid, and a grid walk is starts at point $(0,0)$ and finishes at the point $(10,10)$. The coordinates of each move are non-decreasing (i.e., you can either move right or up only). How many paths are possible if points $(3,3), (7,2), (3,7),(7,7)$ must not be crossed?
I already know that the total number of possible paths without any restrictions are ${10+10\choose 10}$. So, I need to figure out the no. of bad paths that need to get subtracted from ${10+10\choose 10}$. It is fairly straightforward to calculate the paths that need to avoid any of the four points by finding the complement of the paths that pass through one of the points. For example, $(3,3)$ can be visited in ${3+3\choose 3}{10+10-(3+3)\choose 9-3}$ ways.
However, I am facing troubles calculating the bad paths crossing through a combination of points simultaneously. How would I do that?
A:
An alternative to inclusion-exclusion is to use recursion. Let $p(x,y)$ be the number of such paths from $(0,0)$ to $(x,y)$. By considering the last step into $(x,y)$, we find that $$p(x,y)=p(x-1,y)+p(x,y-1),$$ where $p(x,y)=0$ if $x<0$, $y<0$, or $(x,y)$ is blocked. The boundary condition is $p(0,0)=1$, and you want to compute $p(10,10)$.
\begin{matrix}
1 &11 &66 &166 &441 &1283 &3608 &7416 &14410 &29078 &\color{red}{60256} \\
1 &10 &55 &100 &275 &842 &2325 &3808 &6994 &14668 &31178 \\
1 &9 &45 &45 &175 &567 &1483 &1483 &3186 &7674 &16510 \\
1 &8 &36 &0 &130 &392 &916 &0 &1703 &4488 &8836 \\
1 &7 &28 &64 &130 &262 &524 &980 &1703 &2785 &4348 \\
1 &6 &21 &36 &66 &132 &262 &456 &723 &1082 &1563 \\
1 &5 &15 &15 &30 &66 &130 &194 &267 &359 &481 \\
1 &4 &10 &0 &15 &36 &64 &64 &73 &92 &122 \\
1 &3 &6 &10 &15 &21 &28 &0 &9 &19 &30 \\
1 &2 &3 &4 &5 &6 &7 &8 &9 &10 &11 \\
1 &1 &1 &1 &1 &1 &1 &1 &1 &1 &1 \\
\end{matrix}
A:
You are right : without restrictions, the answer is $\binom{20}{10}$.
Now, we wish to count the bad paths, those that pass through at least one of $P=(3,3), Q=(7,2),R=(3,7), S=(7,7)$. Let us call $B$ as the set of bad paths, which pass through at least one of these points.
Let us call $B_P,B_Q,B_R,B_S$ to be the sets of paths passing through $P,Q,R,S$ respectively. Note that $B = B_P \cup B_Q \cup B_R \cup B_S$.The inclusion-exclusion principle tells us that :
$$
|B| = |B_P| + |B_Q| + |B_R| + |B_S| \\
- |B_P \cap B_Q| - |B_P \cap B_R| - |B_R \cap B_S| - |B_Q \cap B_R| - |B_Q \cap B_S| - |B_R \cap B_S| \\
+ |B_P \cap B_Q \cap B_R| + |B_P \cap B_Q \cap B_S| + |B_P\cap B_R\cap B_S| + |B_Q \cap B_R \cap B_S| \\ - |B_P \cap B_Q \cap B_R \cap B_S|
$$
therefore, we must calculate each of these. They feel like a lot of terms, but in truth there are not too many of them. Why? Because a lot of them are zero.
Let us see this. take $Q$ and $R$. Any path passing through both $Q$ and $R$ must either hit $Q$ or $R$ first. If it hits $Q$ first, then it has to go left to hit $R$, impossible. Similarly, any path hitting $R$ first go down to hit $Q$ , impossible.
Thus, no path can cross both $Q$ and $R$. In short, $|B_Q \cap B_R| = 0$. Similarly, any intersection containing both these terms is $0$.
That now gives us :
$$
|B| = |B_P| + |B_Q| + |B_R| + |B_S| \\
- |B_P \cap B_Q| - |B_P \cap B_R| - |B_R \cap B_S| - |B_Q \cap B_S| - |B_R \cap B_S| \\
+ |B_P \cap B_Q \cap B_S| + |B_P\cap B_R\cap B_S|
$$
However, something similar holds with $P$ and $Q$ (I leave you to see this, in the same manner as above). Then, $|B_P \cap B_Q| = 0$, and terms containing it.
We get to:
$$
|B| = |B_P| + |B_Q| + |B_R| + |B_S| \\
- |B_P \cap B_R| - |B_R \cap B_S| - |B_Q \cap B_S| - |B_R \cap B_S| \\
+ |B_P\cap B_R\cap B_S|
$$
Each of $|B_P|,|B_Q|,|B_R|,|B_S|$ is calculable in the manner you mention.
However, what we realize, is that the intersection probabilities can also be computed in the iterative fashion in which we computed these ones above.
For example, take $|B_P \cap B_R|$. This is counting all paths that go through $P$ and $R$. We see that $P$ must come before $R$. Now, the task is simple, and breaks into three independent tasks.
Find the up-right paths from $0$ to $P$.
Find the up-right paths from $P$ to $Q$.
Find the up-right paths from $Q$ to $(10,10)$.
The first and third of these is easy. For the second, imagine such a path from $P = (3,3)$ to $Q= (3,7)$. Translate such a path down by $3$, and left by $3$ : it becomes an up-right path from $(0,0)$ to $(0,4)$, whence the formula applies. So, by a shift, you can count these , and multiplying the three quantities above, you are done.
Something similar happens for all the other intersections.
For $|B_P \cap B_R \cap B_S|$, any path going through each of these first goes to $P$, then $R$ , then $S$. Break up(into four parts), and multiply!
Finally, you can put everything together to finish.
| {
"pile_set_name": "StackExchange"
} |
Q:
Args with Spring MVC
I need help to pars args in a method inside my controller.
i have a form for sending my parameter to function
<form method="post" action="/">
<input type="text" id="query" placeholder="file to search ...">
<input type="submit" id="submit" value="fetch!">
</form>
and in my controller :
@RestController
public class mainController {
@RequestMapping(value = "/index", method = RequestMethod.POST)
public String index(Model model) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
model.addAttribute("query");
String res = drive.checkFile("query");
return res;
the query is a string send via the form. and return res in the same view.
Do you have any tips?
thanks you very mutch
A:
In Spring MVC It will be like this:
@Controller
public class mainController {
@PostMapping( "/index")
public String index(@ModelAttribute FormDataObjectClass object) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
//model.addAttribute("query");
String name = object.getName();
String address = object.getAddress();
String res = drive.checkFile("query");
return res;
}
Here no need of passing Model as argument as we need a custom Object(FormDataObjectClass) to be used.
Create a class FormDataObjectClass as per you data in HTML form/JQuery post method
| {
"pile_set_name": "StackExchange"
} |
Q:
Wifi problems with rtl8723be in Ubuntu 14.04
I have dual booted my Windows 8 laptop with Ubuntu 14.04. The wifi driver is Realtek rtl8723be. It didn't use to work but I updated the kernel to 3.18 and reinstalled the driver and that seemed to solve the problem for a few hours. Then it would be connected for around 30 minutes and then the connection would stop, even though the icon on the system tray would still indicate it's connected. The only thing that works is restarting the computer but then, again, after 30 minutes the connection stops.
A:
I was having these problem with rtl8723be on linux mint 17, and mint17.1. The same procedure should work on ubuntu 14.04 and derivates.
I had to install new module for realtek wifi cards where they solved the constant disconnects:
install required packages
sudo apt-get install build-essential git
git clone new realtek wifi modules
git clone https://github.com/lwfinger/rtlwifi_new/
enter the directory
cd rtlwifi_new
build it
make
install
sudo make install
Now you can reboot or unload/load modules
unload modules
sudo modprobe -r rtl8723be
load new module
sudo modprobe rtl8723be
if it still doesn't work, try the solution from this post
echo "options rtl8723be fwlps=0" | sudo tee /etc/modprobe.d/rtl8723be.conf
Note: After each kernel update, you need to rebuild the modules. That is,
After every kernel update:
cd rtlwifi_new
Clean previous builds
make clean
Update git repository
git pull
Compile
make clean && make
Install
sudo make install
reboot or unload/load modules
EDIT: It seems as of kernel 4.17 kernel APIs have changed:
Note: If your kernel is 4.17 or newer, AND your card is not an RTL8723DE, then you should NOT be using the external driver. The built-in one is the same.
source: https://github.com/lwfinger/rtlwifi_new/
A:
My friend's HP laptop wouldn't display the available Wi-Fi networks.
So I followed the steps from Miodrag Prelec's answer till echo "options rtl8723be fwlps=0" | sudo tee /etc/modprobe.d/rtl8723be.conf
Then, I did
sudo modprobe -r rtl8723be
Then either of:
sudo modprobe rtl8723be ant_sel=1
sudo modprobe rtl8723be ant_sel=2
(whichever works)
After doing this it would list the Wi-Fi signals in the menu.
So I added these lines to /etc/rc.local (above exit 0) so that it would run each time my laptop boots up.
sleep 10
sudo modprobe -r rtl8723be
sudo modprobe rtl8723be ant_sel=1
Note: change ant_sel=1 to ant_sel=2 if required.
source
A:
Run the following command in terminal
echo "options rtl8723be fwlps=N ips=N" | sudo tee /etc/modprobe.d/rtl8723be.conf
as this will disable some of the power management of the card and usually helps.
And then you need to reboot or manually reload the driver
sudo modprobe -rv rtl8723be
sudo modprobe -v rtl8723be
This was found in ubuntuforums. Varunendra is very good troubleshooting the realtek cards.
| {
"pile_set_name": "StackExchange"
} |
Q:
cross combine two RDDs using pyspark
How can I cross combine (is this the correct way to describe?) the two RDDS?
input:
rdd1 = [a, b]
rdd2 = [c, d]
output:
rdd3 = [(a, c), (a, d), (b, c), (b, d)]
I tried rdd3 = rdd1.flatMap(lambda x: rdd2.map(lambda y: (x, y)), it complains that It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation.. I guess that means you can not nest action as in the list comprehension, and one statement can only do one action.
A:
So as you have noticed you can't perform a transformation inside another transformation (note that flatMap & map are transformations rather than actions since they return RDDs). Thankfully, what your trying to accomplish is directly supported by another transformation in the Spark API - namely cartesian (see http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD ).
So you would want to do rdd1.cartesian(rdd2).
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the brain detect the passage of a neutrino?
On a few occasions either in bed or sitting around a fire, with my eyes closed, I rarely but sometimes see a very quick fast flash of white and then, with my eyes still closed, the flash disappears immediately. It happens so fast that I sit up and rethink if it was even real. But I know it is real because I have had it happen to me many times in my life. I have also asked other people if it happens to them and 4/5 replied back saying that they had experienced the flash before.
Is it possible for a neutrino to pass the brain and in response produce the white flash? After all the brain is made of 73% water and neutrino detectors are predominantly water.
I tried submitting this question on biology.stackexchange and I was told that questions like these belonged on the physics.stackexhange site.
A:
The cross-section for neutrino interactions is energy dependent.
For solar neutrinos at $\sim 0.4$ MeV, which would likely dominate any neutrinos likely to interact (the cosmic background neutrinos have way low energies) , the cross-sections are $\sigma \sim 10^{-48}$ m$^2$, for both leptonic processes (elastic scattering from electrons) and neutrino-nucleon interactions.
The mean free path of a neutrino will be given by $l \sim (n\sigma)^{-1}$, where $n$ is number of interacting target particles per cubic metre and $\sigma$ is the cross-section.
If your head is basically water with a density of 1000 kg/m$^3$, then there are $n_e = 3.3\times10^{29}\ m^{-3}$ of electrons and about $6 \times 10^{29} m^{-3}$ of nuclei.
Including both nucleonic and leptonic processes, the mean free path is $\sim 10^{18}\ m$.
So unless your head is 100 light years wide, there is little chance of any individual neutrino interacting with it.
This is only one part of the calculation though - we need to know how many neutrinos are passing through your head per second. The neutrino flux from the Sun is about $7\times 10^{14}$ m$^{-2}$ s$^{-1}$. If your head has an area of about 400 cm$^2$, then there are $3\times 10^{13}$ neutrinos zipping through your brain every second.
Thus is we take $x=20$ cm as the path length through your head, there is a chance $\sim x/l$ of any neutrino interacting, where $l$ was the mean free path calculated earlier.
This probability multiplied by the neutrino flux through your head indicates there are $6\times 10^{-6}$ s$^{-1}$ neutrino interactions in your head, or roughly one every two days.
Whether that would produce any perceptible effect in your brain needs to be shunted back to Biology SE. If we require it (or rather scattered electrons) to produce Cherenkov radiation in the eyeball, then this needs $>5$ MeV neutrinos and so the rate would reduce to 1 per 100 days or even lower due to the smaller number of neutrinos at these energies and the smaller volume of water in the eyeball.
EDIT:
In fact my original answer may be over-optimistic by an order of magnitude since water only acts as a good detector (via Cherenkov radiation) for neutrinos above energies of 5 MeV. Solar neutrinos are predominantly lower energy than this. My calculation ignored atmospheric neutrinos which are produced in far fewer numbers (but at higher energies $\sim 0.1-10$ GeV). The cross-section for these is 4-6 orders of magnitude higher, but I think they are produced in so much lower numbers that they don't contribute.
Conclusion It doesn't have anything to do with neutrinos. The rate would be too low, even if they could be perceived.
A:
If you are that fast in detecting light, you are seeing cosmic ray muons. They are charged and leave an ionizing track in anything they cross and Cerenkov light. in liquid, and the eye is mainly liquid.
They are the most numerous energetic particles arriving at sea level, with a flux of about 1 muon per square centimeter per minute. This can be compared to a solar neutrino flux of about 5 x 10^6 per square centimeter per second.
Even though there are a lot more neutrinos they do not generate photons to first order so as to be detectable in bubble and spark etc chambers, and therefore not even to the eye.
The easy creation of cloud chambers showing muon tracks is recorded on several YouTube videos .
With such a chamber, you could have your eye under the cup and have a friend check for coincidence with one of the tracks coming in, to verify the sharpness of your light detection. :)
Edit after googling:
It is proposed that the primary cosmic radiation is responsible for the light flashes observed by astronauts in translunar flight. Cherenkov radiation may be an important or even the dominant mechanism. An alternative mechanism is the direct excitation of the retina by cosmic ray particles.
And then I remembered a story told me by an oldtimer physicist at those early times of high energy physics experiments where physicists controlled the beams: he would center the beam to his detector by the cerenkov light in his eye. Possibly no connection was made with radiation and cancer at those times, and the beam fluxes were not as strong as the beams we currently have. (just recalled that I asked about it and he did the centering with a very weak beam.)
The retina excitation part cannot hold for one off cosmic muons. One would not see a flash, just a point would be excited by the ionization which only travels microns.
| {
"pile_set_name": "StackExchange"
} |
Q:
PreparedStatement and DateTime
I am trying to use DateTime from the Joda library and I realized that PreparedStatements doesn't support DateTime. What can I do instead? I can set TimeStamp but that's not really what I want. Is there a workaround or do I have to use TimeStamp? In my MySQL database I have also chosen DateTime as the type.
DatabaseConnection dbConnect = new DatabaseConnection();
PreparedStatement query =dbConnect.getConnect().prepareStatement(sql);
query.setInt(1, c.getMemberId());
query.setDateTime(2, c.getStartDate());
query.setDateTime(3, c.getEndDate());
A:
setDate(java.sql.Date) seems like what you're looking for:
query.setDate(2, new java.sql.Date(c.getStartDate().getMillis());
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance - Ruby - Compare large array of hashes (dictionary) to primary hash; update resulting value
I'm attempting to compare my data, which is in the format of an array of hashes, with another large array of hashes (~50K server names and tags) which serves as a dictionary. The dictionary is stripped down to only include the absolutely relevant information.
The code I have works but it is quite slow on this scale and I haven't been able to pinpoint why. I've done verbose printing to isolate the issue to a specific statement (tagged via comments below)--when it is commented out, the code runs ~30x faster.
After reviewing the code extensively, I feel like I'm doing something wrong and perhaps Array#select is not the appropriate method for this task. Thank you so much in advance for your help.
Code:
inventory = File.read('inventory_with_50k_names_and_associate_tag.csv')
# Since my CSV is headerless, I'm forcing manual headers
@dictionary_data = CSV.parse(inventory).map do |name|
Hash[ [:name, :tag].zip(name) ]
end
# ...
# API calls to my app to return an array of hashes is not shown (returns '@app_data')
# ...
@app_data.each do |issue|
# Extract base server name from FQDN (e.g. server_name1.sub.uk => server_name1)
derived_name = issue['name'].split('.').first
# THIS IS THE BLOCK OF CODE that slows down execution 30 fold:
@dictionary_data.select do |src_server|
issue['tag'] = src_server[:tag] if src_server[:asset_name].start_with?(derived_name)
end
end
Sample Data Returned from REST API (@app_data):
@app_data = [{'name' => 'server_name1.sub.emea', 'tag' => 'Europe', 'state' => 'Online'}
{'name' => 'server_name2.sub.us', 'tag' => 'US E.', 'state' => 'Online'}
{'name' => 'server_name3.sub.us', 'tag' => 'US W.', 'state' => 'Failover'}]
Sample Dictionary Hash Content:
@dictionary_data = [{:asset_name => 'server_name1-X98765432', :tag => 'Paris, France'}
{:asset_name => 'server_name2-Y45678920', :tag => 'New York, USA'}
{:asset_name => 'server_name3-Z34534224', :tag => 'Portland, USA'}]
Desired Output:
@app_data = [{'name' => 'server_name1', 'tag' => 'Paris, France', 'state' => 'Up'}
{'name' => 'server_name2', 'tag' => 'New York, USA', 'state' => 'Up'}
{'name' => 'server_name3', 'tag' => 'Portland, USA', 'state' => 'F.O'}]
A:
Assuming "no" on both of my questions in the comments:
#!/usr/bin/env ruby
require 'csv'
@dictionary_data = CSV.open('dict_data.csv') { |csv|
Hash[csv.map { |name, tag| [name[/^.+(?=-\w+$)/], tag] }]
}
@app_data = [{'name' => 'server_name1.sub.emea', 'tag' => 'Europe', 'state' => 'Online'},
{'name' => 'server_name2.sub.us', 'tag' => 'US E.', 'state' => 'Online'},
{'name' => 'server_name3.sub.us', 'tag' => 'US W.', 'state' => 'Failover'}]
STATE_MAP = {
'Online' => 'Up',
'Failover' => 'F.O.'
}
@app_data = @app_data.map do |server|
name = server['name'][/^[^.]+/]
{
'name' => name,
'tag' => @dictionary_data[name],
'state' => STATE_MAP[server['state']],
}
end
p @app_data
# => [{"name"=>"server_name1", "tag"=>"Paris, France", "state"=>"Up"},
# {"name"=>"server_name2", "tag"=>"New York, USA", "state"=>"Up"},
# {"name"=>"server_name3", "tag"=>"Portland, USA", "state"=>"F.O."}]
EDIT: I find it more convenient here to read the CSV without headers, as I don't want it to generate an array of hashes. But to read a headerless CSV as if it had headers, you don't need to touch the data itself, as Ruby's CSV is quite powerful:
CSV.read('dict_data.csv', headers: %i(name tag)).map(&:to_hash)
| {
"pile_set_name": "StackExchange"
} |
Q:
Need help coloring/replacing arbitrary strings using Bash and sed
I'm using a bash script based on the technique used here: Get color output in bash to color the output of my builds and other scripts to make things easier to read. One of the steps in my build executes a "git pull" and the git server spits out a "welcome" string like this amidst a bunch of other output:
** WARNING: THIS IS A PRIVATE NETWORK. UNAUTHORIZED ACCESS IS PROHIBITED. **
Use of this system constitutes your consent to interception, monitoring,
and recording for official purposes of information related to such use,
including criminal investigations.
I'd like to color this specific message yellow or possibly delete it from the output while leaving the rest of the output alone. I've tried to replace a simple string like this:
WelcomeMessage="WARNING"
pathpat=".*"
ccred=$(echo -e "\033[0;31m")
ccyellow=$(echo -e "\033[0;33m")
ccend=$(echo -e "\033[0m")
git pull 2>&1 | sed -r -e "/$WelcomeMessage/ s%$pathpat%$ccyellow&$ccend%g"
The first line of the welcome string is colored yellow as expected but the rest of the lines are not. I'd really like to color the exact welcome string and only that string but for many reasons, this doesn't work:
WelcomeMessage="** WARNING: THIS IS A PRIVATE NETWORK. UNAUTHORIZED ACCESS IS PROHIBITED. **
Use of this system constitutes your consent to interception, monitoring,
and recording for official purposes of information related to such use,
including criminal investigations."
pathpat=".*"
ccred=$(echo -e "\033[0;31m")
ccyellow=$(echo -e "\033[0;33m")
ccend=$(echo -e "\033[0m")
git pull 2>&1 | sed -r -e "/$WelcomeMessage/ s%$pathpat%$ccyellow&$ccend%g"
This fails with the error: sed: -e expression #1, char 78: unterminated address regex
I've looked at a couple other questions and I was able to get the asterisks escaped (by preceding them with backslashes) but I'm baffled by the periods and multiple lines. I'd like to continue using sed to solve this problem since it integrates nicely with the colorizing solution.
Any help is appreciated. Thanks!
A:
The following will colorize in yellow every line from the first instance of ** to the first instance of a period . that's not on the same line. This will match the entire warning message as written.
NORMAL=$(tput sgr0)
YELLOW=$(tput setaf 3)
git pull 2>&1 | sed "/\*\*/,/\./s/.*/$YELLOW&$NORMAL/"
Note: If you want to delete the message you can use this:
git pull 2>&1 | sed '/\*\*/,/\./d'
| {
"pile_set_name": "StackExchange"
} |
Q:
Upload from clipboard not working in VBA Excel
After executing a transaction, I get bunch of user ids, then I copy it and paste it into another part of the transaction
I want to do this with the help of VBA but "UPLOAD FROM CLIPBOARD" doesn't seem to work.
Anybody can help?
Set SAPGUIAuto = GetObject("SAPGUI")
Set SAPapplication = SAPGUIAuto.GetScriptingEngine
Set Connection = SAPapplication.Children(0)
Set session = Connection.Children(0)
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
session.findById("wnd[0]").sendVKey 0
######first part######
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02 1 2"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03 2 7"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04 2 8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04 2 8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04 2 8", "1"
session.findById("wnd[0]/usr/btn%ACTGRPS%APP%-VALU_PUSH").press
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*******"
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").Text = "***********"
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,2]").Text = "************"
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,2]").SetFocus
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,2]").caretPosition = 18
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").currentCellRow = -1
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").selectColumn "BNAME"
#####Got Bunch of User Ids and copied it with the help of Ctrl+C ######
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/tbar[0]/btn[3]").press
###### second part######
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02 1 10"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "03 3 1", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "03 3 1", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "03 3 1", "1"
session.findById("wnd[0]/usr/btn%USER%APP%-VALU_PUSH").press
session.findById("wnd[1]/tbar[0]/btn[24]").press
session.findById("wnd[1]/tbar[0]/btn[8]").press
Here, I copy user ids in first part and store it into BNAME.
But VBA is unable to upload from clipboard in the second part
Maybe because it is not liking Ctrl+C in the first part
A:
You could try the following:
'...
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").selectColumn "BNAME"
'---------------------- new -----------------------------------------
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell/shellcont[1]/shell").selectContextMenuItemByPosition "0"
'---------------------- new -----------------------------------------
'#####Got Bunch of User Ids and copied it with the help of Ctrl+C ######
'...
| {
"pile_set_name": "StackExchange"
} |
Q:
how to change id of form elements before form gets submitted?
I have a table with many rows and each row has select lists. Something like this:
| USER | MANAGER | DEPARTMENT |
| Rob | [John Smith |V] | [Sales |V] |
| Sue | [Bob Jones |V] | [Support |V] |
The user is free to add new rows, there are many rows and the contents of the lists are complex.
I simplified things considerably by giving every manager selector id 'manager', and every department selector id 'department'.
When the form is submitted, I wrote some javascript to cycle through each row, locate each row, and change the ids 'manager_[rownumber]' and 'department_[rownumber]'.
And then I submit the form. My javascript code is below.
Based on debugging with alert popups, the ids are getting changed the way I want, but the servlet only ever receives one 'manager' parameter and one 'department' row number.
Why aren't all the inputs ('manager_1', 'manager_2', and so on) getting submitted? Is there something I have to do after changing the ids to make sure the changes take effect before the submit of the form?
Thanks!
Rob
Here's my code:
function submitForm() {
correctInputIDs();
document.myform.submit();
}
function correctInputIDs() {
var rows = document.getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
var row = rows[i];
selectElements = rows.getElementsByTagName("select");
for (var j=0; j<selectElements.length; j++) {
var selectElement = selectElements[j];
if (selectElement.id == "manager") {
selectElement.id = "manager_"+i;
}
if (selectedElement.id == "department") {
selectElement.id = "department_"+i;
}
}
}
}
A:
Because IDs don't matter with form submission, names do.
Happy Reading
| {
"pile_set_name": "StackExchange"
} |
Q:
Shiro creates a new session for every getSession()
I'm using shiro (1.2.0) in a tapestry app. Right now I only want to use it for session management. While default session management (using ServletContainerSessionManager) works, when I try to switch to native sessions shiro stops keeping track of them:
public static WebSecurityManager decorateWebSecurityManager(WebSecurityManager manager) {
if(manager instanceof TapestryRealmSecurityManager) {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
MemorySessionDAO sessionDAO = new MemorySessionDAO();
sessionManager.setSessionDAO(sessionDAO);
((TapestryRealmSecurityManager) manager).setSessionManager(sessionManager);
}
return null;
}
Debug output:
07-08-12 17:47:57:339 - {TRACE} util.ThreadContext Thread [1072280360@qtp-1531443370-6]; Bound value of type [$WebSecurityManager_19518d48138a] for key [org.apache.shiro.util.ThreadContext_SECURITY_MANAGER_KEY] to thread [1072280360@qtp-1531443370-6]
07-08-12 17:47:57:339 - {TRACE} mgt.DefaultSecurityManager Thread [1072280360@qtp-1531443370-6]; Context already contains a SecurityManager instance. Returning.
07-08-12 17:47:57:339 - {TRACE} mgt.AbstractValidatingSessionManager Thread [1072280360@qtp-1531443370-6]; Attempting to retrieve session with key org.apache.shiro.web.session.mgt.WebSessionKey@1dc49089
07-08-12 17:47:57:339 - {DEBUG} servlet.SimpleCookie Thread [1072280360@qtp-1531443370-6]; Found 'JSESSIONID' cookie value [sbrxl74ij1v8]
07-08-12 17:47:57:339 - {DEBUG} mgt.DefaultSecurityManager Thread [1072280360@qtp-1531443370-6]; Resolved SubjectContext context session is invalid. Ignoring and creating an anonymous (session-less) Subject instance.
org.apache.shiro.session.UnknownSessionException: There is no session with id [sbrxl74ij1v8]
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
A:
The problem was that i forgot to remove the @Persist annotations, which by default use sessions to store data. This caused tapestry to overwrite shiro's JSESSIONID cookie with it's own value.
| {
"pile_set_name": "StackExchange"
} |
Q:
All UPPERCASE to SentenceCase
I have a database that has tables in all CAPITALS eg - TABLENAME.
In my tt file I want to convert these to names to Sentence Case eg - TableName
Has anyone had any success in doing this before?
If all else failed I guess i could capitalise the first letter eg - Tablename would be better than all capitals.
A:
What you mean is the camel case but in your case it's not possible as your program can't possibly guess whether it should be TableName or TablenAme, unless you teach your application all the words in English, at least the ones that are mostly used in software engineering. The .NET Humanizr does something different from what you need, it breaks (well the String extension) long words like "TheVariableThatKeepsNumberOfAttempts" into separate words to create a human readable sentence. But as you can see, this word itself follows camel-case pattern and it's not hard to instruct the program to split the word from where the letters are capital.
If it's not too late, you can change your table names from TABLENAME to TABLE_NAME, so that you can easily do what you want on the code side.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not repeating the function once waypoint reached
Here is the JS for the waypoint call and graph bar function. It repeats every time the waypoint is reached and I would like it to recognise that the waypoint has been reached once already ad not to repeat function. Thanks for your help. :)
$.getScript('http://imakewebthings.com/jquery-waypoints/waypoints.min.js', function() {
$('#jack_bellamy').waypoint(function() {
setTimeout(function start (){
$('.bar').each(function(i)
{
var $bar = $(this);
$(this).append('<span class="count"></span>')
setTimeout(function(){
$bar.css('width', $bar.attr('data-percent'));
}, i*100);
});
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).parent('.bar').attr('data-percent')
}, {
duration: 2000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now) +'%');
}
});
});
}, 500)
});
});
A:
If you don't want a waypoint to keep triggering you can destroy it. To ensure it only runs once, you can destroy it at the end of your handler. The this keyword refers to the waypoint instance you can call destroy on within the handler.
$('#jack_bellamy').waypoint(function() {
// all that animation stuff you mentioned
this.destroy();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open the terminal from inside a snap application?
When i am trying to open my repo in the terminal from the Gitkraken GUI. It states:
There is no terminal configured in your settings. Would you like to configure your terminal now?
Next, I manually set the gnome terminal as custom terminal command with gnome-terminal %d. The keyword %d should be replaced with the repo path. Running this in a terminal works. However in Gitkraken i get:
Command failed. gnome-terminal path/to/repo /bin/sh
1: gnome-terminal: not-found
How do i setup gnome terminal as the default terminal for gitkraken. I am running Ubuntu 18.04.
Edit:
I see that GitKraken is runnig inside a snap. I have broaden the question to how to run a linux command from inside a snap.
A:
Today i learned about snap confinement.
A snap’s confinement level is the degree of isolation it has from your
system.
To allow access to your system’s resources in much the same way traditional packages do You should install the snap with the --classic parameter.
snap install gitkraken --classic
| {
"pile_set_name": "StackExchange"
} |
Q:
Good strategy to handle dependencies between sequential pull requests
Bob clones the project and creates a local branch A from master.
Bob adds some useful helper classes cleaning/refactoring unit tests setups and clean all exising tests thanks to them.
Bob commits, pushes to remote server, then creates a pull request in order to get a code review of this refactoring from John.
John, leading the project, is busy for a week so can't review it immediately.
After asking for code review, Bob wants to write some brand new test files and set of classes ending up with another separated pull request since it is considered as working on a new feature.
Obviously, Bob wants to use his new helpers for those test files.
Which strategy to adopt:
For those new unit tests, Bob should create a B branch derived from master and not A since A has not being reviewed yet. Drawback is that he can't use his unit test helpers yet since not existing in B.
Bob should wait for the code review of the first pull request, merge to master, and then derive B from master. During this time, he should focus on other works that do not depend on his previous pull request.
Bob should derived Bfrom A and use those helpers, taking the risk that A won't be accepted after review. Obviously leading to a rejection of B.
John should shake his ass and as a good leader, should review the first pull request in a short time so that Bob can chain.
What is a good practice to handle dependencies between multiple pull requests in series?
A:
It’s unnecessary to depend and wait your current pull request(PR) on previous ones. For your situation, Bob wants to continue develop/test something based on branch A after a processing PR (issued and not approved yet). He just need to develop the code on branch A, and then commit & push to remote. The PR which merge branch A into master will automatically contains Bob’s second time changes.
So for the multiple PR situation, if you want to update the branch which has already in a pull request, you just need to commit & push changes, the previous PR can update automatically. If you want to update the branch which is not contains in a processing PR, you need to commit & push changes and then create a new PR, and it has no effect on the previous processing PR.
If you just want to add some tiny changes or the feature itself, you should make changes on branch A and use the processing PR. If you need to develop new features, you should make changes on a new feature branch and create a new PR.
For Bob’s condition, developing new feature and need to use helpers on branch A, so he should derive branch B from A even A is not reviewed yet. Because developers need to consider how to develop new function and it’s not efficient to develop new feature until the previous PR is approved. Or if your team really need to use this way, you can still derive B from A and rebase branch B for your needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Make order by with Query in AOT
I have made a query in AOT. My goal is to print information using Group by "CustGroup" and Order by "count(RecId)" desc of CustTable table. The group by works properly, but the order by does not. I can not understand why...
This is what my query looks like:
This is code I use:
Static void Query(Args _args)
{
QueryRun qr;
CustTable myCustTable;
;
qr = new QueryRun(queryStr(MyQuery));
while(qr.next())
{
myCustTable = qr.get(tableNum(CustTable));
info(strFmt("Group %1 Num %2", myCustTable.Custgroup, myCustTable.RecId));
}
}
The result is:
A:
AX does not sort by Count(RecId) but by the grouping.
You can solve your problem by dragging your query to a new view, then doing the sort on the count field of the view. You can also define the view without a query.
| {
"pile_set_name": "StackExchange"
} |
Q:
angular2 - Change color button dynamically
I am creating an application in angular 2 and typescript.
I want to put some background color in my buttons depending on an variable.
<div>
<button md-button>1. Choose travel</button>
<button md-button>2. Choose seats</button>
<button md-button>3. Fill data</button>
<button md-button>4. Pay</button>
</div>
I have a variable in my component:
currentStep: number = 1; //1 Select travel, 2 Choose seats, 3 Fill data, 4 Pay
And for example, I want that when the currentStep is equal to 3, the third button change his background color to blue.
Which is the best way to achieve this ?
Thank you.
A:
You can use ngClass:
[ngClass]="{'fill-data-btn': currentStep == 3 }"
In you css:
.fill-data-btn{
background-color: blue;
}
Just to give you an idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing partition for quicksort in scheme
I am having a lot of trouble with writing scheme...
I am trying to write quicksort using scheme. I have seen tons of answers but they don't really make any sense to me and this is mostly because I barely understand functional programming at all.
I have defined my pivot like this:
(define (pivot lis)
(car lis))
That works fine (and is easy to write..)
For my understanding of the partition function, you have the original list and then you split it into 2 new lists, one that contains values larger than the pivot, and one that contains values smaller or equal to the pivot.
This is how I've tried to implement it:
(define (partition lis)
(if (null? lis) '())
(else (lambda (lis1 lis2)
(if (< (car lis) pivot) append lis1)
(partition (append lis2)))))
This is the error I'm getting:
. else: not allowed as an expression in: (else (lambda (lis1 lis2) (if (< (car lis) pivot) append lis1) (partition (append lis2))))
I am not really sure how to do this, any ideas on how I can make this work? Or is my reasoning off?
A:
(define (partition ls)
(partition-aux ls (pivot ls) '() '()))
(define (parition-aux ls pivot smaller larger)
(cond
((empty? ls) (list smaller larger))
((< (car ls) pivot)
(parition-aux (cdr ls) pivot (cons (car ls) smaller) larger))
(else
(partition-aux (cdr ls) pivot smaller (cons (car ls) larger)))))
you need to define another function to do the job. because you need 2 more arguments to hold the list of smaller and larger numbers. This is one way of doing it. there are other ways that are shorter to type. but I wanted to be explicit.
| {
"pile_set_name": "StackExchange"
} |
Q:
ES6 Set, WeakSet, Map and WeakMap
There is already some questions about map and weak maps, like this: What's the difference between ES6 Map and WeakMap? but I would like to ask in which situation should I favor the use of these data structures? Or what should I take in consideration when I favor one over the others?
Examples of the data structures from:https://github.com/lukehoban/es6features
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set
Bonus. Which of the above data structures will produce the same/similar result of doing: let hash = object.create(null); hash[index] = something;
A:
This is covered in §23.3 of the specification:
If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap.
So the entries in a weak map, if their keys aren't referenced by anything else, will be reclaimed by garbage collection at some point.
In contrast, a Map holds a strong reference to its keys, preventing them from being garbage-collected if the map is the only thing referencing them.
MDN puts it like this:
The key in a WeakMap is held weakly. What this means is that, if there are no other strong references to the key, then the entire entry will be removed from the WeakMap by the garbage collector.
And WeakSet does the same.
...in which situation should I favor the use of this data structures?
Any situation where you don't want the fact you have a map/set using a key to prevent that key from being garbage-collected.
One example of when you might use this would be to have instance-specific information which was truly private to the instance, which looks like this:
let Thing = (() => {
var privateData = new WeakMap();
class Thing {
constructor() {
privateData[this] = {
foo: "some value"
};
}
doSomething() {
console.log(privateData[this].foo);
}
}
return Thing;
})();
There's no way for code outside that scoping function to access the data in privateData. That data is keyed by the instance itself. You wouldn't do that without a WeakMap because if you did you'd have a memory leak, your Thing instances would never be cleaned up. But WeakMap only holds weak references, and so if your code using a Thing instance is done with it and releases its reference to the instance, the WeakMap doesn't prevent the instance from being garbage-collected; instead, the entry keyed by the instance is removed from the map.
Which of the above data structures will produce the same/similar result of doing: let hash = Object.create(null); hash[index] = something;
That would be nearest to Map, because the string index (the property name) will be held by a strong reference in the object (it and its associated property will not be reclaimed if nothing else references it).
| {
"pile_set_name": "StackExchange"
} |
Q:
Are all $[[n, k, d]]$ quantum codes equivalent to additive self-orthogonal $GF(4)^n$ classical codes?
Theorem 2 of [1] states:
Suppose $C$ is an additive self-orthogonal sub-code of $\textrm{GF}(4)^n$, containing $2^{n-k}$ vectors, such that there are no vectors of weight $<d$ in $C^\perp/C$. Then any eigenspace of $\phi^{-1}(C)$ is an additive quantum-error-correcting code with parameters $[[n, k, d]]$.
where here $\phi: \mathbb{Z}_2^{2n} \rightarrow \textrm{GF}(4)^n$ is the map between the binary representation of $n$-fold Pauli operators and their associated codeword, and $C$ is self-orthogonal if $C \subseteq C^\perp$ where $C^\perp$ is the dual of $C$.
This tells us that each additive self-orthogonal $\textrm{GF}(4)^n$ classical code represents a $[[n, k, d]]$ quantum code.
My question is whether the reverse is also true, that is: is every $[[n, k, d]]$ quantum code represented by an additive self-orthogonal $\textrm{GF}(4)^n$ classical code?
Or equivalently: Are there any $[[n, k, d]]$ quantum codes that are not represented by an additive self-orthogonal $\textrm{GF}(4)^n$ classical code?
[1]: Calderbank, A. Robert, et al. "Quantum error correction via codes over GF (4)." IEEE Transactions on Information Theory 44.4 (1998): 1369-1387.
A:
The additive self-orthogonal constraint on the classical codes in order to create stabilizer quantum codes is needed due to the fact that the stabilizer generators must commute between them in order to create a valid code space. When creating quantum codes from classical codes, the commutation relationship for the stabilizers is equivalent to having a self-orthogonal classical code.
However, quantum codes can be constructed from non-self-orthogonal classical codes over $GF(4)^n$ by means of entanglement-assistance. In this constructions, an arbitrary classical code is selected, and by adding some Bell pairs in the qubit system, commutation between the stabilizers is obtained.
This entanglement-assisted paradigm for constructing QECCs from any classical code is presented in arXiv:1610.04013, which is based on the paper "Correcting Quantum Errors with Entanglement" published in Science by Brun, Devetak and Hsieh.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I know whether a random "known not TTL" RS232 device will work with any old random USB-RS232 converter?
I've been hunting around for RS232 converters for a little while now, trying to get my head around the way RS232 works (or at least how it's supposed to), and the way RS232-USB converters (more frequently than not, seem not to) work. Trying to understand the state of things has left me not a little confused, so I'm asking here to try and sort some of my perplexion out :P
To begin with, Wikipedia states the following about RS-232 (emphasis mine):
The RS-232 standard defines the voltage levels that correspond to logical one and logical zero levels for the data transmission and the control signal lines. Valid signals are either in the range of +3 to +15 volts or the range -3 to -15 volts with respect to the ground/common pin; consequently, the range between -3 to +3 volts is not a valid RS-232 level. ...
The standard specifies a maximum open-circuit voltage of 25 volts: signal levels of ±5V, ±10V, ±12V, and ±15V are all commonly seen depending on the voltages available to the line driver circuit. Some RS-232 driver chips have inbuilt circuitry to produce the required voltages from a 3 or 5-volt supply. RS-232 drivers and receivers must be able to withstand indefinite short circuit to ground or to any voltage level up to ±25 volts.
A bit later on, WP also says:
Other serial signaling standards may not interoperate with standard-compliant RS-232 ports. For example, using the TTL levels of near +5 and 0V puts the mark level in the undefined area of the standard. Such levels are sometimes used with NMEA 0183-compliant GPS receivers and depth finders.
All of that makes sense. But then I enter the rabbithole...
When I search for a USB-RS232 converter module (as an alternative to the $40 stuff out there that's just pure profit) which actually follows this spec, I instead find an Internet full of converters which state their operating voltage as either 3.3V or 5V. I can't find any explicitly 10V, 12V or 15V devices anywhere. This is a little worrying, because I've gotten the impression that if the converter can only tolerate 3.3V or 5V, a "real" (?!) RS232 device with 10V or 12V signalling/output voltages has a reasonably high chance of making the converter spontaneously combust in a bad way (on top of not responding to the converter's out-of-spec 3.3V/5V inputs). Thusly, my first question is, how can I tell/find/figure out/identify/etc what converters/devices will and will not work, without an oscillioscope?
The other disturbing trend I've found is that ZT213/MAXx23x voltage level converters only seem to level-shift TX and RX, and chuck all the ancillary (but in certain situations very important) RS232 signals out the window. My second question is, what do I do if I have a "real" (?!) RS232 device using ≥10V signal levels which needs (for example) a DTR line - and all I've got is a 5V USB-RS232 converter? What level shifter can/do I use then?!
Finally, this probably isn't covered by WP's article on RS-232 because it's so out-of-spec, but my third question is this: I've found a lot of the converters out there being referred to as UARTs. I don't get whether this reference is being used with regard to the converter chipset itself, or whether the implication is that it's a USB-to-UART converter, where the UART is the target device. What's the deal with this?
A:
There are some cables that convert directly from USB to RS-232, all of these should say so and all should be (reasonably) compliant with the RS-232 specification.
However, there are also lots of cables that translate from USB to TTL asynchronous serial data, and these will be rated at either 3.3V or 5.0V. Such a cable needs a separate TTL-to-RS-232 converter such as the old MAX232 chip.
This is where the confusion begins — many people call any form of asynchronous serial data "RS-232", even though that term only properly applies to the electrical interface standard. You need to pay attention to exactly what the seller is saying about his cables.
One clue is that if the cable has a D-sub connector (DE-9 or DB-25), it probably really is RS-232. If it has a rectangular header connector, it's probably TTL. YMMV.
The term UART refers to the hardware device that generates and receives asynchronous serial data. Technically, the USB-to-TTL cable contains a chip that comprises two interfaces: a USB device interface and a UART. The chip passes data in both directions between these two interfaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove keys from anywhere in a JSON string without deserialization
Without deserializing and reserializing the following deeply-nested JSON string (if this is possible), how to remove any key with the name "REMOVEME" from any nested level?
Tried:
Reluctantly tried deserializing to JsonObject / LinkedHashMap to traverse the structure with node.remove(e.getKey()) on offending keys, but Gson throws concurrent modification exceptions, and Jackson requires full deserialization.
Before:
{
"a": {
"REMOVEME" : "unwanted",
"b": {
"REMOVEME" : "unwanted",
"c": {
"d": {
"REMOVEME" : "unwanted",
"something": "default",
"e": {
"f": {
"REMOVEME" : "unwanted",
"g": {
"REMOVEME" : "unwanted",
"h": {
... ,
After:
{
"a": {
"b": {
"c": {
"d": {
"something": "default",
"e": {
"f": {
"g": {
"h": {
... ,
A:
One way to solve this is with streaming token-parsing with Gson. This method handles extremely large JSON strings with ease.
Example before and after:
{"a":{"removeme":"unwanted","b":{"c":{"removeme":{"x":1},"d":{"e":123}}}}}
{"a":{"b":{"c":{"d":{"e":123}}}}}
Essential test harness:
String rawJson = "{\"a\":{\"removeme\":\"unwanted\",\"b\":{\"c\":{\"removeme\":{\"x\":1},\"d\":{\"e\":123}}}}}";
final Gson gson = new GsonBuilder().create();
JsonReader reader = gson.newJsonReader( new StringReader( rawJson ) );
StringWriter outWriter = new StringWriter();
JsonWriter writer = gson.newJsonWriter( outWriter );
JsonStreamFilter.streamFilter( reader, writer, Arrays.asList( "removeme" ) );
System.out.println( rawJson );
System.out.println( outWriter.toString() );
Tokenizing and filtering magic:
public class JsonStreamFilter
{
/**
* Filter out all properties with names included in the `propertiesToRemove` list.
*
* @param reader JsonReader to read in the JSON token
* @param writer JsonWriter to accept modified JSON tokens
* @param propertiesToRemove List of property names to remove
* @throws IOException
* @see Gson docs at https://sites.google.com/site/gson/streaming
*/
public static void streamFilter(
final JsonReader reader,
final JsonWriter writer,
final List<String> propertiesToRemove
) throws IOException
{
while ( true )
{
JsonToken token = reader.peek();
switch ( token )
{
case BEGIN_ARRAY:
reader.beginArray();
writer.beginArray();
break;
case END_ARRAY:
reader.endArray();
writer.endArray();
break;
case BEGIN_OBJECT:
reader.beginObject();
writer.beginObject();
break;
case END_OBJECT:
reader.endObject();
writer.endObject();
break;
case NAME:
String name = reader.nextName();
// Skip all nested structures stemming from this property
if ( propertiesToRemove.contains( name ) )
{
reader.skipValue();
break;
}
writer.name( name );
break;
case STRING:
String s = reader.nextString();
writer.value( s );
break;
case NUMBER:
String n = reader.nextString();
writer.value( new BigDecimal( n ) );
break;
case BOOLEAN:
boolean b = reader.nextBoolean();
writer.value( b );
break;
case NULL:
reader.nextNull();
writer.nullValue();
break;
case END_DOCUMENT:
return;
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Are variables case-sensitive in exprtk?
When I define an expression in my exprtk string, like
var x := sqrt(y);
and I try to add another variable
var X := 2*z;
do I get a conflict? Thanks in advance.
A:
I just found the answer: variables defined within exprtk expressions are NOT case sensitive. In the example above you will get a conflict.
A:
As of March 2017, the author of exprtk has added support for case sensitive variables: https://github.com/ArashPartow/exprtk/blob/master/readme.txt#L4477
Just include #define exprtk_disable_caseinsensitivity and you are good to go!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the op integer not change when the buttons are pressed?
I'm new to python so this code is a mess but I have found a bug I can't fix. The program is meant to give you maths sums to solve and I was using buttons that sent an int as a value from 1 to 4 then that is tested in the guess function to generate the next question. The problem is that the int is not changing when the buttons are pressed and every sum is an addition one because it is set as 1 in the root. If anyone could help that would be great, thanks in advance!
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from random import randint
def plus(*args):
op = 1
def minus(*args):
op = 2
def times(*args):
op = 3
def divide(*args):
op = 4
def guess(*args):
try:
numberguess = int(ans.get())
except ValueError:
ask.set('That is not a number!')
global number
gdif = number - numberguess
if gdif == 0:
ask.set('You got it right!')
global score
sco = score.get() + 1
score.set(sco)
result = messagebox.askquestion('', 'Next question')
if result == 'yes':
if top.get() == 0:
noone = randint(1,10)
notwo = randint (1,10)
else:
noone = randint(1,top.get())
notwo = randint(1,top.get())
ans_entry.focus()
if op == 1:
number = noone + notwo
numb.set('What is ' + str(noone) + ' + '+ str(notwo) + '?')
elif op == 2:
number = noone - notwo
numb.set('What is ' + str(noone) + ' - '+ str(notwo) + '?')
elif op == 3:
number = noone * notwo
numb.set('What is ' + str(noone) + ' x '+ str(notwo) + '?')
elif op == 4:
number = noone / notwo
numb.set('What is ' + str(noone) + ' / '+ str(notwo) + '?')
elif result == 'no':
root.destroy()
elif gdif>0:
ask.set(ans.get() + ' is too low')
elif gdif<0:
ask.set(ans.get() + ' is too high')
ans.set('')
root = Tk()
root.title('Maths Game') #window title
mainframe = ttk.Frame(root, padding = '3 3 12 12')
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0,weight = 1)
mainframe.rowconfigure(0, weight = 1)
#organises grid well
ans = StringVar()
numb = StringVar()
ask = StringVar()
pts = StringVar()
score = IntVar()
top = IntVar()
#sets as variables
ans_entry = ttk.Entry(mainframe, width = 7, textvariable = ans) #defines guess entry
ans_entry.grid(column = 2, row = 1, sticky = (W, E)) #places guess entry on grid
ttk.Label(mainframe, textvariable = numb).grid(column = 2, row = 2, sticky = (W, E)) #label
ttk.Label(mainframe, textvariable = ask).grid(column = 3, row = 1, sticky = (W, E)) #label
ttk.Label(mainframe, textvariable = score).grid(column = 3, row = 2, sticky = (E)) #label
ttk.Label(mainframe, textvariable = pts).grid(column = 4, row = 2, sticky = (W, E))
ttk.Button(mainframe, text = 'Answer', command = guess).grid(column = 3, row = 3, sticky = (W, E)) #guess button
top_entry = ttk.Entry(mainframe, width = 3, textvariable = top)
top_entry.grid(column = 3, row = 4, sticky = (E))
ttk.Button(mainframe, text = '+', command = plus).grid(column = 1, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = '-', command = minus).grid(column = 2, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = 'x', command = times).grid(column = 3, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = '/', command = divide).grid(column = 4, row = 5, sticky = (W, E))
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) #pads grid nicely
ans_entry.focus() #cursor starts in box
root.bind('<Return>', guess) #binds entry key to guess button
noone = randint(1,10)
notwo = randint (1,10)
number = noone + notwo
numb.set('What is ' + str(noone) + ' + '+ str(notwo) + '?')
right = False
sco = 0
score.set(sco)
pts.set(' points')
one = 10
op = 1
root.mainloop() #launches main code
A:
Because op is a local variable in every function.
You should add global op:
def plus(*args):
global op
op = 1
.
.
.
But be aware that this is a very sub-optimal way of doing it.
It makes much more sense to have a class, then have these functions as its methods. That way they will all have access to the op variable without it having to be a global.
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS Static web hosting - tedious to update site
I'm using AWS to host a static website. Unfortunately, it's very tedious to upload the directory to S3. Is there any way to streamline the process?
A:
Have you considered using AWSCLI - AWS Command Line Interface to interact with AWS Services & resources.
Once you install and configure the AWSCLI; to update the site all that you need to do is
aws s3 sync s3://my-website-bucket /local/dev/site
This way you can continue developing the static site locally and a simple aws s3 sync command line call would automatically look at the files which have changed since the last sync and automatically uploads to S3 without any mess.
To make the newly created object public (if not done using Bucket Policy)
aws s3 sync s3://my-website-bucket /local/dev/site --acl public-read
The best part is, the multipart upload is built in. Additionally you sync back from S3 to local (the reverse)
| {
"pile_set_name": "StackExchange"
} |
Q:
Call to undefined function curl_init() error with WAMP
I know that it's a very often asked problem, but I've tried all that I found and it still doesn't work.
I use WAMP 2.2 on Windows 7 (64 bits), and PHP 5.4.3. When I call curl_init() in localhost, I've this error message :
Call to undefined function curl_init()
What I've done :
Check php_curl in PHP extensions of WAMP
Restart WAMP many times
Remove ; before extension=php_curl.dll in my two php.ini files
Check extension_dir = "c:/wamp/bin/php/php5.4.3/ext/" in my two php.ini files
Restart WAMP many times
Change the DLL for this supposedly corrected DLL http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Restart WAMP many times
And when I call php_info(), I cannot find curl...
A:
Go to this link download *php_curl-5.4.3-VC9-x64.zip* under "Fixed curl extensions:" and replace the php_curl.dll in ext folder. This worked for me.
A:
Do as 4life suggests, but make sure you get the dll called
php_curl-5.4.3-VC9-x64.zip
do not try to use the one called
php_curl-5.4.3-nts-VC9-x64.zip
WAMP requred Thread Safe dll's and the -nts- stands for Not-Thread_Safe
| {
"pile_set_name": "StackExchange"
} |
Q:
gdb doesn't give a backtrace when a breakpoint is reached but it is specified in the commands file
I'm trying to get a backtrace when a line in the C code is reached.
I feed the command file to gdb and it works except for when it reaches the breakpoint nothing happens.
I am using Debian Testing with the gdb version 9.1-3
my code is compiled with the CFLAGS:
-Og -g3 -m32 -gdwarf-4 -fvar-tracking-assignments -w
gcc version is (Debian 9.3.0-10) 9.3.0
using other versions of dwarf doesn't seem to make any difference.
The file of commands I am including is :
set confirm off
set pagination off
set logging file gdbrogue.txt
set logging overwrite on
set logging on
set breakpoint pending on
#set trace-commands on
directory /home/me/src/github/rogue-54-for-rogomatic
symbol-file -readnow /usr/local/bin/rogue
skip file hardscroll.c
skip file hashmap.c
skip file lib_addch.c
skip file lib_addstr.c
skip file lib_clreol.c
skip file lib_erase.c
skip file lib_getch.c
skip file lib_move.c
skip file lib_mvcur.c
skip file lib_refresh.c
skip file lib_touch.c
skip file lib_tparm.c
skip file lib_tputs.c
skip file lib_winch.c
skip file lib_window.c
skip file tty_update.c
skip function look
skip function msg
skip function read
skip function unctrl
skip function __kernel_vsyscall
define my_prt_mlist
set $current = mlist
while ($current > 0)
printf "curr %p prev %p next %p\n", $current, $current->l_prev, $current->l_next
printf " t_type %c\n", $current->t_type
printf " t_pos.y %d t_pos.x %d\n", $current->t_pos.y, $current->t_pos.x
if ($current->t_dest > 0)
printf " t_dest->y %d t_dest->x %d\n", $current->t_dest->y, $current->t_dest->x
end
set $current = $current->l_next
end
end
break chase.c:32 if (level == 7)
commands
printf "player(y,x) (%d,%d)\n", player.t_pos.y, player.t_pos.x
my_prt_mlist
end
break chase.c:455 if (level == 7)
commands
printf "player(y,x) (%d,%d)\n", player.t_pos.y, player.t_pos.x
my_prt_mlist
backtrace full
end
while (level < 7)
next
end
while (level == 7)
step
end
while (level > 7)
next
end
the ouput shows the break being reached but no backtrace shows up?
roomin (cp=0x582403cc) at chase.c:445
445 roomin(coord *cp) {
452 if (((cp->x > MAXCOLS) || (cp->y > MAXLINES)) ||
454 msg("in some bizarre place (%d, %d)", unc(*cp));
Breakpoint 2, roomin (cp=0x582403cc) at chase.c:455
455 return NULL;
do_chase (th=0x5823ede0) at chase.c:142
142 door = (chat(th->t_pos.y, th->t_pos.x) == DOOR);
Any ideas what I am doing wrong here or is this a gdb/gcc bug?
I have looked for similar problems and answers, but none seem to have this specific issue.
Thanks! :)
A:
Ok, after some various trials and reading I have finally gotten at least a modified version of the above script to work. It seems that the while loops of nexts and steps override any asking of output. When I removed the loops at the end the listing the backtrace does show up.
new gdb script
set confirm off
set pagination off
set logging file gdbrogue.txt
set logging overwrite on
set logging on
set breakpoint pending on
#set trace-commands on
directory /home/me/src/github/rogue-54-for-rogomatic
symbol-file -readnow /usr/local/bin/rogue
skip file hardscroll.c
skip file hashmap.c
skip file lib_addch.c
skip file lib_addstr.c
skip file lib_clreol.c
skip file lib_erase.c
skip file lib_getch.c
skip file lib_move.c
skip file lib_mvcur.c
skip file lib_refresh.c
skip file lib_touch.c
skip file lib_tparm.c
skip file lib_tputs.c
skip file lib_winch.c
skip file lib_window.c
skip file tty_update.c
skip function look
skip function msg
skip function read
skip function unctrl
skip function __kernel_vsyscall
define my_prt_mlist
set $current = mlist
while ($current > 0)
printf "curr %p prev %p next %p\n", $current, $current->l_prev, $current->l_next
printf " t_type %c\n", $current->t_type
printf " t_pos.y %d t_pos.x %d\n", $current->t_pos.y, $current->t_pos.x
if ($current->t_dest > 0)
printf " t_dest->y %d t_dest->x %d\n", $current->t_dest->y, $current->t_dest->x
end
set $current = $current->l_next
end
end
break chase.c:453 if (level == 7)
commands
my_prt_mlist
backtrace full
end
cont
File hardscroll.c will be skipped when stepping.
File hashmap.c will be skipped when stepping.
File lib_addch.c will be skipped when stepping.
File lib_addstr.c will be skipped when stepping.
File lib_clreol.c will be skipped when stepping.
File lib_erase.c will be skipped when stepping.
File lib_getch.c will be skipped when stepping.
File lib_move.c will be skipped when stepping.
File lib_mvcur.c will be skipped when stepping.
File lib_refresh.c will be skipped when stepping.
File lib_touch.c will be skipped when stepping.
File lib_tparm.c will be skipped when stepping.
File lib_tputs.c will be skipped when stepping.
File lib_winch.c will be skipped when stepping.
File lib_window.c will be skipped when stepping.
File tty_update.c will be skipped when stepping.
Function look will be skipped when stepping.
Function msg will be skipped when stepping.
Function read will be skipped when stepping.
Function unctrl will be skipped when stepping.
Function __kernel_vsyscall will be skipped when stepping.
Breakpoint 1 at 0x5662b9a7: file chase.c, line 454.
Breakpoint 1, roomin (cp=0x577483cc) at chase.c:454
454 msg("in some bizarre place (%d, %d)", unc(*cp));
curr 0x577483c0 prev (nil) next 0x57748480
t_type Z
t_pos.y 18 t_pos.x 8
t_dest->y 10 t_dest->x 19
curr 0x57748480 prev 0x577483c0 next 0x57747dc0
t_type S
t_pos.y 8 t_pos.x 19
t_dest->y 10 t_dest->x 19
curr 0x57747dc0 prev 0x57748480 next 0x57746de0
t_type S
t_pos.y 9 t_pos.x 65
t_dest->y 10 t_dest->x 19
curr 0x57746de0 prev 0x57747dc0 next 0x57748300
t_type C
t_pos.y 10 t_pos.x 8
t_dest->y 542792192 t_dest->x 18
curr 0x57748300 prev 0x57746de0 next 0x577482a0
t_type B
t_pos.y 10 t_pos.x 47
curr 0x577482a0 prev 0x57748300 next 0x577481e0
t_type Z
t_pos.y 10 t_pos.x 30
curr 0x577481e0 prev 0x577482a0 next 0x57748120
t_type R
t_pos.y 10 t_pos.x 29
curr 0x57748120 prev 0x577481e0 next 0x577480c0
t_type O
t_pos.y 12 t_pos.x 37
curr 0x577480c0 prev 0x57748120 next 0x57748060
t_type I
t_pos.y 12 t_pos.x 39
curr 0x57748060 prev 0x577480c0 next 0x57747fa0
t_type Z
t_pos.y 11 t_pos.x 43
curr 0x57747fa0 prev 0x57748060 next 0x57746c00
t_type H
t_pos.y 10 t_pos.x 45
curr 0x57746c00 prev 0x57747fa0 next 0x57746d80
t_type I
t_pos.y 18 t_pos.x 15
curr 0x57746d80 prev 0x57746c00 next (nil)
t_type L
t_pos.y 5 t_pos.x 22
#0 roomin (cp=0x577483cc) at chase.c:454
rp = <optimized out>
fp = <optimized out>
#1 0x5662c3c1 in do_chase (th=0x57746de0) at chase.c:137
cp = <optimized out>
rer = 0x56653364 <passages+132>
ree = <optimized out>
mindist = 32767
curdist = <optimized out>
stoprun = false
door = <optimized out>
obj = <optimized out>
this = {x = 65, y = 9}
#2 0x5662c74d in move_monst (tp=0x57746de0) at chase.c:68
No locals.
#3 0x5662c7f3 in runners () at chase.c:41
tp = 0x57746de0
next = 0x57748300
wastarget = false
orig_pos = {x = 8, y = 10}
#4 0x5662df79 in do_daemons (flag=2) at daemon.c:114
dev = 0x56655e20 <d_list>
#5 0x5662de0e in command () at command.c:484
ch = <optimized out>
ntimes = -1
fp = <optimized out>
mp = <optimized out>
countch = 115 's'
direction = 75 'K'
newcount = 1 '\001'
#6 0x566311b7 in playit () at main.c:322
opts = <optimized out>
#7 0x5663162d in main (argc=<optimized out>, argv=<optimized out>, envp=<optimized out>) at main.c:188
env = <optimized out>
lowtime = <optimized out>
pid = <optimized out>
pidfilename = "roguepid.10955", '\000' <repeats 49 times>
pidfp = <optimized out>
[Inferior 1 (process 10955) detached]
| {
"pile_set_name": "StackExchange"
} |
Q:
\insertlecture in subtitle generates error but \insertlecturenumber does not
In beamer, if I use \insertlecture in a subtitle I get:
Undefined control sequence \begin{document}
but the file compiles to PDF (with XeLaTeX) correctly anyway.
But I can use \insertlecturenumber with no error.
MWE:
\documentclass[xcolor=dvipsnames]{beamer}
\let\Tiny=\tiny
\setbeamercolor{structure}{fg=OliveGreen!50!black}
\usetheme{Madrid}
\title[Title]{Long Title}
\subtitle{Lecture \insertlecturenumber : \insertlecture}
\AtBeginLecture{
\setcounter{framenumber}{0}
\begin{frame}[plain]
\titlepage
\end{frame}
}
\begin{document}
\lecture[LectShort]{LectLong}{1}
\begin{frame}
Text
\end{frame}
\end{document}
If I change:
\subtitle{Lecture \insertlecturenumber : \insertlecture}
To:
\subtitle{Lecture \insertlecturenumber}
It works with no error.
A:
I've read somewhere (probably not far away) that some beamer commands are not valid until \begin{document} has been applied. I don't know why and don't know which commands, but I've tested with OP's code and it worked:
\documentclass[xcolor=dvipsnames]{beamer}
\let\Tiny=\tiny
\setbeamercolor{structure}{fg=OliveGreen!50!black}
\usetheme{Madrid}
\AtBeginLecture{
\setcounter{framenumber}{0}
\begin{frame}[plain]
\titlepage
\end{frame}
}
\begin{document}
\title[Title]{Long Title} %<------ Moved to document body
\subtitle{Lecture \insertlecturenumber : \insertlecture} %<--- Moved to document body
\lecture[LectShort]{LectLong}{1}
\begin{frame}
Text
\end{frame}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find minimum of each curvature point?
I'm using Polynomial curve fitting to analyze my data (polyfit and polyval) and i got the curve like this. I want to find the minimum point of each curve (red dot). If i use min() i will get the point only one curve. How to get both point?
Thnak you so much
A:
Simple:
% Your polynomial coefficients
c = [-1 4 5 2 6 2 4 5];
% Find real roots of its derivative
R = roots( [numel(c)-1 : -1 : 1] .* c(1:end-1) );
R = R(imag(R)==0);
% Compute and sort function values of these extrema
if ~isempty(R)
[yExtrema, indsExtrema] = sort(polyval(c, R));
xExtrema = R(indsExtrema);
% Extract the two smallest ones
yMins = yExtrema(1:2);
xMins = xExtrema(1:2);
else
yMins = [];
xMins = [];
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Graph disconnected: cannot obtain value for tensor Tensor("conv2d_1_input:0", shape=(?, 128, 128, 1), dtype=float32)
I'm trying to implement an autoencoder which gets 3 different inputs and fuse this three image. I want to get the output of a layer in the encoder and concatenate it with a layer in the decoder but when I run it I get graph disconnected error.
here is my code:
def create_model(input_shape):
input_1 = keras.layers.Input(input_shape)
input_2 = keras.layers.Input(input_shape)
input_3 = keras.layers.Input(input_shape)
network = keras.models.Sequential([
keras.layers.Conv2D(32, (7, 7), activation=tf.nn.relu, padding='SAME',input_shape=input_shape),
keras.layers.Conv2D(32, (7, 7), activation=tf.nn.relu, padding='SAME', name = 'a'),
keras.layers.AvgPool2D((2, 2)),
keras.layers.BatchNormalization(),
keras.layers.Dropout(0.3)])
encoded_1 = network(input_1)
encoded_2 = network(input_2)
encoded_3 = network(input_3)
a = network.get_layer('a').output
x = keras.layers.Concatenate()([encoded_1,encoded_2,encoded_3])
x = keras.layers.Conv2D(32, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
x = keras.layers.UpSampling2D((2,2))(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Dropout(0.3)(x)
x = keras.layers.Concatenate()([x,a])
x = keras.layers.Conv2D(32, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
x = keras.layers.UpSampling2D((2,2))(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Dropout(0.3)(x)
decoded = keras.layers.Conv2D(3, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
final_net= keras.models.Model(inputs=[input_1,input_2,input_3],outputs=decoded)
return final_net
the error is:
Graph disconnected: cannot obtain value for tensor Tensor("conv2d_1_input:0", shape=(?, 128, 128, 1), dtype=float32) at layer "conv2d_1_input". The following previous layers were accessed without issue: ['input_6', 'input_5', 'input_4', 'sequential_1', 'sequential_1', 'sequential_1', 'concatenate', 'conv2d_2']
and it is because of concatenating [x,a]. I've tried to get the output of layer from three images like:
encoder_1.get_layer('a').output
encoder_2.get_layer('a').output
encoder_3.get_layer('a').output
but I got an error "'Tensor' object has no attribute 'output'"
A:
You need to create a subnetwork if you need to get a1, a2 and a3 outputs. And can connext x and a as follows.
def create_model(input_shape):
input_1 = keras.layers.Input(input_shape)
input_2 = keras.layers.Input(input_shape)
input_3 = keras.layers.Input(input_shape)
network = keras.models.Sequential([
keras.layers.Conv2D(32, (7, 7), activation=tf.nn.relu, padding='SAME',input_shape=input_shape),
keras.layers.Conv2D(32, (7, 7), activation=tf.nn.relu, padding='SAME', name = 'a'),
keras.layers.AvgPool2D((2, 2)),
keras.layers.BatchNormalization(),
keras.layers.Dropout(0.3)])
encoded_1 = network(input_1)
encoded_2 = network(input_2)
encoded_3 = network(input_3)
subnet = keras.models.Sequential()
for l in network.layers:
subnet.add(l)
if l.name == 'a': break
a1 = subnet(input_1)
a2 = subnet(input_2)
a3 = subnet(input_3)
x = keras.layers.Concatenate()([encoded_1,encoded_2,encoded_3])
a = keras.layers.Concatenate()([a1,a2,a3])
x = keras.layers.Conv2D(32, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
x = keras.layers.UpSampling2D((2,2))(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Dropout(0.3)(x)
x = keras.layers.Concatenate()([x,a])
x = keras.layers.Conv2D(32, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
x = keras.layers.UpSampling2D((2,2))(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Dropout(0.3)(x)
decoded = keras.layers.Conv2D(3, (3, 3), activation=tf.nn.relu, padding='SAME')(x)
final_net= keras.models.Model(inputs=[input_1,input_2,input_3],outputs=decoded)
return final_net
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I tell the differences between a 3G, 3G LTE, and 4G phone?
I apologize if this is the wrong place to ask, but it looks like the Gadget StackExchange has been closed.
I've been doing research on mobile phones and looking at different Android devices and I'm a bit confused. Often times, the device advertises 'Speeds up to X Mbps', and lists the available networks (e.g. GSM, HSPA/WCDMA). However, as 3G LTE and 4G standards have been developing, phones are being released that are capable of even greater speeds.
How can I tell if a mobile is 3G LTE or 4G? Can a 3G LTE phone upgrade to 4G? (And for that matter, is there any difference between WiMAX and 4G at this point?)
Thanks!
A:
First, WiMax and 4G are completely separate. WiMax already has real-world implementation, whereas 4G does not; 4G is still in development.
Second, 3G LTE is also completely separate from 4G. LTE also has real-world implementation.
A 3G LTE phone can only operate at 4G speeds if it has hardware capable of it. The manufacturer will undoubtedly advertise this, so it shouldn't be hard to find out. I know of no current phones that can do true 4G, which makes sense given that 4G doesn't really exist yet. The same applies for "regular" 3G phones working at LTE speeds. The Samsung Vibrant, for example, works on T-Mobile's "fake 4G" network with slightly improved speeds, but does not take full advantage of it. The Vibrant 4G, however, does take full advantage of the higher speeds.
Currently, cell providers in the US and elsewhere are referring to various 3G technologies including LTE, HSPA+, etc. as "4G" when they are not actually 4G. Examples of 4G networks in development are LTE Advanced (based on 3G LTE) and WirelessMAN-Advanced (based on WiMax).
Speed requirements for 4G service set the peak download speed at 100 Mbit/s for high mobility communication (such as from trains and cars) and 1 Gbit/s for low mobility communication (such as pedestrians and stationary users). 3G LTE and WiMax do not meet these speed requirements.
The Wikipedia page on 4G is quite informative.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find links via AJAX and bind them same action without duplicating definition
I've already saw Event binding on dynamically created elements? before asking this question but I still don't know why I cannot find a elements from AJAX and don't know how to write the code best way without need to duplicate the whole bind content
I've added the following script to my site (I'm using jQuery 1.11.1):
$().ready(function() {
$('a:not(.flags a)').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
$(document).on('click', '.internal_link', function(e) {
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'json',
data: "{}",
success: function(data) {
document.title = data.meta_title;
$('#articlecontent').fadeOut(400, function()
{
$(this).fadeOut('slow').html(data.content).fadeIn('slow');
});
// It seems that this filter doesn't work
$('#articlecontent a').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
// should I write here code to made AJAX links to have click method?
$('nav li a').removeClass('selected');
$('#nav_'+data.code).addClass('selected');
$('meta[name=keywords]').attr('keywords', data.meta_keys);
$('meta[name=description]').attr('description', data.meta_desc);
}
});
e.preventDefault(); // stop the browser from following the link
});
});
It finds links with the same hostname and add them class internal_link and then for elements with internal_link class it binds onclick action - data are loaded via AJAX.
But the problem appears when data loaded also have links. I would like also for them do the same thing - find links and add them internal_link class (I've already done it but it seems that filter for AJAX content in this case doesn't work) and bind them onclick action but I don't know how to do this. But the problem is that in fact I have to do the same as I already done in my code. Should I have add the whole bind function itself in success again or there is some way to reuse the function one again?
Question: how to achieve this result and is this AJAX secure? I don't have much experience in AJAX and don't know is it safe to load into #articlecontent any data from AJAX request.
A:
The solution was more complex.
In fact using
$('.internal_link').bind('click', function(e) {
that I was using at the beginning caused problem because when new link via AJAX are inserted into document, it seems bind doesn't work for them so I used
$(document).on('click', '.internal_link', function(e) {
But the another problem was finding links in content.
Finally working code is:
$().ready(function() {
$('a:not(.flags a)').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
$(document).on('click', '.internal_link', function(e) {
//$('.internal_link').bind('click', function(e) {
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'json',
data: "{}",
success: function(data) {
contentWrapper = $('<div />').html(data.content);
$(contentWrapper).find('a').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
document.title = data.meta_title;
$('#articlecontent').fadeOut(400, function()
{
$(this).fadeOut('slow').html(contentWrapper.html()).fadeIn('slow');
});
$('nav li a').removeClass('selected');
$('#nav_'+data.code).addClass('selected');
$('meta[name=keywords]').attr('keywords', data.meta_keys);
$('meta[name=description]').attr('description', data.meta_desc);
}
});
e.preventDefault();
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
XML not well formed (invalid token)
When I am trying to build my app using xamarin for android, an error pops up saying
Error parsing XML: not well-formed (invalid token) in line 17
I cannot seem to find where the bad structure is though. As it seem, it has something to do with the way I try to include buttons in the grid layout. I am sure it is something stupid but I just cannot find it. I included my code below:
New error:
Error parsing XML: unbound prefix in line 17
<?xml version="1.0" encoding="utf-8"?>
<GridLayout>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="@+id/gridLayout1"
android:paddingLeft="40"
android:alignmentMode="alignMargins"
android:columnCount="3"
android:rowCount="20"
<Button
android:text="Button"
android:id="@+id/button1"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button2"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button3"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button4"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button5"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button6"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button7"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button8"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button9"
android:height="100"
android:width="100" />
<Button
android:text="Button"
android:id="@+id/button10"
android:height="100"
android:width="100" />
</GridLayout>
A:
If you count the line 17 that it points out to, you reach this line
android:height="100"
Notice the "unbound prefix" or how there is no unit (dp/sp) against that value.
Please fix that and all the other length measurements to contain a unit of measurement, so that the prefix is bound:
android:height="100dp"
| {
"pile_set_name": "StackExchange"
} |
Q:
Increasing the speed of a ball in a brick breaker game
just starting a tuto and I'd like to constantly increase the speed of my ball, but damn I'm so bad at maths I can't even figure how to do, here's what I do at the moment :
// I'm giving the first force (random x) when you engage the ball, in the Start method
System.Random xForce = new System.Random();
rigidBody.AddForce(new Vector2(xForce.Next((int)-speed, (int)speed), speed);
// Later, in the Update code, I use this
rigidBody.AddForce(rigidBody.velocity* speedUp);
speed and speedUp are public variables.
What is bothering me is when I add my first force, I guess that a Vector2(speed, speed) will make a faster ball than (0, speed) right ? So I'd like a way to change the direction of my force, but with the same speed resulting for the eye of the player.
Also, when I increase my speed, I do velocity* speedUp, which means (I still guess) that a Vector2(speed, speed) will increase more than a (0, speed) right ? So I'd like to increase it in the same way no matter the direction of my ball.
I don't know if I'm being clear, I read about normalized vectors on a thread but I don't understand it that's why I'm asking your help guys, thanks in advance !
A:
Okay after a lot of research what I needed was to cap the length of the velocity vector, I got it using the Vector2.ClampMagnitude function :
System.Random xForce = new System.Random();
Vector2 direction = new Vector2(xForce.Next((int)-speed, (int)speed), speed);
Vector2 cappedDirection = (Vector2.ClampMagnitude(direction, speed));
rigidBody.AddForce(cappedDirection, ForceMode2D.Impulse);
Then in my update code, it seems that I just have to use the normalized vector. From what I read a normalized version of your vector keeps the direction with a magnitude of 1 :
rigidBody.AddForce(rigidBody.velocity.normalized * speedUp, ForceMode2D.Impulse);
From what I tested it's working, sorry guys it seems that I wasn't clear about what I asked, I just did want the same speed no matter the direction.
| {
"pile_set_name": "StackExchange"
} |
Q:
using pointers in c programming
I have a problem with pointers in c programming. I would love to get variables from the command line in Linux and than be assigning the value of the variables from command line to a non pointer variable and printing them out!
char *argv[]
this is the function that takes everything written after the name of the c program on the command line and stores it in the pointer *argv[]; Now i would love to store these pointer values in a normal variable and print it on the command line. I get segmentation fault when i execute my code.
int main ( int argc, char *argv[] )
{
char r1;
char a = *argv[1];
char b = *argv[2];
char c = *argv[3];
if ( b == '+') {
r1 = a + c;
printf("%s", r1);
}
}
A:
printf("%s", r1);
This is where your segfault is coming from.
The %s conversion specifier expects its corresponding argument to have type char * and to be the address of the first element of a zero-terminated array of char. r1 is the result of adding the values in a and c, which is not going to be a valid address.
C is not Python or Javascript - values are not magically converted between numbers and strings based on context. If you want to work with numeric values from the command line, you must first manually convert the string representations of those values to their corresponding types.
For example, if your command line is ./foo 1, then argv[1] contains the string "1" (represented as the sequence {'1', 0}). The value of *argv[1] is not 1, it's the encoding value of the character '1', which, assuming ASCII, is 49. You need to use a library function like atoi() or strtol() to convert the string "1" to the integer value 1.
Assuming your input is something like
./foo 1 + 2
and you want it to print 3, then you need to do something like the following:
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char **argv )
{
if ( argc < 4 )
{
fprintf( stderr, "USAGE: %s <val> <op> <val>\n", argv[0] );
return EXIT_FAILURE;
}
/**
* strtol() allows you to detect and reject non-numeric input,
* but I'm omitting that here for brevity.
*/
int lhs = (int) strtol( argv[1], NULL, 0 );
int rhs = (int) strtol( argv[3], NULL, 0 );
if ( *argv[2] == '+' )
{
int r1 = lhs + rhs;
printf( "%d\n", r1 );
}
return EXIT_SUCCESS;
}
Things to remember:
In C, a string is a sequence of character values including a zero-valued terminator - the string "Hello" is represented as the sequence {'H', 'e', 'l', 'l', 'o', 0 }. That trailing 0 is necessary for the sequence to be a string.
Strings are stored in arrays of character type (char for encodings like ASCII, EBCDIC, and UTF-8, wchar_t for "wide" encodings like UTF-16).
Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.
| {
"pile_set_name": "StackExchange"
} |
Q:
If a readied ranged attack action is used against the appearance of a burrowing creature, does the attack provoke an attack of opportunity?
In a recent D&D 4e session the characters readied an action, with the condition being the appearance of a burrowing creature from the ground.
Suddenly the creature burst from the ground in front of them, and the characters got to make their readied attacks, which were ranged attacks.
Does the creature get to make opportunity attacks against any triggering ranged attacks, if it appears in melee range?
A:
The characters provoke opportunity attacks as normal, however the creature who's turn it is does not get an opportunity attack against the readied action
A readied actionDDI is an immediate reaction to the triggering action, and so in this case takes places during the creature's turn.
Opportunity actions DDI cannot be taken during your own turn.
A:
If the normal usage of the ranged attack would provoke an opportunity attack then the readied action would do the same when triggered. As a D.M. I would rule that the O.A. would only happen if you use the attack. So if the burrowing creature never appears in the round, you wouldn't use the attack, there for no O.A. triggered.
As for the actual creature bursting through I would say no, they do not get an O.A. because they can not get and O.A. during their turn. The triggered action would happen as it emerges so clearing the burrow is movement.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linha com valor NULL é desconsiderada pela função SUM?
Participei do concurso do IFNMG, prova elaborada pela Fundação CEFET.
Resolvi a questão a seguir e marquei a letra C, mas o gabarito diz que o correto é a letra A.
Questão 31
Considere que a tabela NotaFiscalItem está armazenada em um
sistema gerenciador de banco de dados (SGBD) relacional, contendo os seguintes dados.
Tabela: NotaFiscalItem
Em seguida, observe o comando SQL apresentado a seguir.
Figura: Comando SQL
O resultado produzido pela execução do comando SQL, ao considerar os dados apresentados na tabela NotaFiscalItem, é
a) 28,00 7,00 48,00
b) 28,00 NULL NULL
c) 48,00 7,00 48,00
d) 48,00 0,00 55,00
e) NULL NULL NULL
A instrução "sum(qtd_item*vlr_unitario - vlr_desconto)" não soma a primeira linha por conta do "null" na coluna "vlr_desconto"? Mas isso não depende do SGBD que se está utilizando?
A:
Na documentação de funções agrupadas do MySQL:
... group functions ignore NULL values.
OU em tradução livre:
... funções agrupadas ignoram valores NULOS.
No SQL Server o NULL de colunas agrupadas invalida a expressão, então para responder com precisão essa questão seria necessário saber qual o SGBD utilizado, porém segundo esta página (a qual não posso atestar com 100% de certeza a veracidade), no padrão ANSI todas as funções agregadas, exceto COUNT vão ignorar os valores NULL ao computar seus resultados.
Schema (MySQL v5.7)
CREATE TABLE NotaFiscalItem(
nro_nota_fiscal int,
nro_item smallint,
qtd_item smallint,
vlr_unitario numeric(7, 2),
vlr_desconto numeric(7, 2)
);
INSERT INTO NotaFiscalItem VALUES
(1, 1, 2, 10.00, NULL),
(1, 2, 2, 7.50, 2.00),
(1, 3, 1, 20.00, 5.00);
Query #1
SELECT SUM(qtd_item * vlr_unitario - vlr_desconto),
SUM(vlr_desconto),
SUM(qtd_item * vlr_unitario) - SUM(vlr_desconto)
FROM NotaFiscalItem;
Resultado:
| SUM(qtd_item * vlr_unitario - vlr_desconto) | SUM(vlr_desconto) | SUM(qtd_item * vlr_unitario) - SUM(vlr_desconto) |
| ------------------------------------------- | ----------------- | ------------------------------------------------ |
| 28 | 7 | 48 |
Você pode verificar a execução no DB Fiddle.
A:
Para criar o banco de dados:
CREATE TABLE NotaFiscalItem (
nro_nota_fiscal integer,
nro_item smallint,
qtd_item smallint,
vlr_unitario numeric(7, 2),
vlr_desconto numeric(7, 2)
);
INSERT INTO NotaFiscalItem (nro_nota_fiscal, nro_item, qtd_item, vlr_unitario, vlr_desconto) VALUES (1, 1, 2, 10, NULL);
INSERT INTO NotaFiscalItem (nro_nota_fiscal, nro_item, qtd_item, vlr_unitario, vlr_desconto) VALUES (1, 2, 2, 7.50, 2.00);
INSERT INTO NotaFiscalItem (nro_nota_fiscal, nro_item, qtd_item, vlr_unitario, vlr_desconto) VALUES (1, 3, 1, 20.00, 5.00);
Transcrevendo o SELECT:
Select sum(qtd_item*vlr_unitario - vlr_desconto),
sum(vlr_desconto),
sum(qtd_item*vlr_unitario) - sum(vlr_desconto)
from NotaFiscalItem
Ao executar isso (no MySQL 5.6), veio essa resposta:
28 7 48
| {
"pile_set_name": "StackExchange"
} |
Q:
How to generate a dict from string separated by semicolon?
I am using Beautifulsoup to search for a specific number in HTML but got stuck here.
The raw data is:
<div class='box_content' hn_bookmark='true' ng_init=" bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='000000'; bookmarkable_type=''; ">
and I want to extract the "bookmarkable_id".
bsobj = BeautifulSoup(text,"html.parser")
questionID_line = bsobj.find("div",{"class":"box_content"})['ng_init']
It returns to me a string with words separated by semicolons:
bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question'
But I don't know how I can extract from here. Please help!
A:
Try this:
data = "bookmarked=false; bookmark_id=''; bookmarks_path='/en-US/bookmarks'; bookmarkable_id='793447'; bookmarkable_type='Question'"
fields = {}
for f in data.split('; '):
k , v = f.split('=')
fields[k] = v.strip("'")
print(fields)
Gives:
{'bookmarked': 'false', 'bookmark_id': '', 'bookmarks_path': '/en-US/bookmarks', 'bookmarkable_type': 'Question', 'bookmarkable_id': '793447'}
| {
"pile_set_name": "StackExchange"
} |
Q:
Disabling WebSockets compression and xor mask on the Browser side
I use "WS" library in my NodeJS project. It is possible to disable compression? I'm trying to do this on the server side
ws = new WebSocketServer({port: 8889, perMessageDeflate: false})
but it does not work
Accept-Encoding: gzip, deflate
Sec-WebSocket-Extensions: permessage-deflate
And I have no idea what can i do to disable xor mask.
A:
You have disabled per message deflate in the server, however you are seeing that the client is announcing its capability of handling it, this is normal. I mean, that HTTP headers you have pasted are from the client request (because a server does not send Accept-* headers).
To know if compression was finally selected as extension for the connection, check the Sec-WebSocket-Extensions header in the server response.
XOR masking cannot be disabled, it is required from client to browser to mitigate some possible attacks and proxies doing funny things: https://softwareengineering.stackexchange.com/questions/226343/is-masking-really-necessary-when-sending-from-websocket-client
| {
"pile_set_name": "StackExchange"
} |
Q:
how to check for file extension in discord.py
i am creating a python discord bot, and i have a function that if a message is sent in a certain channel,
it randomly sends out a response,everything works fine but i want to restrict the bot to react only when the sent message contains a png, jpg or jpeg file
heres the code(look for the bottom if str(message.channel) statement):
@client.event
async def on_message(message):
await client.process_commands(message)
if str(message.channel) not in restr:
if message.content == ".sabaton":
random.seed(time.time())
randnum = random.randint(0, len(songs) - 1)
await message.channel.send(file=discord.File(songs[randnum]))
elif message.content == ".time":
await message.channel.send(f"Current time is {time.localtime()}")
elif message.content == ".pmsh":
await message.channel.send(help)
if client.user.mention in message.content.split():
await message.channel.send('Дарова гандон(иха),мой префикс "."')
if str(message.channel) == "творчество":
random.seed(time.time())
rn3 = random.randint(1,2)
if rn3 == 1 and message.author.bot == False:
await message.channel.send("Заебись творчество")
elif rn3 == 2 and message.author.bot == False:
await message.channel.send("Фигня творчество")
A:
You can use the following conditions to restrict it:
if message.attachments[0].url.endswith('PNG') or message.attachments[0].url.endswith('JPG') or message.attachments[0].url.endswith('JPEG'):
pass
else:
pass
Change the pass according to your content.
| {
"pile_set_name": "StackExchange"
} |
Q:
19F NMR of hexafluorobromine(VII) cation
$\ce{[BrF6]+}$ is an octahedral species, and should have only one fluorine environment due to the symmetry. $\ce{Br}$ has nuclear spin $I=3/2$ and therefore is unlikely to cause splitting due to rapid interconversion between its spin up and spin down states averaging to a zero magnetic effect. Therefore I would expect one singlet in the $\ce{^19F}$ NMR spectrum.
However... the $\ce{^19F}$ NMR is actually two $1:1:1:1$ quartets (at low temperatures). Can someone help me find the flaws in my reasoning?
A:
$\ce{BrF6^+}$ does have an octahedral structure consequently all of the fluorines are equivalent. As you point out, bromine is a spin = 3/2 nucleus, therefore, it is also a quadrupolar nucleus (all nuclei with spin > 1/2 are also quadrupolar). A spin 3/2 nucleus that is coupled to another nucleus (fluorine in this case) will split the nmr signal for the other nucleus into a 1:1:1:1 quartet. In the case of bromine we don't normally see this coupling because bromine typically undergoes rapid quadrupolar relaxation (some quadrupolar nuclei do, some don't) which washes the coupling out (e.g. rapid quadrupolar relaxation effectively decouples the nuclei, that's why the protons in $\ce{CH3Br}$ are a singlet, for example). However, when the quadrupolar nucleus exists in a highly symmetric environment (octahedral, tetrahedral geometry) the electric filed gradient at the nucleus is near zero and quadrupolar relaxation becomes slow (on the nmr timescale) and coupling can often be observed in such cases.
Finally, bromine occurs naturally as a mixture of two isotopes, $\ce{^{79}Br}$ (50.7%) and $\ce{^{81}Br}$ (49.3%). Both isotopes are quadrupolar with spin = 3/2. Because of the slight difference in electronegativity of the two bromine isotopes, they will produce a slight difference in chemical shift for the fluorines bonded to them. Hence, this mixture of $\ce{^{79}BrF6^+}$ and $\ce{^{81}BrF6^+}$ will produce two 1:1:1:1 quartets in the $\ce{^{19}F}$ nmr spectrum.
| {
"pile_set_name": "StackExchange"
} |
Q:
Serilog doesn't work in Reliable Actor Services
I have two Service Fabric application. The first is an Asp.Net Core Service Fabric, the second is an Actor Service that run with timer.
Both are set up with Serilog. The Asp.Net Core work very well. no problem there, but the second service, Actor Service, I use the same configurations and same nuget packages but Serilog doesn't save any log.
Add Config
<add key="serilog:using:Seq" value="Serilog.Sinks.Seq" />
<add key="serilog:write-to:Seq.serverUrl" value="http://*****" />
<add key="serilog:write-to:Seq.apiKey" value="UfKpKLicyZI3hGe7Vc" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:RollingFile.pathFormat" value="C:\File-{Date}.txt" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />
A:
The most likely cause here is that the Serilog Logger is not being Dispose()d before the process hosting the actor shuts down (if you're setting up the static Log class instead of using a logger instance directly, this is achieved with Log.CloseAndFlush()).
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating RSA and writing to file
why do i get exception in this code:
I get output:
[*] Error creating your key
[*] Error creating your key
import os, hashlib
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
raw_key = RSA.generate(2048)
private_key = raw_key.exportKey('PEM')
try:
with open('master_private.pem', 'w+') as keyfile:
keyfile.write(private_key)
keyfile.close()
print ("[*] Successfully created your MASTER RSA private key")
except:
print ("[*] Error creating your key")
make_public = raw_key.publickey()
public_key = make_public.exportKey('PEM')
try:
with open("master_public.pem", "w+") as keyfile:
keyfile.write(public_key)
keyfile.close()
print ("[*] Successfully created your MASTER RSA public key")
except:
print ("[*] Error creating your key")
File is created successfully but it is not filled with anything. I am just starting Python.
A:
you should catch exeception and show to know the problem, but i think your problem is the write method, private_key its bytes but you must be pass a str to write method them you can try:
keyfile.write(private_key.decode())
other problem could be your permission permissions, mabe not have permission to create a file, try catching the excaption and printing to know what happen
try:
with open('master_private.pem', 'w+') as keyfile:
keyfile.write(private_key)
keyfile.close()
print ("[*] Successfully created your MASTER RSA private key")
except Exception as e:
print ("[*] Error creating your key", e)
also check your syntax why that code is not well tried
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding a directory to the system path variable through registry
I am trying to add a directory to the PATH variable in windows. This is what I am entering the command line. (Or a batch file)
@echo off
set value=%path%;%ProgramFiles%\AtomScript\
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Sessions Manager\Environment" /v Path /t REG_EXPAND_SZ /d %value% /f
And it comes up with this message
ERROR: Invalid syntax.
Type "REG ADD /?" for usage.
What am I doing wrong?
A:
You probably have to quote %value% (with double-quotes) because its expansion has embedded blanks for C:\Program Files, etc.
That would be
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Sessions Manager\Environment" /v Path /t REG_EXPAND_SZ /d "%value%" /f
You can see what the actual expansions are by turning echo on in your script:
@echo on
| {
"pile_set_name": "StackExchange"
} |
Q:
Minimum release voltage for Relay
I have an electronic socket that I am using and it uses a HLS8L-DC6V-S-C Helishun relay with a minimum release voltage of 0.3 Volts & max operating voltage 4.5 V
Datasheet - http://www.helishun.com/secure/pdt/hls8-t73.pdf
The voltage being applied to this relay in the socket is around 2.4V and the relay is not switching. But I got another unit of the same relay and it worked. Is the first relay damaged or is it due to something else?
Also, what is minimum release voltage? In this case it is 0.3 V, so what is minimum voltage I should apply to the relay to make it switch?
Thanks for your help!
A:
The datasheet linked above has the figures you quoted for a relay with a Rated Voltage of 6V.
Rated Voltage - 6V
Max Operating Voltage - 4.5V
Min Release Voltage - 0.3V
Max Applied Voltage - 7.8V
What do these all mean?
Rated Voltage 6V - this is the nominal operating voltage - the relay should operate from a voltage reasonably close to this. But power sources are rarely precise, so we need to know more information...
Max Operating Voltage - 4.5V. The relay is guaranteed to operate (switch on) at Max Operate Voltage (4.5V) or higher, so you really can't expect it to switch at 2.4V. If one does, either it is performing better than spec, or check its coil resistance to see if it's a mis-labelled 4.5V relay!
Min Release Voltage - 0.3V When you want it to switch off, reduce the voltage below Min Release Voltage - it will probably release at higher voltages but don't rely on it.
Max Applied Voltage - 7.8V Above this voltage, the coil may overheat and fail. So just keep the voltage less than Max Applied Voltage (7.8V)
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP dynamic select box using $_POST?
I was wondering if there is a way similar to the code below in order to use 'conditional' select boxes. I tried a few jquery methods, but I really got stuck since I use wordpress, and this should be a search box so it complicates things for me.
<form name="main" method="post">
<select name="currency-select">
<option value="default">Currency</option>
<option value="a">U.S Dollars (USD)</option>
<option value="b">Euros (EUR)</option>
<option value="c">British Pounds (GBP)</option>
</select>
</form>
<form name="child">
<select name="currency-child">
<?php if($_POST['currency-select'] == "a"): >
<option value="1">price</option>
<option value="2">100</option>
<option value="3">200</option>
<option value="4">300</option>
<?php endif; ?>
<?php if($_POST['currency-select'] == "b"): >
<option value="5">price</option>
<option value="6">50</option>
<option value="7">60</option>
<option value="8">70</option>
<?php endif; ?>
<?php if($_POST['currency-select'] == "c"): >
<option value="9">price</option>
<option value="10">130</option>
<option value="11">260</option>
<option value="12">390</option>
<?php endif; ?>
</select>
</form>
Update : syntax errors fixed
A:
As long as the form is not submited, PHP don't do any thing about your form, and you don't have a submit button in your html so the values won't be set in your PHP script.
I suggest you jQuery.
I wrote the code below for you, but you have to set the new attributes for your html elements and append a <div> with id="wrapper"--> <div id="wrapper">
If you didn't append wrapper, change $('#wrapper').on('change', 'form#main', function() { with$(document).on('change', 'form#main', function() {.
but in larg codes, I suggest #wrapper instead of document.
CODE:
Add this lines in the <head> of page:
//jQuery
<script type="text/javascript" src="../jQuery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#wrapper').on('change', 'form#main', function() {
if ( $('#a').is(':selected') ) {
$('option.remove').remove();
$('#child1').append('<option value="1" class="remove">price</option>');
$('#child1').append('<option value="2" class="remove">100</option>');
$('#child1').append('<option value="3" class="remove">200</option>');
$('#child1').append('<option value="4" class="remove">300</option>');
}
else if ( $('#b').is(':selected') ) {
$('option.remove').remove();
$('#child1').append('<option value="1" class="remove">price</option>');
$('#child1').append('<option value="6" class="remove">50</option>');
$('#child1').append('<option value="7" class="remove">60</option>');
$('#child1').append('<option value="8" class="remove">70</option>');
}
else if ( $('#c').is(':selected') ) {
$('option.remove').remove();
$('#child1').append('<option value="9" class="remove">price</option>');
$('#child1').append('<option value="10" class="remove">130</option>');
$('#child1').append('<option value="11" class="remove">260</option>');
$('#child1').append('<option value="12" class="remove">390</option>');
}
else if ( $('#default').is(':selected') ) {
$('option.remove').remove();//reset every thing
}
});
});
</script>
Body-html elements-
<body>
<div id="wrapper">
<form name="main" method="post" action="#" id="main">
<select name="currency-select">
<option value="default" id="default">Currency</option>
<option value="a" id="a">U.S Dollars (USD)</option>
<option value="b" id="b">Euros (EUR)</option>
<option value="c" id="c">British Pounds (GBP)</option>
</select>
</form>
<form name="child" id="child" method="post" action="#">
<select name="currency-child" id="child1">
</select>
</form>
</div>
</body>
| {
"pile_set_name": "StackExchange"
} |
Q:
Filtering a signal to have a constant exponential moving average
Problem
I wish to filter a discrete-time input signal, $x[n]$, so as the output signal's, $y[n]$, exponential moving average, $a[n+1] = a[n] + \alpha(y[n] - a[n])$, tracks around a constant reference $\mu_x$ such that $\mathbb{E}\{y[n]\} \approx \mu_x$, and also an approximately constant variance, $\text{var}\{y[n]\} \approx \sigma_x^2$, while maintaining as much information about the incoming signal as possible.
Naive Motivating Solution
1) Maintain an average of the input, $b[n+1] = b[n] + \alpha(x[n] - b[n])$ and an approximation of the signal variance, $c[n]$.
2) Define the output to be $y[n] = \frac{x[n] - b[n]}{\sqrt{c[n]}}$ which tracks a reference of 0 with unity variance.
Question
There are a number of problems with this approach which make it not very numerically robust, such as when low values of variance occur.
Is there a more intelligent way of doing this? Perhaps using a dynamic linear filter? Or high pass filter?
Other Points
The inputs can be considered independent, and are drawn from one of several dynamic distributions.
The application, if you are interested, is comparing the amplitudes of recent inputs with each other by assigning them a "reward" output. This is high reward for relatively higher input values and a low for lower lower values. However, I desire the mean reward to be an approximately constant output mean. Furthermore, there may be some medium-time dynamics in the inputs, such as decaying toward zero over time.
A:
I'll draw on my (limited) experience in audio mixing and mastering. Speech recorded through a microphone requires the same statistical properties (constant moving average and constant variance), and two straightforward processing stages ensure this.
An "exponential moving average" is another word for a 1-pole low-pass filter. This moving average can be brought close to zero by passing the signal through any high-pass filter, such as a "DC killer" or "remove subsonic rumble" filter that an audio processing package such as Audacity or Audition may provide. The stronger the high-pass characteristic, the closer the moving average will stick to the center line.
Second, you want to make the variance constant. That's a job for a level compressor. Find the RMS (square root of variance) of the signal over the next few milliseconds, and adjust the gain (amplification) of the signal over that period to bring the variance up or down to the variance you want. Audio processing packages provide this as well.
You mention numerical stability. The standard DSP literature describes ways to implement a robust high-pass filter. For instance, FIR filters tend to be very stable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Preview multiple uploaded images in symfony
I wanna preview my images with javascript before uploading it, I'm working in symfony & I use its FileType for form.. Here is my Code :
{% block content %}
{{ form_start(form, {'attr': {'id': 'image_form', 'class': 'form-horizontal container'}} ) }}
<div class="col-md-6">
<div class="form-group">
<div class="col-md-3 text-right">
{{ form_label(form.name, 'Images to upload :', {'label_attr': {'class': 'control-label'}}) }}
</div>
<div class="col-md-8">
<div id="wrapper" style="margin-top: 20px;">
{{ form_widget(form.name, {'attr': {'id' : 'fileUpload'}}) }}
</div>
{{ form_errors(form.name) }}
</div>
</div>
<div class="col-md-offset-7">
{{ form_label(form.Upload) }}
{{ form_widget(form.Upload, { 'label': 'Upload', 'attr': {'class': 'btn btn-info'}}) }}
<button type="reset" class="btn btn-default">Clear</button>
</div>
<div id="image-holder"></div>
</div>
{{ form_end(form) }}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
{% endblock %}
I, tried the same thing with a simple html input of type of file, & it was working fine, but why it doesn't in the Symfony form?
A:
It's because Symfony2 form_div_layout adding own id to every widget
{%- block widget_attributes -%}
id="{{ id }}" name="{{ full_name }}"
....
So you have to change {'id' : 'fileUpload'} to {'class' : 'fileUpload'} and $("#fileUpload").on('change' to $(".fileUpload").on('change' and check the result. Or rewrite form layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create folder and make ES File Explorer add icon of my app
I want to associate folder with my application, like WhatsApp and Viber does.
I tried to create folder
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/MyAppName");
folder.mkdir();
But that MyAppName folder is not associated with my app and ES File Explorer can't recognize "what app created the folder?", I want ES File Explorer add the icon of my app to the folder.
What is the way that some apps use for create folders and let ES File Explorer recognize the folders?
A:
All folders on Android are normal folders, ES File Explorer not uses any recognition system, people associates folders and every association is sent to ES File Explorer's database and majority of associations wins and finnaly folder is assigned with icon.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP/MySQL Insert into Database not working
I tried everything I could to fix the link of code but everything I tried gave me a white screen I know that this line of code is the only code is the only one that has a syntax error and the rest of the code is 100% fine. I am trying to insert name, email, password from a Form using $_POST and with md5 hashing for the password.
$link = connect to mySQL Database
$query="INSERT INTO 'users' ('name', 'email', 'password')
VALUES(
'".mysqli_real_escape_string($link, $_POST['name'])"',
'".mysqli_real_escape_string($link, $_POST['email'])."',
'".md5(md5($_POST['email']).$_POST['password'])."')";
A:
Why don't you make it simple instead? Something like:
$name = mysqli_real_escape_string($link, $_POST['name']);
$mail = mysqli_real_escape_string($link, $_POST['email']);
$pass = md5(md5($_POST['email']).$_POST['password']);
$query="INSERT INTO `users` (`name`, `email`, `password`) VALUES('$name','$mail', '$pass')";
| {
"pile_set_name": "StackExchange"
} |
Q:
Using find command but getting the error "paths must precede expression"
I'm trying to use the find command, but get "paths must exceed expression:name"
I've looked at the answers given here previously and added quotes around my expression, but it still is giving me the same error. My $SUB path is /home/year/sessions/subjects/MRI
find $SUB \( -name '*first*.tgz' -o name '*second*.tgz' \) -exec cp {} ./$SUBJECT1 \;
Is my path-to-file incorrect? Thanks in advance
A:
The correct command is:
find $SUB \( -name '*first*.tgz' -o -name '*second*.tgz' \) -exec cp {} ./$SUBJECT1 \;
| {
"pile_set_name": "StackExchange"
} |
Q:
pandas remove records conditionally based on records count of groups
I have a dataframe like this
import pandas as pd
import numpy as np
raw_data = {'Country':['UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK'],
'Product':['A','A','A','A','B','B','B','B','B','B','B','B','C','C','C','D','D','D','D','D','D'],
'Week': [1,2,3,4,1,2,3,4,5,6,7,8,1,2,3,1,2,3,4,5,6],
'val': [5,4,3,1,5,6,7,8,9,10,11,12,5,5,5,5,6,7,8,9,10]
}
df2 = pd.DataFrame(raw_data, columns = ['Country','Product','Week', 'val'])
print(df2)
and mapping dataframe
mapping = pd.DataFrame({'Product':['A','C'],'Product1':['B','D']}, columns = ['Product','Product1'])
and i wanted to compare products as per mapping. product A data should match with product B data.. the logic is product A number of records is 4 so product B records also should be 4 and those 4 records should be from the week number before and after form last week number of product A and including the last week number. so before 1 week of week number 4 i.e. 3rd week and after 2 weeks of week number 4 i.e 5,6 and week 4 data.
similarly product C number of records is 3 so product D records also should be 3 and those records before and after last week number of product C. so product c last week number 3 so product D records will be week number 2,3,4.
wanted data frame will be like below i wanted to remove those yellow records
A:
Define the following function selecting rows from df, for products from
the current row in mapping:
def selRows(row, df):
rows_1 = df[df.Product == row.Product]
nr_1 = rows_1.index.size
lastWk_1 = rows_1.Week.iat[-1]
rows_2 = df[df.Product.eq(row.Product1) & df.Week.ge(lastWk_1 - 1)].iloc[:nr_1]
return pd.concat([rows_1, rows_2])
Then call it the following way:
result = pd.concat([ selRows(row, grp)
for _, grp in df2.groupby(['Country'])
for _, row in mapping.iterrows() ])
The list comprehension above creates a list on DataFrames - results of
calls of selRows on:
each group of rows from df2, for consecutive countries (the outer loop),
each row from mapping (the inner loop).
Then concat concatenates all of them into a single DataFrame.
| {
"pile_set_name": "StackExchange"
} |
Q:
Format/interpretation of NOAA Elevation Data
I've downloaded the all10g data from https://www.ngdc.noaa.gov/mgg/topo/gltiles.html
and also the globedocumentationmanual.pdf from the "The Globe Project Report" link on that page.
The only relevant format info I see there is on pages#82 (the 90th page) through 85.
Are there any other relevant pages in that manual I'm overlooking, or,
better yet, some other more comprehensive description of the data format elsewhere?
As far as pages#82-85 is concerned...
Firstly, the 16-bit little-endian stuff is no problem at all.
As best I can determine, the data is organized as follows:
+--------------------------------------------+
| <-- 10800 cols for 90deg longitude --> | ^
| = 30 arcsec per col resolution | | 4800rows
| ^ | | for 40deg lat,
| and 4800/40 or 6000/50 is also | | | or 6000 for 50
| = 30 arcsec per row resolution | | v
+--------------------------------------v-----+
Is this correct? Or are we talking about some other kind of projection (e.g., mercator) of the Earth's surface onto a plane rectangular grid? And am I correct in assuming that the 10800 longitude cols, even at high latitudes, is simply a waste of space (presumably for simplicity/consistency of format)?
Also, exactly how do you stitch the tiles together at their boundaries? For example, if you wanted to represent 0-to-90 degrees in one-degree intervals, you'd need 91 points, not 90, in order to cover both the 0 and the 90 boundary points. So the page#83 "Table 3. Tile Definitions", e.g.,
A10G min lat=50 max=90 min lon=-180 max=-90
presumably isn't covering both the 50 and 90 lat min/max boundary points. So which one? Or what, exactly?
Aside: while rummaging through the open data sites for elevation data, I also came across
https://lpdaac.usgs.gov/product_search/?keyword=Elevation&view=cards&sort=title
(then choose NASADEM_HGT v001), which seems to be in this pretty-widely-used netcdf (or variants like netcdf4) format, which I hadn't heard of before. Its format seems to be somewhat discussed at, e.g., https://www.researchgate.net/post/Extracting_data_from_a_netCDF_file (and several similar), but I haven't been able to google a nice, concise, meant-for-programmers discussion. Can you point me to one? Thanks.
E d i t --------------
In response to @gerrit's reply below, I already looked over the netcdf format info, as best I could, and will maybe eventually study it more carefully. But that will clearly take lots more time (at least for me) than just dealing with the NOAA format, as discussed above.
My programming is in C, and I've already pretty much dealt with that format, as illustrated by the gif below,
created directly from the f10g file, just as a test.
The temporary test colors are
/* --- colorkey --- */
int colorkey[99] = {
0*256 + 4, /* sea surface and below is 4=blue */
100*256 + 11, /* up to 100m is 11=green */
250*256 + 5, /* up to 250m is yellow */
500*256 + 10, /* 500 maroon */
1000*256 + 2, /* 1000 red */
2500*256 + 8, /* 2500 gray */
10000*256 + 9, /* rest silver */
-1 };
The eventual goal, which really isn't that much more complicated,
is to generate a gif animation, where each successive frame shows
what happens when sea level rises, say, another foot.
In any case, a quick glance at the gif suggests that my naive interpretation of the data's lat,lon grid is, in all likelihood, generally more-or-less correct. And I probably don't need anything more accurate/precise for the intended purpose. But it would be nice (and I'd still like) to have more thorough documentation than what's cited above. Anybody have that info, or just a link to it would be great. Thanks.
E d i t # 2 ------------------
Just to illustrate the intended use, below's an animation, focusing on the Florida region of the f10g tile. Each successive frame raises sea level (actually, lowers the elevation of each land pixel, leaving ocean unchanged) by one meter. The first frame is raw data, and there are 30 frames in all, and then repeat. Of course, one meter times 30 is kind of extreme, but the NOAA data's in meters, so I don't immediately have any finer vertical resolution available. And it's just a prototype illustration (but I know where I'm buying my retirement home:).
The colortable/colorkey is also different than the first gif above,
with light_green-->dark_green for the first twelve meters, and then yellow up to 100 meters, as follows
int colorkey2[99] = {
0*256 + 0, /* sea surface and below is 0=blue */
1*256 + 1, /* 1-12 meters are shades of green */
2*256 + 2, /* " */
3*256 + 3, /* " */
4*256 + 4, /* " */
5*256 + 5, /* " */
6*256 + 6, /* " */
7*256 + 7, /* " */
8*256 + 8, /* " */
9*256 + 9, /* " */
10*256 + 10, /* " */
11*256 + 11, /* " */
12*256 + 12, /* " */
100*256 + 13, /* yellow up to 100 meters */
500*256 + 14, /* red 500 */
99999*256 + 15, /* silver higher */
A:
If you can find a NetCDF file, I would recommend using it. NetCDF is a very common self-documenting format with libraries widely available for any language that is suitable for scientific data analysis. Global elevation data is commonly used and easily available. I've used the NOAA ETOPO dataset, available as NetCDF or geotiff.
If you are using Python, I would recommend using xarray, but the lower level netCDF4 is also quite good. There is also interactive software to visualise NetCDF, such as panoply.
| {
"pile_set_name": "StackExchange"
} |
Q:
Splice array of objects by max-length
There's an array of objects like
var a =[
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}]
How to slice/splice/filter this array to make it return say first 3 items of type t1 and first 4 items of t2?
A:
You can use filter() and then slice(). Pass 0 and number of items to slice() as parameters
var a =[
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}]
function items(type,num){
return a.filter(x => x.type === type).slice(0,num);
}
console.log(items('t1',3));
console.log(items('t2',4));
A:
Use filter followed by slice:
const a = [
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}
];
const t1 = a.filter(x => x.type === 't1').slice(0, 3);
const t2 = a.filter(x => x.type === 't2').slice(0, 4);
console.log(t1);
console.log(t2);
Or use reduce:
const a = [
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}
];
const getByType = (arr, prop, num) =>
arr.reduce(([out, i], x) => (match = x.type === prop, [
match && i < num ? [...out, x] : out,
match ? i + 1 : i
]),
[[], 0])[0];
console.log(getByType(a, 't1', 3));
console.log(getByType(a, 't2', 4));
| {
"pile_set_name": "StackExchange"
} |
Q:
Random Number Generator
I need to write a program in Java to generate random numbers within the range [0,1] using the formula:
Xi = (aXi-1 + b) mod m
assuming any fixed int values of a, b & m and X0 = 0.5 (ie i=0)
How do I go about doing this?
i tried doing this but it's obviously wrong:
int a = 25173, b = 13849, m = 32768;
double X_[i];
for (int i = 1; i<100; i++)
X_[i] = (a*(X_[i]-1) + b) % m;
double X_[0] = 0.5;
double double = new double();
System.out.println [new double];
A:
Here are some hints:
int a, d, m, x;
Multiplication is * and mod is %.
update
Okay, I'll give you a little more of a hint. You only need one X, you don't need all these arrays; since you're only using integers you don't need any floats or doublts.
The important line of code will be
x = (a * x + b) % m ;
You don't need another x there because the x on the right hand side of the = is the OLD x, or xi-1; the one on the left side will be your "new" x, or xi.
Now, from there, you need to write the Java wrapper that will let you make that a method, which means writing a class.
A:
Sounds like homework... so I won't give you a solution in code.
Anyways you need a linear congruential generator.
HINT: You need to write that mathematical formula as a function.
Steps:
Make a class.
Add the required state as member to the class.
Make a function within the class. Have it take input as necessary.
Write the formula for the congruential generator in Java (look up math operations in Java).
Return the result.
My Java is rusty, so I can't say I'm sure about this but these are probably errors:
int a = 25173, b = 13849, m = 32768;
double X_[i];//You need to define a constant array or use perhaps a list, you can't use i without defining it
for (int i = 1; i<100; i++)
X_[i] = (a*(X_[i]-1) + b) % m;
double X_[0] = 0.5;
double double = new double(); //You can't name a variable double, also types like double, don't need to be newed (I think)
System.out.println [new double]; //println uses () not [], in Java I think all functions need to use (), its not implied
| {
"pile_set_name": "StackExchange"
} |
Q:
AFTER INSERT Trigger not firing
I have the below trigger code, which is working for UPDATE, but not INSERT
(we get no errors)
CREATE TRIGGER [dbo].[tr_ClientHistoryTUPEEmployee] ON [dbo].t_HR_TUPEEmployee]
AFTER INSERT, UPDATE
AS
DECLARE @Username int, @Inserted bit, @Deleted bit
SELECT @Inserted = 0, @Deleted = 0
DECLARE @fieldId int
SELECT @fieldId = FieldID FROM t_ClientHistoryFieldConstants WHERE Descn = 'TUPE Start Date'
IF @fieldId IS NULL
SET @fieldId = 9999 -- Improper value if field id not found
IF EXISTS ( SELECT TOP 1 1 INSERTED )
SET @Inserted = 1
IF EXISTS ( SELECT TOP 1 1 DELETED )
SET @Deleted = 1
--Get username
IF CHARINDEX('_',SUSER_SNAME()) = 0
BEGIN
SET @Username = CAST(SUSER_SID(SUSER_SNAME()) AS int)
END
ELSE
BEGIN
SET @Username = SUBSTRING(SUSER_SNAME(),1,CHARINDEX('_',SUSER_SNAME()) - 1)
END
IF ( @Username = 1 and SUSER_SNAME()='sa' )
SET @Username = -2
IF ( @Inserted = 1 and @Deleted = 0 ) -- only insert
BEGIN
INSERT t_ClientHistory (ClientID, FieldID, OldValue, NewValue, ChangeDate, ChangedBy)
SELECT ClientID, @fieldId , '', convert(varchar,TUPEStartDate,103) , GetDate(), @Username
FROM INSERTED
END
ELSE IF ( @Inserted = 1 and @Deleted = 1 ) -- update
BEGIN
INSERT t_ClientHistory (ClientID, FieldID, OldValue, NewValue, ChangeDate, ChangedBy)
SELECT DEL.ClientID, @fieldId , IsNull(convert(varchar,DEL.TUPEStartDate,103),'(No Start Date)'),
IsNull(convert(varchar,INS.TUPEStartDate,103),'(No Start Date)'), GetDate(), @Username
FROM DELETED DEL
INNER JOIN INSERTED INS ON ( INS.TUPEID = DEL.TUPEID )
WHERE IsNull( INS.TUPEStartDate,'1900-01-01') != IsNull( DEL.TUPEStartDate,'1900-01-01')
END
what could I have done here - it compiles ok...no errors
A:
your delete will be always true
IF EXISTS ( SELECT TOP 1 1 DELETED )
SET @Deleted = 1
so this wont work
IF ( @Inserted = 1 and @Deleted = 0 ) -- only insert
You could use return statements like below
--check for updated
if exists(select 1 from inserted ) and exists (select from deleted)
begin
return;
end
--check for inserted
if exists(select 1 from inserted)
begin
return;
end
--check for deleted
if exists(select 1 from deleted)
begin
return;
end
| {
"pile_set_name": "StackExchange"
} |
Q:
.htaccess to load specific index file when url not exist
I am updating urls of a project and have this old url:
http://www.example.com/phones/index.php
This folder phones doesnt exists anymore but I want to catch the old traffic and when someone visits this url I want .htaccess file to load file store.php which is located in the root directory
How can I do this with htaccess file so the url in the address bar to stay
http://www.example.com/phones/index.php but to load store.php file, Thank you in advance !
A:
You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteRule ^([^/]+)/index\.php$ store.php [L,NC]
| {
"pile_set_name": "StackExchange"
} |
Q:
Normal subgroup question/example
Give an example(s) of a group $G$ and $H\leq G$ (i.e., $H$ is a subgroup of $G$) where $H$ is not normal in $G$.
What about $S_3$ and $\langle(1\;2)\rangle=\{(1),(1\;2)\}$? [Since $(1\;2\;3)(1\;2)(1\;3\;2)=(2\;3)\not\in\langle(1\;2)\rangle$] Does this work? Any other ideas?
A:
It is not rare to see examples of subgroups of a given group, which are not normal subgroups. I'll give you one from finite groups.
Consider this finite group of order $8$, call it $G$. Then $2\in G$ and $H=\{0,1\}$ is a subgroup of $G$. But $H$ is not normal, since
$$2H=\{2,4\}\ne\{2,3\}=H2.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTP Response in Android - NetworkOnMainThreadException
I want to check the HTTP response of a certain URL before loading into a webview. I only want to load webview if http response code is 200. This is a workaround for intercepting http errors. I have below:
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();
But I encountered the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo
android.os.NetworkOnMainThreadException
How to fix it? Or any workaround to interept http errors in webview? Thanks
A:
android.os.NetworkOnMainThreadException occurs whenever you try to make long running tasks/process on Main UI Thread directly.
To resolve this issue, cover your webservice call inside AsyncTask. FYI, AsyncTask in android known as Painless Threading which means developer don't need to bother about Thread management. So Go and implement web API call or any long running tasks using AsyncTask, there are plenty of examples available on the web.
Update:
I only want to load webview if http response code is 200.
=> Based on your requirement, I would say include your code inside doInBackground() method and return status code value, Which you can check inside onPostExecute(). Now here you are getting status code value 200/201 then you can load WebView.
A:
class HTTPRequest extends AsyncTask<int, Void, void> {
protected int doInBackground() {
try {
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();
return code;
} catch (Exception e) {
e.printstacktrace();
}
}
protected void onPostExecute(int code) {
// TODO: check this.exception
// retrieve your 'code' here
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Как сделать анимацию вращения круга в звезде?
Как сделать анимацию вращения круга в звезде?
<svg>
<polygon fill-rule="evenodd" stroke="black"
points="150,0 121,90 198,35 102,35 179,90"/>
<circle r="15" cx="150" cy="50" fill="none" stroke="red" stroke-width="4"/>
</svg>
A:
Круг надо разбить на сегменты, иначе не будет видно вращения
stroke-dasharray="3 2"
и применить правило
transform-origin: center center;
transform-box: fill-box;
Чтобы не искать центр вращения
#circ {
stroke:crimson;
stroke-width:6;
stroke-dasharray:3 2;
transform-origin: center center;
transform-box: fill-box;
animation: rotate_disk 2s linear forwards infinite;
}
@keyframes rotate_disk {
100% {
transform: rotateZ(360deg);
}
}
<svg>
<polygon fill-rule="evenodd" stroke="black"
points="150,0 121,90 198,35 102,35 179,90"/>
<circle id="circ" r="15" cx="150" cy="50" fill="none"> </circle>
</svg>
Update
Более подробно о transform-box: fill-box с примерами в этом топике
Как заставить SVG фигуру кружиться вокруг середины блока?
A:
На вопрос уже дан ответ, этот топик для души
А вы заметили, что вместо звезды на шапке появилось сердце?
Добавлю анимацию звезды на старое место, для этого с картинки убираем иконку
Берем звезду из предыдущего ответа и с помощью команд transform="scale(0.35) translate(56 175)" уменьшаем и позиционируем звезду.
<svg height="70vh">
<image xlink:href="https://i.stack.imgur.com/cHM2F.png" width="147px" height="137px" />
<g transform="scale(0.35) translate(56 175)">
<polygon id="star" fill-rule="evenodd" stroke="none" fill="crimson"
points="150,0 121,90 198,35 102,35 179,90"/>
<circle id="circ" r="15" cx="150" cy="50" fill="none"/>
</g>
</svg>
Добавляем анимацию вращения:
#star {
transform-origin: center center;
transform-box:fill-box;
animation: rotate_star 10s linear forwards infinite;
}
@keyframes rotate_star {
100% {transform: rotateZ(360deg);}
}
<svg height="100vh">
<image xlink:href="https://i.stack.imgur.com/cHM2F.png" width="147px" height="137px" />
<g transform="scale(0.35) translate(57 176)">
<circle id="circ" r="50" cx="150" cy="45" fill="none"stroke-width="8" stroke="gold"/>
<polygon id="star" fill-rule="evenodd" stroke="none" fill="crimson"
points="150,0 121,90 198,35 102,35 179,90"/>
</g>
</svg>
A:
Второе очевидное решение - двигать stroke-dashoffset:
<svg id="test"
viewBox=-300,-300,600,600 >
<circle
stroke-dasharray="31.415 31.415"
r=100
stroke=red
stroke-width=30
fill=none >
<animate
attributeName="stroke-dashoffset"
from="0"
to="-62.83"
dur="1s"
repeatCount="indefinite" />
</circle>
</svg>
| {
"pile_set_name": "StackExchange"
} |
Q:
Char array in c & pointer addition
My instructors give me the following function. So don't blame me for ambiguity lol
void step_step_step(char *first, char *second, char *third)
{
if (third[3] == second[2] + 8 && second[2] == first[1] + 8)
printf("8: Illinois\n");
else
printf("8: ERROR\n");
}
I try to call the function in the this way:
char *p8_1 = (char*) malloc(sizeof(char)*11);
char *p8_2 = (char*) malloc(sizeof(char)*11);
char *p8_3 = (char*) malloc(sizeof(char)*11);
p8_1[9] = 'u';
p8_2[2] = p8_1[9];
p8_2[10] = p8_1[9];
p8_3[3] = p8_2[10];
step_step_step(p8_1, p8_2, p8_3);
And it keeps printing error. What am I doing wrong here? I don't understand why that doesn't work when my other solution does:
p8_2[2] = p8_1[1] + 8;
p8_3[3] = p8_2[2] + 8;
step_step_step(p8_1, p8_2, p8_3);
A:
Possible operator precedence bug:
Change to:
if ((third[3] == second[2] + 8) && (second[2] == first[1] + 8))
The wiki article on 'Order of operations' tells more about the evaluation precedence.
If you can't explain to someone in the blink of an eye, in which order some expression will be evaluated - you should use enough parentheses that it won't matter (because no order precedence to care of) or that it's instantly obvious how the clauses are separated.
EDIT:
A closer look makes me realize something fishy is going on. You're not incrementing any pointers. If you were, you would do something like if ((third[3] == second[2 + 8]) && (second[2] == first[1 + 8]))
A:
You believe the if condition should pass, since all the elements you are intending to check is initialized to 'u'. In your code, this is true for p8_3[3], p8_2[10], p8_2[2], and p8_1[9]. Then, there is the call:
step_step_step(p8_1, p8_2, p8_3);
As third takes the p8_3 value, indexing its 3rd element is fine, and it has value 'u'. However, second[2] has the value 'u', and then 8 is added to it before the == comparison. This results in the == to result in a false evaluation. The && is short-circuited, and the else case of the if is taken.
If short-circuiting had not taken place, the right side expression of the && would compare second[2] with first[1] + 8. As first[1] is uninitialized, this would have resulted in undefined behavior.
The indexing operator ptr[index] behaves like *(ptr + index). So, the expression:
second[2] + 8
translates into:
*(second + 2) + 8
which is definitely NOT the same as *(second + 2 + 8).
| {
"pile_set_name": "StackExchange"
} |
Q:
Get number of days between two entries with mongodb
I would like to get number of days between my two last entries with mongoDb grouped by number of days. Here is my table :
-------------------------------------------------
| mac address | date |
-------------------------------------------------
| aa:bb:cc:dd:ee:ff | 2016-11-15 |
| aa:bb:cc:dd:ee:ff | 2016-11-19 |
| aa:bb:cc:dd:ee:ff | 2016-11-20 |
| ff:ee:dd:cc:bb:aa | 2016-11-19 |
| ff:ee:dd:cc:bb:aa | 2016-11-28 |
| aa:aa:aa:aa:aa:aa | 2016-11-21 |
| bb:bb:bb:bb:bb:bb | 2016-11-22 |
| bb:bb:bb:bb:bb:bb | 2016-11-25 |
| cc:cc:cc:cc:cc:cc | 2016-11-20 |
| cc:cc:cc:cc:cc:cc | 2016-11-23 |
-------------------------------------------------
And here what I want to get :
-------------------------------------------------
| Number of days | count |
-------------------------------------------------
| 1 day | 1 |
| 2-7 days | 2 |
| 8-30 days | 1 |
| > 30 days | 0 |
-------------------------------------------------
Is there any possibility to do it in one request using mongodb ?
Thanks a lot.
A:
you can do it in a single query with something like this
db.date.aggregate([
{
$sort:{
date:-1
}
},
{
$group:{
_id:"$mac",
date:{
$push:"$date"
}
}
},
{
$project:{
_id:"$mac",
laps:{
$subtract:[
{
$arrayElemAt:[
"$date",
0
]
},
{
$arrayElemAt:[
"$date",
1
]
}
]
}
}
},
{
"$group":{
"_id":null,
"1_day":{
"$sum":{
"$cond":[
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24)
]
},
1,
0
]
}
},
"2_7days":{
"$sum":{
"$cond":[
{
$and:[
{
"$gt":[
"$laps",
(1000 *60 * 60 * 24*2)
]
},
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24*7)
]
},
]
},
1,
0
]
}
},
"8_30days":{
"$sum":{
"$cond":[
{
$and:[
{
"$gt":[
"$laps",
(1000 *60 * 60 * 24*8)
]
},
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24*30)
]
},
]
},
1,
0
]
}
},
"30+days":{
"$sum":{
"$cond":[
{
"$gte":[
"$laps",
(1000 *60 * 60 * 24*30)
]
},
1,
0
]
}
}
}
}
])
it will return somthing like this:
{
"_id":null,
"1_day":1,
"2_7days":3,
"8_30days":0,
"30+days":0
}
you may need to adjust bounds to better fit your needs
try it online: mongoplayground.net/p/JqolUAp2lfk
| {
"pile_set_name": "StackExchange"
} |
Q:
Return all values in a function by entering "ALL"
I have a function that lists all of a states zip codes and populations of each zip when a state abbreviation is entered (for example "KY" or "AL").
I want to return all zip codes and populations when "ALL" is entered, but I can't seem to figure out how to do that. I have tried to write in a for loop in the function to achieve this with no success.
Here is the function:
StatePop1 <- function(StAbb="KY"){
library(rjson)
St <- c('AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY')
FI <- c('01','02','04','05','06','08','09','10','12','13','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','44','45','46','47','48','49','50','51','53','54','55','56')
FIPS.table <- data.frame(St,FI,stringsAsFactors = FALSE)
StAbb <- toupper(StAbb)
fips_code <- FIPS.table[FIPS.table$St == StAbb,"FI"]
json_file <- paste("http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:",fips_code,sep="")
json_data <- fromJSON(file=json_file)
Pop <- as.data.frame(do.call("rbind", json_data), stringsAsFactors = FALSE)
names(Pop) <- c("Population","FIPS","ZipCode")
Pop <- Pop[-1,]
Pop$Population <- as.numeric(Pop$Population)
Pop$ZipCode <- as.character(Pop$ZipCode)
Pop$State <- StAbb
Pop <- Pop[,c("State","ZipCode","Population")]
return(Pop)
}
Any help would be appreciated.
A:
You just need to vectorize the input, so it can take any number of states, and if it is 'ALL' then make it the whole state list (which is also builtin as state.abb). I switched to jsonlite because it is faster, but should be the same functionality.
StatePop1 <- function(StAbb="KY"){
library(jsonlite)
if (length(StAbb) == 1 && StAbb == "ALL") StAbb <- state.abb # check for ALL
FI <- c('01','02','04','05','06','08','09','10','12','13','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','44','45','46','47','48','49','50','51','53','54','55','56')
FIPS.table <- data.frame(St=state.abb, FI, stringsAsFactors = FALSE)
StAbb <- toupper(StAbb)
fips_code <- FIPS.table[FIPS.table$St %in% StAbb,"FI"] # change to %in%
json_file <- paste("http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:",fips_code,sep="")
json_data <- lapply(json_file, jsonlite::fromJSON)
Pop <- data.frame(do.call(rbind, json_data), stringsAsFactors = FALSE) # dont need as.data.frame
names(Pop) <- c("Population","FIPS","ZipCode")
Pop <- Pop[-1,]
Pop$Population <- as.numeric(Pop$Population)
Pop$ZipCode <- as.character(Pop$ZipCode)
Pop$State <- FIPS.table[match(Pop$FIPS, FIPS.table$FI), "St"] # match states
Pop <- Pop[,c("State","ZipCode","Population")]
return(Pop)
}
## Example, now passing any of the following should work
res <- StatePop1('KY')
res <- StatePop1(c('NH','KY'))
res <- StatePop1('All')
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't include STL header files with Android NDK r5
I've got a very simplistic application:
#include <vector>
void android_main(struct android_app* state)
{
}
When I build it, I get the following error:
test/jni/main.c:14:18: error: vector:
No such file or directory
How the hell do I include STL header files? I've found stlport, and I can see the header files exist in it's directory, but how do include them?
Edit: My Application.mk file has the following line:
APP_STL := stlport_static
A:
test/jni/main.c:14:18: error: vector: No such file or directory
You're compiling with a C compiler, probably. Change the extension to *.cpp and check that a C++ compiler is invoked in the tool-chain.
A:
Read the documentation in $NDKROOT/docs. Specifically CPLUSPLUSSUPPORT.html.
The default C++ library supports only a very limited set of features. The c++ library can be changed with the APP_STL variable in your Application.mk.
| {
"pile_set_name": "StackExchange"
} |
Q:
Independence in card deck
Suppose you pick three cards, one at a time without replacement, from a
pack of 52 cards. Let Hi be the event that the ith card is hearts.
How can i prove that H1 and H2 (first being a heart, and second being a heart) are independent or not
A:
They are dependent. $H_1$ has probability $\dfrac{13}{52} = \dfrac14$ chance of being a heart. If $H_1$ then $H_2$ has probability $\dfrac{12}{51}$, else $H_2$ has probability $\dfrac{13}{51}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
dynamic nested object loop js
here is a json object i want to loop through:
{
node: 'tree',
text: 'Main Node',
childs:[
{
node: 'tree',
text: 'First Child',
childs:[{
node: 'tree',
text: 'first child child'
}....]
},{
node: 'tree',
text: '2nd Child',
childs:[{
node: 'tree',
text: '2nd child child'
}...]
}...]
}
here is the first type of json. but the problem is that json is dynamic and the child element vary depend upon different conditions. so i want to loop through the json and add leaf: true to the end of the last nested element.
here is what is want:
{
node: 'tree',
text: 'Main Node',
childs:[
{
node: 'tree',
text: 'First Child',
childs:[{
node: 'tree',
text: 'first child child',
leaf: true // i want to add this node to every last one
}]
},{
node: 'tree',
text: '2nd Child',
childs:[{
node: 'tree',
text: '2nd child child',
leaf: true
}]
}]
}
A:
You can do it with a recursive function:
let objt = {
node: 'tree',
text: 'Main Node',
childs: [
{
node: 'tree',
text: 'First Child',
childs: [{
node: 'tree',
text: 'Main Node'
}]
}, {
node: 'tree',
text: '2nd Child',
childs: [{
node: 'tree',
text: '2nd child child'
}]
}]
};
function setLeaf(objt) {
if (!objt.childs) {
objt.leaf = true;
} else {
objt.childs.forEach(child => setLeaf(child))
}
}
setLeaf(objt);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can main() and its parameters have attributes?
In standard C++, can the main function and its parameters have attributes?
For example, is this following legal?
[[noreturn]] int main() { std::abort(); }
or something like
[[nodiscard, carries_dependency]]
int main(int argc [[maybe_unused]],
char * argv [[carries_dependency, maybe_unused]] [])
{ /* ... function body omitted ... */ }
A:
Yes, it is legal. There is no wording in the C++ standard (in [basic.start.main], [dcl.attr], or elsewhere) to prevent any of this. One can even mark main() as [[deprecated]] if wanted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are braces after a for() loop statement making my code behave different?
#include<iostream>
int main()
{
int n,t,i;
cout<<"input a number"<<endl;
cin>>n;
for(i=1;i<=10;++i)
t=n*i;
cout<<t<<endl;
return 0;
}
here if I input 10 on console screen then the the output I get is just 100,
while below when I input then the I get the whole table of 10 on my console. I don't understand what stopped my above code to show the below output. Was it the return?
#include<iostream>
int main()
{
int n,t,i;
cout<<"input a number"<<endl;
cin>>n;
for(i=1;i<=10;++i)
{
t=n*i;
cout<<t<<endl;
}
return 0;
}
in this I get whole table until 10. Why is that?
A:
If you indent your code properly, you can see the the first for loop only executes one statement:
#include<iostream>
int main()
{
int n,t,i;
cout<<"input a number"<<endl;
cin>>n;
for(i=1;i<=10;++i)
t=n*i; // Executed within for loop
cout<<t<<endl;
return 0;
}
while
#include<iostream>
int main()
{
int n,t,i;
cout<<"input a number"<<endl;
cin>>n;
for(i=1;i<=10;++i)
{ // Every statement within the scope block is executed in the for loop
t=n*i;
cout<<t<<endl;
}
return 0;
}
Any conditional or loop construct (if,else,for,while,do) followed by a single statement will only execute that statement, if it's followed by a scope block ({}) all statements within the scope block will be executed.
A:
for(i=1;i<=10;++i)
t=n*i;
cout<<t<<endl;
is equivalent to:
for(i=1;i<=10;++i) {
t=n*i;
}
cout<<t<<endl;
so, the first snippet computes t = n * i 10 times, but prints only last evaluation of t due to cout<<t<<endl; that is placed outside the loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where do folds come from on a surfboard and are they bad?
Why are there sometimes folds on the top of a surfboard and where do they come from? Do they mean the board is in bad shape (or more exactly, is the board less usable or less effective)?
A:
Those are creases. They effect performance as the board will flesh (bend) more around that point. The board is much more likely to break in half at that point as well. Creases can be fixed, can be expensive for epoxy boards ($200-$300 minimum) and requires a pro to do it right. A bad fix can weaken the board further.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditionally dequeue dependency of scripts
Please note that, I'm not telling about conditionally enqueue/dequeue scripts, I'm referring to conditionally dequeue certain dependencies from an existing enqueued scripts in front end. And please note the question is not plugin-specific. I want to be enlightened about the general rules.
I used Elementor (page builder) for front end. But it's not used in all my pages. So the default lightbox feature enabled in Elementor doesn't work in those pages. That's why I added my own lightbox throughout the site, using a regex $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i"; hooked to the the_content filter. Thing's working fine, but-
Where there the Elementor gallery or lightbox is triggered, both the scripts are messing up. Two lightbox are being called, sometimes the gallery lightbox are conflicting and not working etc.
Solution 1:
I know I can conditionally filter the_content with the regex like:
if( ! is_singular('cpt') ) {
return $content = preg_replace($pattern, $replacement, $content);
}
But I actually want to keep this feature everywhere. Just want to remove the elementor lightbox where I want 'em to. So, I's trying the solution#2.
Solution 2:
What Elementor did, is something, like:
wp_enqueue_script('elementor-frontend', 'link/to/frontend.js', array('elementor-dialog', 'elementor-waypoints', 'jquery-swiper'), '1.9.7', true);
Now I want not to load the lightbox feature from Elementor, so I tried to dequeue the 'elementor-dialog':
if( is_singular('cpt') ) {
wp_dequeue_script( 'elementor-dialog' );
}
But it's not working, as the dependencies are set in 'elementor-frontend'. So I tried deregistering dialog:
if( is_singular('cpt') ) {
wp_dequeue_script( 'elementor-dialog' );
wp_deregister_script( 'elementor-dialog' );
}
It's devastating, because it dequeued the frontend.js.
How can I change the dependencies of frontend.js (handle: 'elementor-frontend') on the fly, so that I can change the dependencies to array('elementor-waypoints', 'jquery-swiper')?
A:
Solution 1:
Here we will dequeue and deregister elementor-dialog and elementor-frontend, then we will re-register elementor-frontend without the elementor-dialog dependency:
// This needs to fire after priority 5 which is where Elementor
// handles enqueueing scripts. We're ok since the default is 10.
add_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts' );
function wpse_elementor_frontend_scripts() {
// Optionally add guard clauses such as checking if( ! is_singular('cpt') )...
// Bail if Elementor is not available.
if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
return;
}
// Dequeue and deregister elementor-dialog
wp_dequeue_script( 'elementor-dialog' );
wp_deregister_script( 'elementor-dialog' );
// Dequeue and deregister elementor-frontend
wp_dequeue_script( 'elementor-frontend' );
wp_deregister_script( 'elementor-frontend' );
// Re-register elementor-frontend without the elementor-dialog dependency.
$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
wp_register_script(
'elementor-frontend',
ELEMENTOR_ASSETS_URL . 'js/frontend' . $suffix . '.js',
[
//'elementor-dialog', // <-- We removed this
'elementor-waypoints',
'jquery-swiper',
],
ELEMENTOR_VERSION,
true
);
// debugging...
//$scripts = wp_scripts();
//exit ( print_r( $scripts ) );
}
Solution 2:
In this solution, we will use wp_scripts() to modify the $wp_scripts global and then safely deregister elementor-dialog.
We will remove the elementor-dialog dependency from the elementor-frontend handle, then dequeue the elementor-dialog script which is enqueued separately by the Elementor\Frontend class.
/**
* The Elementor\Frontend class runs its register_scripts() method on
* wp_enqueue_scripts at priority 5, so we want to hook in after this has taken place.
*/
add_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts_modifier', 6 );
function wpse_elementor_frontend_scripts_modifier() {
// Customize guard clauses to bail if we don't want to run this code.
/*if ( ! is_singular( 'cpt' ) ) {
return;
}*/
// Get all scripts.
$scripts = wp_scripts();
// Bail if something went wrong.
if ( ! ( $scripts instanceof WP_Scripts ) ) {
return;
}
// Array of handles to remove.
$handles_to_remove = [
'elementor-dialog',
];
// Flag indicating if we have removed the handles.
$handles_updated = false;
// Remove desired handles from the elementor-frontend script.
foreach ( $scripts->registered as $dependency_object_id => $dependency_object ) {
if ( 'elementor-frontend' === $dependency_object_id ) {
// Bail if something went wrong.
if ( ! ( $dependency_object instanceof _WP_Dependency ) ) {
return;
}
// Bail if there are no dependencies for some reason.
if ( empty( $dependency_object->deps ) ) {
return;
}
// Do the handle removal.
foreach ( $dependency_object->deps as $dep_key => $handle ) {
if ( in_array( $handle, $handles_to_remove ) ) {
unset( $dependency_object->deps[ $dep_key ] );
$dependency_object->deps = array_values( $dependency_object->deps ); // "reindex" array
$handles_updated = true;
}
}
}
}
// If we have updated the handles, dequeue the relevant dependencies which
// were enqueued separately Elementor\Frontend.
if ( $handles_updated ) {
wp_dequeue_script( 'elementor-dialog' );
wp_deregister_script( 'elementor-dialog' );
}
}
By modifying elementor-frontend before dequeueing elementor-dialog, we will not unintentionally dequeue elementor-frontend when we dequeue elementor-dialog.
When testing this code, I inspected the $wp_scripts global (via wp_scripts()) to ensure that the desired results took effect. E.g.
$scripts = wp_scripts();
print_r( $scripts );
Relevant part of $scripts before modification:
...
[elementor-dialog] => _WP_Dependency Object
(
[handle] => elementor-dialog
[src] => http://example.com/wp-content/plugins/elementor/assets/lib/dialog/dialog.js
[deps] => Array
(
[0] => jquery-ui-position
)
[ver] => 4.1.0
[args] =>
[extra] => Array
(
[group] => 1
)
)
[elementor-frontend] => _WP_Dependency Object
(
[handle] => elementor-frontend
[src] => http://example.com/wp-content/plugins/elementor/assets/js/frontend.js
[deps] => Array
(
[0] => elementor-dialog
[1] => elementor-waypoints
[2] => jquery-swiper
)
[ver] => 1.9.7
[args] =>
[extra] => Array
(
[group] => 1
)
)
...
Relevant part of $scripts after modification:
(Note that the elementor-dialog node has now been removed.)
...
[elementor-frontend] => _WP_Dependency Object
(
[handle] => elementor-frontend
[src] => http://example.com/wp-content/plugins/elementor/assets/js/frontend.js
[deps] => Array
(
[0] => elementor-waypoints
[1] => jquery-swiper
)
[ver] => 1.9.7
[args] =>
[extra] => Array
(
[group] => 1
)
)
...
| {
"pile_set_name": "StackExchange"
} |
Q:
"Multi-facets" rope puzzle
I've done the following, can you tell me if it's correct?
If $n$ is the number of sides of the rope and $k$ is the number of rotation, e.g. $k=0$ for glue each side to itself then I think the number of colours needed is $$ \# \tt{colours} = \gcd (n,k)$$
I think I can view the rope as $G = (\mathbb Z / n \mathbb Z, +)$ and $k$ as an element of $G$. Then the order of $k$ determines how many sides we can reach. In particular, we can reach $n/\gcd(n,k)$ sides with one colour, the size of the subgroup generated by $k$ (which equals the size of the subgroup generated by $\gcd(n,k)$).
Is this right? Thanks for help!
A:
We can indeed view an $n$-faceted rope as $\mathbb Z / n \mathbb Z$ with addition. If $k$ denotes the number of sides we rotate by then the number of sides we colour with one colour is $n / \gcd (n,k)$ which is the size of the subgroup generated by $k$.
As pointed out in the comments by Thomas Andrews, we have $\mathbb Z / k \mathbb Z \cong \mathbb Z / \gcd (n,k) \mathbb Z$. If $\langle k \rangle$ denotes the subgroup generated by $k$ then $\langle k \rangle \cong \mathbb Z / (n / \gcd (n,k)) \mathbb Z$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined index in PHP post with AJAX
In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.
In my html page (saveInfo.php), I have this jquery code:
<script type="text/javascript">
var jsObj = {"user_id":5, "login":"hsm"};
var jsonobj = JSON.stringify(jsObj);
$.ajax({
type: "POST",
url: "json_handler.php",
data: { 'jsonobj':jsonobj },
success: function(){
alert('success');
window.location = "http://localhost/quranMapping/php/json_handler.php";
}
});
</script>
In the other side, I have my server-side php code (json_handler.php) like that:
<?php
$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];
$result = json_decode($input);
echo $result->user_id;
?>
But when I run that code, I get this error:
A:
You should remove this:
var jsonobj = JSON.stringify(jsObj);
and change
data: { 'jsonobj':jsonobj },
to
data: jsObj,
On the php side to decode the data just use
$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login = isset($_POST["login"])?$_POST["login"]:"";
Also there is no need to do
$input = file_get_contents('php://input');
Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which Mistake in Webview based Android Browser Application?
I'm making an Android Browser Application. Its splash image opens after loading but afterward it crashes. I haven't found what mistake I have in MainActivity.java code.
When i run the code, my default AVD tells me that my application has crashed.
MainActivity.java
package com.example.package;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity
extends Activity
{
private WebView a;
@SuppressLint({"InlinedApi"})
private BroadcastReceiver b = new a(this);
public void a()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Google");
localBuilder.setMessage("Are you sure you want to Exit?");
localBuilder.setIcon(2130837505);
localBuilder.setPositiveButton("YES", new d());
localBuilder.setNegativeButton("NO", new e());
localBuilder.show();
}
public void onBackPressed()
{
a();
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(2);
setContentView(2130903042);
this.a = ((WebView)findViewById(2131230720));
this.a.getSettings().setJavaScriptEnabled(true);
this.a.setFocusableInTouchMode(true);
this.a.getSettings().setLoadWithOverviewMode(true);
this.a.getSettings().setUseWideViewPort(true);
this.a.getSettings().setLoadsImagesAutomatically(true);
this.a.loadUrl("http://www.google.com");
this.a.setWebChromeClient(new b(this));
this.a.setDownloadListener(new c());
this.a.setWebViewClient(new f());
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
super.onCreateOptionsMenu(paramMenu);
paramMenu.add(0, 1, 0, "Home").setIcon(2130837506);
paramMenu.add(0, 2, 0, "Downloads").setIcon(2130837504);
paramMenu.add(0, 3, 0, "Back").setIcon(2130837506);
paramMenu.add(0, 4, 0, "Forward").setIcon(2130837505);
paramMenu.add(0, 5, 0, "Refresh").setIcon(2130837509);
return true;
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
{
if ((paramInt == 4) && (this.a.canGoBack()))
{
this.a.goBack();
return true;
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
super.onOptionsItemSelected(paramMenuItem);
switch (paramMenuItem.getItemId())
{
default:
return false;
case 1:
this.a.loadUrl("http://www.google.com");
return true;
case 3:
this.a.goBack();
return true;
case 5:
this.a.reload();
return true;
case 4:
this.a.goForward();
return true;
}
}
protected void onPause()
{
super.onPause();
unregisterReceiver(this.b);
}
@SuppressLint({"InlinedApi"})
protected void onResume()
{
IntentFilter localIntentFilter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
registerReceiver(this.b, localIntentFilter);
super.onResume();
}
}
a.java
package com.example.package;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.widget.Toast;
class a
extends BroadcastReceiver
{
a(MainActivity paramMainActivity) {}
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, paramContext.getResources().getString(2131034114), 0).show();
}
public static void finish() {
// TODO Auto-generated method stub
}
public static void startActivity(Intent localIntent) {
// TODO Auto-generated method stub
}
}
g.java
package com.example.package;
import android.app.Activity;
import android.content.Intent;
import java.util.TimerTask;
class g
extends TimerTask
{
private Object a;
g(splash paramsplash) {}
public void run()
{
((Activity) this.a).finish();
Intent localIntent = new Intent();
((Activity) this.a).startActivity(localIntent);
}
}
A:
Your problem is almost certainly the issue:
this.a = ((WebView)findViewById(2131230720));
The number "2131230720" is a static reference int to resources, in this case a layout view in your Activity. That number comes from R.java which is created when you "build" your project. Each time you perform a build, it will assign an integer to layout objects, strings, etc. that you define in XML in your res folder.
Using the integer value might work for a while (or is present in source code), but then you change your layouts (or other R objects like strings) or rebuild on a different machine, Android library, etc. and it doesn't work anymore;
That line should look like this:
this.a = ((WebView)findViewById(R.id.my_webview_layout_id));
where "my_webview_layout_id" is from your layout XML file. You should find the "id" of the XML defined object in an XML file in res/layout Use that @+id reference. That will keep track of changes to that static reference.
Then when you build or rebuild your Android app, it will create the R.java file with all of the appropriate references.
| {
"pile_set_name": "StackExchange"
} |
Q:
Permission to activate an Iteration in TFS 2013
I want to give permission for a specific user in my TFS project to do the following.
Create Iterations
Edit the Iterations
Activate the Iteration (In simpler words, 'tick' the Iterations so that they can be seen by others in the team)
MSDN says that
To create or modify areas or iterations, you must either be a member of the Project Administrators group, or your Create and order child nodes, Delete this node, and Edit this node permissions must be set to Allow for the area or iteration node that you want to modify. MSDN
I do not want to give Project Administrator permissions to this specific user.
Hence I gave the following permissions to him in the Parent Iteration.
permissions - screenshot
When logged in as the specific user, TFS says that
You do not have sufficient permissions to configure iterations for this team. You must either be a team administrator or a project administrator.
However, the User can do the following.
Create Child Nodes
Edit the Start/End Dates of existing/new iterations
My question is:
Is there any other way to give a user the permission to 'tick' an iteration without giving him 'Edit collection level permission' or 'project admin permission'
A:
You can create a new TFS group under your team project. Then, grant that group "Edit Project Level Information" permissions. This will allow the user to check the tick box to make the iteration show up in the backlog task board.
What I did was create a "[TEAM PROJECT]\Project Managers" TFS group, I granted that group all permissions on the root node of both the Areas and Iterations. And I also granted that group "Edit Project Level Information." My user was then able to manage areas and iterations - including the "ticking" to activate the iteration.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure Parsley remote validator to handle my API response
I have tried all the possible approaches found, but I am struggled to get the default remote validator working.
I'm just trying to achieve to check if the mail for a registration page of a user is duplicated. Thus, I declare the input as follows:
<input type="email" name="email" required
placeholder="Dirección de correo"
data-parsley-trim-value="true"
data-parsley-trigger="change"
data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp" }'
data-parsley-remote="checkmail.php"
data-parsley-remote-message="Mail duplicated"
class="form-control">
The checkmail.php code is:
require_once("../functions/mysqli_connect.php");
if (empty($_POST['email'])){
$errors[] = 'No llega el parametro de mail';
}else {
$email = trim($_POST['email']);
$q = ("select * from register where email ='" . $email . "'");
$r = mysqli_query($dbc, $q);
if ($r) {
if (($r->num_rows) > 0) {
echo json_encode(404);
} else {
echo json_encode(200);
}
}
}
I've tried multiple combinations for echo response, I've read all the messages on stackoverflow but couldn't find the solution because I've always get the message :
This value seems to be invalid.
As I read on another's user question I've tried:
data-parsley-remote-message="Mail duplicated"
but with no luck either.
The PHP code works as expected, so no errors there, but Parsley always treats the json_encode responses as it is was an error.
Any help would be vey appreciated.
Thanks in advance.
A:
Parsley remote validator looks for HTTP response code not for the body content itself. In your example you're returning json data with probably always HTTP 200 status code.
Maybe look here http://php.net/manual/en/function.http-response-code.php or here Set Response Status Code to see how you could change the response status code.
Best
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an element is best for "Drag and drop" web applications?
I'm building my own "Drag and Drop" web application.
I'm loading data from MySQL and create a HTML element with it.
So I have ID, length, height and so on.
Later I'm going to drag these "blocks" into a square.
Now, which HTML element is best for this?
<div>, <canvas>, <img>?
An example will be with a <div>:
<div style="width: 100px; height:20px; background-color: grey;"></div>
Which element is best suited for being dragged and dropped?
I'm going to save positions for dragged elements, for loading it later..
Specifically, is there a technical reason to prefer one element over any other?
A:
There isn't a best suited element for this. Generally I'll use divs, but it depends on what you want to do. If you wanna do it the HTML5 way, simply add a draggable="true" attribute. If you're open to using libraries, jQuery UI has a very good drag and drop implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How are entities with an identity and a mutable persistent state modelled in a functional programming language?
In an answer to this question (written by Pete) there are some considerations about OOP versus FP. In particular, it is suggested that FP languages are not very suitable for modelling (persistent) objects that have an identity and a mutable state.
I was wondering if this is true or, in other words, how one would model objects in a functional programming language. From my basic knowledge of Haskell I thought that one could use monads in some way, but I really do not know enough on this topic to come up with a clear answer.
So, how are entities with an identity and a mutable persistent state normally modelled in a functional language?
Here are some further details to clarify what I have in mind. Take a typical Java application in which I can (1) read a record from a database table into a Java object, (2) modify the object in different ways, (3) save the modified object to the database.
How would this be implemented e.g. in Haskell? I would initially read the record into a record value (defined by a data definition), perform different transformations by applying functions to this initial value (each intermediate value is a new, modified copy of the original record) and then write the final record value to the database.
Is this all there is to it? How can I ensure that at each moment in time only one copy of the record is valid / accessible? One does not want to have different immutable values representing different snapshots of the same object to be accessible at the same time.
A:
The usual way to go about state changes in a pure language like Haskell is to model them as functions that take the old state and return a modified version. Even for complex objects, this is efficient because of Haskell's lazy evaluation strategy - even though you are syntactically creating a new object, it is not copied in its entirety; each field is evaluated only when it is needed.
If you have more than a few local state changes, things can become clumsy, which is where monads come in. The monad paradigm can be used to encapsulate a state and its changes; the textbook example is the State monad that comes with a standard Haskell install. Note, however, that a monad is nothing special: it's just a data type that exposes two methods (>>= and return), and meets a few expectations (the 'monad laws'). Under the hood, the State monad does exactly the same: take the old state and return a modified state; only the syntax is nicer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a .NET web application run with only dlls and configs?
I remember being told that you can run a .NET web application with only it's DLLs and without the various aspx, ascx asmx files (obviously any html and js files are still required).
Is it possible to publish a .NET web application by copying only the dlls, configs and client side resources?
A:
After a little bit of investigation I don't believe it's possible.
I uploaded just the DLLs (in a bin folder) and the web.config and it didn't work. I added the remaining files and it did.
| {
"pile_set_name": "StackExchange"
} |
Q:
Populate "Lookup Table" with random values
I have three tables, A B and C. For every entry in A x B (where x is a Cartesian product, or cross join) there is an entry in C.
In other words, the table for C might look like this, if there were 2 entries for A and 3 for B:
| A_ID | B_ID | C_Val |
----------------------|
| 1 | 1 | 100 |
| 1 | 2 | 56 |
| 1 | 3 | 19 |
| 2 | 1 | 67 |
| 2 | 2 | 0 |
| 2 | 3 | 99 |
Thus, for any combination of A and B, there's a value to be looked up in C. I hope this all makes sense.
In practice, the size of A x B may be relatively small for a database, but far too large to populate by hand for testing data. Thus, I would like to randomlly populate C's table for whatever data may already be in A and B.
My knowledge of SQL is fairly basic. What I've determined I can do so far is get that cartesian product as an inner query, like so:
(SELECT B.B_ID, C.C_ID
FROM B CROSS JOIN C)
Then I want to say something like follows:
INSERT INTO A(B_ID, C_ID, A_Val) VALUES
(SELECT B.B_ID, C.C_ID, FLOOR(RAND() * 100)
FROM B CROSS JOIN C)
Not surprisingly, this doesn't work. I don't think its valid syntax to genereate a column on the fly like that, nor to try to insert a whole table as values.
How can I basically convert this normal programming pseudocode to proper SQL?
foreach(A_ID in A){
foreach(B_ID in B){
C.insert(A_ID, B_ID, Rand(100));
}
}
A:
The syntax problem is because:
INSERT INTO A(B_ID, C_ID, A_Val) VALUES
(SELECT B.B_ID, C.C_ID, FLOOR(RAND() * 100)
FROM B CROSS JOIN C)
Should be:
INSERT INTO A(B_ID, C_ID, A_Val)
SELECT B.B_ID, C.C_ID, FLOOR(RAND() * 100)
FROM B CROSS JOIN C;
(You don't use VALUES with INSERT/SELECT.)
However you will still have the problem that RAND() is not evaluated for every row; it will have the same value for every row. Assuming the combination of B_ID and C_ID is unique, you can use something like this:
INSERT INTO A(B_ID, C_ID, A_Val)
SELECT B.B_ID, C.C_ID, ABS(CHEKSUM(RAND(B.B_ID*C.C_ID))) % 100
FROM B CROSS JOIN C;
| {
"pile_set_name": "StackExchange"
} |