id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23528200
|
How is that possible?
A: The factorial operation is only defined for non-negative integers. The Java way to handle this would be to simply throw an IllegalArgumentException on a negative input:
public static int factorial (int n) {
if (n < 0) {
throw new IllegalArgumentException ("n must be non-negative");
}
if (n == 0) {
return 1;
}
return n * factorial (n - 1);
}
A: You may use the following code snippet before you call the recursive method -
if(inputNumber<0){
break;
}else{
findFactorial(inputNumber);//recursive method call to find factorial
}
A: If find negative number return function
if(n < 0) {
return;
} else {
findFactorial(n);//recursive method call
}
| |
doc_23528201
|
It's inconveniencing my workflow, and unfortunately I don't see any extensions in the marketplace for exactly this. I am quite happy to find out how to make extensions (specifically Beautify and Emmet) run on other weird file formats.
A: You can add this on your settings.json.
"emmet.syntaxProfiles": {
"smarty": "html"
},
"emmet.triggerExpansionOnTab": true,
"beautify.language": {
"html": [
"smarty"
]
}
A: In your settings.json, add for emmet :
"emmet.includeLanguages": {
"smarty": "html"
},
| |
doc_23528202
|
Here are some commands:
kubectl get events
60m Normal SuccessfulCreate replicaset/frontend-r0ktmgn9-dcc95dfd8 Created pod: frontend-r0ktmgn9-dcc95dfd8-8wn9j
36m Normal ScalingReplicaSet deployment/frontend-r0ktmgn9 Scaled down replica set frontend-r0ktmgn9-6d57cb8698 to 0
36m Normal SuccessfulDelete replicaset/frontend-r0ktmgn9-6d57cb8698 Deleted pod: frontend-r0ktmgn9-6d57cb8698-q52h8
36m Normal ScalingReplicaSet deployment/frontend-r0ktmgn9 Scaled up replica set frontend-r0ktmgn9-58cd8f4c79 to 1
36m Normal SuccessfulCreate replicaset/frontend-r0ktmgn9-58cd8f4c79 Created pod: frontend-r0ktmgn9-58cd8f4c79-fn5q4
kubectl describe po/frontend-r0ktmgn9-58cd8f4c79-fn5q4 (some parts redacted)
Name: frontend-r0ktmgn9-58cd8f4c79-fn5q4
Namespace: default
Priority: 0
Node: <none>
Labels: app=frontend
pod-template-hash=58cd8f4c79
Annotations: kubectl.kubernetes.io/restartedAt: 2021-05-14T20:02:11-05:00
Status: Pending
IP:
IPs: <none>
Controlled By: ReplicaSet/frontend-r0ktmgn9-58cd8f4c79
Containers:
frontend:
Image: [Redacted]
Port: 3000/TCP
Host Port: 0/TCP
Environment: [Redacted]
Mounts: <none>
Volumes: <none>
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events: <none>
I use loft virtual clusters, so the above commands were run in a virtual cluster context, where this pod's deployment is the only resource. When run from the main cluster itself:
kubectl describe nodes
Name: autoscale-pool-01-8bwo1
Roles: <none>
Labels: beta.kubernetes.io/arch=amd64
beta.kubernetes.io/instance-type=g-8vcpu-32gb
beta.kubernetes.io/os=linux
doks.digitalocean.com/node-id=d7c71f70-35bd-4854-9527-28f56adfb4c4
doks.digitalocean.com/node-pool=autoscale-pool-01
doks.digitalocean.com/node-pool-id=c31388cc-29c8-4fb9-9c52-c309dba972d3
doks.digitalocean.com/version=1.20.2-do.0
failure-domain.beta.kubernetes.io/region=nyc1
kubernetes.io/arch=amd64
kubernetes.io/hostname=autoscale-pool-01-8bwo1
kubernetes.io/os=linux
node.kubernetes.io/instance-type=g-8vcpu-32gb
region=nyc1
topology.kubernetes.io/region=nyc1
wireguard_capable=false
Annotations: alpha.kubernetes.io/provided-node-ip: 10.116.0.3
csi.volume.kubernetes.io/nodeid: {"dobs.csi.digitalocean.com":"246129007"}
io.cilium.network.ipv4-cilium-host: 10.244.0.171
io.cilium.network.ipv4-health-ip: 10.244.0.198
io.cilium.network.ipv4-pod-cidr: 10.244.0.128/25
node.alpha.kubernetes.io/ttl: 0
volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp: Fri, 14 May 2021 19:56:44 -0500
Taints: <none>
Unschedulable: false
Lease:
HolderIdentity: autoscale-pool-01-8bwo1
AcquireTime: <unset>
RenewTime: Fri, 14 May 2021 21:33:44 -0500
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
NetworkUnavailable False Fri, 14 May 2021 19:57:01 -0500 Fri, 14 May 2021 19:57:01 -0500 CiliumIsUp Cilium is running on this node
MemoryPressure False Fri, 14 May 2021 21:30:33 -0500 Fri, 14 May 2021 19:56:44 -0500 KubeletHasSufficientMemory kubelet has sufficient memory available
DiskPressure False Fri, 14 May 2021 21:30:33 -0500 Fri, 14 May 2021 19:56:44 -0500 KubeletHasNoDiskPressure kubelet has no disk pressure
PIDPressure False Fri, 14 May 2021 21:30:33 -0500 Fri, 14 May 2021 19:56:44 -0500 KubeletHasSufficientPID kubelet has sufficient PID available
Ready True Fri, 14 May 2021 21:30:33 -0500 Fri, 14 May 2021 19:57:04 -0500 KubeletReady kubelet is posting ready status. AppArmor enabled
Addresses:
Hostname: autoscale-pool-01-8bwo1
InternalIP: 10.116.0.3
ExternalIP: 134.122.31.92
Capacity:
cpu: 8
ephemeral-storage: 103176100Ki
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 32941864Ki
pods: 110
Allocatable:
cpu: 8
ephemeral-storage: 95087093603
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 29222Mi
pods: 110
System Info:
Machine ID: a98e294e721847469503cd531b9bc88e
System UUID: a98e294e-7218-4746-9503-cd531b9bc88e
Boot ID: a16de75d-7532-441d-885a-de90fb2cb286
Kernel Version: 4.19.0-11-amd64
OS Image: Debian GNU/Linux 10 (buster)
Operating System: linux
Architecture: amd64
Container Runtime Version: containerd://1.4.3
Kubelet Version: v1.20.2
Kube-Proxy Version: v1.20.2
ProviderID: digitalocean://246129007
Non-terminated Pods: (28 in total) [Redacted]
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 2727m (34%) 3202m (40%)
memory 9288341376 (30%) 3680Mi (12%)
ephemeral-storage 0 (0%) 0 (0%)
hugepages-1Gi 0 (0%) 0 (0%)
hugepages-2Mi 0 (0%) 0 (0%)
Events: <none>
Name: autoscale-pool-02-8mly8
Roles: <none>
Labels: beta.kubernetes.io/arch=amd64
beta.kubernetes.io/instance-type=m-2vcpu-16gb
beta.kubernetes.io/os=linux
doks.digitalocean.com/node-id=eb0f7d72-d183-4953-af0c-36a88bc64921
doks.digitalocean.com/node-pool=autoscale-pool-02
doks.digitalocean.com/node-pool-id=18a37926-d208-4ab9-b17d-b3f9acb3ce0f
doks.digitalocean.com/version=1.20.2-do.0
failure-domain.beta.kubernetes.io/region=nyc1
kubernetes.io/arch=amd64
kubernetes.io/hostname=autoscale-pool-02-8mly8
kubernetes.io/os=linux
node.kubernetes.io/instance-type=m-2vcpu-16gb
region=nyc1
topology.kubernetes.io/region=nyc1
wireguard_capable=true
Annotations: alpha.kubernetes.io/provided-node-ip: 10.116.0.12
csi.volume.kubernetes.io/nodeid: {"dobs.csi.digitalocean.com":"237830322"}
io.cilium.network.ipv4-cilium-host: 10.244.3.115
io.cilium.network.ipv4-health-ip: 10.244.3.96
io.cilium.network.ipv4-pod-cidr: 10.244.3.0/25
node.alpha.kubernetes.io/ttl: 0
volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp: Sat, 20 Mar 2021 18:14:37 -0500
Taints: <none>
Unschedulable: false
Lease:
HolderIdentity: autoscale-pool-02-8mly8
AcquireTime: <unset>
RenewTime: Fri, 14 May 2021 21:33:44 -0500
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
NetworkUnavailable False Tue, 06 Apr 2021 16:24:45 -0500 Tue, 06 Apr 2021 16:24:45 -0500 CiliumIsUp Cilium is running on this node
MemoryPressure False Fri, 14 May 2021 21:33:35 -0500 Tue, 13 Apr 2021 18:40:21 -0500 KubeletHasSufficientMemory kubelet has sufficient memory available
DiskPressure False Fri, 14 May 2021 21:33:35 -0500 Wed, 05 May 2021 15:16:08 -0500 KubeletHasNoDiskPressure kubelet has no disk pressure
PIDPressure False Fri, 14 May 2021 21:33:35 -0500 Tue, 06 Apr 2021 16:24:40 -0500 KubeletHasSufficientPID kubelet has sufficient PID available
Ready True Fri, 14 May 2021 21:33:35 -0500 Tue, 06 Apr 2021 16:24:49 -0500 KubeletReady kubelet is posting ready status. AppArmor enabled
Addresses:
Hostname: autoscale-pool-02-8mly8
InternalIP: 10.116.0.12
ExternalIP: 157.230.208.24
Capacity:
cpu: 2
ephemeral-storage: 51570124Ki
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 16427892Ki
pods: 110
Allocatable:
cpu: 2
ephemeral-storage: 47527026200
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 13862Mi
pods: 110
System Info:
Machine ID: 7c8d577266284fa09f84afe03296abe8
System UUID: cf5f4cc0-17a8-4fae-b1ab-e0488675ae06
Boot ID: 6698c614-76a0-484c-bb23-11d540e0e6f3
Kernel Version: 4.19.0-16-amd64
OS Image: Debian GNU/Linux 10 (buster)
Operating System: linux
Architecture: amd64
Container Runtime Version: containerd://1.4.4
Kubelet Version: v1.20.5
Kube-Proxy Version: v1.20.5
ProviderID: digitalocean://237830322
Non-terminated Pods: (73 in total) [Redacted]
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 1202m (60%) 202m (10%)
memory 2135Mi (15%) 5170Mi (37%)
ephemeral-storage 0 (0%) 0 (0%)
hugepages-1Gi 0 (0%) 0 (0%)
hugepages-2Mi 0 (0%) 0 (0%)
Events: <none>
| |
doc_23528203
|
Here is an implementation of an the inner loop that bubbles the value to the top:
def pass(xs:List[Int]):List[Int] = xs match {
case Nil => Nil
case x::Nil => x::Nil
case l::r::xs if(l>r) => r::pass(l::xs)
case l::r::xs => l::pass(r::xs)
}
My issue is with case Nil => Nil. I understand that I need this is because I could apply Nil to this function. Is there a way to ensure that Nil can't be provided as an argument in a manner that would satisfy the compiler so I can eliminate this case?
A: List has two subtypes, Nil and ::, so :: represents a list that has at least one element.
def pass(xs: ::[Int]):List[Int] = xs match {
case x::Nil => x::Nil
case l::r::xs if(l>r) => r::pass(new ::(l,xs))
case l::r::xs => l::pass(new ::(r, xs))
}
A: This would roughly correspond to a refinement of the original type, where you would write a type whose members were a subset of the initial type. You would then show that, for every input x to your function, that x was non Nil. As this requires a good amount of proof (you can implement this in Coq with dependent types using a subset type), the better thing to do in this situation might be to introduce a new type, which was a list having no Nil constructor, only a constructor for cons and a single element.
EDIT: As Scala allows you to use subtyping over the List type to enforce this, you can prove it in the type system decidably using that subtype. This is still a proof, in the sense that any type checking corresponds to a proof that the program does indeed inhabit some type, it's just something the compiler can prove completely.
A: In that case you can simply play with the case clauses order:
def pass(xs:List[Int]):List[Int] = xs match {
case l::r::xs if(l>r) => r::pass(l::xs)
case l::r::xs => l::pass(r::xs)
case xs => xs
}
The first two clauses will only match lists with one or more elements. The last clause will match elsewhere.
| |
doc_23528204
|
Now, I want to write a separate backend in Django Rest framework in order for the users to be able upload the house pictures for their houses.
Will it be possible to do that? To be more specific, my thought is to connect to that SQLAlchemy database and whenever the user types a url (.../user34/house55/) my code triggers my model which retrieves the Token and extracts the user ID and house ID and gets ready for the POST from that specific user. So when the user uploads the image, my backend simply saves a new field in SQLAlchemy. Or would that be impossible as the user backend does not have a field for that?
| |
doc_23528205
|
Since the referential integrity of my legacy database is kinda crappy, I'd like to know if there's a workaround or if there's an alternative mapping I can use.
Example:
//no query when loading the entity
References<User>(x => x.User, "UserId").LazyLoad().Nullable();
//performs a hundred queries when I load my entities
References<User>(x => x.User, "UserId").LazyLoad().Nullable().NotFound.Ignore();
A: This is a known problem unfortunately, there is an issue in NHibernate JIRA (https://nhibernate.jira.com/browse/NH-1001)
There is a workaround though but it isn't pretty. In the Entity you need to do something along the lines of this:
class Entity {
private int? _userId;
private User user;
public User User
{
get {
if (_userId == null)
return null;
return user;
};
set {
if (value == null)
_userId = null;
else
_userId = value.UserId;
_user = value;
};
}
}
And in the mapping you would map the reference as normal but without the not-found = ignore setting but you also map the foreign key field:
References<User>(Reveal.Membmer<User>("_user"), "UserId").LazyLoad();
Map(Reveal.Membmer<int?>("_userId")).Nullable().Not.Update().Not.Insert(); // Suppress updates and inserts so that they don't conflict with the mapping of User.
Basically you let NHibernate operate as normal on the _user field and then use the _userId field to manually do the null check. This way you avoid the N+1 selects problem. The downside is that it complicates the Entity and will make queries harder to write. If you want to be able to use the User-property in a LINQ query for example you will have to expose the internal _user field and use that instead.
| |
doc_23528206
|
A: If you want to share properties between projects use property sheets (.props files). In those you can set the include directories and library locations (and additional properties if necessary).
If you want to use the libraries in another project you only have to add the property sheet to it.
You can find a detailed guide on project properties (including property sheets) in the Microsoft documentation.
A: e.g. templates are the best you can do (until otherwise corrected):
https://www.wikihow.com/Set-Up-an-OpenGL-FreeGLUT-GLEW-Template-Project-in-Visual-Studio-2017
| |
doc_23528207
|
Question: is there a way to dynamically have the pivot update its target range to the active worksheet and not the last sheet you copied it from?
my goal is to get something like
=activesheet!$a$1:$b:$2
why I'm asking this question: I never really liked pivot tables, always thought they were a waste of time, but since my boss likes them and doesn't like vba, I gotta conform and use the dumb pivots.
really not sure what kind of other materials or proof of research you guys want with this question, but i did try to search on my own and found nothing. if theres anything else you guys want just ask. Thx
A: Can't comment, so please don't complain for putting it in here ;-)
There is something which could ease the pain when updating the data source after pasting the pivot table into a new workbook:
If the Pivot Table does not refer to a range but to an Excel table instead (cf. Ribbon -> Insert-Tab -> Table), then you will just need to remove the file name in the data source without updating the range (because there is no range, just the table name)
| |
doc_23528208
|
<a4j:commandButton id="editAlarm" immediate="false" execute="@this" actionListener="#{cfsBean.updateCfsGroupFeature(itemsComp,tableIndex.index)}"
action="#{addFeaturePopUpBean.updateCfsGroupFeature(itemsComp,tableIndex.index)}" >
and Bean have this code
public String updateCfsGroupFeature(ActionEvent event,CompositeCharGroupVo value, Integer row) {
}
But i am getting
javax.el.MethodNotFoundException' when invoking action listener
'#{cfsBean.updateCfsGroupFeature(itemsComp,tableIndex.index)}' for
component 'editAlarm'
Now Differences between action and actionListener @Baluc mentioned we can pass argument in actionListner as well
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
| |
doc_23528209
|
HTML
<div id="yourcontroller" ng-app="" data-ng-controller="mainController" data-module="yourcontroller">
</div>
And inside my run I'm trying to call the controller function like below
angular.module('modulename', [])
.controller('myCtrl', ['$scope', '$window', function ($scope, $window ) {
$scope.yourControllerMethod = function(){
console.log("inside yourControllerMethod");
};
}])
.run(function($rootScope, $log, $window) {
var scope = angular.element(document.getElementById('yourcontroller')).scope();
scope.yourControllerMethod();
});
But, I'm getting Uncaught TypeError: Cannot read property 'yourControllerMethod' of undefined
Can someone answer where I'm missing?
A: You need to add the module in the ng-app attribute and the controller is myCtrl not yourcontroller.
<div id="myCtrl" ng-app="modulename" data-ng-controller="myCtrl" data-module="yourcontroller">
</div>
I am also not sure if the app has bootstraped by the time the run is called.
A: Why would you need the scope in order to call the method? I did something similar from plain JavaScript code. But things to mention: I linked ng-app to the body, attached a handler on a ready event, didn't use scope, but controller() function directly. Hope this helps:
angular.element(document).ready(function () {
var input = document.getElementById('myInputId');
input.onkeypress = function (event) {
if (event) {
if (event.keyCode === 13) {
angular.element(document.body).controller().aMethodFromTheController();
}
}
}
});
| |
doc_23528210
|
the base table:
ID COLUMN_NAME VALUE ROW_INDEX
017QZ Course Completion Confirmed? Yes 1
017QZ Course Completion Confirmed? Yes 2
017QZ Course Type A&S 1
017QZ Course Expiry Date 04/30/2021 1
017QZ Course Type Life Upgrade 2
017QZ Date Completion Verified 08/17/2020 1
017QZ Course Provider R Publishing 2
017QZ Course Completed Date 04/30/2020 1
017QZ Course Provider R Publishing 1
017QZ Course Expiry Date 05/01/2021 2
017QZ Course Completed Date 05/01/2020 2
I need just this output: Course Name and Expired date.
ID A&S Life Upgrade
017QZ 04/30/2021 05/01/2021
I was able to achieve this by using 2 separate PIVOT views but I am wondering is there more efficient way?
Thank you!
A: Do you just want conditional aggregation?
select id,
max(case when row_index = 1 and column_name = 'Course Expiry Date' then value end) as a_and_s,
max(case when row_index = 2 and column_name = 'Course Expiry Date' then value end) as life_upgrade
from base
group by id
| |
doc_23528211
|
for file in *.info; do
gz_file="${file:(-4)}" # wrong... what is right?
# gz_file=`echo "$file" | sed -e 's/.info//'` # easy alternative I'm trying to avoid
if [[ ! -f "${gz_file}" ]]; then
rm "${file}"
fi
done
I realize this can easily be done with sed, as shown in the commented-out line, but I'd like to do it with the variable manipulation capabilities built into bash, if that's possible, because I think it'll be handy to have figured out how to make it work that way.
A: Did you try ${file%.*} ?
This should remove the extension.
A: $ x=/foo/bar.info
$ echo ${x%.info}
/foo/bar
$
| |
doc_23528212
|
1. Open popup on homepage load.
2. Popup should be in center for all browsers.
3. Popup should be fade in.
4. Should open only one time for one user.
this is my test website http://popuptest.mybigcommerce.com/
So far Popup opening, For me popup in center and looks fade in working. but session not working .
Below is the code i am working
In index.html
<div id="boxes">
<div style="top: 199.5px; left: 551.5px; display: none;" id="dialog" class="window">
<img src="images/coupon2011.jpg" width="507" height="300" />
<a href="#" class="close"><img src="images/closelabel.gif" width="66" height="22" /></a>
</div>
<!-- Mask to cover the whole screen -->
<div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask"></div>
</div>
Now in htmlhead.html, below code used.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
</script>
<script type="text/javascript">
var once_per_session=1
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function loadpopunder(){
if (get_cookie('popunder')==''){
loadpopunder()
document.cookie="popunder=yes"
}
}
function loadpopunder(){
if (once_per_session==0)
loadpopunder()
else
{
if (get_cookie('popunder')==''){
loadpopunder()
document.cookie="popunder=yes"
}
}
}
</script>
Any suggestion or tutorial would be great to complete.
A: You can use the JavaScript library js-cookie. With this library you can easily set and get cookies.
If you use js-cookie your htmlhead.html code should look something like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Check if cookie exists
if (Cookies.get('popunder')) {
return;
}
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
// Set cookie to be sure the popover activated again
Cookies.set('popunder', '1');
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
</script>
| |
doc_23528213
|
NOTE: I am on a shared hosting plus no frameworks.
| |
doc_23528214
|
for(int i=0; i<[mutableTempArray count]; i++){
//...
[tempInfoDictionary setValue:i forKey:@"tag"];
//...
}
The warning is:
passing argument 1 of 'setValue:forKey:' makes pointer from integer without a cast
What am I doing wrong here?
A: Collections in Objective-C can only hold objects, so you'll need to wrap i in an NSNumber object.
i itself is a primitive type, not an object, so it can't be put inside a collection object.
The first argument to setValue:forKey: is expected to be of pointer type, which i itself clearly isn't.
I suggest using the setObject:forKey: method on an NSDictionary instead of setValue:forKey:, because it states your intentions better. You're not only storing a value, you're storing an object
[tempInfoDictionary setObject:[NSNumber numberWithInt:i] forKey:@"tag"];
A: You're trying to put an int into an object array, but it's expecting an id i.e. a pointer. Try [tempInfoDictionary setValue:[NSNumber numberWithInt:i] forKey:@"tag"];
| |
doc_23528215
|
def post(self):
while True:
try:
data = pickle.loads(self.sock.recv(1024))
print data[0] % tuple(data[1])
except (socket.error, EOFError):
break
I then have a GUI that redirects stdout to a textctrl like so:
import wx
import sys
import threading
class Redirect:
def __init__(self, ctrl):
self.out = ctrl
def write(self, string):
wx.CallAfter(self.out.AppendText,string)
class GUI(wx.Frame):
def __init__(self, parent):
self.monitor = wx.TextCtrl(self, wx.ID_ANY, \
style = wx.TE_MULTILINE | wx.TE_READONLY)
redir = Redirect(self.monitor)
sys.stdout = redir
self.sizer = BoxSizer(wx.VERTICAL)
self.sizer.Add(self.monitor, 1, wx.GROW | wx.ALL)
self.SetSizer(self.sizer)
self.Show(True)
if __name__ == "__main__":
app = wx.App(False)
frame = GUI(None)
app.MainLoop()
I've also got a second textctrl that accepts input (left out for simplicity). The issue is that sometimes CallAfter(AppendText,string) is not printing out the entire string. It is very rare, but sometimes the print will just be stopped abruptly in the middle of the string, at which point the next string is printed (and the app continues printing the strings as they're received as if nothing happened).
I've no idea what's causing this behavior, I've tried to induce it by typing into the second textctrl to see if that's causing it, but even if I do nothing, these "partial prints" appear every now and then. What's going on?
A: This is not a real answer, just a way how to replicate the problem:
import wx
import sys
import threading
def post():
a = 0
for stop in range(100):
a = (a + 1) % 10
data = str(a) * 1000 + " <END>"
print(data)
for i, line in enumerate(frame.monitor.Value.split("\n")[:-1]):
if not line.endswith(" <END>"):
print("Invalid line %d" % (i+1))
class Redirect:
def __init__(self, ctrl):
self.out = ctrl
def write(self, string):
wx.CallAfter(self.out.AppendText, string)
class GUI(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.monitor = wx.TextCtrl(self, wx.ID_ANY, style = wx.TE_MULTILINE | wx.TE_READONLY)
redir = Redirect(self.monitor)
sys.stdout = redir
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.monitor, 1, wx.GROW | wx.ALL)
self.SetSizer(self.sizer)
self.Show(True)
if __name__ == "__main__":
app = wx.App(False)
frame = GUI(None)
t = threading.Thread(target=post)
t.start()
app.MainLoop()
When ran on my setup, I get (usually, not always):
Invalid line 30
Invalid line 63
I tried playing with delays and mutexes / locks, but it seem that I did not find why this happens yet.
| |
doc_23528216
|
Here is what I have so far:
function flyToLocation() {
var place = autocomplete.getPlace();
var geometry = place.geometry;
var location = geometry.location;
var viewport = geometry.viewport; // {fa: {b: 70, d: 40}, la: {b: 27, d: 179}}
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setLatitude(location.b);
lookAt.setLongitude(location.d);
lookAt.setTilt(lookAt.getTilt() + 15.0);
lookAt.setRange(500); // todo base this off of viewport
ge.getView().setAbstractView(lookAt);
ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);
}
This will aim the camera at the correct location, but the range is currently hard coded. I would like to base the range off the viewport, but I'm not quite sure how.
Questions
*
*How would I set the range so that the PlaceResult's viewport fits
within the user's viewport?
*Or is there a much easier way to do this?
The code must exist somewhere because the Google Earth desktop app does this perfectly, but I can't seem to find it in the API.
A: If you want to translate the Viewport (LatLngBounds) to something that can be displayed in the Google Earth plugin I would recommend the GEarthExtensions Library.
With it you can create a bounds object based on the viewport and then set that to the current view. e.g.
// the viewport is simply the SouthWest and NorthEast points.
var viewport = geometry.viewport;
// create a geo.bounds based on the viewport
var bounds = new geo.Bounds(viewport.getSouthWest(), viewport.getNorthEast());
// set the bounds (viewport) to the GEPlugin view
gex.view.setToBoundsView(bounds, { aspectRatio: 1.0 });
Here is a fully working example.
"The code must exist somewhere because the Google Earth desktop app
does this perfectly"
Just to note, simply because some functionality exists in one, it doesn't mean that it is available in the other. Indeed, there are lots of features in the full application not available to the plugin.
| |
doc_23528217
|
void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
CResizingDialog::OnSize(nType, cx, cy);
m_gridBackupLog.ExpandLastColumn();
}
Why is it being flagged?
C26434 Function 'CRestoreSettingsDlg::OnSize' hides a non-virtual function 'CRestoreDialogDlg::OnSize'.
As you can see, I call the base class method.
Declarations and Definitions
*
*CRestoreSettingsDlg:
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
CResizingDialog::OnSize(nType, cx, cy);
m_gridBackupLog.ExpandLastColumn();
}
*
*CResizingDialog:
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
void CResizingDialog::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
Invalidate(TRUE);
}
*
*The boilerplate base class (afxwin.h) appears to have:
protected:
afx_msg void OnSize(UINT nType, int cx, int cy);
_AFXWIN_INLINE void CWnd::OnSize(UINT, int, int)
{ Default(); }
Inheritance
*
*class CRestoreSettingsDlg : public CResizingDialog
*class CResizingDialog : public CDialogEx
A: C26434 warning documentation links to C.128 C++ Core Guidelines Rule. It explains that to enforce correct usage of virtual functions, non-virtual function hiding should produce a warning.
However, with MFC message maps, you have to name your message handler as specified in macro, OnSize in this case, and, since message handlers already dispatched by a virtual function (that is hidden in *_MESSAGE_MAP() macros), message handler by themselves don't have to be virtual.
So it may be seen as a false alarm. Or maybe seen as violation of the above mentioned C.128 rule by MFC itself. No surprise - MFC is decades older than these guidelines.
So I guess you can go ahead and suppress it for all afx_msg functions. Maybe redefine afx_msg to include __pragma(warning(suppress(...))), or just have suppression around afx_msg block.
Some options for suppression (Godbolt's compiler explorer demo):
#define afx_msg // this is normally defined by MFC
struct base
{
afx_msg void OnSize(){}
};
struct derived1 : base
{
afx_msg void OnSize() {} // produces C26434
};
// Suppression by adding some code:
struct derived2 : base
{
#pragma warning(push)
#pragma warning(disable:26434)
afx_msg void OnSize() {}
#pragma warning(pop)
};
struct derived3 : base
{
[[gsl::suppress(c.128)]] afx_msg void OnSize() {}
};
// Suppression by redefining MFC macro -- dirty but less intrusive:
#undef afx_msg
#define afx_msg __pragma(warning(suppress:26434))
struct derived4 : base
{
afx_msg void OnSize() {}
};
#undef afx_msg
#define afx_msg [[gsl::suppress(c.128)]]
struct derived5 : base
{
afx_msg void OnSize() {}
};
| |
doc_23528218
|
I have tried lots of solutions on the net and lots more but no luck so far. Can anyone help me ?
Why doesn't this script show anything ? How do i display the custom field "prijs" ?
<?php
function showdetails_shortcode( $attr, $content = null ) {
return <?php $key="prijs"; echo get_post_meta($post->ID, $key, true); ?>
}
add_shortcode('showdetails', 'showdetails_shortcode');
?>
A: Why doesn't this script show anything?
The provided code shows a couple of syntax errors, of which the most crucial is the re-invocation of <?php within a PHP statement.
If prijs is a good custom field key for the post where this shortcode is placed, then it should work.
function showdetails_shortcode( ) {
$post_id = get_the_ID();
//either output the value or let us know the code is working but the value has not been found
$output = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'NO CUSTOM VALUE FOUND' ;
return $output;
}
add_shortcode('showdetails', 'showdetails_shortcode');
Responding to a comment, here's a version with two fields and tabular output, keeping in mind that there would be cleaner (more flexible and parsimonious) ways to derive the variables and produce the output for a larger number of fields.
function showdetails_shortcode( ) {
$post_id = get_the_ID();
//extract the field values
$field1 = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'PRIJS NOT FOUND';
$field2 = get_post_meta( $post_id, 'prijs2', true) ? get_post_meta( $post_id, 'prijs2', true) : 'PRIJS2 NOT FOUND';
//prepare html table output
$output = '<table><tbody>';
$output .= '<tr><td>' . $field1 . '</td></tr>';
$output .= '<tr><td>' . $field2 . '</td></tr>';
$output .= '</tbody></table>';
//return the html
return $output;
}
add_shortcode('showdetails', 'showdetails_shortcode');
| |
doc_23528219
|
What is the question asking for? The topic is discrete mathematics.
A: The notation f : A → B means "f is a function whose domain is A and whose codomain is B." Intuitively, this means that f takes as input an element of A and produces an output that's an element of B.
In C, for example, this would be like the function prototype
B f(A);
This just says that f takes in an A and returns a B, with the actual way that f performs the transformation not specified.
Hope this helps!
A: These are common math notations.
http://www.solving-math-problems.com/math-symbols-set-special.html
f: R->R means when you plug in a real number for x you will get back a real number.
f: Z->R mean when you plug in an integer you will get back a real number.
These notations are used in advance math topics to help analyze the nature of the math equation rather than getting stuck on numbers.
A: #myfirstpostinStackOverflow
The above answers are very formal answers, and what I would've given had I answered it first.
Considering that OP is reading about discrete math, I'll offer this heuristic, not necessarily rigorous but good enough.
If a function has the set of real numbers as its domain, then it's possible that we may be dealing with a continuous structure. On the other hand, if a function has the set of integers as its domain, we're dealing with a discrete structure.
If you graph the function f defined by f(n) = n, where n is an integer, it looks like a diagonal line passing through the origin, but instead of a straight line, it's a set of points.
Going back, this function f is f: Z ----> Z. It has domain Z and codomain Z.
It also satisfies the dictionary definition of discrete.
dis·crete dəˈskrēt/ adjective individually separate and distinct.
| |
doc_23528220
|
I try to retrieve data from local SQL Server. The connection is right, and so is the stored procedure. But when I read rows from the SqlDataReader, it is empty. But when I watch the SqlDataReader, there is something with ? inside, but is not the result.
The SQL query works fine in SQL Server Management Studio.
Here is my code:
List<Customer> customers = new List<Customer>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=DESKTOP-U8E1S5I;Database=Queue;Trusted_Connection=true";
conn.Open();
SqlCommand command = new SqlCommand("GetCustomers", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
customers.Add(new Customer
{
Name = (string)reader["CustomerName"],
WaitingNumber = (int?)reader["CustomerNumber"],
EnterTime = (DateTime?)reader["CustomerNumber"],
Status = (int)reader["CustomerStatus"]
});
}
}
}
and the result is "Enumeration Yielded No Results" with two rows that contains ?: (break point is before the reader.read())
Enumeration Yielded No Results
Thank for help.
A: By default, the SqlCommand has the property CommandType defined as CommandType.Text which is used by ad-hoc sql. You have to specify you are using stored procedure by setting CommandType on your command. For sample:
SqlCommand command = new SqlCommand("GetCustomers", conn);
command.CommandType = CommandType.StoredProcedure;
Do not forget to add the namespace System.Data.
A: You need to specify that you're using a stored procedure, see below
SqlCommand command = new SqlCommand("GetCustomers", conn);
command.CommandType = CommandType.StoredProcedure;
Or
SqlCommand command = new SqlCommand("GetCustomers", conn) {
CommandType = CommandType.StoredProcedure
};
| |
doc_23528221
|
I didn't find any resource on youtube about this, they just let the user do the normal login and use the current_user.is_authenticated to access the admin page
any tips from flask_security to let that happen
| |
doc_23528222
|
in the documentation: https://wiki.duraspace.org/display/DSDOC18/XMLUI+Configuration+and+Customization#XMLUIConfigurationandCustomization-AdditionalXMLUILearningResources
IT is not clear how the order of the aspect is determined, hence how they are actually chained.
I red in a doc of 2005 that Manakin Developer Guide, that the order was determined from a file aspect.xml.
Please could someone, explain briefly how one match uri to a chain of aspect? but it seems like it is not in dspace 1.8.2 anymore. Could it be that one can work without it ? or is there another way to associate an uri to a chain ?
Beside I do never understand yet what means {1} or {2} and etc. in the DRI path. A hint here would help me understand better.
A: The documentation is a bit obscure. There is one aspect chain. Every dynamically generated page passes through it.
To understand how it all works, you need to keep in mind that XMLUI is a Cocoon application, and in particular you need to understand the Cocoon "sitemap" which is built up from a number of .xmap files. Incoming requests are guided through the sitemap by map components called Matchers. XMLUI embodies the Aspect chain in a portion of the sitemap.
Where the aspect chain is defined: config/xmlui.xconf, as the content of the <aspects> element. The order given there is the order in which the defined Aspects will be applied to the developing DRI document. (This is stated a bit higher up in XMLUI Configuration and Customization, at https://wiki.duraspace.org/display/DSDOC18/XMLUI+Configuration+and+Customization#XMLUIConfigurationandCustomization-UnderstandingtheFlowofanXMLUIRequest in step 3b.)
I can't find any instance of an 'aspect.xml'. webapps/xmlui/aspects/aspects.xmap is a Cocoon sitemap file that causes the aspect chain to be applied. The AspectMatcher component is where the ordering of Aspects is enforced.
As stated above, every request for a dynamic page causes the resulting document to be sent down the single Aspect chain.
The tokens like {1} represent URI text which is matched by wildcards ('*' or '**') in the nearest enclosing element's 'match' attribute. This is similar to the subexpression match variables provided by some regular expression packages. (This feature is provided by Cocoon; it is not a part of DSpace, but is used by XMLUI.)
I recommend reading up a bit on Cocoon, if you can find a good resource. I usually refer to Cocoon Developer's Handbook by Moczar and Aston. It is now outdated, but it's much more complete than the current online Cocoon documentation.
| |
doc_23528223
|
this list will upload to Zabbix item by string or (you suggest), and I want to ask can Zabbix read this list and generate problems according the list.
For example, list[1] -> problem 1, list[2] -> problem 2
A: It seems like you might want to create a custom LLD rule. This will require formatting your list in JSON according to the linked manual page. LLD will create items and triggers as per the configuration of prototypes.
| |
doc_23528224
|
methods: {
renderAnswers() {
let answers = this.question;
let newAnswers = answers.map((isAnswer) => ({
answers: isAnswer,
}))
console.log(newAnswers);
},
async createQuiz(quiz, question) {
try {
let add = await axios.post("http://localhost:3000/v1/quiz/" , {
name: quiz.name,
type: question.type,
question: this.renderAnswers(),
});
router.push({path: '/listQuizzesInstructor'});
} catch(e) {
this.errors.push(e);
}
}
A: You need to return a value from renderAnswers.
methods: {
// add a return statement
renderAnswers() {
return this.question.map((isAnswer) => ({ answers: isAnswer }))
},
async createQuiz(quiz, question) {
try {
let add = await axios.post("http://localhost:3000/v1/quiz/" , {
name: quiz.name,
type: question.type,
question: this.renderAnswers(),
});
router.push({path: '/listQuizzesInstructor'});
} catch(e) {
this.errors.push(e);
}
}
| |
doc_23528225
|
The response the API Server is supposed to give me should look something like below:
{
"email": "example email",
"euid": "example euid",
"leid": "example leid"
}
However, I don't get any response or error message from the server. I do get false when I use var_dump.
Here is my code:
$api_url_str = "https://us6.api.mailchimp.com/2.0/lists/subscribe";
$api_data_str = '{
"apikey": "'.$my_api_key.'",
"id": "'.$my_list_id.'",
"email": {"email": "'.$my_email_addr.'"},
"double_optin": false,
"merge_vars":
{
"FNAME": "'.$my_first_name.'",
"LNAME": "'.$my_last_name.'",
"OPTIN_IP": "'.$my_ip_address.'",
"OPTIN_TIME": "2015-05-22 10:22:09"
}
}';
$ch = curl_init($api_url_str);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $api_data_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($api_data_str)));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$api_response_str = curl_exec($ch);
curl_close($ch);
The above code works (as expected) when I run it on my local PC (also PHP 5.5).
Anyone have this issue?
A: After trying a couple of things, I stumbled on the following solution that works (I got the relevant code from here).
Here's the full code:
$api_url_str = "https://us6.api.mailchimp.com/2.0/lists/subscribe";
$api_data_str = '{
"apikey": "'.$my_api_key.'",
"id": "'.$my_list_id.'",
"email": {"email": "'.$my_email_addr.'"},
"double_optin": false,
"merge_vars":
{
"FNAME": "'.$my_first_name.'",
"LNAME": "'.$my_last_name.'",
"OPTIN_IP": "'.$my_ip_address.'",
"OPTIN_TIME": "2015-05-22 10:22:09"
}
}';
$json_data = $api_data_str;
$context = array(
'http' => array(
'user_agent' => 'PHP-MCAPI/2.0',
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'content' => $json_data
)
);
$context = stream_context_create($context);
$api_response_str = file_get_contents($api_url_str, false, $context);
I'm not sure if it's prone to the breakage I've just recently experienced with CURL on Google PHP App Engine though, but for now it will have to do. I had a test script that I used to test Mandrill mail sends that worked with App Engine about a month ago, but it doesn't anymore, probably the same issue with CURL.
I hope this helps someone with the same challenge.
| |
doc_23528226
|
On click on logout button I call
siteminder.xxx.it/siteminderagent/xxx-logout.fcc/
and the first logout makes these calls
302 HTTP siteminder.xxx.it /siteminderagent/xxx-logout.fcc/ 313 no-store text/html; charset=iso-8859-1 iexplore:40080
302 HTTP xxx.yyy.it /client-web 461 no-store text/html; charset=iso-8859-1 iexplore:40080
200 HTTP siteminder.xxx.it /siteminderagent/mylogin.fcc?TYPE=33554433&REALMOID=06-00006cf6-458d-1d40-964a-0265c0a85024&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-yx%2fRAnRmsQJxM%2fCmccgQ4%2bXx0vaGseQ3Fsv1KWcytAoO6LfYuVpjXDQ6XkxgUsWf&TARGET=-SM-http%3a%2f%2fxxx%2eyyy%2eit%2fclient--web 2.897 no-store text/html; charset=iso-8859-1 iexplore:40080
302 HTTP siteminder.xxx.it /siteminderagent/xxx-logout.fcc 313 no-store text/html; charset=iso-8859-1 iexplore:40080
302 HTTP xxx.yyy.it /client-web 461 no-store text/html; charset=iso-8859-1 iexplore:40080
200 HTTP siteminder.xxx.it /siteminderagent/mylogin.fcc?TYPE=33554433&REALMOID=06-00006cf6-458d-1d40-964a-0265c0a85024&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-yx%2fRAnRmsQJxM%2fCmccgQ4%2bXx0vaGseQ3Fsv1KWcytAoO6LfYuVpjXDQ6XkxgUsWf&TARGET=-SM-http%3a%2f%2fxxx%2eyyy%2eit%2fclient--web 2.897 no-store text/html; charset=iso-8859-1 iexplore:40080
If I make again the login on siteminder, I'm correctly redirected to my flex web app. The next logout doesn't work because seems that IE) ignore this 302 redirect
302 HTTP siteminder.xxx.it /siteminderagent/xxx-logout.fcc/ 313 no-store text/html; charset=iso-8859-1 iexplore:36916
From fiddler I can see that the response of this call is
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://xxx.yyy.it/client-web">here</a>.</p>
<hr>
<address>Apache/2.2.3 (Red Hat) Server at siteminder.xxx.it Port 80</address>
</body></html>
On cache tab i can see
Cache-Control : no-store
Date: Fri, 04 Oct 2013 16:03:54 GMT
Why IE9 doesn't read correctly this 302 redirect ?
NOTE : If I disable IE cache, all works correctly !!
| |
doc_23528227
|
i did come across Membership.GetUser but i can't figure out how to use it.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AccountInfo([Bind(Include = "UserName, Address, Region, Email, Phone")]UserProfile UserProfile)
{
if (ModelState.IsValid)
{
}
}
Am not sure how to code this part.
A: If you are using ASP.net membership,then code like below :
MembershipUser u = Membership.GetUser(User.Identity.Name);
u.Email = someValue;
Membership.UpdateUser(u);
| |
doc_23528228
|
Below is the assets part of my pubspec.yaml file
assets:
- assets/
- assets/images/
Using VSCode and it shows any images I reference or if I mouse over the reference it shows the images.
@protected
Future<ui.Codec> _loadAsync(AssetBundleImageKey key, DecoderCallback decode) async {
ByteData data;
// Hot reload/restart could change whether an asset bundle or key in a
// bundle are available, or if it is a network backed bundle.
try {
data = await key.bundle.load(key.name);
} on FlutterError {
PaintingBinding.instance.imageCache.evict(key);
rethrow; <---- crashes here
}
I am not grabbing any external images (URL) in my code. I added Google Maps SDK so maybe its something it is trying to grab? But not sure why no stack trace?
VSCode see the images before I send it to the iOS simulator. These are the images that it cannot find. It finds all other images referenced in the file.
A:
Below is the assets part of my pubspec.yaml file
assets:
- assets/
- assets/images/
Try to follow the indentation of the documentation.
Here is an example:
flutter:
assets:
- assets/my_icon.png
- assets/background.png
If the error still exist, try to follow the workaround here:
It worked for me:
*
*Set only full path to asset in pubspec.yaml
e.g.
assets:
- assets/files/asset.txt
- assets/images/icons/myicon.png
Whole folder not worked for me - assets/
*Add ./ to the beginning of your asset path when you loading it
e.g. rootBundle.loadString('./assets/path/to your/asset.txt
*flutter clean
Also, as mentioned in this comment, using flutter clean is a good idea if there are some weird behavior from your app.
| |
doc_23528229
|
Possible Duplicates:
Adding rows to a table with jQuery
Jquery and adding row to table.
I currently have a table that has one row and with this table row, I have five cells where a user can place in required information.
What I would like to achieve is a means of having an "Add Row" button using jQuery, by where the user can create on the fly, additional rows/cells within this table if required by pressing the "Add Row" button.
Basically would like to keep appending rows within this table and then go through each of these rows and store the data into a database table.
A: See my answer here: Adding rows to a table with jQuery
| |
doc_23528230
|
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>signing</id>
<goals>
<goal>sign</goal>
</goals>
<phase>package</phase>
<inherited>true</inherited>
<configuration>
<archiveDirectory></archiveDirectory>
<includes>
<include>target/*.apk</include>
</includes>
<keystore>${keystore}</keystore>
<storepass>${password}</storepass>
<keypass>${password}</keypass>
<alias>rimbit</alias>
<arguments>
<argument>-sigalg</argument><argument>SHA256withRSA</argument>
<argument>-digestalg</argument><argument>SHA256</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
But during the build process I get this:
[DEBUG] Configuring mojo org.apache.maven.plugins:maven-jarsigner-plugin:1.3.2:sign from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-jarsigner-plugin:1.3.2, parent: sun.misc.Launcher$AppClassLoader@48c4fedd]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-jarsigner-plugin:1.3.2:sign' with basic configurator -->
[DEBUG] (f) alias = rimbit
[DEBUG] (f) arguments = [-sigalg, SHA256withRSA, -digestalg, SHA256]
[DEBUG] (f) includes = [target/*.apk]
[DEBUG] (f) keypass = SECRET
[DEBUG] (f) keystore = ../rimbit_wallet.keystore
[DEBUG] (f) processAttachedArtifacts = true
[DEBUG] (f) processMainArtifact = true
[DEBUG] (f) protectedAuthenticationPath = false
[DEBUG] (f) removeExistingSignatures = false
[DEBUG] (f) skip = false
[DEBUG] (f) storepass = SECRET
[DEBUG] (f) verbose = false
[DEBUG] (f) workingDirectory = /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet
[DEBUG] (f) project = MavenProject: com.rimbit.wallet:wallet:1.0 @ /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet/pom.xml
[DEBUG] (f) session = org.apache.maven.execution.MavenSession@10385cb0
[DEBUG] -- end configuration --
[DEBUG] Processing /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet/target/wallet-1.0.apk
[DEBUG] /bin/sh -c cd /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet && /usr/lib/jvm/java-6-openjdk-amd64/jre/../bin/jarsigner -keystore ../rimbit_wallet.keystore -storepass '*****' -sigalg SHA256withRSA -digestalg SHA256 -keypass '*****' /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet/target/wallet-1.0.apk rimbit
[DEBUG] Executing: /bin/sh -c cd /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet && /usr/lib/jvm/java-6-openjdk-amd64/jre/../bin/jarsigner -keystore ../rimbit_wallet.keystore -storepass '*****' -sigalg SHA256withRSA -digestalg SHA256 -keypass '*****' /home/matt/Programming/ADT/workspace/rimbit-android-wallet/wallet/target/wallet-1.0.apk rimbit
[DEBUG] jarsigner error: java.util.zip.ZipException: ZIP file must have at least one entry
A: OK, I was trying to use SHA256, but it seems jarsigner does not allow that. That was the problem. I'm using SHA1 now.
| |
doc_23528231
|
A:
About Objective-C Command Line Syntax
The basic command line syntax for translating a single file is
sourceanalyzer -b -clean
sourceanalyzer -b xcodebuild [compiler options]
where:
[compiler options] are options passed to xcode.
Can you please test it on Mac device.
A: You need to run it on a Mac, because sourceanalyzer will need to run xcodebuild (see: command line syntax documented by other comments). And xcodebuild only runs on Mac OS. There is more to it than just scanning source code, as an analysis will also build the product, hence the need for Mac OS.
| |
doc_23528232
|
And write it into destination folder.
Is there anyway I can do it parallel via pyspark?
I am using below code, but it is only picking header from first file, which is producing wrong output.
Df.read.option(“header”, “true”).parquet(directory/*.parquet)
Df.write.option(“header”,”true”).csv(directory)
Please help me if you know how can I read all the files with source headers of their own.
Thanks!
| |
doc_23528233
|
I have this code to draw tabs with border:
private func drawBorder(selectedTab: UIButton) {
// The Tab frame (below one)
guard let tabContainerFrame = vTabContainer?.frame else { return }
let borderColor = selectedTab.titleColor(for: .selected)
let tabFrame = selectedTab.convert(selectedTab.bounds, to: self)
let topMargin: CGFloat = 5
let tabOrigin = CGPoint(x: tabFrame.origin.x, y: tabFrame.origin.y - topMargin)
// Make paths to draw
let path = UIBezierPath()
path.move(to: tabOrigin) // Origin (top left)
path.addLine(to: CGPoint(x: tabFrame.maxX, y: tabOrigin.y)) // -> right
path.addLine(to: CGPoint(x: tabFrame.maxX, y: tabFrame.maxY)) // -> down
if tabFrame.maxX != tabContainerFrame.maxX {
path.addLine(to: CGPoint(x: tabContainerFrame.maxX, y: tabContainerFrame.origin.y)) // -> right
}
path.addLine(to: CGPoint(x: tabContainerFrame.maxX, y: tabContainerFrame.maxY)) // -> Down
path.addLine(to: CGPoint(x: tabContainerFrame.origin.x, y: tabContainerFrame.maxY)) // -> left
path.addLine(to: CGPoint(x: tabContainerFrame.origin.x, y: tabContainerFrame.origin.y)) // -> up
if tabOrigin.x != tabContainerFrame.origin.x {
path.addLine(to: CGPoint(x: tabOrigin.x, y: tabContainerFrame.origin.y)) // -> right
}
// Close the path. This will create the last line automatically.
path.close()
// Draw
let borderLayer = CAShapeLayer()
borderLayer.path = path.cgPath
borderLayer.lineCap = kCALineCapRound
borderLayer.lineJoin = kCALineJoinBevel
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor?.cgColor
borderLayer.cornerRadius = 10
borderLayer.lineWidth = 2
layer.addSublayer(borderLayer)
self.borderLayer = borderLayer
}
This is the result:
As you can see, even though I add cornerRadius = 10, it just doesn't work. borderLayer.lineCap = kCALineCapRound and borderLayer.lineJoin = kCALineJoinBevel doesn't help also.
Bonus:
I'd like to have a way to implement dynamic @IBInspectable var lineCornerRadius: CGFloat = 10.
A: If you are using UIBezierPath to draw a shape, setting cornerRadius will have no effect on that path.
Instead, you want to use path.addCurve(to: ...) to make your rounded corners.
For example:
*
*the green dotted line is tabFrame
*pt1 is tabFrame's "left" and "top + 10" (your radius)
*pt2 is tabFrame's "left + 10" and "top"
*pt3 is the first curve's second "control point" - the top-left corner of tabFrame
*pt4 is tabFrame's "right - 10" and "top"
*pt5 is tabFrame's "right" and "top + 10"
*pt6 is the second curve's second "control point" - the top-right corner of tabFrame
So
path.addCurve(to: pt2, controlPoint1: pt1, controlPoint2: pt3)
adds a curve to pt2 ... from pt1 ... with curve control point of pt3
then:
path.addLine(to: pt4)
adds a line from the current point (pt2) to pt4
then:
path.addCurve(to: pt5, controlPoint1: pt4, controlPoint2: pt6)
adds a curve to pt5 ... from pt4 ... with curve control point of pt6
The rest of your shape is normal line segments.
| |
doc_23528234
|
x = 0
Name = [None]*1000
Score = [0]*100
text_file = open("txt.Scores.txt","a")
def write_in_file():
global text_file
text_file.write(Name[x])
text_file.write("\n")
text_file.write(Score[x])
text_file.write("\n")
text_file.write("\n")
text_file.close()
text_file = open("txt.Scores.txt","a")
for i in name:
Name[x] = input("Username:")
Score[x] = input("Score:")
write_in_file()
print(Score)
x += 1
when i run the code, it gives me an output that looks like this:
Username:Jonny
Score:15
['15', 0, 0, 0, 0]
Username:Max
Score:15
['15', '15', 0, 0, 0, 0]
and the text file looks like this:
Jonny
15
Max
15
I am trying to get it to print the 5 highest scores only
A: you have not defined name which you use in your for loop,you should use while True:instead, then make an empty list name to fill it depending on the input.
A: At first read about file's descriptors If you don’t use “with”, when does Python close files? The answer is: It depends.
You can use python's sort as:
with open('txt.Scores.txt', 'r') as f:
data = f.readlines()
data = [int(line.strip()) for line in data if line.strip() != str() and all(i.isdigit() for i in line.strip())]
print sorted(data, reverse=True)
Or GNU sort ass executed command with specific keys.
A: You can use a dictionary to store Name and its corresponding score, and print the highest score values.
X = {}
with open("txt.Scores.txt", 'w+') as score:
while len(X) < 10:
Name = input("Username: ")
Score = int(input("Score: "))
X[Score] = Name
print(Name + '\t\t' + str(Score), file=score)
Y = sorted(list(X.keys()), reverse=True)
y = range(0, len(Y))
Scores = [Y[i] for i in y[:5]]
print(Scores)
print([X[i] for i in Scores])
This code will get 10 names and scores as input, store them in 'txt.Scores.txt' and print 5 highest scores stored in a list, and their corresponding names in another list.
Let me know if it worked for you.
| |
doc_23528235
|
It seems to me that I should be able to simplify this using a custom tag and passing the field that I want but I can't seem to get it to work.
customtags.py:
from django import template
register = template.Library()
@register.simple_tag
def get_latest_record(issue, field):
record = issue.history.filter(field = 1).most_recent
return record
in my template:
{% get_latest_record issue 'name_of_field' %}
A: Make shure your customtags.py file is in templatetags directory (__init__.py is also required) and then restart server
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
Then in template {% load customtags %}
| |
doc_23528236
|
Thanks for your help.
[Updates]:
We are stuck with 0.98.6, so ConnectionFactory is not available.
I found the bellow jira suggesting to create an "unmanaged" connection and use a single ExecuteService to create HTable. Why can't we simply use the getTable method of the unmanaged connection to get HTable? Is that because of HTable is not thread safe?
https://issues.apache.org/jira/browse/HBASE-7463
A: Im stuck with old versions (<0.94.11) in which you can still use HTablePool but since it has been deprecated by HBASE-6580 I think requests from HTables to the RS are now automatically pooled by providing an ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(10);
Connection connection = ConnectionFactory.createConnection(conf, executor);
Table table = connection.getTable(TableName.valueOf("mytable"));
try {
table.get(...);
...
} finally {
table.close();
connection.close();
}
I've been unable to find any good examples/docs about it, so please notice this is untested code which may not work as expected.
For more information you can take a look to the ConnectionFactory documentation & to the JIRA issue:
https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/ConnectionFactory.html
https://issues.apache.org/jira/browse/HBASE-6580
Update, since you're using 0.98.6 and ConnectionFactory is not available you can use HConnectionManager instead:
HConnection connection = HConnectionManager.createConnection(config); // You can also provide an ExecutorService if you want to override the default one. HConnection is thread safe.
HTableInterface table = connection.getTable("table1");
try {
// Use the table as needed, for a single operation and a single thread
} finally {
table.close();
connection.close();
}
HTable is not thread safe so you must make sure you always get a new instance (it's a lightweight process) with HTableInterface table = connection.getTable("table1") and close it afterwards with table.close().
The flow would be:
*
*
*
*Start your process
*
*Initialize your HConnection
*
*Each thread:
*3.1 Gets a table from your HConnection
*3.2 Writes/reads from the table
*3.3 Closes the table
*
*Close your HConnection when your process ends
HConnectionManager: http://archive.cloudera.com/cdh5/cdh/5/hbase/apidocs/org/apache/hadoop/hbase/client/HConnectionManager.html#createConnection(org.apache.hadoop.conf.Configuration)
HTable: http://archive.cloudera.com/cdh5/cdh/5/hbase/apidocs/org/apache/hadoop/hbase/client/HTable.html
| |
doc_23528237
|
but is it a good idea to create language model of whole vocabulary? (Language model of english language is 125 MB in size)
How can I implement "speech to text" for many languages. Should I create language model for each language? and what about my build size if I import 10 language model in my app?
Thanks in advance.
A: OpenEars developer here. OpenEars supports two languages and it doesn't perform large vocabulary recognition. This is described in its docs, so check them out for the answers to these questions and more.
| |
doc_23528238
|
This is my Xaml code:
<DataTemplate>
<Border BorderBrush="#cbc6c0"
BorderThickness="3"
CornerRadius="3"
Background="#FFF9F6F4">
<Grid Margin="5">
<ContentControl Content="{Binding Converter={StaticResource Groupdetails}}" />
</Grid>
</Border>
</DataTemplate>
... and the C# code for my converter:
public class ListDetailsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Model_Detail ObjDetail = value as Model_Detail;
TextBlock TbInfo = new TextBlock();
TbInfo.Margin = new Thickness(5, 5, 5, 5);
TbInfo.TextWrapping = TextWrapping.Wrap;
TbInfo.Foreground = new SolidColorBrush(Colors.Black);
Bold TbTitle = new Bold();
string StrTitle = ObjDetail.QuestionTitle;
TbTitle.Inlines.Add(StrTitle);
string StrDetails = " : " + ObjDetail.Detail;
TbInfo.Inlines.Clear();
TbInfo.Inlines.Add(TbTitle);
TbInfo.Inlines.Add(StrDetails);
return TbInfo;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
At the top of the Page xaml I have declared:
xmlns:MyConverter="clr-namespace:Magnitude_Gold.MGConverter"
<phone:PhoneApplicationPage.Resources>
<MyConverter:ListDetailsConverter x:Key="Groupdetails" />
</phone:PhoneApplicationPage.Resources>
What is wrong with this..?
A: Use this, Replace Model_Detail with you enity or Object
<ContentControl Content="{Binding Path=Model_Detail Converter={StaticResource Groupdetails}}" />
| |
doc_23528239
|
Example:
I would like to define a class (class A) which hold and controls some resources. There will be another class (class B) which has some data/state information and that would need to use resources hold by class A. So user API would be to define only one class A and then multiple class B instances which they can add/register to class A instance. Is it possible to make it so that some attributes and methods of class B instances are only visible/accessible by class A instance and not by the user? E.g. if there is a an attribute holding some datetime value then only class A instance could access that, but user directly can't.
EDIT:
I know I can make those attributes and methods 'private' and in that way kind of achieve what I want. But this goes against the concept of private attributes/methods (they are still used externally by some). Also, I am hoping that maybe there is a more elegant (pythonic) way of achieving this.
A: No, it's not possible to do this. Either an attribute can be accessed or it can't. Other than private attributes, which can only be accessed within the same class (unless you mangle the name by hand), there's no access control based on where the attribute reference is.
| |
doc_23528240
|
But when i try to create a sublevel ( without any reference at this time ) Lets say , i want to have a new sublevel where users can not be assigned just yet. It does not work.
Current Scheme:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
password String
firstName String
lastName String
address String
postalCode String
city String
country String
email_verified Boolean
subLevelId String?
sub SubLevel? @relation(fields: [subLevelId], references: [id], onDelete: Cascade)
}
model SubLevel {
id String @id @default(auto()) @map("_id") @db.ObjectId
sublevelName String
sublevelCost Float
users User[]
}
The error i get is:
3 export const createSubLevel = ({ input }) => { api | → 14 return db.subLevel.create({ api | data: { api |
sublevelName: 'Cryptek-Standard', api | sublevelCost: 0,
api | + user: { api | + create?:
UserCreateWithoutSubLevelInput |
UserUncheckedCreateWithoutSubLevelInput, api | +
connectOrCreate?: UserCreateOrConnectWithoutSubLevelInput, api |
*
*
connect?: UserWhereUniqueInput api | + }, api | ? id?: String api | } api | }) api | api | Argument
user for data.user is missing. api | api | Note: Lines with + are
required, lines with ? are optional.
Is it not possible in prisma to do this ? I searched the docu but i can not seem to find the answer for it.
A: Changed into a 1-1 relationship
| |
doc_23528241
|
If I want pressing key X to execute my listener and no other, is there any way to carry that out in javascript, short of modifying all external js on the page that might add a handler?
A: DOM2 (addEventListener) handlers are called in the order in which they were registered. So as long as you register yours first, it will be called first, and you can prevent others from being called by using stopPropagation and stopImmediatePropagation.
The above is in relation to the specific element, however. If your handler is on a container element and there's an element inside that container with a handler directly attached to it, then all of the handlers for that inner element are called before yours on the container element (this is for bubbling; there's another phase called capture where it's the other way around, but almost no one uses it). [See the old DOM3 events spec (but it's still valid).]
So for what you're describing, it sounds like you have your handler on a container element, and the library has its handler on an element inside that container. To get in front of that handler, you'd have to register yours on that specific element first, before that lib does.
| |
doc_23528242
|
Declare @JSON varchar(max)
SELECT @JSON=BulkColumn
FROM OPENROWSET (BULK 'C:\Users\amartinez\US.json', SINGLE_CLOB) j
SELECT * FROM OPENJSON (@JSON)
WITH (
[CTY_CODE] varchar(max) '$.CTY_CODE',
[CTY_NAME] varchar(max) '$.CTY_NAME',
[I_ENDUSE] varchar(max) '$.I_ENDUSE',
[I_ENDUSE_LDESC] varchar(max) '$.I_ENDUSE_LDESC',
[GEN_VAL_MO] int '$.GEN_VAL_MO',
[CON_VAL_MO] int '$.CON_VAL_MO',
[time] varchar(max) '$.time'
) as tradeF;
Input file
A: Please try the following solution.
Your JSON is a JSON array, so it needs a slightly different syntax.
SQL
DECLARE @JSON VARCHAR(MAX);
SELECT @JSON=BulkColumn
FROM OPENROWSET (BULK 'C:\Users\amartinez\US.json', SINGLE_CLOB) j;
SELECT tradeF.*
FROM OPENJSON (@JSON)
WITH (
[CTY_CODE] varchar(max) '$[0]',
[CTY_NAME] varchar(max) '$[1]',
[I_ENDUSE] varchar(max) '$[2]',
[I_ENDUSE_LDESC] varchar(max) '$[3]',
[GEN_VAL_MO] varchar(max) '$[4]',
[CON_VAL_MO] varchar(max) '$[5]',
[time] varchar(max) '$[6]'
) as tradeF;
| |
doc_23528243
|
What I need is a way to tell the api to use the last waypoint of my optimized route as a destination.
A: You could make multiple requests to the directions service, one with each possible waypoint as the final destination, pick the shortest resulting distance.
proof of concept fiddle
code snippet:
var map;
var directionsServices = [];
var directionsDisplays = [];
// constant "start" address
var start = "Paramus, NJ";
// list of possible candidate destinations/waypoints (must be < 9)
var locations = ["67 E Ridgewood Ave, Paramus, NJ 07652",
"450 Rochelle Ave, Rochelle Park, NJ 07662,",
"720 River Rd, New Milford, NJ 07646",
"280 Main St, New Milford, NJ 07646",
"469 Passaic St, Hackensack, NJ 07601",
"91 Broadway, Elmwood Park, NJ 07407",
"206 Market St, Saddle Brook, NJ 07662"
];
var routes = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
document.getElementById('info').innerHTML += "<u><b>intermediate results:</b></u><br>";
getDirections(start, locations, map);
}
google.maps.event.addDomListener(window, "load", initialize);
function getDirections(start, waypoints, map) {
var requests = [];
var request = {
origin: start,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
for (var j = 0; j < waypoints.length; j++) {
var waypts = [];
for (var i = 0; i < waypoints.length; i++) {
if (i != j) {
waypts.push({
location: waypoints[i],
stopover: true
});
}
}
requests[j] = {};
requests[j].destination = waypoints[j];
requests[j].waypoints = waypts;
requests[j].origin = start;
requests[j].optimizeWaypoints = true;
requests[j].travelMode = google.maps.TravelMode.DRIVING;
setTimeout(function(request, j) {
sendDirectionsRequest(request, j, map);
}(requests[j], j), 3000 * j);
}
}
function sendDirectionsRequest(request, index, map) {
var directionsService = new google.maps.DirectionsService();
directionsServices.push(directionsService);
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
routes.push(route);
var distance = 0;
var duration = 0;
for (var i = 0; i < route.legs.length; i++) {
distance += route.legs[i].distance.value;
duration += route.legs[i].duration.value;
}
route.distance = distance;
route.duration = duration;
route.index = index;
document.getElementById('info').innerHTML += (routes.length - 1) + " dist:" + (route.distance / 1000).toFixed(2) + " km dur:" + (route.duration / 60).toFixed(2) + " min dest:" + index + " loc:" + locations[index] + " waypt order:" + route.waypoint_order + "<br>";
if (routes.length == locations.length) {
routes.sort(sortFcn);
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
polylineOptions: {
strokeOpacity: 0.9,
strokeWeight: 4,
strokeColor: "black",
zIndex: 10
}
});
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
document.getElementById('info').innerHTML += "<u><b>shortest result:</b></u><br>" + routes[0].index + " dist:" + (routes[0].distance / 1000).toFixed(2) + " km dur:" + (routes[0].duration / 60).toFixed(2) + " min dest:" + routes[0].index + " loc:" + locations[index] + " waypt order:" + routes[0].waypoint_order + "<br>";
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function sortFcn(a, b) {
if (a.distance > b.distance) return 1;
else if (a.distance < b.distance) return -1;
else return 0;
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="info"></div>
<div id="map_canvas"></div>
| |
doc_23528244
|
<LinearLayout style="@style/ActivityBody"
android:orientation="vertical"
>
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dip"
android:layout_gravity="left"
android:layout_marginLeft="20dp"
>
<Button
android:id="@+id/btnMaterialIssue"
style="@style/DashboardButton"
android:drawableTop="@drawable/materialissue"
android:text="Material Issue"
android:onClick="onGol"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnWorkCompletion"
style="@style/DashboardButton"
android:drawableTop="@drawable/workcompletion"
android:text="Work Completion"
android:onClick="onGol"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
My style file is like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="Theme" parent="android:Theme"></style>
<style name="Theme.D1t" parent="android:style/Theme.Light">
<item name="android:windowNoTitle">false</item>
<item name="android:windowContentOverlay">@null</item>
</style>
<style name="Theme.D1" parent="android:style/Theme.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
<style name="Theme.tranlucent" parent="android:style/Theme.Translucent">
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
<style name="Home">
<item name="android:layout_gravity">center_vertical</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">0</item>
<item name="android:background">#fff</item>
</style>
<style name="HomeText">
<item name="android:layout_gravity">center_vertical</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">0</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:textSize"> 18sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/foreground</item>
</style>
<style name="TitleBar">
<item name="android:id">@id/title_container</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">45dip</item>
<item name="android:orientation">horizontal</item>
<item name="android:background">@color/title_background</item>
</style>
<style name="TitleBarOperation">
<item name="android:layout_width">45dip</item>
<item name="android:layout_height">fill_parent</item>
</style>
<style name="TitleBarLogo">
<item name="android:id">@id/title_logo</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">fill_parent</item>
</style>
<style name="TitleBarText">
<item name="android:id">@id/title_text</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:layout_weight">1</item>
<item name="android:gravity">center_vertical</item>
<item name="android:textSize">18sp</item>
<item name="android:paddingLeft">12dip</item>
<item name="android:paddingRight">12dip</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/title_text</item>
<item name="android:singleLine">true</item>
<item name="android:ellipsize">end</item>
</style>
<style name="TextBody">
<item name="android:textSize">15sp</item>
<item name="android:lineSpacingMultiplier">1.1</item>
<item name="android:textColor">@color/textBody</item>
<item name="android:textStyle">bold</item>
</style>
<style name="ActivityBody">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="DashboardButton">
<item name="android:layout_gravity">center_vertical</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:drawablePadding">2dp</item>
<item name="android:textSize">9dp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">#fff</item>
<item name="android:background">@null</item>
</style>
</resources
A: what you can do is to use the relative layout and align them to left and right
below is the code
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dip"
android:layout_gravity="left"
android:layout_marginLeft="20dp">
<Button
android:id="@+id/btnMaterialIssue"
style="@style/DashboardButton"
android:drawableTop="@drawable/materialissue"
android:text="Material Issue"
android:onClick="onGol"
android:layout_alignParentRight="true"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnWorkCompletion"
android:layout_alignParentLeft="true"
style="@style/DashboardButton"
android:drawableTop="@drawable/workcompletion"
android:text="Work Completion"
android:onClick="onGol"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
A: *
*Option:
Use margins to the left of right button and to the right of the left button.
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dip"
android:layout_gravity="left"
android:layout_marginLeft="20dp"
>
<Button
android:id="@+id/btnMaterialIssue"
style="@style/DashboardButton"
android:drawableTop="@drawable/materialissue"
android:text="Material Issue"
android:onClick="onGol"
layout_marginRight="20dp"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnWorkCompletion"
style="@style/DashboardButton"
android:drawableTop="@drawable/workcompletion"
android:text="Work Completion"
android:onClick="onGol"
layout_marginLeft="20dp"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
*Option:
place something (another view (Linearlayout)) in the middle, between the buttons.
*Option:
Try to play with layout_weight
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="New Button"
android:layout_weight="1"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1">
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="New Button"
android:layout_weight="1"/>
</LinearLayout>
A: you have to use android:layout_weight
to use layout_weight you want to set layout_width as "0dp"
android:layout_width="0dp"
android:layout_weight="1"
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dip"
android:layout_gravity="left"
android:layout_marginLeft="20dp"
>
<Button
android:id="@+id/btnMaterialIssue"
style="@style/DashboardButton"
android:drawableTop="@drawable/materialissue"
android:text="Material Issue"
android:onClick="onGol"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnWorkCompletion"
style="@style/DashboardButton"
android:drawableTop="@drawable/workcompletion"
android:text="Work Completion"
android:onClick="onGol"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
A: Add all linearlayout in relativelayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:orientation="horizontal" >
And in linearlayout or button add android:layout_alignParentRight="true"
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="15dp"
android:background="@drawable/stitch_button"
android:text="@string/add" />
| |
doc_23528245
|
I'm able to create users (PFUser) ,login, and create custom objects just fine. I now would like to implement Roles and the role I have in mind will be called "admin".
The goal of creating this role is to know when a user is an admin so they have more access to things in the app. I read through the documentation but I did not understand it as much as I would have liked and I know roles are something you don't want to mess up.
So, these are my questions:
*
*How can I create a user role called "admin" from the Parse Dashboard? When I click on the "Role" tab, it asks me to create a new row and then I'm not sure what to do from there.
*How can I assign an already created user the role admin? Can I simply go into the dashboard and change the ACL there?
*How can I check if the role assigned to the current user is "admin" from iOS (Objective-C)?
Thank you so much for your help!
| |
doc_23528246
|
I noticed that the the java process had to do multiple rollback of messages back to the queue due to a network timeout issue while processing them on the day I faced the problem
I have attached the Spring MDP configuration below
<!-- WebSphere MQ Connection Factory -->
<bean id="mqConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName">
<value>${mq.wal.queue_hostname}</value>
</property>
<property name="port">
<value>${mq.wal.queue_port}</value>
</property>
<property name="queueManager">
<value>${mq.wal.queue_manager}</value>
</property>
<property name="transportType">
<!-- BINDING MODE -->
<value>${mq.wal.transport_type}</value>
</property>
</bean>
<!-- JMS Queue Connection Factory -->
<bean id="jmsQueueConnectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<ref bean="mqConnectionFactory" />
</property>
</bean>
<!-- IN queue -->
<bean id="in_queue" class="com.ibm.mq.jms.MQQueue"
depends-on="jmsQueueConnectionFactory">
<property name="baseQueueManagerName" value="${mq.queue_manager}" />
<property name="baseQueueName" value="${mq.inqueue}" />
</bean>
<!-- Error handler -->
<bean id="messageErrorHandler" class="coop.mm.wallet.access.service.MessagingErrorHandler"></bean>
<!-- End error handler -->
<!-- Listener containers for INBOUND Queues -->
<!-- listener container -->
<bean id="listener_container"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="jmsQueueConnectionFactory" />
<property name="destination" ref="in_queue" />
<property name="messageListener" ref="messageListener" />
<property name="sessionTransacted" value="true" />
<property name="concurrency" value="${listener_count}" />
<property name="errorHandler" ref="messageErrorHandler"/>
</bean>
| |
doc_23528247
|
class RunTest {
public static void main(String a[]) {
try {
String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
BufferedWriter out = new BufferedWriter(new FileWriter("test1.py"));
out.write(prg);
int number1 = 1;
int number2 = 2;
ProcessBuilder pb = new ProcessBuilder("python","test1.py",""+number1,""+number2);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int ret = new Integer(in.readLine()).intValue();
System.out.println("value is : "+ret);
} catch(Exception e) {
e.printStackTrace();
}
}
}
When I run this code (I'm using Eclipse), I get the stack trace:
java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at RunTest.main(RunTest.java:11)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 1 more
Anyone have any idea why and what I can do?
Thanks!
A: You have to flush() and you should close() (which will also flush()) after you write to the File.
out.write(prg);
out.close(); // <-- add this.
Also, you'll need to add python to your PATH.
A: Sorry, this is probably really unhelpful, but somehow, it just started working. No idea why or how, because I haven't changed anything. Eclipse basically just restarted itself randomly and now it works! Sorry I couldn't post a solution that will help others, but thanks anyway for your help @MadProgrammer and @Elliott !
| |
doc_23528248
|
private void makeMP4()
{
Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
saveFileDialog.Filter = "Media File (*.mp4)|*.mp4";
saveFileDialog.InitialDirectory = @"D:\temp\mp4output\";
saveFileDialog.FileName = myImageHandler.SuggestedFileName + ".mp4";
// If I remove the following line, memory usage is stable at 1GB. If I keep this line
// memory grows linearly until program terminates.
_ = saveFileDialog.ShowDialog();
// I also tried passing current window handle to ShowDialog (with same outcome):
//_ = saveFileDialog.ShowDialog(Application.Current.Windows.OfType<MainWindow>().FirstOrDefault());
MP4Maker mp4Maker = new(myImageHandler);
mp4Maker.GenerateMP4(@"D:\temp\mp4maker\hardcodedFileName.mp4");
}
As explained by the comments in the code above, if I call the ShowDialog method my applicaiton consumes too much memory while processing the mp4 file. But if I omit the call to ShowDialog, the memory usage is stable at about 1GB.
Two suggested solutions I've seen (and reasons they have not worked for me) are:
*
*Passing the current window (parent/owner) handle to the ShowDialog method (see my attempt to do this commented out in code above: This didn't change the memory usage.
*Using system.windows.forms.savefiledialog as an alternative to Microsoft.Win32.SaveFileDialog: I wasn't able to do this because I am using .Net5 (my understanding is that you can't refernce System.windows.forms from a .net5 application?)
Can anybody see why calls to ShowDialog are causing memory leakage and how to prevent it? Thank you.
A: After running the SaveFileDialog.ShowDialog you should try running
GC.Collect(); GC.WaitForPendingFinalizers();
Which should force .Net to clean up any memory relating to the previous calls before then calling the next routines.
| |
doc_23528249
|
For example - generate a random number from 1,2,4,5 (no 3 allowed).
A: You can create an array with all your predefined set into it, then you fill an integer index with a random number from 0 to the array's length. That should do the trick :)
| |
doc_23528250
|
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
$row = mysql_fetch_row($result); //gets the rows refering to the query
echo $row[0]; //returns the data in column 1
?>
In the code above, echo $row[0]; returns the data in the first column in the table, but how does it know which row to take this data from (assuming the query returns more than one row)?
Moreover, if I put the code in a loop:
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
for ($j = 0 ; $J < 4 ; ++$j)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
?>
The values echoed are the values in (row1,column1) (row2,column1,) (row3,column1). How does this work if the incremented value $j isnt directly affecting the mysql_fetch_row function??
A: It advances to the next row each time you call it, which is why it's typically used in a while loop
A: you nust have to add a "where" to your select:
for example:
$value="mozart";
$query = " SELECT * FROM classics where author='$value' ";
the sentence is: select all data from classics where the author is mozart
| |
doc_23528251
|
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
#!/usr/bin/python
#
# We have to tell python what stuff we're
# going to use. We do this by asking to import
# the code we'll be making use of
#
import curses
import random
import time
#
# We'll be using a screen handling
# package called "curses" so we need
# to initialise the screen
stdscr = curses.initscr()
# We need to make sure that
# keys we type will not show up
# on the screen spoiling the
# stuff we're drawing
curses.noecho()
# We need to tell curses that we don't
# want to wait when we ask for keys from
# the user, if there's non there then
# we want curses to carry on
stdscr.nodelay( True )
# This ones a bit tricky to explain.
# Basically it puts the keyboard into
# a mode which allows curses to do
# things with it...
curses.cbreak()
# Ok, now we can do the fun stuff
# First thing we need to do is to
# find out how big our screen is
max_y, max_x = stdscr.getmaxyx()
stdscr.box()
min_x = 1
min_y = 1
max_y = max_y - 2
max_x = max_x - 2
stdscr.addstr( min_y, min_x, "1" )
stdscr.addstr( min_y, max_x, "2" )
stdscr.addstr( max_y, min_x, "3" )
stdscr.addstr( max_y, max_x, "4" )
dir_x = 1
dir_y = 1
# Then we can pick a random point on the
# screen in both the y (up-down) and x
# (left-right) directions
y = random.randint( 0, max_y )
x = random.randint( 0, max_x )
# Ok, this basically says, while trying to
# get a key from the user keeps coming back
# with an error, meaning there aren't any keys
# to return, do the code inside the loop
while( stdscr.getch() == curses.ERR ):
# Ok, at the location we got, put a "0"
stdscr.addstr( y, x, "O" )
# stdscr.addstr( str( (y, x) ) )
# this just moves the cursor to a new location so we can see the "O" better
stdscr.move( 0, 0 )
# have the screen update
stdscr.refresh()
# now choose a new location
x = x + dir_x
y = y + dir_y
# have we gone too far
if x > max_x or x < min_x:
# change direction
dir_x = -dir_x
x = x + dir_x
if y > max_y or y < min_y:
# change direction
dir_y = -dir_y
y = y + dir_y
# wait a bit so we can see the screen we've drawn.
time.sleep( 0.05 )
# Ok, we're finished. Tidy up
curses.nocbreak()
stdscr.keypad( False )
curses.echo()
curses.endwin()
I ran the program and was quite pleased. However, when the ball hits the edge, it seems to "slide" and not bounce cleanly.
It's quite late in the evening so I couldn't get my head around it and I thought I'd throw it out there and see if anyone could explain why.
I'm not after fixing the code, I'm pretty sure that with <= or >= the tests would work. I just can't understand what it does what it does...
Thx
Mark.
A: You are figuring out a new x and y coordinate before you are testing. So, say the ball is at 20, 1 and is drawn, and assume the dir is North East with slope 1. The next position will be calculated at 21, 0. Here you see the y is out of range now. So you set it back to 1 when what you really want is 2, so you get a slide across the edge. Usually, what I do is test for the next conditions first, then add the new offsets. So...
if x + dir_x > max_x or x - dir_x < min_x:
A: You need to add twice dir_* in the "change direction" code.
A: Getting this kind of simulation to work properly at the edges is tricky. I ran it here and it looks nice to me (OS X). When it hits the edge you'll get two O's in a row at the edge but then it comes back. At a guess, this has to do with how far your virtual x,y point has to penetrate before reversal happens, which depends on how fast it's moving.
A: Took me a while to work out what you're meaning. You mean the double 'OO' on the wall when it changes direction? Seems to me the conditional allows the ball to go over (not up to) the line and then pulls it back again. I changed this bit:
# have we gone too far
if x >= max_x or x <= min_x:
# change direction
dir_x = -dir_x
#x = x + dir_x
if y >= max_y or y <= min_y:
# change direction
dir_y = -dir_y
#y = y + dir_y
(Note I changed > to >= and same with < and I also commented out the second increment - if you catch it on the line you don't need it.)
Nice little example by the way.
A: Not really too familiar with python, but is
dir_x = -dir_x
Acceptable? Maybe try
dir_x *= -1
or
dir_x = dir_x * -1
?
| |
doc_23528252
|
In my application I am getting the audio file path from the server. Now when the user clicks on listen button in my app, then I have to play that audio file.
For example: http://traffic.libsyn.com/wpradio/WPRadio_29.mp3
What are the different ways to play the above audio file.
Thanks
A: If I were you I wouldn't do that with MediaElemnt - it will work, but not in Background - question here.
Much better option is to play it with Background Audio and AudioStreamingAgent. Here you have one blog where you can find usefull information. There are also many examples.
A: Yes you can play it with MediaElement.
You must have audio uri path.
MediaElement remotePlayer= new MediaElement();
remotePlayer.AutoPlay=true;
//FileName is your remote uri
remotePlayer.Source = new Uri(FileName, UriKind.Absolute);
remotePlayer.Play();
| |
doc_23528253
|
Right now I have a solution that is basically getting each frame of output, filtering it, setting that output image to an @Published property and then displaying that in a Metal view, but I don't really understand what's going on with Metal, and I'm sure there's a faster way than doing this through an @Published property.
What I have now is working, but I assume it's very inefficient and not taking advantage of Metal.
tl;dr: What's the most efficient way to make a AVCaptureVideoPreviewLayer equivalent but add filters to the live preview as it's happening?
A: I think this is the most effective way.
Core Image (in its default config) uses Metal to perform the image filtering operations on the GPU. An MTKView is meant to be used for displaying results of a Metal pipeline, so that fits.
As for the @Published property: I think it doesn't really matter how the pixel buffers are propagated to your filter chain and ultimately to the view as long as the method doesn't add too much overhead. Using Combine should be totally fine.
There is, unfortunately, no convenient way for applying CIFilters to the camera feed as there is for video playback and export (using AVVideoComposition).
| |
doc_23528254
|
Here is a reproducible example of what I want to achieve:
mat = rbinom(n=1000, size=1, prob=0.8)
dim(mat) = c(200, 5)
umat = unique(mat)
idVec = numeric(nrow(mat))
for(i in seq_len(nrow(umat))){
for(j in seq_len(nrow(mat))){
if(isTRUE(all.equal(mat[j,], umat[i,]))){
idVec[j] = i
}
}
}
cbind(idVec, mat)
table(idVec)
Actually this function http://www.stat.washington.edu/~rje42/lca/html/group.html would just be perfect. However, it's not on CRAN, no source code, and was built prior to R 3.0.0.
Thank's for your help!
A: I reduced your example mat a bit for better handling:
mat = rbinom(n=100, size=1, prob=0.8)
dim(mat) = c(20, 5)
Now you can create the idVec like this (assuming you don't care about the actual numbers, just the correct "mapping"):
idVec <- as.integer(factor(apply(mat, 1, toString)))
And of course you can add it or create the table:
> cbind(idVec, mat)
idVec
[1,] 6 1 1 1 1 1
[2,] 5 1 1 1 1 0
[3,] 6 1 1 1 1 1
[4,] 5 1 1 1 1 0
[5,] 1 0 1 1 0 1
[6,] 2 0 1 1 1 1
[7,] 6 1 1 1 1 1
[8,] 6 1 1 1 1 1
[9,] 6 1 1 1 1 1
[10,] 5 1 1 1 1 0
[11,] 4 1 0 1 1 1
[12,] 5 1 1 1 1 0
[13,] 6 1 1 1 1 1
[14,] 4 1 0 1 1 1
[15,] 3 1 0 1 0 0
[16,] 1 0 1 1 0 1
[17,] 6 1 1 1 1 1
[18,] 6 1 1 1 1 1
[19,] 6 1 1 1 1 1
[20,] 2 0 1 1 1 1
> table(idVec)
idVec
1 2 3 4 5 6
2 2 1 2 4 9
| |
doc_23528255
|
I am using double pointer to do this, here is the code which works fine,
//Example # 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myalloc( char ** ptr)
{
*ptr = malloc(255);
strcpy( *ptr, "Hello World");
}
int main()
{
char *ptr = 0;
myalloc( &ptr );
printf("String is %s\n", ptr);
free(ptr);
return 0;
}
But following code does not work and gives segmentation fault.
I think this is another way to use double pointers.
//Example # 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myalloc( char ** ptr)
{
*ptr = malloc(255);
strcpy( *ptr, "Hello World");
}
int main()
{
char **ptr = 0;
myalloc( ptr );
printf("String is %s\n", *ptr);
free(*ptr);
return 0;
}
Please clarify me, why it is giving me seg fault in second example.
Note: Language = C, Compiler = GCC 4.5.1, OS = Fedora Core 14
Also, i know that there are some question already been asked related to memory allocation using double pointers, but they don't address this issue, so please don't flag it as repetitive question.
A: char **ptr = 0;
*ptr = malloc(255);
tries to write the pointer returned by malloc to the address(of type char*) pointed to by ptr. The address turns out to be ... 0, which is not writable memory.
ptr should point to an address you can write to. You can do one of the following:
char *stackPtr; // Pointer on the stack, value irrelevant (gets overwritten)
ptr = &stackPtr;
// or
char **ptr = alloca(sizeof(char*)); // Equivalent to above
// or
char **ptr = malloc(sizeof(char*)); // Allocate memory on the heap
// note that ptr can be 0 if heap allocation fails
A: char **ptr = 0;
foo( ptr );
You are passing the value that ptr points to. But you havent pointed ptr to anything yet.
*ptr = malloc(255);
Now you are assigning some memory to that "nothing". So this wont work, and will segfault.
Why are you saying that this is another way of using double pointers? I apologise if I am wrong, but I guess you worked with type of program in Turbo-C earlier?
A: In the second case, you are passing the value of main's ptr, which is 0 (NULL), to myalloc()'s ptr. myalloc() then tries to dereference its null pointer, ptr.
| |
doc_23528256
|
Used JVM:
java.vm.name=IBM J9 VM
java.vm.specification.name=Java Virtual Machine Specification
java.vm.specification.vendor=Oracle Corporation
java.vm.specification.version=1.8
java.vm.vendor=IBM Corporation
java.vm.version=2.8
stack trace:
java.lang.IllegalStateException: Fail to request https://sonarserver/api/system/status
at org.sonarsource.sonarlint.core.util.ws.HttpConnector.doCall(HttpConnector.java:179)
at org.sonarsource.sonarlint.core.util.ws.HttpConnector.get(HttpConnector.java:111)
at org.sonarsource.sonarlint.core.util.ws.HttpConnector.call(HttpConnector.java:100)
at org.sonarsource.sonarlint.core.container.connected.SonarLintWsClient.rawGet(SonarLintWsClient.java:112)
at org.sonarsource.sonarlint.core.container.connected.validate.ServerVersionAndStatusChecker.fetchServerInfos(ServerVersionAndStatusChecker.java:97)
at org.sonarsource.sonarlint.core.container.connected.validate.ServerVersionAndStatusChecker.checkVersionAndStatus(ServerVersionAndStatusChecker.java:61)
at org.sonarsource.sonarlint.core.container.connected.validate.ServerVersionAndStatusChecker.checkVersionAndStatus(ServerVersionAndStatusChecker.java:51)
at org.sonarsource.sonarlint.core.container.connected.update.perform.GlobalStorageUpdateExecutor.update(GlobalStorageUpdateExecutor.java:76)
at org.sonarsource.sonarlint.core.container.connected.ConnectedContainer.update(ConnectedContainer.java:109)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.lambda$null$1(ConnectedSonarLintEngineImpl.java:178)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl$$Lambda$230.000000002247FC40.apply(Unknown Source)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.runInConnectedContainer(ConnectedSonarLintEngineImpl.java:305)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.lambda$update$2(ConnectedSonarLintEngineImpl.java:178)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl$$Lambda$229.00000000222B2D20.get(Unknown Source)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.withRwLock(ConnectedSonarLintEngineImpl.java:319)
at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.update(ConnectedSonarLintEngineImpl.java:173)
at org.sonarlint.eclipse.core.internal.server.Server.updateStorage(Server.java:289)
at org.sonarlint.eclipse.core.internal.jobs.ServerUpdateJob.run(ServerUpdateJob.java:47)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:220)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at com.ibm.jsse2.a.a(a.java:134)
at com.ibm.jsse2.a.a(a.java:219)
at com.ibm.jsse2.as.a(as.java:648)
at com.ibm.jsse2.as.i(as.java:895)
at com.ibm.jsse2.as.a(as.java:283)
at com.ibm.jsse2.as.startHandshake(as.java:115)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:268)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:238)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:149)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:192)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
at okhttp3.RealCall.execute(RealCall.java:69)
at org.sonarsource.sonarlint.core.util.ws.HttpConnector.doCall(HttpConnector.java:176)
... 18 more
If I use oracle JVM (1.8 / 25.144-b01) to start eclipse everything works fine but I need to use IBM J9 VM.
javax.net.ssl.trustStore / javax.net.ssl.trustStorePassword entries in eclipse.ini seem to work different in these JVMs. I already compared java.security-files. Hope someone has any suggestions.
A: A workmate of mine fixed the problem. The ssl_protocols and ssl_ciphers configuration of nginx server was to strict IBM JVM... "intermediate configuration" need to be used.
helpful link: https://mozilla.github.io/server-side-tls/ssl-config-generator/
| |
doc_23528257
|
My code
$mails = file('blacklist.txt');
$email = "hendrik@anonbox.net";
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) > 0) {
$fail = true;
}
}
if($fail) {
echo "Fail";
} else {
echo "you can use that";
}
The blacklist.txt can be found here http://pastebin.com/aJyVkcNx.
I would expect strpos return a position for at least one string in the blacklist, but it does not. I am guessing that somehow I am generating not the kind of values within the $mails as I am expecting.
EDIT this is print_r($mails) http://pastebin.com/83ZqVwHx
EDIT2 some clarification: I want to see if a domain is within an email, even if the mail contains subdomain.domain.tld. And I tried to use !== false instead of my > 0 which yielded the same result.
A: strpos returns FALSE if the string was not found.'
Simply use this :
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) === false) {
$fail = true;
}
}
Or even better use this:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik@anonbox.net";
if(strpos($email, $blacklist) === false){
echo "fail";
} else {
echo "This email is not blacklisted";
}
A: Though you might still use foreach, that’s array reduce pattern:
function check_against($carry, $mail, $blacklisted) {
return $carry ||= strpos($mail, $blacklisted) !== false;
};
var_dump(array_reduce($mails, "check_against", $email_to_check));
Hope it helps.
A: You have found the common pitfall with the strpos function. The return value of the strpos function refers to the position at which it found the string. In this instance, if the string begins at the first character, it will return 0. Note that 0 !== false.
The correct way to use the function is:
if(strpos($email, $mail) !== false){
// the string was found, potentially at position 0
}
However, this function may not be necessary at all; if you are simply checking if $mail is the same as $email, instead of seeing if the string exists within a larger string, then just use:
if($mail == $email){
// they are the same
}
A: You need to parse the email well since you're checking the domain of the email address if its inside the blacklist. Example:
$email = "hendrik@foo.anonbox.net";
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
preg_match('/@.*?([^.]+[.]\w{3}|[^.])$/', $email, $matches);
if(!empty($matches) && isset($matches[1])) {
$domain = $matches[1];
} else {
// not good email
exit;
}
// THIS IS FOR SAMPLES SAKE, i know youre using file()
$blacklist = explode("\n", file_get_contents('http://pastebin.com/raw.php?i=aJyVkcNx'));
foreach($blacklist as $email) {
if(stripos($email, $domain) !== false) {
echo 'you are blacklisted';
exit;
}
}
}
// his/her email is ok continue
A: Yet another way to solve this. Works fine:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik@x.ip6.li";
$domain = substr(trim($email), strpos($email, '@')+1);
if(strpos($blacklist, $domain)){
echo "Your email has been blacklisted!";
}else{
echo "You are all good to go! not blacklisted :-)";
}
Goodluck!
| |
doc_23528258
|
class Track{
static belongsTo = [createdBy: User, modifiedBy: User, Course]
}
But its giving me error, Finally i dont want to have course object[course: Course] but only have to specify that it belongs to Course [Course]. How to do this
A: I think you are using the GORM associations a bit too extensively. belongsTo indicates ownership, and the GORM associations, in general, indicate more about the cascading relationship between objects than anything else.
If you only want to associate User with your Track, you just need to have the createdBy and modifiedBy fields, which don't need to be in any special sort of association. Then you would have static belongsTo = [Course] to show that the Course owns the Track, meaning that if you deleted the Course, that the Track would get deleted as well.
Here's the class I think you are looking for:
class Track {
User createdBy
User modifiedBy
static belongsTo = [Course]
}
| |
doc_23528259
|
A: inline fun Context.withNetwork(isToNotify: Boolean = true, block: () -> Unit) {
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
connectivityManager?.let {
val netInfo = it.activeNetworkInfo
val isConnected = netInfo != null && netInfo.isConnectedOrConnecting
if (isToNotify && !isConnected){
toast(R.string.message_no_network_message)
//Use Here Intent For Another Activity
}else{
block()
}
}
}
| |
doc_23528260
|
Here's the blue highlighted line from logcat at com.example.chemicalequationbalancer.HelpGuide.onCreate(HelpGuide.java:37)
Here's line 37 navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { followed by the code of the same activity added below:
The HelpGuide.java class imports: (Most of my classes extend AppCompatActivity)
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import mehdi.sakout.aboutpage.AboutPage;
import mehdi.sakout.aboutpage.BuildConfig;
import mehdi.sakout.aboutpage.Element;
The BottomNavigationView code in the activity:
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.nav_bottom);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent a = new Intent(AboutUs.this, MainActivity.class);
startActivity(a);
break;
case R.id.nav_aboutus:
break;
case R.id.nav_help:
Intent b = new Intent(AboutUs.this, HelpGuide.class);
startActivity(b);
break;
}
return false;
}
});
ActivityMainfest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ChemicalEquationBalancer">
<activity android:name="com.example.chemicalequationbalancer.AboutUs" android:theme="@style/Theme.ChemicalEquationBalancer.NoActionBar"/>
<activity android:name="com.example.chemicalequationbalancer.HelpGuide" android:theme="@style/Theme.ChemicalEquationBalancer.NoActionBar"/>
<activity android:name="com.example.chemicalequationbalancer.eleView" android:theme="@style/Theme.ChemicalEquationBalancer.NoActionBar"/>
<activity
android:name="com.example.chemicalequationbalancer.MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.ChemicalEquationBalancer.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Logcat:
2021-02-17 18:19:13.303 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: >>> msg'1s executing time is too long
2021-02-17 18:19:13.303 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Blocked msg = { when=-2s884ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@ec0d4dc } , cost = 1542 ms
2021-02-17 18:19:13.303 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: >>>Current msg List is:
2021-02-17 18:19:13.304 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <1> = { when=-2s883ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@ec0d4dc }
2021-02-17 18:19:13.304 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <2> = { when=-2s882ms what=0 target=android.app.ActivityThread$H callback=com.android.internal.util.function.pooled.PooledLambdaImpl }
2021-02-17 18:19:13.305 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <3> = { when=-2s882ms what=149 target=android.app.ActivityThread$H obj=android.os.BinderProxy@ec0d4dc }
2021-02-17 18:19:13.306 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <4> = { when=-2s403ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@ec0d4dc }
2021-02-17 18:19:13.306 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <5> = { when=-2s403ms what=137 target=android.app.ActivityThread$H arg1=1 obj=android.os.BinderProxy@ec0d4dc }
2021-02-17 18:19:13.307 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <6> = { when=-1s126ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 }
2021-02-17 18:19:13.307 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <7> = { when=-390ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 }
2021-02-17 18:19:13.308 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <8> = { when=-382ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 }
2021-02-17 18:19:13.308 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <9> = { when=-332ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 }
2021-02-17 18:19:13.309 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: Current msg <10> = { when=-325ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 }
2021-02-17 18:19:13.309 20042-20042/com.example.chemicalequationbalancer E/ANR_LOG: >>>CURRENT MSG DUMP OVER<<<
2021-02-17 18:19:13.329 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.389 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.449 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.510 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.533 20042-20217/com.example.chemicalequationbalancer E/GED: Failed to get GED Log Buf, err(0)
2021-02-17 18:19:13.571 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.610 681-681/? E/Situation: processEvent, handle:26, flush_action:0
2021-02-17 18:19:13.611 681-681/? E/libc: Access denied finding property "ro.build.flavor"
2021-02-17 18:19:13.632 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.691 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.737 20042-20217/com.example.chemicalequationbalancer E/ion: ioctl c0044901 failed with code -1: Invalid argument
2021-02-17 18:19:13.738 20042-20217/com.example.chemicalequationbalancer E/GED: Failed to get GED Log Buf, err(0)
2021-02-17 18:19:13.739 1192-1503/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
2021-02-17 18:19:13.749 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.811 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.871 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.930 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:13.938 739-817/? E/facereg_hal: do_identify failed FACE_ERROR_CANCELLED
2021-02-17 18:19:13.989 686-20185/? E/MDP: DpIspStream::waitComplete m_DREPABufferStartIndexList empty
2021-02-17 18:19:14.030 1192-2967/? E/PowerHalWrapper: <amsBoostStop> duration: 6000ms
2021-02-17 18:19:14.077 681-1296/? E/SensorContext: activate, handle = 4, index = 3
2021-02-17 18:19:14.143 681-1296/? E/SensorContext: activate, handle = 3, index = 2
2021-02-17 18:19:14.178 681-681/? E/SensorContext: activate, handle = 3, index = 2
2021-02-17 18:19:14.179 681-681/? E/SensorContext: activate, handle = 1, index = 1
2021-02-17 18:19:14.184 681-681/? E/SensorContext: activate, handle = 0, index = 0
2021-02-17 18:19:14.189 681-681/? E/SensorContext: activate, handle = 0, index = 0
2021-02-17 18:19:14.360 1192-2967/? E/Process: get_ion_cache_memory: Unable to open /d/ion/heaps/system
2021-02-17 18:19:16.568 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.590 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.606 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.638 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.721 741-741/? E/CryptoEngInvokeCommand: crypto_eng_invoke_command set pms flag
2021-02-17 18:19:16.742 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.782 1192-1292/? E/DisplayEventDispatcher: dispatcher 0x7af60b7be0 ~ last event processed while scheduling was for 26200050
2021-02-17 18:19:16.799 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.801 2512-3009/? E/neodaemon: ERROR elsaNotifyAppSwitch is NULL
2021-02-17 18:19:16.804 741-741/? E/cryptoeng_hidl: commondcs service exist.
2021-02-17 18:19:16.843 1192-3201/? E/OifaceUtil: Cannot connect to OifaceService
2021-02-17 18:19:16.846 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.854 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.858 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.860 1825-1825/? E/OppoTelephonyFunction: leon operatorNumic is not included in our romupdate xml file
2021-02-17 18:19:16.861 1825-1825/? E/m.android.phon: Invalid ID 0x00000000.
2021-02-17 18:19:16.865 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.881 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.892 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.900 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.912 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:16.950 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.001 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.016 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.039 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.045 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.078 19888-19970/? E/GED: Failed to get GED Log Buf, err(0)
2021-02-17 18:19:17.087 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.110 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.123 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.155 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.173 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.177 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.216 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.248 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.252 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.252 4823-17448/? E/CheckPermission: _bluetooth code = 14
2021-02-17 18:19:17.263 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.270 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.333 1192-1338/? E/WifiScanRequestProxy: Scan failure received. reason: -1,description: not available
2021-02-17 18:19:17.342 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:17.350 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.452 19888-19888/? E/DisplayEventDispatcher: dispatcher 0x7b0181d280 ~ last event processed while scheduling was for 26201742
2021-02-17 18:19:18.472 19982-19985/? E/adbd: remote usb: read terminated (message): No such device
2021-02-17 18:19:18.568 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.617 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.622 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.636 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.643 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.645 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.647 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.924 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.933 1192-1215/? E/NotificationService: Suppressing notification from package by user request.
2021-02-17 18:19:18.965 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.969 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.972 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.976 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:18.980 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:19.071 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:19.074 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:19.076 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:19.080 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:20.163 20042-20217/com.example.chemicalequationbalancer E/GED: Failed to get GED Log Buf, err(0)
2021-02-17 18:19:19.098 1192-1215/? E/NotificationService: Suppressing notification from package by user request.
2021-02-17 18:19:22.995 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.051 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.054 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.068 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.121 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.304 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.307 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.317 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.326 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.329 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:23.450 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:24.339 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:24.343 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:26.124 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:26.179 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:27.598 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:27.864 681-1296/? E/Situation: processEvent, handle:26, flush_action:0
2021-02-17 18:19:27.864 681-1296/? E/libc: Access denied finding property "ro.build.flavor"
2021-02-17 18:19:30.293 9892-9904/? E/rutils: releaseProcess gCount = 1
2021-02-17 18:19:31.407 2512-3009/? E/neodaemon: ERROR elsaResume is NULL
2021-02-17 18:19:31.480 1192-3201/? E/OifaceUtil: Cannot connect to OifaceService
2021-02-17 18:19:31.490 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:31.493 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:31.766 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.100 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.130 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.148 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.222 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.345 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:32.367 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:33.032 1192-3236/? E/OifaceUtil: Cannot connect to OifaceService
2021-02-17 18:19:33.038 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:33.139 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:33.365 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:34.393 2512-3009/? E/neodaemon: ERROR elsaResume is NULL
2021-02-17 18:19:34.433 1192-3211/? E/OifaceUtil: Cannot connect to OifaceService
2021-02-17 18:19:34.442 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:34.446 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:34.505 20042-20042/com.example.chemicalequationbalancer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chemicalequationbalancer, PID: 20042
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chemicalequationbalancer/com.example.chemicalequationbalancer.HelpGuide}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3197)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7191)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference
at com.example.chemicalequationbalancer.HelpGuide.onCreate(HelpGuide.java:37)
at android.app.Activity.performCreate(Activity.java:7376)
at android.app.Activity.performCreate(Activity.java:7367)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3177)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7191)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
2021-02-17 18:19:34.591 1192-1321/? E/InputDispatcher: channel 'a589010 com.example.chemicalequationbalancer/com.example.chemicalequationbalancer.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2021-02-17 18:19:34.630 2512-3009/? E/neodaemon: ERROR elsaNotifyAppSwitch is NULL
2021-02-17 18:19:34.645 1192-2916/? E/OifaceUtil: Cannot connect to OifaceService
2021-02-17 18:19:34.651 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
2021-02-17 18:19:34.662 2512-3009/? E/neodaemon: ERROR elsaGetPackageFreezing is NULL
Please ask for any extra file or piece of code needed!
Thanks once again!
EDIT: Logcat added
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/nav_bottom"
android:layout_alignParentBottom="true"
app:itemTextColor="@android:color/black"
app:menu="@menu/drawer_view" />
The menu drawer xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Home"
android:id="@+id/nav_home"
android:icon="@drawable/ic_baseline_home"/>
<item android:title="About Us"
android:id="@+id/nav_aboutus"
android:icon="@drawable/ic_baseline_abus"/>
<item android:title="Help"
android:id="@+id/nav_help"
android:icon="@drawable/ic_baseline_help"/>
This menu does appear on the main activity. Just when I click on the HelpGuide activity or the other activity which also uses this navbar, the app crashes.
HelpGuide.java:
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import mehdi.sakout.aboutpage.AboutPage;
import mehdi.sakout.aboutpage.BuildConfig;
import mehdi.sakout.aboutpage.Element;
public class HelpGuide extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Element developersElement = new Element();
developersElement.setTitle("Help Guide");
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.nav_bottom);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent a = new Intent(HelpGuide.this, MainActivity.class);
startActivity(a);
break;
case R.id.nav_aboutus:
Intent b = new Intent(HelpGuide.this, AboutUs.class);
startActivity(b);
break;
case R.id.nav_help:
break;
}
return false;
}
});
AboutPage aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.mipmap.ic_launcher)
.setDescription(getString(R.string.helpguide));
View aboutPageView = aboutPage.create();
}
}
A: Actually your helpguide activity dont have the reference of xml file and you have to set content view in activity like below.
public class HelpGuide extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlhelpguide); <----- here is the solution
Element developersElement = new Element();
developersElement.setTitle("Help Guide");
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.nav_bottom);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent a = new Intent(HelpGuide.this, MainActivity.class);
startActivity(a);
break;
case R.id.nav_aboutus:
Intent b = new Intent(HelpGuide.this, AboutUs.class);
startActivity(b);
break;
case R.id.nav_help:
break;
}
return false;
}
});
AboutPage aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.mipmap.ic_launcher)
.setDescription(getString(R.string.helpguide));
View aboutPageView = aboutPage.create();
}
}
and add your bottom navigation view in help guide xml view.
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/nav_bottom"
android:layout_alignParentBottom="true"
app:itemTextColor="@android:color/black"
app:menu="@menu/drawer_view" />
| |
doc_23528261
|
Expected to decode Double but found a string/data instead.
class MyClass : Codable {
var decimal: Decimal?
}
then trying to parse it
let json = "{\"decimal\":\"0.007\"}"
let data = json.data(using: .utf8)
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "s1", negativeInfinity: "s2", nan: "s3")
do {
let t = try decoder.decode(MyClass.self, from: data!)
} catch {
print(error)
}
If I change json string as
let json = "{\"decimal\":0.007}"
It works, but then again we are losing precision. Any ideas?
A: You would need to extend KeyedDecodingContainer and add an implementation for Decimal.Type.
extension KeyedDecodingContainer {
func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal {
let stringValue = try decode(String.self, forKey: key)
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
}
Here is an example:
let json = """
{
"capAmount": "123.45"
}
"""
struct Status: Decodable {
let capAmount: Decimal
enum CodingKeys: String, CodingKey {
case capAmount
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
capAmount = try container.decode(Decimal.self, forKey: .capAmount)
}
}
// Execute it
if let data = json.data(using: .utf8){
let status = try JSONDecoder().decode(Status.self, from: data)
print(status.capAmount)
}
A: struct Root: Codable {
let decimal: Decimal
}
extension Root {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
decimal = try Decimal(string: container.decode(String.self, forKey: .decimal)) ?? .zero
}
}
let json = #"{"decimal":"0.007"}"#
do {
let root = try JSONDecoder().decode(Root.self, from: .init(json.utf8))
print(root)
} catch {
print(error)
}
This will print
Root(decimal: 0.007)
A: I just add the following code.
It supports optional as well.
extension KeyedDecodingContainer {
func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal {
let stringValue = try decode(String.self, forKey: key)
guard let decimalValue = Decimal(string: stringValue) else {
let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
throw DecodingError.typeMismatch(type, context)
}
return decimalValue
}
func decodeIfPresent(_ type: Decimal.Type, forKey key: K) throws -> Decimal? {
guard
let stringValue = try? decodeIfPresent(String.self, forKey: key),
let decimalValue = Decimal(string: stringValue)
else { return nil }
return decimalValue
}
}
A: That decoding strategy has nothing to do with numbers being represented as strings. What you need to do is to implement init(from:) and convert from string there
class MyClass : Codable {
var decimal: Double?
enum CodingKeys: String, CodingKey {
case decimal = "test"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
decimal = Double(try container.decode(String.self, forKey: .decimal)
//or if Decimal is used:
//decimal = Decimal(string: try container.decode(String.self, forKey: .decimal)
}
}
Note that I am using Double instead of Decimal here to make it simpler
A: I believe that a cleaner solution is declare value not like a string but like a value:
"test": 0.007
having a struct like that:
struct Stuff {
var test: Decimal
}
and then:
let decoder = JSONDecoder()
let stuff = try decoder.decode(Stuff.self, from: json)
otherwise you can use this example:
https://forums.swift.org/t/parsing-decimal-values-from-json/6906/3
A: The type should be Double and define also in the parsing as Double. Swift will figure out the rest
struct MyClass: Decodable {
let decimal: Double
//can be renamed to follow the API name.
enum CodingKeys: String, CodingKey {
case decimal
}
}
extension MyClass {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
decimal = try values.decode(Double.self, forKey: .decimal)
}
}
| |
doc_23528262
|
I am writing an application that makes heavy use of numbers with higher precision than allowed by the ECMAScript native Number type. So I need to use a custom type (currently BigNumber) to represent those values.
I am looking hungrily at the proposed BigInt type, which when implemented as standard will be an improvement for many applications including the one I'm writing. However that won't help at all with JSON, which knows nothing about BigInt any more than BigNumber.
Whichever custom type I choose, there are many values of this type throughout the application state. So much that it's worth considering a custom hook in the serialisation / deserialisation layer that will handle transforming it to / from JSON.
Presumably the JSON document will have to represent the values as JSON native types (e.g. Object or String instances). How then, when de-serialising the entire complex application state, to reliably recognise and de-serialise those instances among all the others, to the correct value of the correct BigInt or BigNumber type?
How can I serialise that state, such that any BigNumber (or insert some other arbitrary-precision number type) value reliably survives the serialisation / de-serialisation process, to correct values of the correct type?
A: If modifying the type (by adding a property to the prototype) is feasible, there is a toJSON hook from JSON.stringify, designed specifically to help custom types collaborate with JSON serialisation.
If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.
So you could add a new method to the BigNumber class:
BigNumber.prototype.toJSON = function toJSON(key) {
return {
_type: 'BigNumber',
_data: Object.assign({}, this),
};
};
state = {
lorem: true,
ipsum: "Consecteur non dibale",
dolor: new BigNumber(107.58),
sit: { spam: 5, eggs: 6, beans: 7 },
amet: false,
};
serialisedState = JSON.stringify(state);
console.debug("serialisedState:", serialisedState);
// → '{"lorem":true,"ipsum":"Consecteur non dibale","dolor":{"_type":"BigNumber","_data":{"s":1,"e":2,"c":[1,0,7,5,8]}},"sit":{"spam":5,"eggs":6,"beans":7},"amet":false}'
You can then recognise those specific objects when de-serialising, using the reviver parameter of JSON.parse:
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. [If the return value is not undefined], the property is redefined to be the return value.
function reviveFromJSON(key, value) {
let result = value;
if (
(typeof value === 'object' && value !== null)
&& (value.hasOwnProperty('_type'))) {
switch (value._type) {
case 'BigNumber':
result = Object.assign(new BigNumber(0), value._data);
}
}
return result;
}
state = JSON.parse(serialisedState, reviveFromJSON);
console.debug("state:", state);
// → { … dolor: BigNumber { s: 1, e: 2, c: [ 1, 0, 7, 5, 8 ] }, … }
A: One potential solution is the Granola library for Node.js.
granola provides a JSON compatible stringifier and parser with support for modern language and object primitives.
This would require:
*
*Convert the application from using BigNumber values to BigInt values.
*Wait for tools to support BigInt in the entire build tool chain.
| |
doc_23528263
|
"java.io.FileNotFoundException: dbfs:/df_xl.xlsx"
path= 'abfss://raw@tkm.dfs.core.windows.net/db_folder/'
df1.to_excel('df_xl.xlsx',sheet_name='Sheet1',index=False)
dbutils.fs.cp('dbfs:/df_xl.xlsx', path + 'output')
If i do the same thing with csv it is working perfectly.
Can you please help me with thi?
| |
doc_23528264
|
I would like to encrypt the production file with a password and a staging file with an other password to avoid other teams having access to production secrets.
Is it possible to do that ?
I have done something like that. My secrets :
cat /group_vars/all/vault_production.yml (encrypt with password A)
production_password: 'test1'
cat/group_vars/all/vault_staging.yml (encrypt with password B)
staging_password: 'test2'
My environments :
cat hosts-production
[all:vars]
env_type=production
cat hosts-staging
[all:vars]
env_type=staging
My script :
- copy:
content: |
env PASS={{hostvars[inventory_hostname][env_type + '_password']}}
...
And I launch the playbook like that.
# for production
ansible-playbook -i hosts-staging test.yml --vault-password-file .password_a
# for staging
ansible-playbook -i hosts-staging test.yml --vault-password-file .password_b
But that doesn't work because there is 2 differents passwords (ERROR! Decryption failed).
Do you know how to do that ?
Thanks.
BR,
Eric
A: Multiple vault passwords are supported since Ansible 2.4:
ansible-playbook --vault-id dev@dev-password --vault-id prod@prompt site.yml
If multiple vault passwords are provided, by default Ansible will attempt to decrypt vault content by trying each vault secret in the order they were provided on the command line.
In the above case, the ‘dev’ password will be tried first, then the ‘prod’ password for cases where Ansible doesn’t know which vault id is used to encrypt something.
A: Sorry, only one vault password allowed per run today. Best way to work around this in the case where you really only need one or the other is to dynamically load a vaulted file based on a var; eg:
- hosts: localhost
vars_files:
- secretstuff-{{ env_type }}.yml
tasks:
...
or
- hosts: localhost
tasks:
- include_vars: secretstuff-{{ env_type }}.yml
...
depending on if you need the vars to survive for one play or the entire run (the latter will bring them in as facts instead of play vars).
| |
doc_23528265
|
I have created an ubuntu:14.04 docker container and I have installed the Visual C++ for Linux dependencies in the container, namely openssh-server, g++, gdb and gdbserver. I have committed the container, creating an image to work with. I think I now need to run the container opening up a port so that I can connect to the container from Visual Studio.
How is this done? Does the container need to be further set up so that there is some kind of handler to handle communication on the port which is going to be opened? For instance does Bash need to be assigned to handle communication over the port? Or does one of the dependencies, perhaps openssh-server, need to be assigned to handle communication over the port? Or was something set up when I installed the dependencies? If so on which port?
In the Visual C++ for Linux Development instructions it shows that credentials such as Host name, Port, User name, Authentication type, and Password can be provided when connecting to a VM. Naturally Port will be required but will the others be required? If so do these credentials need to be set in the Ubuntu container or discovered somehow? If so how?
A: you can use this docker image ducatel/visual-studio-linux-build-box with a VM (like in the readme) or with docker for windows
| |
doc_23528266
|
A: For more efficient way to merge multiple files, you may try it in bash (if you are using Linux / macOS).
cat *.pb name.proto > your_merged_file
For Windows systems, you can do this in cmd:
type *.pb name.proto > your_merged_file
| |
doc_23528267
| ||
doc_23528268
|
I am currently using this function:
SELECT ...
case when FLAG1 is null then upper(FLAG2) else FLAG1 END as STATUS,
...;
The UPPER() function however renders all my FLAG2 words to be fully capitalized. Anyone know how to capitalize the first letter of words in Snowflake?
A: Use initcap() function, it returns the input string (expr) with the first letter of each word in uppercase and the subsequent letters in lowercase.
If you want only first letter in a string to be capitalized, ignoring word delimiters (i.e. the input expression is treated as a single, continuous word), specify empty string as delimiters parameter
INITCAP( str, '')
A: SELECT column1, IFF(column1, UPPER(SUBSTRING(column2,1,1)) || LOWER(SUBSTRING(column2,2)), column2)
FROM VALUES
(true,'all_lower'),
(true, 'ALL_UPPER'),
(true, 'mIxEd'),
(false,'all_lower'),
(false, 'ALL_UPPER'),
(false, 'mIxEd');
which can be unpacked a little to see the parts at work.
SELECT column1 as flag
,column2 as orig
,UPPER(SUBSTRING(column2,1,1)) || LOWER(SUBSTRING(column2,2)) as first_upper
,IFF(flag, first_upper, orig)
FROM VALUES
(true,'all_lower'),
(true, 'ALL_UPPER'),
(true, 'mIxEd'),
(false,'all_lower'),
(false, 'ALL_UPPER'),
(false, 'mIxEd');
which gives:
FLAG ORIG FIRST_UPPER IFF(FLAG, FIRST_UPPER, ORIG)
TRUE all_lower All_lower All_lower
TRUE ALL_UPPER All_upper All_upper
TRUE mIxEd Mixed Mixed
FALSE all_lower All_lower all_lower
FALSE ALL_UPPER All_upper ALL_UPPER
FALSE mIxEd Mixed mIxEd
| |
doc_23528269
|
here it is:
http://milosznowicki.ml/seedmed/
I've set it up on a server, now everything looks good in Firefox, but i have problems with chrome.
I'm trying to do a responsive svg with padding hack.
Also, here is fiddle for some of my svg containers (it seems to work fine in those browsers).
https://jsfiddle.net/4egzxsb9/4/
<div id='str' class='strategy container col-m8 col-s5'>
<div class='container three-rows col-s3 col-m3 row-12'>
<div class=' col-s6 col-m12 center'>
<div class='icon-2'>
<iframe class='if' src='https://image.flaticon.com/icons/svg/126/126472.svg'>
</iframe>
</div>
</div>
<p id='desc' class='description col-s6 col-m12'>
Endokrynologi
</p>
</div>
<div class='container three-rows col-s3 col-m3 row-12'>
<div class=' col-s6 col-m12 center'>
<div class='icon-2'>
<iframe class='if' src='https://image.flaticon.com/icons/svg/126/126472.svg'>
</iframe>
</div>
</div>
<p id='desc' class='description col-s6 col-m12'>
Ondoskopi
</p>
</div>
<div class='container three-rows col-s3 col-m3 row-12'>
<div class=' col-s6 col-m12 center'>
<div class='icon-2'>
<iframe class='if' src='https://image.flaticon.com/icons/svg/126/126472.svg'>
</iframe>
</div>
</div>
<p id='desc' class='description col-s6 col-m12'>
Weterynari
</p>
</div>
<div class='container three-rows col-s3 col-m3 row-12'>
<div class=' col-s6 col-m12 center'>
<div class='icon-2'>
<iframe class='if' src='https://image.flaticon.com/icons/svg/126/126472.svg'>
</iframe>
</div>
</div>
<p id='desc' class='description col-s6 col-m12'>
Onkologi
</p>
</div>
</div>
And here is my CSS :
@media (min-width:200px){
.col-s6{
flex-basis:50%
}
}
@media (min-width:768px){
.container{
flex-flow:row wrap;
}
.col-m12{
flex-basis:100%
}
#str{
flex-flow: nowrap;
}
#desc{
margin-top: 20px;
margin-left: 0;
}
}
.container{
display:flex;
flex-flow:column nowrap;
}
.icon-2{
width: 100px;
height: 100px;
position: relative;
padding-top: 100%;
}
.if{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border:none;
}
.three-rows{
justify-content: center;
}
.description{
text-align: center;
margin-top: 20px;
}
.center{
display: flex;
justify-content: center;
}
.strategy{
justify-content: center;
align-items: center;
}
#desc{
padding: 12px 0 12px 0;
}
| |
doc_23528270
|
time=60
from time import sleep
while (time>0):
print ("you have") (time) ("seconds left")
time-=1
sleep(1)
below is the result:
>>>
you have
Traceback (most recent call last):
File "H:\counter.py", line 4, in <module>
print ("you have") (time) ("seconds left")
TypeError: 'NoneType' object is not callable
Can anyone spot this error?
using %s has also failed me along with using +'s and str() around the time variable
A: A function can have only a single set of arguments.
print_statement = "you have" + str(time) + "seconds left"
print(print_statement)
The above code should work.
A: You are using the wrong syntax for the print function. Please note that print in python-3 is a callable. So when you call it, you can pass all that you need to be printed as parameters.
Hence
print ("you have", time, "seconds left")
is the correct syntax. You can optionally also specify a separator.
For posterity, TypeError: 'NoneType' object is not callable is an error thrown when you try to use an NoneType object as a callable. Python flagged out when it discovered that you had tried to pass time (an object) to print ("you have") which returns a NoneType object.
Remember, in python-3 print is a callable and it essentially returns a NullType object (which is nothing at all for that matter, and hence not callable).
| |
doc_23528271
|
but I'm using Google Spreadsheet. Even though it's not considered a "programming" topic, regex syntax it be the same.
I need to extract text between two tags. Eg:
START sample text END
When I apply this regex syntax everything works:
"START(.*)END"
But if the sample text contains a new line it does not. Any hints?
A: If you want to get rid off the new line character, one solution would be to replace the new line character with "", e.g:
=regexextract(regexreplace(A1, "\n", ""), "START (.+) END")
If you want to keep the new line character, you could try:
=regexextract(A1, "START (\w+\n\w+) END")
Alternatively if you want a solution that works with strings WITH and WITHOUT new line character, try:
=regexextract(A1, "START (\w+|\w+\n\w+) END")
| |
doc_23528272
|
How much is this different from ipfs and will it be possible to use them together?
A: The technical spec makes it sound as though it does not compete with IPFS, since everything seems to be done in the usual single-server-over-HTTP regime, which makes me think that it should be able to be used on top of IPFS instead with minimal pain. Really the decentralized part seems to be the access to the data, not the storage of the data itself, which is a key value-add for IPFS.
One unfortunate thing is that they have come up with their own version of IPLD called Linked Data, so I'm not sure how that would interface with IPFS's content addressing solution.
I expect the first place more answers will show up is this forum thread.
A: Solid and IPFS are compatible but have different trade offs.
Both systems are driven by URIs, and typically Solid will use http style URIs, but is it not limited to them. IPFS will use ipfs type URIs, which play nicely with linked data.
The advantage of ipfs URIs is that they are content addressable and therefore can be long lived, mirrored and findable on a P2P network without the need for DNS. The advantage of http URIs is that they have a large network effect, lots of tooling, and most devices are able to interact with them without extra installation.
Both teams collaborate in a friendly way and even share developers. Hopefully as IPFS grows in popularity both systems can offer more choice to end users as a way to store data. Solid apps will be able to benefit from both types of data, and even mix them together.
| |
doc_23528273
|
I don't want to use the Silvelright's screen navigation system.
I tried to programmatically create a PhotoCamera, VideoBrush and UIElementRenderer classes, the problem is that when I make a new UIElementRenderer I get a NullReferenceException error. I do the following:
UIElementRenderer slRender;
Grid element;
element = new Grid();
slRender = new UIElementRenderer(element, 800, 480);
Any idea on how to solve it? Thanks.
A: You will have to use the Silverlight interop layer to access the live camera feed. XNA doesn't support it directly.
| |
doc_23528274
|
Here is my code:
if (CGRectIsEmpty(self.bounds)) {
return nil;
}
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [[UIScreen mainScreen] scale]);
[self drawViewHierarchyInRect:self.bounds
afterScreenUpdates:NO];
UIImage *renderImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Even if I compress the screenshot image, there is still some pulses in memory usages.
So my question is: Is there any good way to take a high resolution screenshot and avoid memory pressure?
A: I faced the same problems while working with images - memory usage can be extreme causing memory warnings and crashes, especially if using UIImageJPEGRepresentation method on older devices (iPhone 4). So I tried to avoid using this method by saving pictures to Gallery and fetching them afterwards, this does not help much though, memory jumps persist anyway.
I suppose "pulses" are caused by copying the whole data to memory during converting. Possible solution would be to implement custom disk caching and decoding mechanism so the data could be processed in chunks, but still don't know if it worth to do. For me this problem still persists, maybe following list could be helpful.
Also refer to this question.
Other solution is to free view controllers resources in didReceiveMemoryWarning method if possible.
| |
doc_23528275
|
A: you need to upload your excel file to Drive convert it to Sheets and use IMPORTRANGE to extract given range into your spreadsheet.
uploading can be automated via https://www.google.com/drive/download/backup-and-sync/
conversion can be automated via https://stackoverflow.com/a/55645062/5632629
and IMPORTRANGE formula syntax is:
=IMPORTRANGE("spreadsheet_ID_here"; "sheet_name_here!A1:D20")
| |
doc_23528276
|
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="NotFound.aspx" />
</customErrors>
And I have the [HandleError] attribute:
[Authorize]
[HandleError]
public class HomeController : Controller
{ // etc.
Yet when I type in http://localhost:1986/blah, I get the following error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /NotFound.aspx
The URL it's trying to go to is as you would expect:
http://localhost:1986/NotFound.aspx?aspxerrorpath=/blah
So it IS attempting to go to the custom error file -- however it can't find it. I do have NotFound.aspx in the Shared directory -- same place as the Error.aspx supplied by Microsoft as a default. Why can't it find it?
A: If the Error.aspx and NotFound.aspx are in the shared directory is there a controller wired to served them? If you do not have some sort of controller route configured to serve the files then the fact that they are in the shared folder is irrelevant.
You have a few options, you could create an ErrorController which will handle the requests for those views and define routes pointing to those controller actions:
[OutputCache(CacheProfile = "Default", VaryByParam = "none")]
public class ErrorController : DefaultAreaBaseController
{
public ViewResult ServiceUnavailable() {
Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
return View("ServiceUnavailable");
}
public ViewResult ServerError() {
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return View("ServerError");
}
public new ViewResult NotFound() {
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View("NotFound");
}
}
Or as an alternative, you can create ignore routes pointing at the physical files and place the error pages somewhere other than the Views folder (like your root directory):
routes.IgnoreRoute("Error.aspx/{*pathInfo}");
routes.IgnoreRoute("NotFound.aspx/{*pathInfo}");
Either of these solutions is viable however depending on your configuration using an IgnoreRoute() may be more ideal as it will forgo the need to pipe the request to MVC only to serve a static error page.
A: Option One:
is to build an Errors Controller with a "NotFound" view along with a "Unknown" view. This will take anything that is a 500 Server error or a 404 NotFound error and redirect you to the appropriate URL. I don't totally love this solution as the visitor is always redirected to an error page.
http://example.com/Error/Unknown
<customErrors mode="On" defaultRedirect="Error/Unknown">
<error statusCode="404" redirect="Error/NotFound" />
<error statusCode="500" redirect="Error/Unknown" />
</customErrors>
*
*wwwroot/
*
*Controllers
*
*Error.cs
*Views/
*
*Error/
*NotFound.aspx
*Unknown.aspx
Option Two:
I Definitely don't prefer this method (as it is basically reverting back to web forms, The second option is to simply have a static Error.aspx page and ignore the route in MVC), but it works none the less. What you're doing here is ignoring a "Static" directory, placing your physical Error pages in there, and skirting around MVC.
routes.IgnoreRoute("/Static/{*pathInfo}"); //This will ignore everything in the "Static" directory
*
*wwwroot/
*
*Controllers/
*Static/
*
*Error.aspx
*Views/
Option Three:
The third option (THIS IS MY FAVORITE) is to return an Error View from whatever view is catching the error. This would require you to code up Try/Catch blocks along the way for "known" errors and then you can use HandleError for the unknown errors that might creep up. What this will do is preserve the originally requested URL but return the ERROR view.
EXAMPLE:
http://example.com/Products/1234 will show a details page for ProductID 1234
http://example.com/Products/9999 will show a NotFound error page because ProductID 9999 doesn't exist
http://example.com/Errors/NotFound "should" never be shown because you handle those errors individually in your controllers.
Web.Config
<customErrors mode="On">
</customErrors>
Controller
// Use as many or as few of these as you need
[HandleError(ExceptionType = typeof(SqlException), View = "SqlError")]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "NullError")]
[HandleError(ExceptionType = typeof(SecurityException), View = "SecurityError")]
[HandleError(ExceptionType = typeof(ResourceNotFoundException), View = "NotFound")]
Public Class ProductController: Controller{
public ViewResult Item(string itemID)
{
try
{
Item item = ItemRepository.GetItem(itemID);
return View(item);
}
catch()
{
return View("NotFound");
}
}
}
Folder Structure
*
*wwwroot/
*
*Controllers/
*Shared/
*
*NotFound.aspx
*NullError.aspx
*SecurityError.aspx
*SqlError.aspx
*Views/
Option Four:
The last option would be that you build your own custom filter for things like ResourceNotFoundException and attach it to your controller class. This will do the exact same thing as above but with the added benefit of sending the error code down the line to the client as well.
Richard Dingwall talks about it on his blog.
A: Your mixing web forms and MVC concepts here. Turn custom errors off in the web.config. Then in the HandleError attribute optionally specify the type and view, by default error.aspx is searched for in views\CurrentController then views\shared. Whilst you can get 404 handling working with the HandleError filter you probably want to create a filter just for 404 handling, the reasons and how to are explained in detail here:
http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/
| |
doc_23528277
|
http://jsfiddle.net/8t5kc/1/
A: If you change <input type="search" /> to <input type="text" /> it seems to be working - http://jsfiddle.net/8t5kc/2/
"WebKit has big time restrictions on what you can change on a search input. I would guess the idea is consistency." - read more
A: http://www.w3.org/TR/css3-color/
Note. If RGBA values are not supported by a user agent, they should be treated like unrecognized values per the CSS forward compatibility parsing rules ([CSS21], Chapter 4). RGBA values must not be treated as simply an RGB value with the opacity ignored.
| |
doc_23528278
|
The stored procedure isn't the issue, I transformed the select statement from te stored procedure to a regular select statement which looks like:
DECLARE @contentRootId int = 900589
DECLARE @RealtorIdList varchar(2000) = ';880;884;1000;881;885;'
DECLARE @publishSoldOrRentedSinceDate int = 8
DECLARE @isForSale BIT= 1
DECLARE @isForRent BIT= 0
DECLARE @isResidential BIT= 1
--...(another 55 variables)...
--Table to be returned
DECLARE @resultTable TABLE
(
variableName varchar(100),
[value] varchar(200)
)
-- Create table based of inputvariable. Example: turns ';18;118;' to a table containing two ints 18 AND 118
DECLARE @RealtorIdTable table(RealtorId int)
INSERT INTO @RealtorIdTable SELECT * FROM dbo.Split(@RealtorIdList,';') option (maxrecursion 150)
INSERT INTO @resultTable ([value], variableName)
SELECT [Value], VariableName FROM(
Select count(*) as TotalCount,
ISNULL(SUM(CASE WHEN reps.ForRecreation = 1 THEN 1 else 0 end), 0) as ForRecreation,
ISNULL(SUM(CASE WHEN reps.IsQualifiedForSeniors = 1 THEN 1 else 0 end), 0) as IsQualifiedForSeniors,
--...(A whole bunch more SUM(CASE)...
FROM TABLE1 reps
LEFT JOIN temp t on
t.ContentRootID = @contentRootId
AND t.RealEstatePropertyID = reps.ID
WHERE
(EXISTS(select 1 from @RealtorIdTable where RealtorId = reps.RealtorID))
AND (@SelectedGroupIds IS NULL OR EXISTS(select 1 from @SelectedGroupIdtable where GroupId = t.RealEstatePropertyGroupID))
AND (ISNULL(reps.IsForSale,0) = ISNULL(@isForSale,0))
AND (ISNULL(reps.IsForRent, 0) = ISNULL(@isForRent,0))
AND (ISNULL(reps.IsResidential, 0) = ISNULL(@isResidential,0))
AND (ISNULL(reps.IsCommercial, 0) = ISNULL(@isCommercial,0))
AND (ISNULL(reps.IsInvestment, 0) = ISNULL(@isInvestment,0))
AND (ISNULL(reps.IsAgricultural, 0) = ISNULL(@isAgricultural,0))
--...(Around 50 more of these WHERE-statements)...
) as tbl
UNPIVOT (
[Value]
FOR [VariableName] IN(
[TotalCount],
[ForRecreation],
[IsQualifiedForSeniors],
--...(All the other things i selected in above query)...
)
) as d
select * from @resultTable
The combination of a Realtor- and contentID gives me a set default set of X amount of records. When I choose a Combination which gives me ~4600 records, the execution time is around 250ms. When I execute the sattement with a combination that gives me ~600 record, the execution time is about 20ms.
I would like to know why this is happening. I tried removing all SUM(CASE in the select, I tried removing almost everything from the WHERE-clause, and I tried removing the JOIN. But I keep seeing the huge difference between the resultset of 4600 and 600.
A: Table variables can perform worse when the number of records is large. Consider using a temporary table instead. See When should I use a table variable vs temporary table in sql server?
Also, consider replacing the UNPIVOT by alternative SQL code. Writing your own TSQL code will give you more control and even increase performance. See for example PIVOT, UNPIVOT and performance
| |
doc_23528279
|
#include <iostream>
#include <vector>
class FunctionState;
class Function {
public:
virtual FunctionState* NewFunctionState() = 0;
protected:
std::vector<FunctionState*> states;
};
class FunctionState {
public:
FunctionState(Function* func) : mFunc(func) {}
virtual void RunState() = 0;
void ExecuteFunctionLotsAndLotsOfTimes();
private:
Function* mFunc;
};
#define VERY_BIG_NUMBER 10
void FunctionState::ExecuteFunctionLotsAndLotsOfTimes() {
for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
RunState();
}
};
class PrintFunction : public Function {
FunctionState* NewFunctionState();
};
class PrintFunctionState : public FunctionState {
public:
PrintFunctionState(PrintFunction* func) : FunctionState(func) {}
void RunState() override {
std::cout << "in print function state" << '\n';
}
};
FunctionState* PrintFunction::NewFunctionState() {
FunctionState* state = new PrintFunctionState(this);
states.push_back(state);
return state;
}
class AddFunction : public Function {
FunctionState* NewFunctionState();
};
class AddFunctionState : public FunctionState {
public:
AddFunctionState(AddFunction* func) : FunctionState(func), x(0) {}
void RunState() override {
++x;
}
private:
int x;
};
FunctionState* AddFunction::NewFunctionState() {
FunctionState* state = new AddFunctionState(this);
states.push_back(state);
return state;
}
int main() {
Function* func = new PrintFunction();
Function* func2 = new AddFunction();
std::vector<Function*> vec = {func, func2};
for(auto& func : vec) {
func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
}
return 0;
}
Now I have profiled my code, and have seen that there is a hotspot at FunctionState::ExecuteFunctionLotsAndLotsOfTimes(). The issue is that this function loops many times and calls RunState(), a virtual function on the FunctionState class. In there, I perform a lot of operations that will potentially flush vtable pointers out of the L1 cache, causing an L1 cache miss each iteration of the loop.
So I want to remove the need for the virtual call. I decided a good way to do this was with CRTP. The FunctionState class will take a template parameter of the type of class implementing it and call it's appropriate method, with no virtual call to RunState() required.
Now when I tried to do move it to CRTP, I ran into some issues with the Function class:
*
*How can I forward declare the FunctionState class (as it is templated now)?
*Will I need to add a template parameter to the Function class as well?
3. What would construction of a Function object look like if I template it? How would I remove the need for classes which use a Function object to specify a type parameter?
Please note that this is just a trivial version of my real codebase. The real codebase is 10K+ lines of code (not unmanageable, but a full rewrite is out of the question).
Also if there is another method to remove the virtual call to RunState() that does not involve CRTP, then that would also be appreciated.
My attempt to use CRTP:
#include <iostream>
#include <vector>
class Function;
template<class T>
class FunctionState {
public:
FunctionState(Function* func) : mFunc(func) {}
void RunState() {
static_cast<T*>(this)->RunState();
};
void ExecuteFunctionLotsAndLotsOfTimes();
private:
Function* mFunc;
};
class Function {
public:
virtual FunctionState* NewFunctionState() = 0;
protected:
std::vector<FunctionState*> states;
};
#define VERY_BIG_NUMBER 10
template <typename T>
void FunctionState<T>::ExecuteFunctionLotsAndLotsOfTimes() {
for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
RunState();
}
};
class PrintFunctionState;
class PrintFunction : public Function {
PrintFunctionState* NewFunctionState();
};
class PrintFunctionState : public FunctionState<PrintFunctionState> {
public:
PrintFunctionState(PrintFunction* func) : FunctionState<PrintFunctionState>(func) {}
void RunState() {
std::cout << "in print function state" << '\n';
}
};
PrintFunctionState* PrintFunction::NewFunctionState() {
PrintFunctionState* state = new PrintFunctionState(this);
states.push_back(state);
return state;
}
class AddFunctionState;
class AddFunction : public Function {
AddFunctionState* NewFunctionState();
};
class AddFunctionState : public FunctionState<AddFunctionState> {
public:
AddFunctionState(AddFunction* func) : FunctionState<AddFunctionState>(func), x(0) {}
void RunState() {
++x;
}
private:
int x;
};
AddFunctionState* AddFunction::NewFunctionState() {
AddFunctionState* state = new AddFunctionState(this);
states.push_back(state);
return state;
}
int main() {
Function* func = new PrintFunction();
Function* func2 = new AddFunction();
std::vector<Function*> vec = {func, func2};
for(auto& func : vec) {
func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
}
return 0;
}
A: What about a mixed solution based on type-erasure and CRTP?
It follows a minimal, working example based on the snippet in the question:
#include <iostream>
#include <vector>
class PrintFunctionState;
class AddFunctionState;
class FunctionState;
class Function {
template<typename T>
static FunctionState * InternalNewFunctionState(Function *self, std::vector<FunctionState*> &states) {
FunctionState* state = new T(self);
states.push_back(state);
return state;
}
public:
template<typename T>
static Function * create() {
Function *func = new Function;
func->internalNewFunctionState = &InternalNewFunctionState<T>;
return func;
}
FunctionState* NewFunctionState() {
return internalNewFunctionState(this, states);
}
private:
FunctionState * (*internalNewFunctionState)(Function *, std::vector<FunctionState*> &);
std::vector<FunctionState*> states;
};
class FunctionState {
public:
FunctionState() = default;
virtual ~FunctionState() = default;
virtual void ExecuteFunctionLotsAndLotsOfTimes() = 0;
};
template<typename Derived>
class IntermediateFunctionState: public FunctionState {
public:
IntermediateFunctionState(Function* func) : mFunc(func) {}
void ExecuteFunctionLotsAndLotsOfTimes() override {
Derived *self = static_cast<Derived *>(this);
for(int i = 0; i < 10; ++i) {
self->RunState();
}
}
private:
Function* mFunc;
};
class PrintFunctionState : public IntermediateFunctionState<PrintFunctionState> {
public:
PrintFunctionState(Function* func) : IntermediateFunctionState(func) {}
void RunState() {
std::cout << "in print function state" << '\n';
}
};
class AddFunctionState : public IntermediateFunctionState<AddFunctionState> {
public:
AddFunctionState(Function* func) : IntermediateFunctionState(func), x(0) {}
void RunState() {
std::cout << "in add function state" << '\n';
++x;
}
private:
int x;
};
int main() {
Function* func = Function::create<PrintFunctionState>();
Function* func2 = Function::create<AddFunctionState>();
std::vector<Function*> vec = { func, func2 };
for(auto& func : vec) {
func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
}
return 0;
}
I removed a couple of classes that were no longer required.
Hoping the code speaks for itself, let me know in the comments if I can add more details.
A: Function has to have a non-template type as the return value of NewFunctionState, so you need an additional base class
class FunctionStateBase {
virtual void ExecuteFunctionLotsAndLotsOfTimes() = 0;
// No void RunState()!
}
template<typename T>
class FunctionState {
void ExecuteFunctionLotsAndLotsOfTimes();
// Still no void RunState()!
}
class PrintFunctionState : public FunctionState<PrintFunctionState> {
void RunState();
}
template <typename T>
void FunctionState<T>::ExecuteFunctionLotsAndLotsOfTimes() {
for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
static_cast<T*>(this)->RunState(); // Statically bound!
}
};
A: If I understand your problem correctly, this can be solved by using template chaining. Here's a rough example of how it works:
#include <iostream>
/*
Just make print invocations a little less cluttered for our purposes here.
*/
template <typename Type>
void Show(Type value)
{
std::cout << value << std::endl;
}
/*
Base class for function types
*/
template <typename Self>
class Function
{
public:
/*
For the best performance possible, we'll always inline this function.
*/
inline void RunState()
{
static_cast<Self*>(this)->RunState();
}
void ExecuteFunctionLotsAndLotsOfTimes(int iterations = 1)
{
for(int i = 0; i < iterations; ++i)
{
Show("...Loop...");
RunState();
}
}
};
/*
Everything here is placed in an internal namespace, as none of it will be used by the caller.
*/
namespace Internal_
{
/*
ChainFunctionLink works like an array of functions. Each of it's members
is either some kind of function object or another ChainFunctionLink.
*/
template <typename First, typename Second>
struct ChainFunctionLink : Function<ChainFunctionLink<First, Second>>
{
ChainFunctionLink(First first, Second second)
: first(first), second(second)
{ }
inline void RunState()
{
first.RunState();
second.RunState();
}
First
first;
Second
second;
};
/*
We won't be able to explicitly specify the template parameters of ChainFunctionLink
later, so a generating function will be needed to deduce them for us.
*/
template <typename First, typename Second>
ChainFunctionLink<First, Second> MakeChainFunctionLink(First first, Second second)
{
return ChainFunctionLink<First, Second>(first, second);
}
} // namespace Internal_
/*
ChainFunction generates ChainFunctionLink's for the caller.
*/
template <typename First, typename Second, typename ...Next>
auto ChainFunction(First first, Second second, Next ...next)
{
return Internal_::MakeChainFunctionLink(first, ChainFunction(second, next...));
}
/*
The last link in the chain.
*/
template <typename Last>
Last ChainFunction(Last last)
{
return last;
}
// Example usage:
class PrintFunction : public Function<PrintFunction>
{
public:
inline void RunState()
{
Show("PrintFunction::RunState()");
}
};
class AddFunction : public Function<AddFunction>
{
public:
inline void RunState()
{
Show("AddFunction::RunState()");
}
};
int main()
{
auto
chain = ChainFunction(AddFunction(), AddFunction(), AddFunction(), PrintFunction());
chain.ExecuteFunctionLotsAndLotsOfTimes(4);
}
Granted, it might not be practical to have, say, thousands and thousands of function objects chained together in this fashion, but it does allow you to inline (and decouple) just about everything.
EDIT
There is one additional caveat to that particular kind of implementation: The chained functions are stored by value. If you want to avoid that, just redefine ChainFunctionLink's members first and second as references. Won't allow you to pass temporaries as parameters to ChainFunction though, of course...
| |
doc_23528280
|
export interface Preferences {
theme: Theme;
}
with Theme being defined as an enum:
export enum Theme {
dark = 'dark',
light = 'light'
}
Suppose I have a JSON file as follows:
{
"theme": "light"
}
Suppose also that I want to use it in a service as follows:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Preferences } from '../models/preferences';
import prefExample from '../../assets/preferences.json';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private httpClient: HttpClient) { }
getPreferences(): Observable<Preferences> {
return of(prefExample);
}
}
When I try and run the above code, it tells me:
Types of property 'theme' are incompatible.
Type 'string' is not assignable to type 'Theme'.
A: If you are sure there is valid JSON data of Preferences, you can just tell TypeScript compiler to use prefExample object as Preferences, like this:
getPreferences(): Observable<Preferences> {
return of(prefExample as Preferences);
}
| |
doc_23528281
|
d = {'c1':['a', 'a', 'b', 'b', 'c', 'c', 'c', 'd'], 'c2':['False', 'True', 'True', 'True', 'True', 'True', 'False', 'False']}
dd = pd.DataFrame(data=d)
dd.groupby('c1')['c2'].value_counts(normalize=True)
c1 c2
a False 0.500000
True 0.500000
b True 1.000000
c True 0.666667
False 0.333333
d False 1.000000
I'd like to take the max number with True in the c2 column divides by other numbers with True.
For the above example, it will be 1 / 0.500000 and 1 / 0.666667
Expected output
A: Basically, all you have to do is use the .xs method on your value counts.
Take:
series = dd.groupby('c1')['c2'].value_counts(normalize=True)
To get the number of Trues by c1 you can do
true_counts = series.xs('True', level=1)
Which returns something like this:
c1
a 0.500000
b 1.000000
c 0.666667
Name: c2, dtype: float64
Now you can do all your operations on a single index Series. Start by taking the max_index and max_value, which, in this case (because it's normalized), could be achieved by true_counts.loc[true_counts == 1] and then retrieving the values and index, or:
max_index = true_counts.index[true_counts.argmax()]
max_val = true_counts[max_index]
And then, doing the calculation over the remaining rows:
true_counts_dropped = true_counts.drop(max_index)
ans = max_val / true_counts_dropped
To make the index look like b/a, b/c, you can do:
ans.index = [max_index + '/' + idx for idx in ans.index]
And the final result:
>>> ans
b/a 2.0
b/c 1.5
Name: c2, dtype: float64
A: An alternative way to achieve the expected output is turning your indexes into columns. You could try out something like this:
import pandas as pd
d = {'c1':['a', 'a', 'b', 'b', 'c', 'c', 'c', 'd'],
'c2':['False', 'True', 'True', 'True', 'True', 'True', 'False', 'False']}
dd = pd.DataFrame(data=d)
dd = dd.groupby('c1')['c2'].value_counts(normalize=True).to_frame()
dd.rename(columns={"c2": "freq"}, inplace=True)
dd.reset_index(inplace=True)
max_true = max(dd.loc[dd["c2"] == "True"]["freq"])
dd2 = dd.copy()
dd2["result"] = max_true/dd2[["freq"]]
dd2.loc[dd2["c2"]!="True","result"] = None
As a result you get:
>>> print(max_true)
1.0
>>> print(dd)
c1 c2 freq
0 a False 0.500000
1 a True 0.500000
2 b True 1.000000
3 c True 0.666667
4 c False 0.333333
5 d False 1.000000
>>> print(dd2)
c1 c2 freq result
0 a False 0.500000 NaN
1 a True 0.500000 2.0
2 b True 1.000000 1.0
3 c True 0.666667 1.5
4 c False 0.333333 NaN
5 d False 1.000000 NaN
A: You could continue on from your value_counts and unstack the first index before creating a new dataframe:
reshape = (dd.groupby("c1")["c2"]
.value_counts(normalize=True)
.unstack("c1")
.loc["True"])
mapping = {"Calculation": ["b/a", "b/c"],
"Ans": [reshape["b"] / reshape["a"],
reshape["b"] / reshape["c"]],
}
pd.DataFrame(mapping)
Calculation Ans
0 b/a 2.0
1 b/c 1.5
| |
doc_23528282
|
<script type="text/javascript">
$(function() {
$("#dialog").dialog();
});
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
and firebug says jquery-ui-1.7.2.custom.min.js is loaded.
Any idea?
Regards
Javi
A: Your code works, you can see a working demo here.
Are you sure you're including the stylesheet for jQuery UI as well? You either need to include the one that came with your download (and related images in their same relative folders), or use the CDN hosted ones. You can find the CDN links for 1.7.2 for the various default themes on the jQuery UI blog here: http://blog.jqueryui.com/2009/06/jquery-ui-172/ (under Google Ajax Libraries API > Themes)
One last thing, as the commenters mention above, you should accept answers to your questions, it'll help you get answers to your future questions quicker.
| |
doc_23528283
|
Dim adapter As New eVoteTableAdapters.ballotsTableAdapter
Dim ballot_IDIn As Integer = ballot_ID
Dim name As String
Dim sd As Date
Dim ed As Date
name = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT name FROM ballots WHERE ballod_ID = @ballot_IDIn), String)
sd = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT startDate FROM ballots WHERE ballod_ID = @ballot_IDIn), Date)
ed = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT endDate FROM ballots WHERE ballod_ID = @ballot_IDIn), Date)
Sorry in advance I am sure this is a amateur question.
A: You need provide query as a string and provide sql parameters for your query
Public Function GetName(ballotId As Interger) As String
Dim query As String = "SELECT name FROM ballots WHERE ballod_ID = @ballot_IDIn"
Using connection = New SqlConnection("connection string")
Using command = New SqlCommand(query, connection)
Dim parameter = New SqlParameter With
{
.ParameterName = "ballot_IDIn",
.SqlDbType = SqlDbType.Int,
.Value = ballotId
}
command.Parameters.Add(parameter)
connection.Open()
Dim result = commnad.ExecuteScalar()
Return result.ToString()
End Using
End Using
End Function
I suggest using separate SqlCommand without TableAdapter and even create new instance of SqlConnection for every query.
| |
doc_23528284
|
This applet tries to invoke a phpscript . So I must read the URL when the button is clicked.
I m new beginner in java. Could you explain what is wrong
Error 44: IO exception must be caught or declared to be thrown
URLConnection myURLConnection = myURL.openConnection();
Error 46: IO exception must be caught or declared to be thrown
myURLConnection.connect();
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class RegisterUser extends Applet{
//Applet components
TextField panel1 = new TextField(10);
TextField panel2 = new TextField(10);
TextField panel3 = new TextField(10);
Button save = new Button("Save");
public void init(){
//There is two text fields and a button
add(panel1);
add(new Label("Name:"));
addNewLine();
add(panel2);
add(new Label("Last:"));
addNewLine();
add(save);
addNewLine();
// Now tell the button what it should do when it clicked
save.addActionListener(new SaveListener());
}
class SaveListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
try
{
URL myURL = new URL("http://www.myplace.com/save.php?name="+panel1.getText()+"&last_name="+panel2.getText()+"&email="+panel3.getText());
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
private void addHorizontalLine(Color c)
{
// Add a Canvas 10000 pixels wide but only 1 pixel high, which acts as
// a horizontal line to separate one group of components from the next.
Canvas line = new Canvas( );
line.setSize(10000,1);
line.setBackground(c);
add(line);
}
private void addNewLine( )
{
// Add a horizontal line in the background color. The line itself is
// invisible, but it serves to force the next Component onto a new line.
addHorizontalLine(getBackground( ));
}
}
A: You have to catch the checked IOException like this
catch (IOException exc) {
// handle exception
}
In your try catch you catch only MalformedURLException that is why you get a compilation error.
A: It looks like you have a } too much after the try-block.
And you also have to catch the IOException
Write it like this:
try{
URL myURL = new URL("http://www.myplace.com/save.php?name="+panel1.getText()+"&last_name="+panel2.getText()+"&email="+panel3.getText());
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}catch (MalformedURLException e){
System.out.println(e.getMessage());
}catch (IOException e2){
System.out.println(e2.getMessage());
}
| |
doc_23528285
|
Golang code:
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/url"
"strings"
http "github.com/useflyent/fhttp"
"github.com/Carcraftz/CycleTLS/cycletls"
)
var client = cycletls.Init()
func main() {
port := flag.String("port", "8082", "A port number (default 8082)")
flag.Parse()
addr := "127.0.0.1:" + string(*port)
fmt.Println("Hosting a TLS API on http://" + addr)
http.HandleFunc("/", handleReq)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatalln("Error starting the HTTP server:", err)
}
}
func handleReq(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// Ensure page URL header is provided
pageURL := r.Header.Get("Poptls-Url")
if pageURL == "" {
http.Error(w, "ERROR: No Page URL Provided", http.StatusBadRequest)
return
}
// Remove header to ignore later
r.Header.Del("Poptls-Url")
// Ensure user agent header is provided
userAgent := r.Header.Get("User-Agent")
if userAgent == "" {
http.Error(w, "ERROR: No User Agent Provided", http.StatusBadRequest)
return
}
// Extract proxy from header
proxy := r.Header.Get("Poptls-Proxy")
if proxy != "" {
r.Header.Del("Poptls-Proxy")
}
redirectVal := r.Header.Get("Poptls-Allowredirect")
allowRedirect := true
if redirectVal != "" {
if redirectVal == "false" {
fmt.Println(("redirects disabled"))
allowRedirect = false
}
}
if redirectVal != "" {
r.Header.Del("Poptls-Allowredirect")
}
// Change JA3
// Use Chrome JA3 by default
//TODO: ADD MORE JA3 HASHES
tlsClient := "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0"
if strings.Contains(strings.ToLower(userAgent), "firefox") {
tlsClient = "771,4865-4867-4866-49195-49199-52393-52392-49196-49200-49162-49161-49171-49172-156-157-47-53-10,0-23-65281-10-11-35-16-5-51-43-13-45-28-21,29-23-24-25-256-257,0"
}
// Forward body
body, _ := ioutil.ReadAll(r.Body)
// Forward query params
var addedQuery string
for k, v := range r.URL.Query() {
addedQuery += "&" + k + "=" + v[0]
}
endpoint := pageURL + "?" + addedQuery
if strings.Contains(pageURL, "?") {
endpoint = pageURL + addedQuery
} else if addedQuery != "" {
endpoint = pageURL + "?" + addedQuery[1:]
}
u, err := url.Parse(endpoint)
if err != nil {
panic(err)
}
// Forward headers
headers := make(map[string]string)
//fmt.Println(r.Cookies()) //Delete this
//fmt.Println(r.Method) //Delete this
for k := range r.Header {
if k != "Content-Length" {
headers[k] = r.Header.Get(k)
}
}
headers["Host"] = u.Host
// Set options
opts := cycletls.Options{
Body: string(body), // ideally, body should be passed as bytes
Ja3: tlsClient,
UserAgent: userAgent,
Headers: headers,
Method: r.Method,
Proxy: proxy,
AllowRedirect: allowRedirect,
}
// Perform request
res, err := client.Do(endpoint, opts, r.Method)
if err != nil {
log.Println("Request failed:", err)
}
fmt.Println(res.Response.Status)
//fmt.Println(res.Response.Headers) //Delete this
// Forward response headers
for k, v := range res.Response.Headers {
// Do not forward the content length and encoding headers, as we will handle the decoding ourselves
if k != "Content-Length" && k != "Content-Encoding" {
w.Header().Set(k, v)
}
}
// Forward respone status
w.WriteHeader(res.Response.Status)
// Write forwarded proxy request
if _, err := fmt.Fprint(w, res.Response.Body); err != nil {
log.Println("Error writing body:", err)
}
}
Python code:
import cloudscraper
from http.server import HTTPServer, BaseHTTPRequestHandler
from sys import argv
def main():
req = cloudscraper.create_scraper()
akamai_api_login = req.post(
api,
data={
'usrnm': 'user',
'pass': 'pass'
}
)
abc = req.get(website_endpoint)
print(f'cookie: {abc.cookies}')
a_api = req.post(
api_site,
data={
'hello': 'world'
}
)
senreq = req.get(web)
sendata = senreq.json()
# Checking for valid
# Using the TLS Proxy
tls = req.post(
'http://127.0.0.1:8082',
headers={
'poptls-url': website,
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'script',
'sec-fetch-mode': 'no-cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36'
},
json={
'data': data
},
cookies= dict(abc.cookies)
)
print(tls.cookies)
req.close()
main()
| |
doc_23528286
|
I am getting following error message while downloading a file from Web API Controller.
Non-invocable member 'File' cannot be used like a method
This is my database table:
CREATE TABLE [cafe].[t06_03_02_jobAttachments](
[ID] [int] IDENTITY(1,1) NOT NULL,
[jobAttachmentId] [int] NOT NULL,
[jobId] [int] NOT NULL,
[file] [varbinary](max) NOT NULL,
[name] [varchar](100) NOT NULL,
[fileExtension] [varchar](10) NOT NULL,
[contentType] [varchar](50) NOT NULL,
[fileSize] [int] NOT NULL
) ON [PRIMARY]
This is my Data Model:
namespace api.Models.Jobs
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("cafe.t06_03_02_jobAttachments")]
public partial class t06_03_02_jobAttachments
{
public int ID { get; set; }
public int jobAttachmentId { get; set; }
public int jobId { get; set; }
[Required]
public byte[] file { get; set; }
[Required]
[StringLength(100)]
public string name { get; set; }
[Required]
[StringLength(10)]
public string fileExtension { get; set; }
[Required]
[StringLength(50)]
public string contentType { get; set; }
public int fileSize { get; set; }
}
}
Here is my controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using api.Models;
using api.Models.Jobs;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Web.Mvc;
namespace api.Controllers.jobs
{
public class JobsController : ApiController
{
[HttpGet]
[ResponseType(typeof(t06_03_02_jobAttachments))]
public async Task<IHttpActionResult> Gett06_03_02_jobAttachments(int id)
{
t06_03_02_jobAttachments t06_03_02_jobAttachments = await db.t06_03_02_jobAttachments.FindAsync(id);
if (t06_03_02_jobAttachments == null)
{
return NotFound();
}
return File(t06_03_02_jobAttachments.file, t06_03_02_jobAttachments.contentType, t06_03_02_jobAttachments.name);
}
}
}
I am getting this error on my controller when I try to return File as a text file. All I want to do is read the file (saved as Byte array in database) and return it to my Angular application. I have tried multiple solutions posted online but non of them helped me. I would appreciate any help I receive from this blog. I am using .NET Framework 4.6.1 and MVC 5.2.7. Thanks
A: I made a FileResult class that you can use to return your binary content.
public class FileResult : IHttpActionResult
{
private byte[] _content;
private string _contentType;
public FileResult(byte[] content, string contentType)
{
_content = content;
_contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return null;
// per https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api do not wrap this in a using block
System.IO.MemoryStream stream = new System.IO.MemoryStream(_content);
stream.Seek(0, System.IO.SeekOrigin.Begin);
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_contentType);
return Task.FromResult(response);
}
}
| |
doc_23528287
|
SM-N900P 4.4.4 19
java.lang.NullPointerException
at android.view.ViewRootImpl.setMultiWindowScale(ViewRootImpl.java:7992)
at android.view.WindowManagerGlobal.setMultiWindowScale(WindowManagerGlobal.java:538)
at com.android.internal.policy.impl.MultiPhoneWindow.adjustScaleFactor(MultiPhoneWindow.java:1602)
at com.android.internal.policy.impl.MultiPhoneWindow.access$2300(MultiPhoneWindow.java:107)
at com.android.internal.policy.impl.MultiPhoneWindow$MultiPhoneDecorView.onAttachedToWindow(MultiPhoneWindow.java:1120)
at android.view.View.dispatchAttachedToWindow(View.java:13637)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2703)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1533)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1270)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6686)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
at android.view.Choreographer.doCallbacks(Choreographer.java:613)
at android.view.Choreographer.doFrame(Choreographer.java:583)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5727)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
It's not in my code and I can't reproduce it in an emulator since I can't create an AVD with 4.4.4.
With the AVD 4.4.2 it works. I have tried the physical phone in a store/shop with version 4.4.2 and it works. I can however not get hold of a 4.4.4 version.
*
*How can I create and AVD with 4.4.4?
*Why is Google not providing a 4.4.4 AVD?
*Anyone an idea how to solve the dump?
*I can't even find the line 7992 and method setMultiWindowScale in AOSP?
Thanks!
A:
How can I create and AVD with 4.4.4?
Genymotion will let you emulate a Samsung Note 3 running on 4.4.4.
It has plugin support for Eclipse and Android Studio, follow instructions here for installing.
Why is Google not providing a 4.4.4 AVD?
I don't know why not AVD, but they are providing binaries for 4.4.4 here if you have access to a Nexus device you may want to double check/confirm that the problem is Samsung related only.
Anyone an idea how to solve the dump?
Posted stack trace above looks like the exception was thrown after your application was attached to a multi window and the view was scaled, or at least it was going to be scaled if that NPE was not thrown. Check your manifest settings using this step by step guide for multi window support, check max and min window sizes. If the emulator does not work and if you can't reproduce the exception, as a last resort reach that user somehow and communicate to reproduce the problem/test your solution and iterate until its fixed. Good luck!
I can't even find the line 7992 and method setMultiWindowScale in
AOSP?
As this looks like very much related to a Samsung specific implementation of the android.view.ViewRootImpl class to support multi window and other Samsung stuff, I doubt that you can find the actual source code unless Samsung has published it somewhere.
| |
doc_23528288
|
The scenario is as follows
*
*I need to access the meta data for a file and I only have the file path (I can't use the /drive/items/{item-id} method)
*When the path gets too big, I am unable to access the metadata.
https://tenant-my.sharepoint.com/personal/some_user_some_domain_elasticadev_com/_api/v2.0/drive/root:/mauze/test/This is supposed/This is really supposed to be a really long name for a folder which normally isn't the case!/SomeName-123456789012345678901234567890123456789012345678901234567890123456789012.txt
The error
401 Unauthorized
The length of the URL for this request exceeds the configured maxUrlLength value.
When using Sharepoint Online APIs, I used to cater this issue by using the URL parameters like
https://tenant-my.sharepoint.com/personal/user_account_tenant_onmicrosoft_com/_api/web/getfilebyserverrelativeurl(@v)/startupload(uploadId=guid'bla-bla')?@v='/personal/user_account_tenant_onmicrosoft_com/Documents/Test/reeeaaaaallllyyybiiignameblablblalblalb.txt'
I am unable to use this technique with the OneDrive API. Is there any work around for this?
One side question, I do have the ListItemUniqueId for the file (the UniqueID of the file on Sharepoint)
Can I somehow use that to translate it into OneDrive ID? Any facet for this purpose? i.e, the reverse of SharepointIds Facet.
A: You should be able to use a similar aliasing approach with the OneDrive API, but it may not be as flexible in terms of alias naming.
https://tenant-my.sharepoint.com/personal/some_user_some_domain_elasticadev_com/_api/v2.0/drive/root:@path?@path='/mauze/test/This%20is%20supposed/This%20is%20really%20supposed%20to%20be%20a%20really%20long%20name%20for%20a%20folder%20which%20normally%20isn''t%20the%20case!/SomeName-123456789012345678901234567890123456789012345678901234567890123456789012.txt'
Having said that, we really should be supporting URLs of that length now so I'll need to follow up to see what's going wrong on that front.
| |
doc_23528289
|
//For the rooms
$(document).ready(function () {
var tpropval = $('input[name=Typeofproperty]:checked').val()
if (tpropval != 'Plot' || tpropval != 'Studio Appartment') {
$('#chkroomdetails').show();
}
else {
$('#chkroomdetails').hide();
}
})
<div id="chkroomdetails" class="roomdetails">
<h5>* Room Details :</h5>
<input type="checkbox" class="roomdetails" name="Roomdetails" id="1bed" value="1BHK" />1 BHK
<input type="checkbox" class="roomdetails" name="Roomdetails" id="2bed" value="2BHK" />2 BHK
<input type="checkbox" class="roomdetails" name="Roomdetails" id="3bed" value="3BHK" />3 BHK
<input type="checkbox" class="roomdetails" name="Roomdetails" id="4bed" value="4BHK" />4 BHK
<input type="checkbox" class="roomdetails" name="Roomdetails" id="5bed" value="5BHK" />5 BHK
@Html.ValidationMessageFor(model => model.Roomdetails)
</div>
<script type="text/javascript">
$(document).ready(function () {
var arr = $("#hiddenroomdetails").val().split(", ");
$('input[type=checkbox]').each(function () {
if ($.inArray($(this).val(), arr) >= 0) {
$(this).attr("checked", true);
}
});
});
I have 2 radio buttons of apartment and house. The attribute called "hiddenroomdetails" is the property of the model which carries the details of the rooms in the type of house like 2BHK and 3BHK. In db they are stored with a comma separation(", "). While retrieving the details uising this jquery I'm not getting the check-boxes ticked on the Edit page.
A: Instead of $(this).attr("checked", true); use $(this).prop("checked", true); or use $(this).attr("checked", "checked");
After your edit your complete jquery code should be like :
$(document).ready(function () {
var tpropval = $('input[name=Typeofproperty]:checked').val()
if (tpropval != 'Plot' || tpropval != 'Studio Appartment') {
var arr = $("#hiddenroomdetails").val().split(", ");
$('input[type=checkbox]').each(function () {
if ($.inArray($(this).val(), arr) > -1) {
$(this).prop("checked", true);
}
});
$('#chkroomdetails').show();
}
else {
$('#chkroomdetails').hide();
}
});
A: Try this:
$(this).attr("checked", "checked");
| |
doc_23528290
|
FileInputFormat.addInputPath(job, new Path(args[0]));
FileSystem.get(conf).delete(new Path("file:///tmp/inter/"),true);
FileOutputFormat.setOutputPath(job, new Path("file:///tmp/inter/"));
boolean complete = job.waitForCompletion(true);
Job job2 = Job.getInstance(conf, "Q4a");
job2.setJarByClass(Q4a.class);
job2.setMapperClass(TokenizerMapper2.class);
job2.setCombinerClass(CountReducer2.class);
job2.setReducerClass(CountReducer2.class);
job2.setOutputKeyClass(Text.class);
job2.setOutputValueClass(Text.class);
// FileInputFormat.addInputPath(job2, new Path("file:///tmp/inter/part*"));
FileInputFormat.addInputPath(job2, new Path("file:///tmp/inter/"));
FileOutputFormat.setOutputPath(job2, new Path(args[1]));
System.exit(job2.waitForCompletion(true) ? 0 : 1);
The first mapper & reducer execute fully, and then the error is thrown.
Line 58 is the last line in the pasted code, but I believe the error is from the temp input path? Do I need to refer to temp files in a different manner in Azure? Any help is much appreciated, thankyou.
A: Okay I just solved this. Looks like HDInsight does not support the folder structure I specified. I changed the path to simply "out" instead of "file:///tmp/inter" and it worked.
| |
doc_23528291
|
int reallocToMinSize(char** friends, int len)
{
int i = 0;
int reallocSuccess = 1;
char* newFriendPtr = 0;
for (i = 0; i < len && reallocSuccess; i++)
{
printf("Reallocating: %s, size: %i", friends[i], (strlen(friends[i]) + 1));
friends[i] = (char*) realloc(friends[i], (strlen(friends[i]) + 1) * sizeof(char));
if (friends[i] == 0)
{
reallocSuccess = 0;
}
printf("%s\n", friends[i]);
}
return reallocSuccess;
}
A: Probable causes are
*
*you never initialized friends[i] before to do the realloc
*or you realloc a freed block
*or friends[i] was not set by NULL or the result of malloc
Because you do
realloc(friends[i], (strlen(friends[i]) + 1) * sizeof(char));
and the printf just before is probably valid I suspect you are in third error case and you do something wrong like
friends[i] = "aze";
...
reallocToMinSize(friends, ...);
or
char s[...];
...
friends[i] = s;
...
reallocToMinSize(friends, ...);
or
char * s = malloc(...);
...
friends[i] = s + offset; /* offset not null */
...
reallocToMinSize(friends, ...);
or
...
friends[i] = strtok(...);
...
reallocToMinSize(friends, ...);
or may be the second error case doing
char * s = malloc(...); /* unique allocation */
...
for (i = ...) { ... friends[i] = s; ... } /* always the same value of s */
...
reallocToMinSize(friends, ...);
because malloc can free its first argument, so in reallocToMinSize for a given index you apply realloc on a block freed for a lower index
| |
doc_23528292
|
Every time there is an outage the logs contain the following entries:
Message: java.util.zip.ZipException: ZIP_Read: error reading zip file ZIP_Read: error reading zip file
Exception type: java.util.zip.ZipException
Failed method: java.util.zip.ZipFile.access$1400
With the following call stack.
java.lang.IllegalStateException:
at org.apache.catalina.webresources.JarWarResourceSet.getArchiveEntries (JarWarResourceSet.java133)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.getResource (AbstractArchiveResourceSet.java256)
at org.apache.catalina.webresources.StandardRoot.getResourceInternal (StandardRoot.java281)
at org.apache.catalina.webresources.CachedResource.validateResource (CachedResource.java97)
at org.apache.catalina.webresources.Cache.getResource (Cache.java69)
at org.apache.catalina.webresources.StandardRoot.getResource (StandardRoot.java216)
at org.apache.catalina.webresources.StandardRoot.getResource (StandardRoot.java206)
at org.apache.catalina.mapper.Mapper.internalMapWrapper (Mapper.java1027)
at org.apache.catalina.mapper.Mapper.internalMap (Mapper.java842)
at org.apache.catalina.mapper.Mapper.map (Mapper.java698)
at org.apache.catalina.connector.CoyoteAdapter.postParseRequest (CoyoteAdapter.java679)
at org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java336)
at org.apache.coyote.http11.Http11Processor.service (Http11Processor.java803)
at org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process (AbstractProtocol.java868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun (NioEndpoint.java1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java49)
at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run (TaskThread.java61)
at java.lang.Thread.run (Thread.java748)
Inner exception java.util.zip.ZipException handled at org.apache.catalina.webresources.JarWarResourceSet.getArchiveEntries:
at java.util.zip.ZipFile.access$1400 (ZipFile.java60)
at java.util.zip.ZipFile$ZipFileInputStream.read (ZipFile.java734)
at java.io.FilterInputStream.read (FilterInputStream.java133)
at java.io.PushbackInputStream.read (PushbackInputStream.java186)
at java.util.zip.ZipInputStream.readFully (ZipInputStream.java403)
at java.util.zip.ZipInputStream.readLOC (ZipInputStream.java278)
at java.util.zip.ZipInputStream.getNextEntry (ZipInputStream.java122)
at java.util.jar.JarInputStream.<init> (JarInputStream.java83)
at java.util.jar.JarInputStream.<init> (JarInputStream.java62)
at org.apache.catalina.webresources.TomcatJarInputStream.<init> (TomcatJarInputStream.java37)
at org.apache.catalina.webresources.JarWarResourceSet.getArchiveEntries (JarWarResourceSet.java108)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.getResource (AbstractArchiveResourceSet.java256)
at org.apache.catalina.webresources.StandardRoot.getResourceInternal (StandardRoot.java281)
at org.apache.catalina.webresources.CachedResource.validateResource (CachedResource.java97)
at org.apache.catalina.webresources.Cache.getResource (Cache.java69)
at org.apache.catalina.webresources.StandardRoot.getResource (StandardRoot.java216)
at org.apache.catalina.webresources.StandardRoot.getResource (StandardRoot.java206)
at org.apache.catalina.mapper.Mapper.internalMapWrapper (Mapper.java1027)
at org.apache.catalina.mapper.Mapper.internalMap (Mapper.java842)
at org.apache.catalina.mapper.Mapper.map (Mapper.java698)
at org.apache.catalina.connector.CoyoteAdapter.postParseRequest (CoyoteAdapter.java679)
at org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java336)
at org.apache.coyote.http11.Http11Processor.service (Http11Processor.java803)
at org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process (AbstractProtocol.java868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun (NioEndpoint.java1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java49)
at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run (TaskThread.java61)
at java.lang.Thread.run (Thread.java748)
As soon as this occurs, all calls to the rest service returns a 500 and the log gets another entry like above. This continues until I manually reboot the app service.
I'm struggling to figure out what is the issue. Googling the exception only returns results for issues with opening zip files. The app does not do any zipping/unzipping in itself and the call stack seems to indicate that it's tomcat things(that could be caused by something I've done on Azure, in SpringBoot, the JVM or something else entirely).
CPU or memory usage appear to be fine preceding the outages so that doesn't seem to be a factor.
This issue is not preceded by any deployments or platform changes.
I'm stumped regarding what to do next, if anyone can point me in the right direction to investigate, it'll be much appreciated.
| |
doc_23528293
|
Thanks in advance.
A: Use a left join
Select * from tableb left join tablea on tableb.column = tablea.coulmn where tablea.column is null
A: Some databases support except or minus. But not MySQL. I would recommend not exists:
select b.*
from b
where not exists (select 1
from a
where a.col1 = b.col1 and a.col2 = b.col2 and . . .
);
Note that this will not work if any columns have NULL values.
If you need to handle NULLs, you could use (not a.col1 <=> b.col1) and (not a.col2 <=> b.col2) . . .. Or, you could use aggregation:
select col1, col2, . . .
from ((select a.*, 1 as is_a, 0 as is_b
from a
) union all
(select b.*, 0, 1
from b
)
) ab
group by col1, col2, . . .
having max(is_a) = 0 and max(is_b) = 1;
A: Suppose the rows are same if their primary keys are same (for example, id field). Than you can:
select id from b where id not in (select id from a)
If your tables has no primary keys or they do not match - you can alter the query to your tables structure.
| |
doc_23528294
|
Generating code coverage report, this
may take a
moment./tmp/hudson3472766550808527893.sh:
line 3: 5237 Terminated
/usr/local/bin/phpunit --verbose -d
memory_limit=1024M --log-junit
../../build/logs/phpunit.xml
--coverage-clover ../../build/logs/coverage/clover.xml
--coverage-html ../../build/logs/coverage-html/
Any help would be greatly appreciated. This is negatively affecting our dev. team. Below is the latest error message.
.......................................
Time: 34 seconds, Memory: 94.50Mb
[30;42m[2KOK (56 tests, 493
assertions) [0m[2K Writing code
coverage data to XML file, this may
take a moment. Fatal error: Out of
memory (allocated 555483136) (tried to
allocate 71 bytes) in
/usr/local/lib/php/PHP/Token/Stream.php
on line 155
/tmp/hudson1430922411819914240.sh:
line 3: 26479 Terminated
/usr/local/bin/phpunit --verbose -d
memory_limit=1024M --log-junit
../../build/logs/phpunit.xml
--coverage-clover ../../build/logs/coverage/clover.xml
--coverage-html ../../build/logs/coverage-html/
A: Something terminates the PHP process before it completes, but it is not possible to tell the reason from this log. Check the syslog on the server, it may have some hints about what is going on.
A: We had Problems with PHPUnit running out of Memory, when the Memory available on the Server was low ... just to give you a hint ... (we used apache to start the tests, and there would be arount 10 processes, each eating 2GB of memory ...) the tests started to fail randomly.
Another issue is that you might have with, is high Memory Usage ... this might be caused by phpunits restore global state functionality. If you disable it, you have to cleanup after your tests so they wont disturb the other ones, but you will use less memory.
A: As the number of files being included for code coverage grew, the memory usage grew. This question is similar to, but not the same as, the link below.
PHPUnit code coverage generation causing memory exhaustion
| |
doc_23528295
|
"Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in..."
even though the query returns a result in mysql workbench.
This is my code:
<?php
$con=mysqli_connect("localhost","root","","eshkol");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="SET Names utf8";
$sql = mysql_query("SELECT * FROM student WHERE idStudent=2");
$r = mysql_fetch_array($sql);
echo $r["idStudent"];
if (!mysqli_query($con,$sql1))
{
die('Error hebrew: ' . mysqli_error($con));
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "success";
mysqli_close($con);
?>
What am I doing wrong here?
A: You're mixing mysql_* and mysqli_* functions.
$sql = mysql_query($con, "SELECT * FROM student WHERE idStudent=2");
$r = mysql_fetch_array($sql);
should be
$sql = mysqli_query($con, "SELECT * FROM student WHERE idStudent=2");
$r = mysqli_fetch_array($sql);
What's interesting is you're using them just below that code:
if (!mysqli_query($con,$sql1))
{
die('Error hebrew: ' . mysqli_error($con));
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
You probably want to combine the two to clean up your code:
$sql = mysql_query($con, "SELECT * FROM student WHERE idStudent=2");
if (!$sql) {
die('Error: ' . mysqli_error($con));
}
$r = mysql_fetch_array($sql);
| |
doc_23528296
|
I want to use jQuery on my website, but only if it is displayed on a desktop computer. If my site is displayed on a mobile device, I don't want it to load jQuery.
What's the best way to do this?
Should I use Javascript or PHP for detecting the device type?
A: http://jsfiddle.net/fk9kC/
The code above is pretty much self-explanatory - by using a DOM element being hidden or shown depending by a screen width you're being able to target mobile phones more or less accurately.
Furthermore, you can also replace the device-width statement with max-device-width.
A: What about this? Auto detect mobile browser (via user-agent?)
A: You would need to check the user agent.
You will need to define what is a mobile platform to you.
One hack may be to include a media type mobile stylesheet, and have it set an element to something specific that you could check for using JavaScript. This is hacky though, but it will mean you won't need to parse user agents.
| |
doc_23528297
|
I want to render a texture on my winforms panel and not want to create another SDL window form just for rendering. How can I do that?
| |
doc_23528298
|
parent.location='mailto:' + email + '?subject=' + "Test";
But the problem is I have multiple email accounts linked up to my outlook, so when I click on the mailto link it always uses the first email address in the From drop down menu in Outlook. But I want to use the second email address. Is there a way to select which email address to use in mailto?
A: Sorry I don't think that's possible. The mailto link doesn't talk to outlook per say, it just opens the default email client set on the machine and sets a subject, to, cc and message.
| |
doc_23528299
|
I have tabbed pages in which I have a Message Tab which consists of a collection view which shows the user messages. When the app starts I download about 5 messages and then wait for the remainingitemthresholdreached to fire so I can go ahead and fetch more data but unfortunately, it doesn't fire and I am stuck with the initial 5 messages.
XAML
<CollectionView Grid.Row="1" ItemsSource="{Binding AllMessages, Mode=TwoWay}" x:Name="myMessagesCV" SelectionMode="Single" SelectionChanged="MyMessagesCV_SelectionChanged" RemainingItemsThresholdReached="MyMessagesCV_RemainingItemsThresholdReached" RemainingItemsThreshold="5">
<CollectionView.ItemTemplate>
<DataTemplate>
// Some Code here
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Code Behind
private void MyMessagesCV_RemainingItemsThresholdReached(object sender, EventArgs e)
{
if (IsBusy)
return;
IsBusy = true;
if (!LoadedAllMyMessages)
{
GetMyMessages();
}
if (LoadedAllMyMessages)
{
myMessagesCV.RemainingItemsThreshold = -1;
}
}
Please someone save me. Cheers guys!
A: The RemainingItemsThresholdReached could be triggered with enough items.
You could check it in IncrementalLoadingPage of Scrolling. Or you could use the RemainingItemsThresholdReachedCommand
Here is the example for yoru reference. https://github.com/xamarin/xamarin-forms-samples/tree/master/UserInterface/CollectionViewDemos
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.