source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0047854730.txt"
] | Q:
reverse string using for of in javascript
I don't understand how this work, but the function below is fine. I'm confused, isn't the first iteration of for of loop print h? h + '' = h, how it got reversed?
function reverse(str) {
let reversed = ''
for (let char of str) {
reversed = char + reversed
}
return reversed
}
console.log(reverse('hello world'))
A:
Note : I am adding this answer just to help understand OP.
So its fairly simple to understand if you add an console.log() inside the inner loop.
Basically reversed = char + reversed; here is what all logic is.
Lets try breaking it :
1) The inner loop begin with the first character of the string passed and the prepend it to existing local var reversed so its now ''+h = 'h'
2) Now in second iteration we have e. so in loop we have 'h' and what happens is h = e + h which turn out to be "eh"
3) follow the same path and you have a reversed String... :D
function reverse(str) {
let reversed = ''
for(let char of str){
reversed = char + reversed;
// add this line to understand how this works!
console.log(reversed);
}
return reversed;
}
console.log(reverse('hello world'));
|
[
"superuser",
"0000139665.txt"
] | Q:
How to save RDP credentials into a file?
I'm trying to use RDP and save my credentials in a file so I don't have to enter it each time I connect.
I remember doing it before and it involved changing a group policy setting. What exactly do I need to change in Group Policy within Windows 7 in the host & client machines to accomplish this?
A:
Actually found a link (archive.org) that solved this problem:
Hit Start –> Run and type "gpedit.msc".
Navigate to Local Computer Policy –> Computer Configuration –> Administrative Templates –> System –> Credentials Delegation.
Double click the policy "Allow Delegating Default Credentials with NTLM-only Server Authentication".
Set the policy to “Enabled”.
Click the Show button and enter the string “TERMSRV/*” into the list. You can also be more specific here in case you don’t want to allow the use of saved credentials with all remote machines but rather just a select few.
Click OK twice to close the policy. Repeat steps 3–6 for the following policies:
"Allow Delegating Default Credentials"
"Allow Delegating Saved Credentials with NTLM-only Server Authentication"
"Allow Delegating Saved Credentials"
A:
Open the Group Policy editor (Start > Run > gpedit.msc) and navigate to Computer Configuration -> Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Connection Client
For value Do not allow passwords to be saved, change to Disabled.
When connecting to a machine in Remote Desktop Connector, expand the Options panel and confirm that Allow me to save credentials is checked.
|
[
"stackoverflow",
"0011349677.txt"
] | Q:
Urban Airship Push Notifications not working with Production Certificate
I am developing an iOS App with Push Notifications. I am able to successfully test the push notifications using the Developer APN Certificate but it does not work with the Production APN Certificate.
I have ensured that the profiles in the iOS Developer Portal (adhoc / distribution) are generated after Push Notification is enabled for the APP ID and have taken care to use the correct UA_KEY and UA_SECRET in AppDelegate.m.
Can anybody please provide insights on as to what could be the possible reason(s) why Push notifications are failing using Production Certificate but working fine with Development Certificate.
A:
I finally seemed to have sorted this out and posting back here in hope that it may help.
The key point which helped me to identify the problem was to turn on 'Debugging' in the UA Console to see the details errors. (This was actually the suggestion provided by their support team)
|
[
"security.stackexchange",
"0000086522.txt"
] | Q:
PGP Owner Trust Field & Signature Trust Field Distinction
I'm reading Cryptography and Network Security Principles and Practices (5th ed, p584) and reading about PGP keyrings, I'm a little confused about the differences between the owner trust field and the signature trust field. I quote:
In turn, each signature has associated with it a signature trust field that indicates the degree to which this PGP user trusts the signer to certify public keys.
and ...
An owner trust field is included that indicates the degree to which this public key is trusted to sign other public-key certificates.
The powerpoint slides I'm reading don't seem to make a clear distinction between the two either:
Signature trust field:
Measures how far the PGP user trusts the signer to certify public keys. (The key
legitimacy field for an entry derives from the signature trust fields.)
Owner trust field:
Indicates the degree to which this PGP user trusts the key's owner to sign other public-key certificates. PGP doesn't compute this level of trust; the PGP user assigns it. You
can think of a signature trust field as a cached copy of the owner trust field from
another entry.
Am I correct in saying that the owner trust field is the extent to which I (the keyring owner) trust the public key entry in the table?
Does the signature trust field get set manually by the user?
If I have a public key entry from Bob, and Charlie and David have signed it, would I have two signature trust entries for that key? - And do I have to set these manually? - What if I don't know David, what would the value be?
A:
Owner and Signature Trust
Signature trust means a user puts trust into the identity of another user. If Alice signs (or certifies, which is the term I will use from now on for signing other's keys) Bob's key, she declares (following whatever rules) she puts trust in his identity. These certifications are usually publicly available on the key servers. You can fetch those certifications (by fetching somebody else's key, you automatically also receive all certifications on that key), but for now they're still useless (unless issued by yourself).
Owner trust is only issued by you, and not shared with others. It defines, whether you put trust in somebody else's capabilities of doing proper certifications (ie., Alice checking Bob's ID carefully).
If you take both kinds of trust together, you can validate other's keys, although you never met somebody. Given you know Alice and certified her key (signature trust), her key is valid (you're sure about who she is). Without issuing owner trust to her, her certification on Bob is not considered for validating Bob's key yet. If you also issue owner trust on Alice's key (thus, trusting her decisions on certifying others), her outgoing certifications are also considered; Bob's key is now also valid.
For more details, have a look at What is the exact meaning of this gpg output regarding trust?.
Your Questions
Am I correct in saying that the owner trust field is the extent to which I (the keyring owner) trust the public key entry in the table?
Yes -- and no. It is a part of trust as described above; trust into the key owner's ability to correctly issue certifications.
Does the signature trust field get set manually by the user?
THe other way round: signature trust is issued by anybody and shared on the key servers. Each OpenPGP user has to manually (and on his own) set owner trust.
If I have a public key entry from Bob, and Charlie and David have signed it, would I have two signature trust entries for that key? - And do I have to set these manually? - What if I don't know David, what would the value be?
If the certifications (signatures) have been uploaded to the key servers, you could fetch them by loading Bob's key from the key servers. So no, you don't need to set them manually, nor should you (if you didn't verify Bob's key). You could issue owner trust, though.
If you don't know David (ie., not certified his key), the value wouldn't change, or in better words: David's certification would not change anything, as you probably did not put owner trust on David's key.
|
[
"stackoverflow",
"0059676457.txt"
] | Q:
Firebase Android. When I update/change my "User" profile image, how do I update the image associated with all "Posts"?
public class PostActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ProgressDialog loadingBar;
private ImageButton selectPostImage;
private Button updatePostButton;
private EditText postDescription;
private static final int Gallery_Pick = 1;
private Uri imageUri;
private String description;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadUrl, current_user_id, specialKey;
private long countPosts = 0;
private StorageReference postsImageReference;
private DatabaseReference usersRef, postRef;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
postsImageReference = FirebaseStorage.getInstance().getReference().child("Post Images");
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts");
selectPostImage = (ImageButton) findViewById(R.id.select_post_image);
updatePostButton = (Button) findViewById(R.id.update_post_button);
postDescription = (EditText) findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
selectPostImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OpenGallery();
}
});
updatePostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
description = postDescription.getText().toString();
if(imageUri==null){
Toast.makeText(this, "Please Select Post Image...", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(description)){
Toast.makeText(this, "Please Say Something About Your Image...", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Adding New Post");
loadingBar.setMessage("Please Wait, While We Are Updating Your New Post...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm:ss");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = postsImageReference.child(imageUri.getLastPathSegment() + ".jpg");
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
downloadUrl = uri.toString();
SavingPostInformationToDatabase();
}
});
}
});
}
private void SavingPostInformationToDatabase(){
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("date", saveCurrentDate);
postsMap.put("time", saveCurrentTime);
postsMap.put("description", description);
postsMap.put("postimage", downloadUrl);
postsMap.put("postprofileimage", userProfileImage);
postsMap.put("postfullname", userFullName);
postsMap.put("timestamp", getCurrentTimeStamp());
postRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this, "New Post Updated Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
Toast.makeText(PostActivity.this, "ERROR Occurred While Updating Your Post.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private EditText userName, userProfName, userStatus, userCountry, userGender, userRelation, userDOB;
private Button updateAccountSettingsButton;
private CircleImageView userProfImage;
private ProgressDialog loadingBar;
private DatabaseReference userRef, postRef;
private FirebaseAuth mAuth;
private StorageReference UserProfileImageRef;
private String downloadUrl;
private String currentUserId;
final static int Gallery_Pick = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
userRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(currentUserId);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Account Settings");// this is the back arrow bar
userName = (EditText) findViewById(R.id.settings_username);
userProfName = (EditText) findViewById(R.id.settings_profile_full_name);
userStatus = (EditText) findViewById(R.id.settings_status);
userCountry = (EditText) findViewById(R.id.settings_profile_country);
userGender = (EditText) findViewById(R.id.settings_gender);
userRelation = (EditText) findViewById(R.id.settings_relationship_status);
userDOB = (EditText) findViewById(R.id.settings_profile_dob);
userProfImage = (CircleImageView) findViewById(R.id.settings_profile_image);
updateAccountSettingsButton = (Button) findViewById(R.id.update_account_settings_button);
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String myProfileImage = dataSnapshot.child("profileimage").getValue().toString();
String myUserName = dataSnapshot.child("username").getValue().toString();
String myProfileName = dataSnapshot.child("fullname").getValue().toString();
String myProfileStatus = dataSnapshot.child("status").getValue().toString();
String myDOB = dataSnapshot.child("dob").getValue().toString();
String myCountry = dataSnapshot.child("country").getValue().toString();
String myGender = dataSnapshot.child("gender").getValue().toString();
String myRelationStatus = dataSnapshot.child("relationshipstatus").getValue().toString();
Picasso.get().load(myProfileImage).placeholder(R.drawable.profile).into(userProfImage);
userName.setText(myUserName);
userProfName.setText(myProfileName);
userStatus.setText(myProfileStatus);
userDOB.setText(myDOB);
userCountry.setText(myCountry);
userGender.setText(myGender);
userRelation.setText(myRelationStatus);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
updateAccountSettingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ValidateAccountInfo();
}
});
userProfImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
}
// In settings start this when a new pic is selected to replace the existing profile pic
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
// Get the result of the image and store it in resultUri
Uri resultUri = result.getUri();
// Get a reference to the storage in Firebase. Its a filepath to the Firebase Storage
// Create a child and store to the user with a file type .jpg
final StorageReference filePath = UserProfileImageRef.child(currentUserId + ".jpg");
// Store the cropped image "resultUri" into the profile image's folder
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
downloadUrl = uri.toString();
userRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
//Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
//startActivity(selfIntent);
Toast.makeText(SettingsActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SettingsActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
I'm not having any problem storing my images and text to Firebase and then back to my app when I make a post. However, when I decided to create a settings Class and allow the user to change the profile image, the image's URLs that are stored in each Post are not updating. I can't figure out how to navigate to "Posts/uniqueID/postprofileimage". I though about getting rid of the unique Id, and then realized that each new post would overwrite the old post. I need to generate a unique id so my posts are unique, but I can't figure out how to update the postprofileimage when I update the "Users/profileimage" I tried researching how to perform atomic multi-thread updates, but just can't seem to figure it out. I'm new to Android Studio and Firebase. I've spent a week stumped on this and have come here begging for someone's help. When I update the profile image under "Users", how do I update the image on all of the past Posts associated with the current user? The unique ID that I create ("currentUserID" + date + time) seems to be my issue. I can't figure out how to reach the .child(postprofileimage). Thank you in advance. After trouble shooting, I realized that when I change the image the new URL isn't carrying over to the old posts. Then I realized that I need to manually update the old posts with the new image URL, but can't figure out how to do that. All of this is new to me, and I can't seem to find any videos or posts that help me figure this out.
A:
The unique ID that I create ("currentUserID" + date + time) seems to be my issue.
No, it's not.
how do I update the image on all of the past posts associated with the current user?
To update all the image of all posts, please use the following line of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
Query query = postsRef.orderByChild("uid").equalTo(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.child("postprofileimage").getRef().setValue("newPostProfileImage");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
|
[
"stackoverflow",
"0059952562.txt"
] | Q:
Spartacus not loading translations from local JSON files when using SSR
When loading translations from json files in the local assets folder,they can't be loaded by the Node server when using Server-side rendering.
Steps to reproduce:
Add config for loading translations from local files to the
i18n: {
backend: {
loadPath: 'assets/translations/{{lng}}/{{ns}}.json',
},
chunks: translationChunksConfig,
fallbackLang: 'en'
},
Activate Server-side rendering using the Spartacus documentation
Build an run the SSR application using
yarn build:ssr and
yarn serve:ssr
Deactivate Javascript in the browser to see what is rendered on the server
The translations are not loaded by the Node application:
One possible workaround is to just compile the translation into the code using Typescript files. But is there a way to also get this to work with JSON?
Thank you,
Armin
A:
While the issue was addressed before in in https://github.com/SAP/cloud-commerce-spartacus-storefront/issues/6030, there has been a new bug observed: https://github.com/SAP/cloud-commerce-spartacus-storefront/issues/6307. The latter is fixed, but not yet merged. I've just raised priority and hope we can deliver this soon in a patch release for 1.4.x.
|
[
"stackoverflow",
"0015790647.txt"
] | Q:
How to set duplicates at EList
I have been trying to set duplicates,Strings,at EList.
The issue that the following method bans to add duplicates:
elist.set(index, value);
I have been searching on a way that fixes that and I have found that I need to disable Uniqueness but this would may affect the rest of framework.
Any ideas would be appreciated.
Thanks.
A:
Disable the uniqueness setting has been how I have handled this. What are the effects to the rest of the framework?
|
[
"stackoverflow",
"0035220288.txt"
] | Q:
How can I install libicui18n.so.52 on travis?
How can I install libicui18n.so.52 on travis ?
I have a problem with libicui18n.so.52
[phantomjs.launcher]: /home/travis/build/MyProject/node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/lib/phantom/bin/phantomjs: error while loading shared libraries: libicui18n.so.52: cannot open shared object file: No such file or directory
I tried this in my .travis.yml :
sudo: false
before_install:
- apt-get install -i libicu52_52.1-3ubuntu0.4_amd64.deb
But I have this error :
The command "sudo apt-get install -y libicu52_52.1-3ubuntu0.4_amd64.deb" failed and exited with 100 during .
A:
Solved with this :
sudo: required
before_install:
- sudo wget http://security.ubuntu.com/ubuntu/pool/main/i/icu/libicu52_52.1-3ubuntu0.4_amd64.deb
- sudo dpkg -i libicu52_52.1-3ubuntu0.4_amd64.deb
|
[
"stackoverflow",
"0019787549.txt"
] | Q:
get data from 3 relational tables
I have three tables Guardian, Student and StudentsGuardian. Table information is as under
Guardian:
id(pk)
Student:
id(pk)
name
address
StudentsGuardian:
student_id(fk)
guardian_id(fk)
I want to select those students whose guardian_id=2(suppose). Actually these are relational tables so i am unable to think a way to accomplish it. If i apply join it would return a joint table but i need only the information of those students having guardian_id= specific id.
It could be a basic question but i am stuck in it. Thanks
A:
Use below query:
SELECT s.id, s.name, s.address
FROM Student s
INNER JOIN StudentsGuardian sg ON s.id = sg.student_id
WHERE sg.guardian_id = 'somespecific_id'
|
[
"stackoverflow",
"0036254379.txt"
] | Q:
Difference between architectural styles and architectural patterns
what is the difference between architectural styles and patterns in software architecture?
Are they considered the same?
Thanx
A:
Architecture Style
It is broader perspective in terms of defining a centralized layered concept for a system
Architecture Patterns
It is a coarse-grained solution to given architectural case study to follow certain principles, guidelines to build a robust system.
To answer to your Question
Both denotes the same meaning and please find this link supporting to this statement.
|
[
"stackoverflow",
"0014121009.txt"
] | Q:
Getting all vertices of a rectangle
In my program, I had a requirement to plot a rectangle that that is prependicular to a line coming from the centre.
To orient the rectangle in this way in 3D space, I used the gluLookAt giving it the lookAt point and plotted the rectangular figure. This worked correctly for me.
To draw the rectangle (in my framework, that uses openGL at the back), I now use a rectangle class and have extended it with a 3D Node (where node is something that has a lookAt point). Given width, height and the top vertex, the rectangle is drawn (node is at the top left vertex and orients the rectangle using lookAt).
Node also has a getPosition() function that gives me its 3D position (top left in rectangle - say 300,400,20). I am trying to get the position of the other three vertices in 3D space to use for my operation. Since the rectangle is oriented in 3D space, other three vertices can't just be fetched by addition of width and height. With the rectangle oriented in 3D, how do I get the position of the other three vertices?
A:
You can retreive the position of the 3 other points using the normal of the rectangle. In order to orient a rectangle in space, you need 2 information:
its position, commonly represented as a 3 or 4 components vector, or a 4x4 matrix ;
its orientation, commonly represented as a quaternion.
If you have the orientation represented with a normal, and only have one point, you just can’t deduce the other points (because you need another information to solve the rotation equation around the normal). I think the best idea is to use quaternion to orient things in space (you can still retreive the normal from it), but you can also use a normal + one vector from the rectangle. You said you only have one point, and a tuple (width,height), so the common method based on the × operation won’t make it through.
I suggest you to:
make your Node class a class that correctly handles orientation; lookAt isn’t designed for that job ;
combine the translation matrix (position) with a cast matrix from the quaternion (orientation) to correctly handle both position and orientation ;
use that matrix to extract a rotated vector you’ll used like rotated × normal to get the 3 points.
|
[
"stackoverflow",
"0032580890.txt"
] | Q:
Charts.js: thin donut chart background
I want to create a donut chart with a thin gray background in it.
The only way I found to create it is adding a second donut chart to create the background.
Is there any way to do it simpler?
HTML:
<div class="chart-cont">
<canvas id="pointsUsed" height="200"></canvas>
<canvas id="pointsUsedBg" height="200"></canvas>
</div>
CSS:
.chart-cont {
position: relative;
}
#pointsUsed {
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
#pointsUsedBg {
position: absolute;
top: 0;
left: 0;
transform: scale(0.96,0.96);
}
JavaScript:
var pointsUsed = [
{
value: 44250,
color: "#FF5F33",
},
{
value: 100000,
color: "transparent",
},
];
var pointsUsedBg = [
{
value: 100000,
color: "#EEEEEE",
},
];
var pointsUsed_ctx = document.getElementById("pointsUsed").getContext("2d");
var pointsUsedBg_ctx = document.getElementById("pointsUsedBg").getContext("2d");
var pointsUsed = new Chart(pointsUsed_ctx).Doughnut(pointsUsed, {
segmentShowStroke: false,
segmentStrokeWidth : 0,
percentageInnerCutout: 87,
showTooltips: false,
animationEasing: 'easeInOutCubic',
responsive: true
});
var pointsUsedBg = new Chart(pointsUsedBg_ctx).Doughnut(pointsUsedBg, {
segmentShowStroke: false,
segmentStrokeWidth : 0,
percentageInnerCutout: 94,
showTooltips: false,
animation: false,
responsive: true
});
JSFiddle
Thanks!
A:
You can extend the Doughnut chart to do this, like so
Chart.types.Doughnut.extend({
name: "DoughnutAlt",
initialize: function (data) {
// call the actual initialize
Chart.types.Doughnut.prototype.initialize.apply(this, arguments);
// save the actual clear method
var originalClear = this.clear;
// override the clear method to draw the background after each clear
this.clear = function () {
// call the original clear method first
originalClear.apply(this, arguments)
var ctx = this.chart.ctx;
// use any one of the segments to get the inner and outer radius and center x and y
var firstSegment = this.segments[0];
// adjust 0.3 to increaase / decrease the width of the background
var gap = (firstSegment.outerRadius - firstSegment.innerRadius) * (1 - 0.3) / 2;
// draw the background
ctx.save();
ctx.fillStyle = "#EEE";
ctx.beginPath();
ctx.arc(firstSegment.x, firstSegment.y, firstSegment.outerRadius - gap, 0, 2 * Math.PI);
ctx.arc(firstSegment.x, firstSegment.y, firstSegment.innerRadius + gap, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
});
You would call it like this
var pointsUsed = new Chart(pointsUsed_ctx).DoughnutAlt(pointsUsed, {
...
Fiddle - http://jsfiddle.net/7nfL1m7d/
|
[
"sharepoint.stackexchange",
"0000169308.txt"
] | Q:
Get user permissions using CSOM
For SharePoint Online, I am trying to get user permissions on a site, including library, folders and files, using CSOM.
I have the following code:
ClientResult<BasePermissions> info = site.Web.GetUserEffectivePermissions(user.LoginName);
and well I have two problems, first, info is null.
Second, I cannot use info.RoleAssignments Visual Studio gives me the error:
Error 1 'Microsoft.SharePoint.Client.ClientResult' does not contain a definition for 'RoleAssignments' and no extension method 'RoleAssignments' accepting a first argument of type 'Microsoft.SharePoint.Client.ClientResult' could be found (are you missing a using directive or an assembly reference?)
I read that when you are using SharePoint dll you may have used the wrong one, but I am using SharePoint.Client so, any ideas?
This is the first part of the code:
using (ClientContext site = new ClientContext(siteTextBox.Text))
{
SecureString password = new SecureString();
foreach (char c in "mypass".ToCharArray()) passWord.AppendChar(c);
site.Credentials = new SharePointOnlineCredentials("[email protected]", password);
site.Load(site.Web);
site.ExecuteQuery();
Web web = site.Web;
User user = web.EnsureUser(userTextBox.Text); //string is like: [email protected] on userTextBox
site.Load(user);
site.ExecuteQuery();
ClientResult<BasePermissions> info = site.Web.GetUserEffectivePermissions(user.LoginName);
//info.RoleAssignments is not recognized
foreach (SPRoleAssignment roleAssignment in info.RoleAssignments)
{
//Do something
}
}
A:
RoleAssignment and BasePermissions are two different things.
RoleAssignment specifies a binding between:
Principal (User or Group),
SecurableObject (an object you can assign permissions to, like Web, List, ListItem),
Collection of RoleDefinition bindings (or permission levels. Each RoleDefinition is a set of specific rights - BasePermissions).
BasePermission object (result of GetUserEffectivePermissions method), represents the actual rights user has on particular SecurableObject (web in your example). Those rights are sum of all permissions assigned to user directly, through group membership or inherited from parent objects.
There is no API to iterate RoleAssignments or permissions of specific user. You need to iterate all the objects. This may be a starting point:
using (ClientContext context = new ClientContext("https://contoso.com"))
{
//no need to load web
var web = context.Web;
var user = web.EnsureUser(userLogin);
context.Load(user, u => u.LoginName);
var lists = web.Lists;
context.Load(lists, lc => lc.Include(l => l.Title));
//you can use one execute per multiple loads
context.ExecuteQuery();
foreach (var list in lists)
{
var permissions = list.GetUserEffectivePermissions(user.LoginName);
var assignments = list.RoleAssignments;
context.Load(assignments, ac => ac.Include(
a => a.RoleDefinitionBindings, a => a.Member.LoginName));
context.ExecuteQuery();
//check edit rights on the object
var canEdit = permissions.Value.Has(PermissionKind.EditListItems);
if (canEdit)
{
Console.WriteLine("User has edit rights to: {0}", list.Title);
}
//get role assignments
var assignment = assignments.FirstOrDefault(a => a.Member.LoginName == user.LoginName);
if (assignment != null)
{
foreach (var role in assignment.RoleDefinitionBindings)
{
Console.WriteLine(" Role: {0}", role.Name);
}
}
}
}
|
[
"stackoverflow",
"0017072978.txt"
] | Q:
Need help to figure out a batch file
How do I determine the value of variable ecg in the batch file given below ?
for /f "Tokens=1-4 Delims=/ " %%i in ('date /t') do set ecg=%%l%%j%%k
A:
an easy way is to add the following line
echo.ecg=%ecg%
By way of explanation...
%%i would be the first token (day of week) which you are not using
%%j is the 2nd token (month)
%%k is the 3rd token (day of month)
%%l is the 4th token (year)
So ecg will contain something like 20130612... depending on the date format your PC is set to use.
|
[
"stackoverflow",
"0059656961.txt"
] | Q:
In a DAG, how to find vertices where paths converge?
I have a type of directed acyclic graph, with some constraints.
There is only one "entry" vertex
There can be multiple leaf vertices
Once a path splits, anything under that path cannot reach into the other path (this will become clearer with some examples below)
There can be any number of "split" vertices. They can be nested.
A "split" vertex can split into any number of paths. The examples below only show 2 paths for each, but it could be more.
My challenge is the following: for each "split" vertex (any vertex that has at least 2 outgoing edges), find the vertices where its paths reconnect - if such a vertex exists. The solution should be as efficient as possible.
Example A:
example a
In this example, vertex A is a "split" vertex, and its "reconnect vertex" is F.
Example B:
example b
Here, there are two split vertices: A and E. For both of them vertex G is the reconnect vertex.
Example C:
example c
Now there are three split vertices: A, D and E. The corresponding reconnect vertices are:
A -> K
D -> K
E -> J
Example D:
example d
Here we have three split vertices again: A, D and E. But this time, vertex E doesn't have a reconnect vertex because one of the paths terminates early.
A:
Sounds like what you want is:
Connect each vertex with out-degree 0 to a single terminal vertex
Construct the dominator tree of the edge-reversed graph. The linked wikipedia article points to a couple algorithms for doing this.
The "reconnect vertex" for a split vertex is its immediate dominator in the edge-reversed graph, i.e., its parent in that dominator tree. This is called its "postdominator" in your original graph. If it's the terminal vertex that you added, then it doesn't have a reconnect vertex in your original graph.
|
[
"gamedev.stackexchange",
"0000090100.txt"
] | Q:
Memory strategy for multilayer, tilebased maps
I am currently developing a 2d mmorpg and am having some memory issues with regards to my tile based map. The client takes a little while to load and then sits around 1GB ram, because I am loading each tile, for each layer, into memory. My map is currently 1/3 of its expected size.
My map has multiple layers which are drawn on top of each other - ground, building, and object. Each of these layers is stored in a separate short[] array. My question is how can I do this better.
I have thought of some ideas:
Load zones into memory (i.e. 500x500) and when user goes into next zone disgard and load new 500x500
Load zones into memory (i.e. 500x500) and when user goes 250 tiles east disgard 0-250 tiles
Read from filesystem rather than memory
Can anyone give some suggestions and perspectives as to why, which above (or other ideas) work best?
Somes notes/issues I've found:
My game has 1 seamless world map(hard to split to zones)
Users can be teleported by GM/DEVs - but will usually only happen if they are stuck somewhere(potiential issues for storing chunks in memory)
My game is www.KisnardOnline.com for anyone interested.
Thanks anyone/everyone for taking a look and your help.
A:
I can address your ideas and some of the issues related with them.
Load zones into memory (i.e. 500x500) and when user goes into next
zone disgard and load new 500x500
This is the basic idea of what you want to achieve for a seamless world. However, if left at this basic approach you will incur what is known as "image popping". When the player gets to the boundary of that zone, he will see nothing, and then, BAM, the entire zone is pushed into his screen. So, while this is the right step, it has some issues.
Load zones into memory (i.e. 500x500) and when user goes 250 tiles
east disgard 0-250 tiles
This is more of the complete step to your previous idea was looking for. Now, you are essentially buffering the viewport against image popping. This is a much better solution then the previous.
Read from filesystem rather than memory
No, no, don't do that. Ram is MUCH faster then the file system. Not too mention, you need to have room in ram to pull in that data, so if you're blocking room for that data...just read it anyways!
My game has 1 seamless world map(hard to split to zones)
You solved that issue with your second idea.
Users can be teleported by GM/DEVs - but will usually only happen if
they are stuck somewhere(potiential issues for storing chunks in
memory)
I don't want to recommend this because I hate loading screens, but if it's an issue with graphics lag etc, you might have to throw up a loading screen when gm teleports them. Or, just let the elements pop in. It's fun to watch sometimes.
|
[
"stackoverflow",
"0036603652.txt"
] | Q:
Extracting data from a wikipedia page
This question might be really specific. I am trying to extract the number of employees from the Wikipedia pages of companies such as https://en.wikipedia.org/wiki/3M.
I tried using the Wikipedia python API and some regex queries. However, I couldn't find anything solid that I could generalize for any company (not considering exceptions).
Also, because the table row does not have an id or a class I cannot directly access the value. Following is the source:
<tr>
<th scope="row" style="padding-right:0.5em;">
<div style="padding:0.1em 0;line-height:1.2em;">Number of employees</div>
</th>
<td style="line-height:1.35em;">89,800 (2015)<sup id="cite_ref-FY_1-5" class="reference"><a href="#cite_note-FY-1">[1]</a></sup></td>
</tr>
So, even though I have the id of the table - infobox vcard so I couldn't figure out a way to scrape this information using beautifulSoup.
Is there a way to extract this information? It is present in the summary table on the right at the beginning of the page.
A:
Using lxml.etree instead of BeautifulSoup, you can get what you want with an XPath expression:
>>> from lxml import etree
>>> import requests
>>> r = requests.get('https://en.wikipedia.org/wiki/3M')
>>> doc = etree.fromstring(r.text)
>>> e = doc.xpath('//table[@class="infobox vcard"]/tr[th/div/text()="Number of employees"]/td')
>>> e[0].text
'89,800 (2015)'
Let's take a closer look at that expression:
//table[@class="infobox vcard"]/tr[th/div/text()="Number of employees"]/td
That says:
Find all table elements that have attribute class set to infobox
vcard, and inside those elements look for tr elements that have a
child th element that has a child div element that contains the
text "Number of employees", and inside that tr element, get the
first td element.
|
[
"electronics.stackexchange",
"0000039231.txt"
] | Q:
Why does an op-amp perform poorly with no load?
I have a THS4221 evaluation module (THS4221EVM, schematic on pg 1-3) powered with a bipolar +/-5V supply.
My function generator (AtelierRobin F125) is generating a nice 1 MHz square wave, which I have verified with my GDS-1102A scope. I have the square wave hooked up to the input of the THS4221EVM, and am monitoring the floating output (VOUT in the THS4221EVM schematic) through the second channel of my GDS-1102A scope (high impedance input).
The output voltage on the THS4221EVM takes a long time (~250 nS) to settle at the final value after each voltage change in the square wave. It initially slews very quickly, but slows down as the it approaches the target voltage.
If I connect VOUT to ground so R5 (935 ohms) becomes the output load, and measure at U1_1, the output is as expected.
Why is the performance affected in this way when there's no load?
Strangely, TI's hookup diagram (pg 2-1 in the manual) for this evaluation board says to connect the output directly to a scope, but if the opamp doesn't work properly with no load, then why is it setup that way? Even with a load on VOUT, I have to manually probe the circuit to measure the opamp output since the VOUT connector is after R5.
EDIT: TI's hookup diagram makes sense now; I missed where the 'scope is referred to as a "50-ohm monitoring instrument". They expect the connection to provide a 50-ohm load, but my scope has a high-impedance input. A 50 ohm termination resistor would provide the load.
A:
Well I'll hazard an answer and say that the problem to me looks like output capacitance of the opamp and the board traces. The description of the way the voltage settles to me looks like charging and discharging of a capacitor. Very quickly at first and then slower and slower as the voltage settles. I'd almost describe that as exponential function.
The evaluation board documentation says quite clearly that the minimum load is 1000 ohms and that is reached on the board using 953 ohm resistor which should be placed in series with the 50 ohm resistor of the measurement device.
From the schematic, we see that the resistor R6 "does not apply" to THS4221EVM board, so I'd take that to mean that it isn't there (BOM says so too). The result of that is that we have nothing to drive the output signal to the ground, so what we have is remaining basically a capacitor (Take a look at the PCB layers. Which circuit component consists of two parallel plates? And what do the ground planes and the trace near R6 look like?), which, well, behaves exactly like a capacitor should behave. You have a resistor formed using op-amp's output resistance, resistance of the traces and the R5 through the capacitor consisting of the output trace and ground plane. I'd say that it's capacitance is around 250 pF, but I'm not experienced enough to claim that the number is correct.
Now about the bad performance of the board side: First, what are you going to do with an op-amp whose output is floating? It's basically useless! I'd say it's reasonable to exclude such usage scenario when we're constructing a device.
Cases where the input impedance of the next stage of the circuit is high enough so that it seems that the op-amp is floating are special. High impedance circuits require experience to make properly and countless factors (such as parasitic capacitances and inductances everywhere) need to be taken into account. For that reason, we have the R6 pads. If we do place R6 and connect the op-amp to a high impedance circuit, well have a high impedance in parallel with low impedance. The result which op-amp sees is going to be lower than the lower of the two impedances and the op-amp will be able to swing the voltage quickly, since by decreasing the impedance, we decreased the time constant of the parasitic capacitor circuit we have here. If we placed R6 there all the time, even when the next stage has low input impedance, we'd be providing unnecessarily high load on the op-amp and we'd be wasting power too.
Also note that all characteristics in the datasheet are made with load resistor of 499 ohms, unless otherwise noted (and settling times do use that resistance)!
|
[
"stackoverflow",
"0027860193.txt"
] | Q:
Modifying HTML using java
I am trying to read a HTML file and add link to some of the texts :
for example :
I want to add link to "Campaign0" text. :
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">101</span></p></td>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">Campaign0</span>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">unknown</span></p></td>
Link to be added:
<a href="Second.html">
I need a JAVA program that modify html to add hyperlink over "Campaign0" .
How i do this with Jsoup ?
I tried this with JSoup :
File input = new File("D://First.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span").first(); <-- this is only for first span tag :(
span.wrap("<a href="Second.html"></a>");
Is this correct ?? It's not working :(
In short : is there anything like-->
if find <span>Campaign0</span>
then replace by <span><a href="">Campaign0</a></span>
using JSoup or any technology inside JAVA code??
A:
Your code seems pretty much correct. To find the span elements with "Campaign0", "Campaign1", etc., you can use the JSoup selector "span:containsOwn(Campaign0)". See additional documentation for JSoup selectors at jsoup.org.
After finding the elements and wrapping them with the link, calling doc.html() should return the modified HTML code. Here's a working sample:
input.html:
<table>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign0</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign1</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</table>
Code:
File input = new File("input.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span:containsOwn(Campaign0)").first();
span.wrap("<a href=\"First.html\"></a>");
span = doc.select("span:containsOwn(Campaign1)").first();
span.wrap("<a href=\"Second.html\"></a>");
String html = doc.html();
BufferedWriter htmlWriter =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.html"), "UTF-8"));
htmlWriter.write(html);
htmlWriter.close();
output:
<html>
<head></head>
<body>
<table>
<tbody>
<tr>
<td><p><span>101</span></p></td>
<td><p><a href="First.html"><span>Campaign0</span></a></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><a href="Second.html"><span>Campaign1</span></a></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</tbody>
</table>
</body>
</html>
|
[
"stackoverflow",
"0006200414.txt"
] | Q:
java.lang.NoSuchMethodError: java.lang.NoSuchMethodError
Running Tomcat 7 through eclipse
The error reported is:
javax.servlet.ServletException: java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getProblems()[Lorg/eclipse/jdt/core/compiler/IProblem;
at org.apache.jasper.compiler.JDTCompiler$2.acceptResult(JDTCompiler.java:341)
I have tried both jasper-jdt-6.0.13.jar and tomcat-6.0.16-jasper-jdt.jar and both report the same error. In a way I shouldn't be surprised because I ran:
jar tf tomcat-6.0.16-jasper-jdt.jar
and it doesn't have the class org.eclipse.jdt.internal.compiler.CompilationResult in it. But this site http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadtomcat6016jasperjdtjar.htm says it does!!
Can someone tell me what the correct jar file is and where to get it from?
It seems to be a recurring theme. http://www.findjar.com lists a number of jars that purport to have this class - but do not.
OK, Found it in jasper-compiler-jdt-5.5.23.jar
A:
Found it in jasper-compiler-jdt-5.5.23.jar
|
[
"stackoverflow",
"0021668239.txt"
] | Q:
How do I track file download count?
I'm trying to track when a user downloads a .zip file from my Rails site. The file is hosted by S3/Cloudfront. If the HTML is something like:
<a href="http://something.cloudfront.net/path/to/file.zip">Download File</a>
I could attach a JQuery event that will send a GET request to my server that will increment the downloads column in my database. However, if the user goes to the URL directly, the download will occur but it will not be tracked.
Is there a solution?
A:
Yudong's answer is the only one which would work by just providing a download link, but Amazon states that they log on a "best effort" basis and it's by no means accurate accounting. I think the simplest way would do a redirect and count the redirects and the most accurate would be to stream the zip file yourself through your server (would not really make a huge difference if hosted on Amazon as well unless you have a lot of traffic and huge files). Another way would be to use a CDN which gives you accurate access logs. Your Jquery idea is as good as the redirect.
|
[
"stackoverflow",
"0048769443.txt"
] | Q:
git reflog in bare repository with core.logAllRefUpdates set true returns nothing
I have mirrored a git repository using git clone --mirror, then set git config core.logAllRefUpdates true, then later updated with git fetch -p.
On the server hosting the repo, if I run git reflog in the repository.git directory, I get no output.
The docs for core.logAllRefUpdates states that refs are placed in $GIT_DIR/logs/<ref>, but I have no logs directory. Do I need to create it manually?
core.logAllRefUpdates
Enable the reflog. Updates to a ref is logged to the file "$GIT_DIR/logs/", by appending the new and old SHA-1, the date/time and the reason of the update, but only when the file exists. If this configuration variable is set to true, missing "$GIT_DIR/logs/" file is automatically created for branch heads (i.e. under refs/heads/), remote refs (i.e. under refs/remotes/), note refs (i.e. under refs/notes/), and the symbolic ref HEAD. If it is set to always, then a missing reflog is automatically created for any ref under refs/.
A:
No, you do not have to create that directory. For bare repositories just enable the reflogs via
git config core.logAllRefUpdates true
The values true and always are supported. Then to see the reflog for a branch type
git reflog <branch>
See more details here, and the documentation page of git reflog, for other configuration options.
|
[
"stackoverflow",
"0042599759.txt"
] | Q:
Python circles in a 1x1 square not overlapping or outside the square
So what I have to do is create 50 circles wich are not overlapping or outside a square (0,0) to (1,1) here is my code so far:
fig = plt.figure()
ax = fig.add_axes([.1, .1, .8, .8], axisbg = 'Violet', aspect = 'equal')
clist = []
def overlap(c1, c2):
distance = ((c1.center[0] - c2.center[0])**2 + (c1.center[0] - c2.center[0])**2)**0.5
return distance < c1.radius + c2.radius
for i in range(1000):
x = np.random.rand(1)
y = np.random.rand(1)
c = Circle(xy=(x, y), radius = 0.05, fc = 'Blue', ec = 'DarkBlue', lw = 1.5)
if x - 0.05 >= 0.0:
if x + 0.05 <= 1.0:
if y - 0.05 >= 0.0:
if y + 0.05 <= 1.0:
if len(clist) == 0:
clist.append(c)
ax.add_patch(c)
else:
for j in range(len(clist)):
if overlap(c, clist[j]) == True:
break
if j == len(clist) - 1:
if overlap(c, clist) == False:
clist.append(c)
ax.add_atch(c)
if len(clist) == 50:
break
ax.autoscale()
If I would print my list I would get the following:
[<matplotlib.patches.Circle object at 0x07E5F3D0>]
So when I run my code this error occurs:
AttributeError Traceback (most recent call last)
<ipython-input-35-48e3a2854e8e> in <module>()
24 break
25 if j == len(clist) - 1:
---> 26 if overlap(c, clist) == False:
27 clist.append(c)
28 ax.add_atch(c)
<ipython-input-35-48e3a2854e8e> in overlap(c1, c2)
4
5 def overlap(c1, c2):
----> 6 distance = ((c1.center[0] - c2.center[0])**2 + (c1.center[0] - c2.center[0])**2)**0.5
7 return distance < c1.radius + c2.radius
8
AttributeError: 'list' object has no attribute 'center'
So the mistake is that the circle is stored correctly in the list, but I have seen other people doing it this way. What am I doing wrong?
A:
You are creating c as a Circle with this code:
c = Circle(xy=(x, y), radius = 0.05, fc = 'Blue', ec = 'DarkBlue', lw = 1.5)
You are eventually executing this code with clist:
clist.append(c)
Clearly, one is a Circle, and the other is a list.
You later execute this code:
if overlap(c, clist[j]) == True:
Showing that clist[j] is a circle, as expected.
Then, you do this:
if overlap(c, clist) == False:
You can't do that. clist is a list, not a Circle. You have to index it, like clist[j] or whatever.
|
[
"stats.stackexchange",
"0000057746.txt"
] | Q:
What is residual standard error?
When running a multiple regression model in R, one of the outputs is a residual standard error of 0.0589 on 95,161 degrees of freedom. I know that the 95,161 degrees of freedom is given by the difference between the number of observations in my sample and the number of variables in my model. What is the residual standard error?
A:
Say we have the following ANOVA table (adapted from R's example(aov) command):
Df Sum Sq Mean Sq F value Pr(>F)
Model 1 37.0 37.00 0.483 0.525
Residuals 4 306.3 76.57
If you divide the sum of squares from any source of variation (model or residuals) by its respective degrees of freedom, you get the mean square. Particularly for the residuals:
$$
\frac{306.3}{4} = 76.575 \approx 76.57
$$
So 76.57 is the mean square of the residuals, i.e., the amount of residual (after applying the model) variation on your response variable.
The residual standard error you've asked about is nothing more than the positive square root of the mean square error. In my example, the residual standard error would be equal to $\sqrt{76.57}$, or approximately 8.75. R would output this information as "8.75 on 4 degrees of freedom".
A:
A fitted regression model uses the parameters to generate point estimate predictions which are the means of observed responses if you were to replicate the study with the same $X$ values an infinite number of times (and when the linear model is true). The difference between these predicted values and the ones used to fit the model are called "residuals" which, when replicating the data collection process, have properties of random variables with 0 means.
The observed residuals are then used to subsequently estimate the variability in these values and to estimate the sampling distribution of the parameters. When the residual standard error is exactly 0 then the model fits the data perfectly (likely due to overfitting). If the residual standard error can not be shown to be significantly different from the variability in the unconditional response, then there is little evidence to suggest the linear model has any predictive ability.
A:
Typically you will have a regression model looks like this:
$$
Y = \beta_{0} + \beta_{1}X + \epsilon
$$
where $ \epsilon $ is an error term independent of $ X $.
If $ \beta_{0} $ and $ \beta_{1} $ are known, we still cannot perfectly predict Y using X due to $ \epsilon $. Therefore, we use RSE as a judgement value of the Standard Deviation of $ \epsilon $.
RSE is explained pretty much clearly in "Introduction to Statistical Learning".
|
[
"stackoverflow",
"0037027870.txt"
] | Q:
How to disable Timer service in Wildfly 10?
In my Java EE application I have a @Singleton with several @Scheduled methods. When I deploy the app on Wildfly, the Timer service starts executing these methods, which is correct.
Since during development I test my app on a secondary server, I'd like to disable the Timer service on that instance of Wildfly, to prevent the execution of those methods.
Problem is… I can't find any setting to do this.
How can I disable the Timer service in Wildfly 10?
A:
Try to remove block timer-service in standalone.xml.
<subsystem xmlns="urn:jboss:domain:ejb3:3.0">
...
<timer-service thread-pool-name="default" default-data-store="default-file-store">
<data-stores>
<file-data-store name="default-file-store" path="timer-service-data" relative-to="jboss.server.data.dir"/>
</data-stores>
</timer-service>
It works for wildfly 9.
|
[
"wordpress.stackexchange",
"0000110569.txt"
] | Q:
Private Posts/Pages & Search
I have a site up where there is one private page and one private post. When logged is as admin, i can view both of these, and they even appear in the search.
However, when logged in as an editor, I can still see the posts, but they don't appear in the search. I found this a bit strange, was wondering if anyone has experienced this or knows how to make the private pages and posts appear in the search when logged in as an editor?
A:
This is the default WordPress behavior.
http://codex.wordpress.org/Content_Visibility#Private_Content
Private posts are automatically published but not visible to anyone but those with the appropriate permission levels (Editor or Administrator).
WARNING: If your site has multiple editors or administrators, they will be able to see your protected and private posts in the Edit panel.
If you want to show private posts on the front-end of the site to logged-in editors you can add this code to functions.php.
add_action('pre_get_posts','filter_search');
function filter_Search($query){
if( is_admin() || ! $query->is_main_query() ) return;
if ($query->is_search) {
if( current_user_can('edit_private_posts') ) {
$query->set('post_status',array('private','publish'));
}
}
}
|
[
"stackoverflow",
"0060470849.txt"
] | Q:
Vuetify expansion panel with v-for loop?
I am working with the Vuetify expansion panel and i am using an array Headers to loop over and get the headers and another array named elements to loop over and get the desired text. How can i make it so that the text from elements array show up only under their respective panel. So basically for the panel, Animals, only Cat an Dog show up etc.
Here is a link to the sample codepen
new Vue({
el: "#app",
data() {
return {
headers: [{
text: 'Animals'
},
{
text: 'Food'
},
{
text: 'Colors'
}
],
elements: [{
text: 'Cat',
panel: 'Animals'
},
{
text: 'Dog',
panel: 'Animals'
},
{
text: 'Chocolates',
panel: 'Food'
},
{
text: 'Pizza',
panel: 'Food'
},
{
text: 'Red',
panel: 'Colors'
},
{
text: 'Yellow',
panel: 'Colors'
}
]
}
}
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<v-app id="inspire">
<v-expansion-panel>
<v-expansion-panel-content v-for="(header,i) in headers" :key="i">
<template v-slot:header>
<div>{{header.text}}</div>
</template>
<template v-for="element in elements" :key="element">
<v-card v-if="element.panel == 'Animals'">
<v-card-text >
{{element.text}}
</v-card-text>
</v-card>
</template>
</v-expansion-panel-content>
</v-expansion-panel>
</v-app>
</div>
So basically the Animals Content should contain Dog and Cat, Food should contain Chocolate and Pizza and Colors should contain Red and yellow. Thank You :)
A:
One solution, that doesn't require changing the data format, rather than hard code the v-if as in
<v-card v-if="element.panel == 'Animals'">
You want to check if the element panel belongs to the current header
<v-card v-if="element.panel == header.text">
You can also change the data format (not tested, could be errors below)
new Vue({
el: "#app",
data() {
return {
headers: [{
text: 'Animals',
elements: [{
text: 'Cat'
}, {
text: 'Dog'
}
]
}, {
text: 'Food',
elements: [{
text: 'Chocolates'
}, {
text: 'Pizza'
}
]
}, {
text: 'Colors',
elements: [{
text: 'Red'
}, {
text: 'Yellow'
}
]
}
]
}
}
});
and then the markup would be
<div id="app">
<v-app id="inspire">
<v-expansion-panel>
<v-expansion-panel-content v-for="(header,i) in headers" :key="i">
<template v-slot:header>
<div>{{header.text}}</div>
</template>
<v-card v-for="element in header.elements" :key="element">
<v-card-text >
{{element.text}}
</v-card-text>
</v-card>
</v-expansion-panel-content>
</v-expansion-panel>
</v-app>
</div>
|
[
"stackoverflow",
"0021299926.txt"
] | Q:
App-Inventor 2 and IMPORT multiple rows with a single query
I am pretty new to App Inventor 2. I want to be able to import multiple rows (equal to or less than 10) with a single query to a fusion table.
Even if I managed to create the blocks correctly using INSERT INTO and following the syntax indicated by Google (INSERT INTO table_ID (Column1, Column2, Column3, Column4) VALUES "('value1','value2','value3','value4')"; INSERT INTO table_ID (Column1, Column2, Column3, Column4) VALUES "('value5','value6','value7','value8')"; etc.), this was only OK for less than 8 rows and then got an error -big url-.
So, I had to turn to the import method as indicated.
But, I have a hard time trying to configure the blocks.
I've seen the example here: http://puravidaapps.com/taifunFT2.php#import but I cannot understand what the procedures WebQuery.PostText and printResult are.
Furthermore, AI2 has no 'make text' and 'call _ text' blocks.
Finally, in this example the url seems to be a bit different from that indicated, here: https://developers.google.com/fusiontables/docs/v1/using#ImportingRowsIntoTables;
/fusiontables/docs/v1/.. vs /upload/fusiontables/v1/tables/.
A:
You probably have seen the Note in the Inserting a Row chapter
Note: To insert a large number of rows, use the import method instead, which
will be faster and more reliable than using many SQL INSERT
statements.
However, if you are using the built in Fusiontable controls of App Inventor, you only can use the possibilites in working with rows but not in working with tables. Therefore you have to use the INSERT INTO statement.
Alternatively, and this is described in that link (btw. I'm the author of that page ;-)), you can also access fusiontables with the web component of App Inventor, and there you have more possibilities including the mentioned IMPORT ROWS
For more information how to get the source code of that example, just read the green box on the bottom of that page. Thank you.
And to learn about the differences between AI1 and AI2, see here.
|
[
"parenting.stackexchange",
"0000014937.txt"
] | Q:
My wife wants another baby but we are already grandparents! Help!
My wife wants another child. We have 9 already between us. Our oldest is 23 and youngest just turned 2. Our oldest made us grandparents in April and just found out that she's expecting again. I am going to be 63 when the youngest graduates high school. We each had 3 when we met and have 3 between us. Ages for all kids are 23, 22, 20,19, 17, 16, 7, 4, and 2.
Help!
A:
Having or not having children is an individual decision which should not be forced on another person; that is, you have a right (and likely many good reasons) to refuse to have any more children, and your wife has a right to continue having children - but not with you.
Clearly that's a drastic solution that I do not recommend. You have children and grandchildren between you, and to separate would be tragic for so many people. But your wife cannot force you to have more children, any more than you should be able to force her to have children against her will.
I can't imagine that you haven't talked about this. If you cannot work this out between yourselves, you should seek counseling to try to discover why it is so important for your wife to continue childbearing and child rearing, and what can be done about it. There is something driving your wife's desire, and it should be dealt with straightforwardly (with help).
|
[
"stackoverflow",
"0023580716.txt"
] | Q:
Insertion into a Binary Heap: Number of exchanges in worst case
I was going through Cormen's 'Algorithms Unlocked'. In chapter 6 on shortest path algorithms, on inserting data into a binary heap, I find this: "Since the path to the root has at most floor(lg(n)) edges, at most floor(lg(n))-1 exchanges occur, and so INSERT takes O(lg(n)) time." Now, I know the resulting complexity of insertion in a binary heap is as mentioned, but about the number of exchanges in the worst case, should it not be floor(lg(n)) instead of floor(lg(n))-1. The book's errata says nothing regarding this. So I was wondering if I missed something.
Thanks and Regards,
Aditya
A:
floor(lg(n)) is the correct expression for the maximum number of edges on a path between a leaf and the root, and when you do swaps, you may end up doing one swap for each edge. So floor(lg(n)) is the correct answer for the worst-case number of swaps. The author most likely confused the number of edges on the path with the number of VERTICES on the path when they were writing. If you have V vertices on the path between the leaf and the root, then V-1 is the number of edges so V-1 is the number of swaps you might do in the worst-case.
|
[
"stackoverflow",
"0020533320.txt"
] | Q:
ASP.Net Warnings and Errors after following a tutorial - Need assistance
I'm in a web programming class and our current assignment has to be done using ASP.Net. The problem and cause of my frustration is due to my professors lack teaching, unclear directions, and outdated "guide." I'm using the 2012 version of Visual Studio Ultimate.
I'm supposed to make a completely different program than this "guide," but I have no idea how I'm supposed to do so when I have all of these errors/warning doing EXACTLY as his guide shows.
In his poorly written guide.. he states: "Upon debugging a few errors will show up. Fix them and your webpage will display." Yet using his code and following everything as he did.. I have 52 errors and 3 warnings. I searched for most of them on Google and only found Q&A specific questions for other peoples programs.
There's not much code and I don't get how there are so many errors from replicating my professors code/guide. I'll add some of the errors/warning followed by the code from the files below. If someone can help me fix some of these errors, I'd more than greatly appreciate it. Thanks!
3 warnings:
Warning 34 Function without an 'As' clause; return type of Object assumed. \\vmware-host\shared folders\Documents\Visual Studio 2012\WebSites\CS316Program5\game.aspx.vb 26 14 CS316Program5(1)
Warning 50 Function without an 'As' clause; return type of Object assumed. \\vmware-host\shared folders\Documents\Visual Studio 2012\WebSites\CS316Program5\game.aspx.vb 58 14 CS316Program5(1)
Warning 53 Function without an 'As' clause; return type of Object assumed. \\vmware-host\shared folders\Documents\Visual Studio 2012\WebSites\CS316Program5\game.aspx.vb 91 14 CS316Program5(1)
Some of the 52 errors :(
Error 1 'Context' is not a member of 'game'. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 128
Error 3 Class 'game_aspx' must implement 'ReadOnly Property IsReusable As Boolean' for interface 'System.Web.IHttpHandler'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 144
Error 4 Class 'game_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler'. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 144
Error 5 'GetWrappedFileDependencies' is not a member of 'ASP.game_aspx'. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 163
Error 6 'Server' is not a member of 'ASP.game_aspx'. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 166
Error 7 property 'SupportAutoEvents' cannot be declared 'Overrides' because it does not override a property in a base class. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 169
Error 8 Value of type 'ASP.game_aspx' cannot be converted to 'System.Web.UI.Page'. C:\Users\Justin Geis\AppData\Local\Temp\Temporary ASP.NET Files\root\95a42970\24c7c528\App_Web_mrk1wbiu.0.vb 230
game.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="game.aspx.vb" Inherits="game" Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Customer Data</title>
</head>
<body>
<form id="form1" runat="server">
Name:
<asp:TextBox ID="username" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="username" ErrorMessage="name required"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" onClick="nameEntered" runat="server" Text="Submit" />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<h1>
<asp:Label ID="pageloaded" runat="server" Text=""></asp:Label>
</h1>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" Visible="false">
<ContentTemplate>
<br />
Zip Code:
<asp:TextBox ID="Zip" runat="server" AutoPostBack="true" OnTextChanged="ZipChanged"></asp:TextBox>
<asp:Label ForeColor="Red" ID="errormessage" runat="server" Text=" "> </asp:Label>
<br />
Address:
<asp:TextBox ID="Address" AutoPostBack="true" runat="server"></asp:TextBox>
<asp:Label ForeColor="Red" ID="errormessage2" runat="server" Text=" "> </asp:Label>
<br />
City:
<asp:TextBox ID="City" runat="server"></asp:TextBox>
<br />
State:
<asp:TextBox ID="State" runat="server"></asp:TextBox>
<asp:Label ID="updatemessage" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
game.aspx.vb
' game.aspx.vb
' asp.net vb.net example
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
' code behind is in a class like this
' the name customer must match the name in the inherits
' attribute of the page directive at the top of the aspx file
Partial Class customer
Inherits System.Web.UI.Page
' zipchanged executed when user clicks in address textbox
Function ZipChanged(ByVal sender As Object, ByVal e As System.EventArgs)
' verify that user entered 5 digits for zip code
' using regualr expression pattern matching
Dim myMatch As Match = System.Text.RegularExpressions.Regex.Match(Zip.Text, "^\d{5}$")
' if 5 digits entered
If myMatch.Success Then
errormessage.Text = "" ' blank out any previous error message
updatemessage.Text = "City/State updated at " + DateTime.Now.ToString()
' VB case (select/switch) statement
Select Case Zip.Text ' select on zip code entered
Case "40502"
' update text boxes
City.Text = "Lexington"
State.Text = "KY"
Case "60609"
City.Text = "Chicago"
State.Text = "IL"
Case Else ' entered zip code not found
City.Text = ""
State.Text = ""
updatemessage.Text = "Unknown zip code"
End Select
Else ' invalid zip code entered
errormessage.Text = "zip code must be 5 digits"
City.Text = ""
State.Text = ""
updatemessage.Text = ""
End If
End Function
' Page_Load executed whenever page is loaded by user
Function Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Page.IsPostBack is used to check if this is
' the first load of the page (not an Ajax update)
If Not Page.IsPostBack Then
' first load - not Ajax update of page
Dim I As Integer ' iterator for cookie search
Dim foundcookie As Boolean = False ' flag if cookie found
Dim currenttime As String ' current time kept here
currenttime = DateTime.Now.ToString()
' Running on your local PC cookies kept
' under "localhost". Iterate thru all local cookies.
For I = 0 To Request.Cookies.Count - 1
' If not first execution within 24 hours
' the time was put in a cookie named LastAccess
If Request.Cookies.Item(I).Name = "LastAccess" Then
foundcookie = True
' Get the cookie value and display to user
pageloaded.Text = "Page last loaded at: " + Request.Cookies.Item(I).Value
End If
Next
If Not foundcookie Then
pageloaded.Text = "First load of page at: " + currenttime
End If
' Save current time in a cookie named LastAccess
Dim myCookie As New HttpCookie("LastAccess")
' cookie value
myCookie.Value = currenttime
' cookie expires in 24 hours
myCookie.Expires = DateTime.Now.AddHours(24)
' now add the cookie (name in myCookie: LastAccess)
Response.Cookies.Add(myCookie)
End If ' if not first load of page
End Function
Function nameEntered(ByVal sender As Object, ByVal e As System.EventArgs)
Button1.Text = "Clicked"
UpdatePanel1.Visible = True
End Function
End Class
Web.Config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<appSettings>
<add key="webpages:Enabled" value="true"/>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
</appSettings>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
A:
There's some code missing here, among other things.
The code-behind class - game.aspx.vb - is referenced in the page declaration at the top of game.aspx: -
CodeFile="game.aspx.vb" Inherits="game"
But the class in game.aspx.vb is called customer ? This won't work. The 'inherits' part of the page declaration clearly states it is looking for a class called 'game'.
Also, a bunch of your errors are related to an IHttpHandler implementation: -
Error 3 Class 'game_aspx' must implement 'ReadOnly Property IsReusable As Boolean' for interface 'System.Web.IHttpHandler'... (snip)
Apparently, these are in a class called game_aspx which is not in anything you posted.
Your lecturer is trying to get you to solve stupid and confusing problems before you have seen how things work properly. This is an idiotic way of teaching, especially when he is showing you a whole load of concepts you probably haven't seen before.
I feel sorry for you. Nobody should have to suffer such poor quality teaching.
Anyway - if you can dig out the rest of the code and post it, I might be able to help.
|
[
"stats.stackexchange",
"0000272270.txt"
] | Q:
What is the overall outcome of a multiple regression analysis?
If one is measuring safety climate (which has dimensions or contributing factors to the overall safety climate), what do the results of a regression tell you? I know it either states if they are related as in being statistically significant or not, but how?
A:
First of all we'll need to be sure that the model is well specified, assumptions are checked and not grossly violated, influential data point or other anomalies are addressed...etc. Then we would look at the regression output. If you are not sure about the above steps, get statistical help because the output of an atrocious model and that of a wonderful model can look very similar to untrained eyes.
Resources on how to appreciate regression output are plenty online. It'd also help if you know which software you'll be using because while they are all regressions, the outputs do look a bit different albeit containing mostly the same information.
Here are a few that may help you to get started: 1, 2, 3, 4.
In addition, consider reading up on some applied statistics or biostatistics text chapters. Usually in 1-2 chapters we can glean some ideas on how to appreciate the regression outputs.
|
[
"stackoverflow",
"0024841070.txt"
] | Q:
console log shows the entire file instead of data
index.php
<script>
var h = $(window).height();
alert (h); // works fine - shows 580
$.ajax({
type: "POST",
url: 'index.php',
data: {h : h},
success:(function(data){
console.log( data );
})
});
</script>
As a result console shows the entire index.php file, instead of h data (580) !?
A:
The data you use in the line console.log( data ); is the data you declare in the line success:(function(data){ which is the body of the HTTP response you get from requesting index.php.
It has nothing to do with the data property you use in the line data: {h : h}, or the variable h.
|
[
"stackoverflow",
"0000158986.txt"
] | Q:
How to relate objects from multiple contexts using the Entity Framework
I am very new to the entity framework, so please bear with me...
How can I relate two objects from different contexts together?
The example below throws the following exception:
System.InvalidOperationException: The
relationship between the two objects
cannot be defined because they are
attached to different ObjectContext
objects.
void MyFunction()
{
using (TCPSEntities model = new TCPSEntities())
{
EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
er.Roles = GetDefaultRole();
model.SaveChanges();
}
}
private static Roles GetDefaultRole()
{
Roles r = null;
using (TCPSEntities model = new TCPSEntities())
{
r = model.Roles.First(p => p.RoleId == 1);
}
return r;
}
Using one context is not an option because we are using the EF in an ASP.NET application.
A:
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity.
EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs.
You could simply pass the context.. IE:
void MyFunction()
{
using (TCPSEntities model = new TCPSEntities())
{
EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
er.Roles = GetDefaultRole(model);
model.SaveChanges();
}
}
private static Roles GetDefaultRole(TCPSEntities model)
{
Roles r = null;
r = model.Roles.First(p => p.RoleId == 1);
return r;
}
A:
Another approach that you could use here is to detach objects from one context, and then attach them to another context. That's a bit of a hack, and it may not work in your situation, but it might be an option.
public void GuestUserTest()
{
SlideLincEntities ctx1 = new SlideLincEntities();
GuestUser user = GuestUser.CreateGuestUser();
user.UserName = "Something";
ctx1.AddToUser(user);
ctx1.SaveChanges();
SlideLincEntities ctx2 = new SlideLincEntities();
ctx1.Detach(user);
user.UserName = "Something Else";
ctx2.Attach(user);
ctx2.SaveChanges();
}
|
[
"stackoverflow",
"0007218970.txt"
] | Q:
save data from form with custom foreign key field in django
I have the following Model classes:
class ContactPerson(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Appartment(models.Model):
contact_person = models.ForeignKey(ContactPerson)
Problem: In template file I want a user to fill contact person's name, so I overwrite contact_person field as follows:
class AppartmentSellForm(ModelForm):
contact_person = forms.CharField(max_length=30)
class Meta:
model = Appartment
In my view function I am doing the following to save data from a form submitted:
def appartment_submit(request):
if request.method == "POST":
form = AppartmentSellForm(request.POST)
if form.is_valid():
appartment = form.save(commit=False) # ERROR HERE
cp = models.ContactPerson(name=form.cleaned_data['contact_person'])
appartment.contact_person = cp
appartment.save()
form.save();
return HttpResponseRedirect('/sell/')
else:
form = AppartmentSellForm()
return render_to_response('sell_appartment_form.html', {'form' : form})
Error message:
#ValueError at /sell/sell_appartment/appartment_submit/
Cannot assign "u'blabla'": "Appartment.contact_person" must be a "ContactPerson" instance.**
I am using SQLite, and django version 1.1.1
Question: How to solve this problem?
A:
I think the code that you are putting in your view would be better suited to the ModelForm's validation.
Override the model form's clean_contact_person method and add the code there so that it a) checks that the name is valid and if so, b) sets the form field's value to the actual ContactPerson instance.
Something like: (off the top of my head)
class AppartmentSellForm(ModelForm):
contact_person = forms.CharField(max_length=30)
class Meta:
model = Appartment
def clean_contact_person(self):
name = self.cleaned_data['contact_person']
# check the name if you need to
try:
# maybe check if it already exists?
person = models.ContactPerson.objects.get(name=name)
except ContactPerson.DoesNotExist:
person = models.ContactPerson(name=name)
# you probably only want to save this when the form is saved (in the view)
return person
Your view will may still need to use commit=False (since you will need to save the ContactPerson record). You can do this using the save_m2m method.
There's more info about save_m2m in the ModelForm documentation and information about cleaning fields in the validation documentation.
I hope that helps, good luck!
|
[
"stackoverflow",
"0008066666.txt"
] | Q:
Random issues creating new types in Dexterity TTW
I have just installed dexterity into our office's intranet site so that I can create some new types for particular styles of documents. I had hoped just to use just the TTW capabilities, but I'm seeing extraordinary behaviour. When I try to create the fields of a new type, any, or all of the following problems can be seen, almost non-deterministically:
After saving the attributes of a new field, the field sometimes doesn't get shown in the page showing the fields of that new type.
Sometime a page refesh does show it, other times it doesn't.
Clicking on the Settings for a field (when it is visible) sometimes shows the error dialog indicationg that this page does not exist.
Sometimes the settings dialog does come up, and then attempts to save it fail with another error dialog to say that this page does not exist.
With a bit of persistance by retrying and refreshing often, I can get a type defined with a couple fields. Then when If I create an instance of this new type, often only some subset of those new fields are shown in the creation form. When I try to save it, the form is shown again but this time with the required fields that were originally hidden now highlighted in red. Finally saving that object then displays it with some fields (but not all) missing.
It's seems utterly random.
I have added the following to my buildout:
extends =
base.cfg
versions.cfg
http://good-py.appspot.com/release/dexterity/1.0.3?plone=4.1
...
eggs =
...
plone.app.dexterity
My Plone is:
Plone 4111
CMF 2.2.4
Zope 2.13.8
The event.log doesn't have any messages in it when these problem are occuring.
Any insights appreciated.
A:
Do you have a caching server in front of Plone? Maybe that is being too agressive and it is caching stale content. Try accessing Plone directly without any caching servers in between and see if that helps.
|
[
"stackoverflow",
"0006172262.txt"
] | Q:
MVC3 RemoteAttribute and muliple submit buttons
I have discovered what appears to be a bug using MVC 3 with the RemoteAttibute and the ActionNameSelectorAttribute.
I have implemented a solution to support multiple submit buttons on the same view similar to this post: http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/
The solution works however, when I introduce the RemoteAttribute in my model, the controllerContext.RequestContext.HttpContext.Request no longer contains any of my submit buttons which causes the the "multi-submit-button" solution to fail.
Has anyone else experienced this scenario?
A:
The problem manifests itself when the RemoteAttribute is used on a model in a view where mutliple submit buttons are used. Regardless of what "multi-button" solution you use, the POST no longer contains any submit inputs.
I managed to solve the problem with a few tweeks to the ActionMethodSelectorAttribute and the addition of a hidden view field and some javascript to help wire up the pieces.
ViewModel
public class NomineeViewModel
{
[Remote("UserAlreadyRegistered", "Nominee", AdditionalFields="Version", ErrorMessage="This Username is already registered with the agency.")]
public string UserName { get; set; }
public int Version {get; set;}
public string SubmitButtonName{ get; set; }
}
ActionMethodSelectorAttribute
public class OnlyIfPostedFromButtonAttribute : ActionMethodSelectorAttribute
{
public String SubmitButton { get; set; }
public String ViewModelSubmitButton { get; set; }
public override Boolean IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var buttonName = controllerContext.HttpContext.Request[SubmitButton];
if (buttonName == null)
{
//This is neccessary to support the RemoteAttribute that appears to intercepted the form post
//and removes the submit button from the Request (normally detected in the code above)
var viewModelSubmitButton = controllerContext.HttpContext.Request[ViewModelSubmitButton];
if ((viewModelSubmitButton == null) || (viewModelSubmitButton != SubmitButton))
return false;
}
// Modify the requested action to the name of the method the attribute is attached to
controllerContext.RouteData.Values["action"] = methodInfo.Name;
return true;
}
}
View
<script type="text/javascript" language="javascript">
$(function () {
$("input[type=submit][data-action]").click(function (e) {
var action = $(this).attr('data-action');
$("#SubmitButtonName").val(action);
});
});
</script>
<% using (Html.BeginForm())
{%>
<p>
<%= Html.LabelFor(m => m.UserName)%>
<%= Html.DisplayFor(m => m.UserName)%>
</p>
<input type="submit" name="editNominee" value="Edit" data-action="editNominee" />
<input type="submit" name="sendActivationEmail" value="SendActivationEmail" data-action="sendActivationEmail" />
<%=Html.HiddenFor(m=>m.SubmitButtonName) %>
<% } %>
Controller
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("Details")]
[OnlyIfPostedFromButton(SubmitButton = "editNominee", ViewModelSubmitButton = "SubmitButtonName")]
public ActionResult DetailsEditNominee(NomineeViewModel nom)
{
return RedirectToAction("Edit", "Nominee", new { id = nom.UserName });
}
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("Details")]
[OnlyIfPostedFromButton(SubmitButton = "sendActivationEmail", ViewModelSubmitButton = "SubmitButtonName")]
public ActionResult DetailsSendActivationEmail(NomineeViewModel nom)
{
return RedirectToAction("SendActivationEmail", "Nominee", new { id = nom.UserName });
}
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult UserAlreadyRegistered(string UserName, int Version)
{
//Only validate this property for new records (i.e. Version != zero)
return Version != 0 ? Json(true, JsonRequestBehavior.AllowGet)
: Json(! nomineeService.UserNameAlreadyRegistered(CurrentLogonDetails.TaxAgentId, UserName), JsonRequestBehavior.AllowGet);
}
|
[
"stackoverflow",
"0027511656.txt"
] | Q:
jQuery .ready method
My .ready() method does not call the function that it supposed to. The function alone is working fine, but when I try to execute it as the first thing after page is loaded, it does nothing. I went through existing topic but could not find the way of fixing it.
I should add that I want my function to be executed after page is loaded as well as after clicking a button(that part works at the moment)
My code:
<script>
$(document).ready(function() {
calculation();
});
function calculation() {
variable = new XMLHttpRequest();
var total = 0;
if($('#p1').val() && $('#qty').val()){
var price = $('#p1').val();
var qty = $('#qty').val();
total += price * qty;
}
$('#total').val(total);
}
</script>
A:
You need to load jQuery before your script runs.
<!-- Put jQuery Here -->
<script>
$(document).ready(function() {
calculation();
});
//etc...
</script>
The reason that your code was working previously is because you were using jQuery inside a function that was being triggered by a button. That code would never run until the button was clicked, which was happening after your browser loaded jQuery.
|
[
"stackoverflow",
"0028707077.txt"
] | Q:
Selenium tests - Everything is printed all the time no matter what
This might sound like a very silly question but here it is:
I'm writing selenium tests in python, and basically my base test class looks like that:
chromedriver = "../selenium-tests/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
class TestsFoo(unittest.TestCase):
base_url = None
language = None
def setUp(self):
self.driver = webdriver.Chrome(chromedriver)
self.verificationErrors = []
self.accept_next_alert = True
self.driver.set_window_size(1100, 800)
Then all of my other test classes extend from that class. Example:
class TestsFooChild(TestsFoo):
def test_something(self):
driver = self.driver
driver.get("{}{}/myurl.html".format(
self.base_url,
self.language)
)
# do stuff
print driver.current_url
self.assertTrue(somethingTrue)
def tearDown(self):
self.driver.close()
self.driver.quit()
language and url are defined thanks to this:
if __name__ == "__main__":
TestsFoo.base_url = os.environ.get('URL')
TestsFoo.language = os.environ.get('LANGUAGE')
unittest.main()
So that's a lot of informations for a very very tiny question:
When doing unittest, if you let a print somewhere, it'll only be printed if the test fails.
Then why in my case, are every prints printed no matter what the result of the test is? I only want to print my current_url when the test fails.
Also, I'm just looking at why it does that. I'm actively working on finding a way to only print it when my test fails. So that part is taken care of. But I'm curious..
A:
I almost never use unittest all by itself but, as far as I can tell, that print results in output to the console is the default behavior with unittest. Here's an example file:
import unittest
class Test(unittest.TestCase):
def test_one(self):
print "Foo"
if __name__ == "__main__":
unittest.main()
If you save it as test.py and run it with python test.py, you'll get Foo printed on the console.
However, if you run it with nose like this nosetests test.py (or even just nosetests in the directory where the file is), you won't see Foo on the console. You'd have to run it with -s or --nocapture to see Foo.
|
[
"stackoverflow",
"0051368739.txt"
] | Q:
Python - replace missing dates with sudo date
I have a dataframe with missing date values, how should I replace them with 9999-01-01 00:00:00?
import pandas as pd
df = pd.read_excel('sample-data.xlsx',converters={'sample_date':str})
df['sample_date']
output of df['sample_date']:
0 2017-11-08 00:00:00
1 2016-08-03 00:00:00
2 2015-09-29 00:00:00
3 NaT
4 2015-09-29 00:00:00
5 NaT
if df['sample_date'] == "" or df['sample_date'] == None or df['sample_date'] == "NaT" or df['sample_date'] == "NaN":
df['sample_date'] == "9999-01-01 00:00:00"
I am getting error like: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
A:
Try using pandas fillna() function to fill the NaT values in your dataframe.
df['sample_date'] = df['sample_date'].fillna('9999-01-01 00:00:00')
I dont know if this works with NaT values, but if my memory serves correct it does.
|
[
"stackoverflow",
"0005942491.txt"
] | Q:
Interface builder problem when Iphone app converted to Universal app
I built an iphone app and in one of the views(buit using IB), I put an activity indicator ( little spinner indicating network activity) in the middle. It works fine on my iphone but once I use an Ipad the spinner goes to the to left corner. So the spinner never correspond to the intended location on Ipad no matter where I move it in IB.
Any suggestion to solve this problem? Do I have to rebuild the app specifically for ipad?
Thanks
A:
In Interface Builder, select the Activity Indicator and open the Size Inspector.
Default shortcut in Xcode 4 is ⌥ ⌘ 5, icon looks like a ruler.
Second section, on the left, a box labeled "Autosizing". The bars around the outside turn each anchor on or off, and the arrows inside turn autoresizing on/off for either direction (x / y)
With the indicator centered in the view, turn all four anchors on.
Solid red is on, semitransparent is off.
|
[
"math.stackexchange",
"0001780155.txt"
] | Q:
Let $1 + \frac{1}{3^3} + \frac{1}{5^3} + \frac{1}{7^3} + \dots=s$, show that then $\sum_1^\infty\frac{1}{n^3}=\frac{8}{7}s$
Let $1 + \frac{1}{3^3} + \frac{1}{5^3} + \frac{1}{7^3} + \dots=s$, show that then $\sum_1^\infty\frac{1}{n^3}=\frac{8}{7}s$.
This is the last part of a problem that I am working on. So far, we have shown that the cosine series for $x^2$ is
$x^2=\frac{\pi^2}{3}+4\sum_1^\infty (-1)^n\frac{\cos(nx)}{n^2}$
The sine series for $x^2$ is
$x^2=2\pi\sum_1^\infty(-1)^{n+1}\frac{\sin nx}{n}-\frac{8}{\pi}\sum_1^\infty\frac{\sin ((2n-1)x)}{(2n-1)^3}$
The sine series for x is
$x=2(\sin x -\frac{\sin 2x}{2}+ \frac{\sin 3x}{3}-\dots)$
and using the above we got that
$\frac{\pi^3}{32}=1 - \frac{1}{3^3}+\frac{1}{5^3}-\frac{1}{7^3}+\dots$.
Not sure if any of this matters, I just don't know how to use this information to solve the last part. I don't really know if this information is needed at all, but I assume it is.
A:
\begin{align*}
\sum_1^{\infty} \frac 1 {n^3} &= \sum_{\text{even}} \frac 1 {n^3} + s \\
&= \sum_1^{\infty} \frac{1}{(2k)^3} + s\\
&= \frac 1 8 \sum_1^{\infty} \frac 1 {k^3} + s
\end{align*}
Rearrange for the desired result.
|
[
"stackoverflow",
"0007709703.txt"
] | Q:
Type not inherited in SFINAE for multiple inheritance?
I am using a SFINAE mechanism to deduce a type. Resolve<T>::type is deduced to T if class T doesn't contain yes and it's deduced to MyClass if it contains yes.
class MyClass {};
template<typename>
struct void_ { typedef void check; };
template<typename T, typename = void>
struct Resolve { typedef T type; };
template<typename T>
struct Resolve <T, typename void_<typename T::yes>::check> {
typedef MyClass type;
};
Now, I have the simple test classes as,
struct B1 { typedef int yes; }; // 1
struct B2 { typedef int yes; }; // 2
struct D1 {}; // 3
struct D2 : B1 {}; // 4
struct D3 : B1, B2 {}; // 5 <----
According to the logic following should be the result for above tests:
Resove<B1>::type = MyClass
Resove<B2>::type = MyClass
Resove<D1>::type = D1
Resove<D2>::type = MyClass
Resove<D3>::type = MyClass or compiler error (due to ambiguity between B1, B2)
Strangely, in test case (5) it doesn't happen so. The result is,
Resolve<D3>::type = D3;
Can anyone explain, what magic is happening specially for multiple inheritance ? Not getting compiler error is a standard compliant behavior ? Here is the demo.
A:
Why would you expect a compiler error? You know SFINAE stands for Substitution Failure Is Not An Error right?
When you substitute T by D3 the expression becames ambiguous. Due to SFINAE, this failure is not considered an error and your specialization is simply removed as a candidate. It's all about NOT getting a compiler error.
|
[
"salesforce.stackexchange",
"0000281180.txt"
] | Q:
Datetime conversion from date vs explicit midnight
I've just spent two days banging my head against the Salesforce wall, and the problem came down to this:
Date wkStart = Date.newInstance(2019,10,12);
Datetime wkStart1 = wkStart;
Datetime wkStart2 = Datetime.newInstance(wkStart,Time.newInstance(0,0,0,0));
wkStart1 and wkStart2 are not equal, at least in my non-GMT timezone. It appears that the implicit cast sets it to midnight GMT, while the explicit newInstance sets it to midnight my time zone. (An explicit cast behaves the same as the implicit cast.)
Is there a logic behind that? Why would an implicit midnight be interpreted differently than an explicit midnight?
Further, is that documented somewhere? I've searched all I can think of to search on in the Apex manual, and haven't been able to find anything.
A:
Yes, this is a problematic behavior that does exist. No, it is not documented (that I'm aware of), and cannot likely ever be fixed without causing hammer fails. It's something you, a developer, needs to be aware of once you run in to it, and avoid this situation. Basically, do not ever compare a Date to a DateTime and expect to get a correct comparison/conversion, and do not convert a Date to a DateTime implicitly, even though it's "legally" allowed by the runtime. The only way you can compare a Date and a DateTime legally is to call the "date" method:
Date wkStart = Date.newInstance(2019,10,12);
Datetime wkStart2 = Datetime.newInstance(wkStart,Time.newInstance(0,0,0,0));
Boolean areEqualDates = wkStart2.date() == wkStart;
The date() method should return the same value for all time periods within the same day, thus returning a true value. You'll still need to be aware of certain situations, as it is time-zone dependent. Always compare GMT to GMT or local-time to local-time, and do not mix the two.
|
[
"stackoverflow",
"0041103111.txt"
] | Q:
How can I import .java file in eclipse IDE?
I downloaded Java exercises from exercism.io, I use the Eclipse IDE. I can create new projects in Eclipse and work on them, but can't figure out how to import 'filename.java' and adjust that!
How can I do it? I'm using Ubuntu, do you recommend me to use a different IDE than Eclipse for Java projects?
A:
Create a new JavaProject
Create a new class in that java project (located in workspace)
Name the class the same as the .java you want to import
Then simply copy and paste your java code into Eclipse
|
[
"stackoverflow",
"0056446048.txt"
] | Q:
What is this function doing? i'm most confused with the Read and write part
I know this is a constructor function but it i don't get the read and write part.. i know it has an if and else statement but i'm confused with what it doing!
self.CondInspecChks_RevValve_UI = ko.computed({
read: function () {
return self.CondInspecChks_RevValve() == 1 ? true : false;
},
write: function (newValue) {
self.CondInspecChks_RevValve(newValue ? 1 : 0);
}
});
A:
This is a Knockout computed observable - it allows a dynamic value to be assigned to a KO observable.
const normalObservable = ko.observable("hello");
const computedObservable = ko.computed(function() {
return "my dynamic value is: " + normalObservable();
})
console.log(normalObservable())
console.log(computedObservable())
//update the observable
normalObservable("world");
console.log(normalObservable())
//the computed also changed
console.log(computedObservable())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
In this particular case, this is using advanced construction of the computed to make it a writeable computed.
const someWriteableValue = ko.observable("hello")
const computed = ko.computed({
read: function () {
return "my dynamic value is: " + someWriteableValue();
},
write: function (value) {
someWriteableValue(value);
}
})
console.log(computed());
//update the computed
computed("world");
console.log(computed());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
|
[
"stackoverflow",
"0014515955.txt"
] | Q:
BouncyCastle auto-appending the signature in Encrypted files
I am using BouncyCastle package for OpenPGP encryption.
Everything is smooth except one part. When I write the encrypted text to file, it's appending the below message
-----BEGIN PGP MESSAGE-----
Version: BCPG v1.47
//encrypted text here
-----END PGP MESSAGE-----
But i don't want the signature part in the file.
Here's the code I am using for encryption
public void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck) throws IOException, NoSuchProviderException, PGPException {
//armor = true; integrityCheck = true
Security.addProvider(new BouncyCastleProvider());
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_256);
dataEncryptor.setWithIntegrityPacket(withIntegrityCheck);
dataEncryptor.setSecureRandom(new SecureRandom());
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = encryptedDataGenerator.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
}
A:
This is not the signature but an envelope for armored data. Turn off armoring and you'll get binary encrypted data. If you remove the envelope and keep armoring, conformant decrypting OpenPGP tools won't know what to do with this - they wouldn't be able to distinguish armored from non-armored data.
|
[
"stackoverflow",
"0046569963.txt"
] | Q:
How to create a offset in Bootstrap 4
First of all Big apologies for my bad English.
I am using bootstrap version 4 beta version ( latest not alpha). It is good. But i'm wondering in the new version of bootstrap they removed offset class. I will thankful if someone give me the solution how can I make a offset using flexbox with any amount. I mean before I used .col-offset-2 this means offset 2 column, I want this with flexbox. Thank you
A:
You can use .offset- .offset-sm- .offset-md- .offset-lg- .offset-xl-
<div class="offset-2 col-8">
test
</div>
Here are some examples - http://formoid.com/articles/bootstrap-offset-example-961.html
A:
The offset classes have been replace by margin classes. These are prefixed mr- for margin-right and ml- for margin-left.
The documentation demonstrates the use of ml-*-auto (where * is the target resolution -- eg lg or md.) This is the equivalent of setting margin-left: auto in your CSS, which is effectively saying "push this as far left as you can." By using both ml-*-auto and mr-*-auto, you can effectively center your columns.
This is the full list of prefixes for the auto property:
ml- margin left
mr- margin right
mb- margin bottom
mt- margin top
mx- horizontal margin (margin left + margin right)
my- vertical margin (margin top + margin bottom)
m- all margins
In addition to auto, you can specify the column widths -- ml-lg-2, etc.
So col-offset-2, which (I think) would shove the content left two spaces is equivalent to something like ml-2 or ml-lg-2.
A:
Offset is replaced with ml-**-auto.
The below code will be 12 in sizes smaller than md, but 9 with an offset of 3 in sizes md and higher.. Because I have placed md inside ml-**-auto
<div class="col-12 col-md-9 ml-md-auto">
test
</div>
See the official doc here https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns
Also, there's also a really good answer here on how offset works in bootstrap 4
Offsetting columns is not working (Bootstrap v4.0.0-beta)
EDIT: 2018/10/25
Offset's were restored in Bootstrap 4 Beta 2. Here's an example:
<div class="row">
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4 offset-md-4">.col-md-4 .offset-md-4</div>
</div>
|
[
"stackoverflow",
"0014175309.txt"
] | Q:
Simplest way to sort coordinates by y-value in Java?
Suppose that I have an (unsorted in any way) array:
[ 12 64 35 ]
[ 95 89 95 ]
[ 32 54 09 ]
[ 87 56 12 ]
I want to sort it so that the second column is in ascending order:
[ 32 54 09 ]
[ 87 56 12 ]
[ 12 64 35 ]
[ 95 89 95 ]
Here are the ways that I thought about dealing with this:
Make each [ x y z ] value into a list, and correlate each xyz value with an identifier, whose property is the y-value of the xyz value. Then, sort the identifiers. (I'm not sure if sorting Java arrays keeps the corresponding values in that row)
Use a hashmap to do the same thing as the previous
However, the above 2 methods are obviously somewhat wasteful and complicated since they rely on an external identifier value which is unneeded, so is there a simpler, faster, and more elegant way to do this?
Sorry if this is a dumb question, I'm not familiar at all with the way that Java sorts arrays.
A:
Easiest and most cleanest way would be to write a small comparator class. That will give you more flexibility in controlling the behavior of sorting also; for example you can sort 1st element or any element of arrays.
Comparator will be something like:
new Comparator(){
public int compare ( Integer[] obj1, Integer[] obj2)
{
return obj1[1].compareTo(obj2[1]);
}
A:
This is a one-liner (if you count an anonymous class as one line), making use of Arrays.sort() and a suitably typed and coded Comparator:
Arrays.sort(grid, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
Note the simple comparison expression o1[1] - o2[1] - no need to unbox to Integer and use Integer.compareTo().
Here's a test with your data:
public static void main(String[] args) {
int[][] grid = new int[][] {
{ 12, 64, 35 },
{ 95, 89, 95 },
{ 32, 54, 9 },
{ 87, 56, 12 }};
Arrays.sort(grid, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
System.out.println(Arrays.deepToString(grid).replace("],", "],\n"));
}
Output:
[[32, 54, 9],
[87, 56, 12],
[12, 64, 35],
[95, 89, 95]]
Just for fun, here it is literally as one line:
Arrays.sort(grid, new Comparator<int[]>() {public int compare(int[] o1, int[] o2) {return o1[1] - o2[1];}});
|
[
"stackoverflow",
"0011261986.txt"
] | Q:
django - TypeError: coercing to Unicode
I'm getting TypeError: coercing to Unicode: need string or buffer, int found
This is my models.py:
class FollowingModel(models.Model):
user = models.ForeignKey(User)
person = models.IntegerField(max_length=20, blank=False)
def __unicode__(self):
return self.person
When I retrieve the values from the FollowingModel in my views like this
g = FollowingModel.objects.all()
g[0] -----> I'm getting that error
I tried changing the def __unicode__(self): as
def __unicode__(self):
return str(self.person)
But no use, still I'm getting the same error. Could anyone guide me?
Thanks!
UPDATE
>>>g = FollowingModel.objects.all()
>>>g
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 72, in __repr__
return repr(data)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 370, in __repr__
u = unicode(self)
TypeError: coercing to Unicode: need string or buffer, int found
A:
The __unicode__ method should return just that, unicode:
def __unicode__(self):
return unicode(self.person)
|
[
"stackoverflow",
"0012902472.txt"
] | Q:
Custom Validation in Spring MVC 3.0 - Pass @Model to Validator
I am trying to write a custom validator in a Spring MVC application. I would like to know if there a way to pass the @Model object to a custom spring validator?
Say, I have a Person object and Account object. I have to write a custom validator to validate Person, but the validation is dependent of the Account object and other objects in session.
For example, Person cannot have more than 3 accounts, account types have to be of specific category and not old than 3 years (this value, ie the number years is dynamic based on the profile logged in and is in session).
How can I pass both objects, especially @Model to the validator.
public class ServiceValidator implements Validator {
@Autowired
private ServiceDAO servicesDao;
@Override
public boolean supports(Class<?> clasz) {
return clasz.isAssignableFrom(Person.class);
}
@Override
public void validate(Object obj, Errors errors) {
Person subscriber = (Person) obj;
// How can I access @Model object here ???
}
A:
Doubt if you can but have two workarounds:
a. If it is persisted data that you are looking for, probably it is just better to retrieve it once more in the validator and validate using that data, so for eg, in your case if you are validating person and persons account details are retrievable from DB, then get it from DB and validate in your validator using the retrieved data.
b. Probably this is a better approach if the number of places where you need to use the validator is fairly confined:
public class ServiceValidator {
@Autowired
private ServiceDAO servicesDao;
public void validate(Person subscriber, List<Account> accounts, ..., Errors errors) {
}
Just call the above validator directly from your requestmapped methods..
In your controller..
List<Account> accounts = //retrieve from session
serviceValidator.validate(subscriber, accounts, ...errors);
if (errors.hasErrors())..
else..
|
[
"stackoverflow",
"0023766196.txt"
] | Q:
SELECT query returns no result without ORDER BY clause
I have this query:
SELECT `Stocks`.`id` AS `Stocks.id` , `Locations`.`id` AS `Locations.id`
FROM `rowiusnew`.`c_stocks` AS `Stocks`
LEFT JOIN `rowiusnew`.`g_locations` AS `Locations` ON ( `Locations`.`ref_id` = `Stocks`.`id` AND `Locations`.`ref_type` = 'stock' )
GROUP BY `Stocks`.`id`
HAVING `Locations.id` IS NOT NULL
This returns 0 results.
When I add
ORDER BY Locations.id
to the exactly same query, I correctly get 3 results.
Noteworthy: When I discard the GROUP BY clause, I get the same 3 results. The grouping is necessary for the complete query with additional joins; this is the simplified one to demonstrate the problem.
My question is: Why do I not get a result with the original query?
Note that there are two conditions in the JOIN ON clause. Changing or removing the braces or changing the order of these conditions does not change the outcome.
Usually, you would suspect that the field id in g_locations is sometimes NULL, thus the ORDER BY clause makes the correct referenced result be displayed "at the top" of the group dataset. This is not the case; the id field is correctly set up as a primary key field and uses auto_increment.
The EXPLAIN statement shows that filesort is used instead of the index in those cases when I actually get a result. The original query looks like this:
The modified, working query looks like this:
Below is the table definitions:
CREATE TABLE IF NOT EXISTS `c_stocks` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_stock_type` int(10) unsigned DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`locality` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `StockType_idx` (`id_stock_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `g_locations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`ref_type` enum('stock','object','branch') DEFAULT NULL,
`ref_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UniqueLocation` (`ref_type`,`ref_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The ref_id field features a long comment that I omitted in this definition.
A:
After being unable to reproduce the error on SQLFiddle.com and also on my second computer, I realized that there must be a bug involved.
Indeed, my used version 5.6.12 suffers from this bug:
Some LEFT JOIN queries with GROUP BY could return incorrect results. (Bug #68897, Bug #16620047)
See the change log of MySQL 5.6.13: http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-13.html
An upgrade to 5.6.17 solved my problem. I am not getting the results I expect, independent of ORDER clauses and aggregate functions.
|
[
"stackoverflow",
"0056270675.txt"
] | Q:
Google ReCaptcha V3 - Missing required parameters: sitekey
I'm trying to implement Google ReCaptcha V3 (which is a different implementation from V2, so please don't mark as duplicate).
Here's my page's JS script that initializes the ReCaptcha (Replacing MyKey with my actual key I registered here):
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
$(function () {
grecaptcha.ready(function () {
grecaptcha.execute('MyKey', {action: 'homepage'});
});
});
</script>
When loading the page I get the following error in the browser's dev console:
Uncaught Error: Missing required parameters: sitekey
What am I missing here?
A:
Replace reCAPTCHA_site_key
on https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key
with your actual key.
|
[
"stackoverflow",
"0007336662.txt"
] | Q:
batch script to copy lowercase file
I have files being uploaded to a folder. I need a batch script to redirect those files to separate folders based on filenames. That's all fine except for two sets of files that have very similar names but only different by case. Ie. log0000.txt and LOG0000.txt.
What I would like to do is search through the folder and check all files and if they have a lowercase "log", move them to one folder and if they have uppercase "LOG", move them to the other.
I know how to loop through the files in the folder, but I'm unsure how to match the comparision and match each file based on case.
Thanks.
A:
Since you already know how to loop and move,
@echo off
for /f "usebackq delims=" %%f in (`dir /s /b log* ^| findstr "log"`) do (
@rem code to copy all lower case files
)
for /f "usebackq delims=" %%f in (`dir /s /b log* ^| findstr "LOG"`) do (
@rem code to copy all upper case files
)
|
[
"stackoverflow",
"0012762530.txt"
] | Q:
Type is not declared error
I am getting an error saying 'T' does not name a type. I am confused as to what this means. I thought i declared it in the class saying Virtual T?
template <class T>
class ABList : public ABCList<T> {
private:
T a [LIST_MAX];
int size;
public:
ABList ();
virtual bool isEmpty ();
virtual int getLength ();
virtual void insert (int pos, T item);
virtual T remove (int pos);
virtual T retrieve (int pos);
};
.
T ABList::retrieve (int pos) throw (ListException)
{
if (pos <= 0 || pos >= count)
throw new ListException();
return item[pos – 1];
}
A:
You have to write that as:
template<typename T>
T ABList<T>::retrieve (int pos) throw (ListException)
{
//...
}
because ABList a class template.
Note that you've to define the member functions in the same file itself in which you've defined the class template. Defining class template in .h file, and member functions in .cpp would not work in case of templates.
|
[
"stackoverflow",
"0021441089.txt"
] | Q:
Efficient way to check if unicode is a digit or a decimal in Python
What is the most efficient way to check if unicode is a digit or a decimal, I know I can do various if statements like:
if unicode.isdigit(self.initial_bet.text) and unicode.isdigit(self.initial_odds.text)...
The unicode can be both, two of type decimal, two of type digit or combination of either, is there a better way to check other than many if statements?
Pseudocoe:
if a is a digit and b is a digit:
return func
elif a is a decimal and b is a decimal:
return func
elif a is a digit and b is a decimal:
return func
and so on ....
else
do something else
A:
If all inputs need to be either a decimal or a digit, then the following will work:
conds = [unicode.isdigit, unicode.isdecimal]
check = lambda v: any(f(v) for f in conds)
vals = [self.initial_bet.text, self.initial_odds.text]
if all(map(check, vals)):
return func
# do something else
This will work for any number of inputs and any number of conditions, such that each input must satisfy at least one condition.
Also, it seems that unicode.isdigit is a superset of the functionality of unicode.isdecimal, thus any decimal should be a digit -- most of the difference lies in various unicode scripts, but with the ASCII range, the functions should have identical behavior.
|
[
"stackoverflow",
"0031958370.txt"
] | Q:
Why php function str_word_count() returns different count from js equivalent?
I have this JS code which I think is equivalent to the PHP str_word_count() function, but still they return different words counts.
My JS code:
//element f9 value is:
"Yes, for all people asking ? ? ? their selfs Have you ever dreamed to
visite World Travel Market 2015 ? we can confirm that now it is a great
time to go to London for World Travel Market 2015Yes, for all people
asking their selfs Have you ever dreamed to visite World Travel Market 2015 ?
we can confirm that now it is a great time to go to London for World
Travel Market 2015Yes, for all people asking their selfs Have you ever
dreamed to visite World Travel Market 2015 ? we can confirm that now it is
a great time to go to London for World 2015Yes, for all people asking
their selfs Have you ever dreamed to visite World 2015 we can confirm that
now it is a great time to go to London for World Travel Market 2015Yes, for
all people asking their selfs Have you ever dreamed to visite World Travel
Market 2015 ? we can confirm that now it is a great time to go to London
for World 2015Yes, for all people asking their selfs Have you ever dreamed
to visite World Travel Market 2015 ? we can confirm that now it is a great
time to go to London for World Travel Market 2015Yes, for all people asking
their selfs Have you ever dreamed to visite World 2015 we can confirm that
now it is a great time to go to London for World 2015Yes, for all people
asking their selfs Have you ever dreamed to visite World Travel Market
2015 ? we can confirm that now it is a great time to go to London for World
2015Yes, for all people asking their selfs Have you ever dreamed to visite
World 2015 ? we can confirm that now it is a great time to go to London for
World 2015"
var words = document.getElementById("f9").value.replace(/([(\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '');
words = words.replace(/(^\s*)|(\s*$)/gi,"");
words = words.replace(/[ ]{2,}/gi," ");
words = words.replace(/\n /,"\n");
words = words.split(' ').length;
outputs: 300
My PHP code:
str_word_count("Yes, for all people asking ? ? ? their selfs Have you ever dreamed to
visite World Travel Market 2015 ? we can confirm that now it is a great
time to go to London for World Travel Market 2015Yes, for all people
asking their selfs Have you ever dreamed to visite World Travel Market 2015 ?
we can confirm that now it is a great time to go to London for World
Travel Market 2015Yes, for all people asking their selfs Have you ever
dreamed to visite World Travel Market 2015 ? we can confirm that now it is
a great time to go to London for World 2015Yes, for all people asking
their selfs Have you ever dreamed to visite World 2015 we can confirm that
now it is a great time to go to London for World Travel Market 2015Yes, for
all people asking their selfs Have you ever dreamed to visite World Travel
Market 2015 ? we can confirm that now it is a great time to go to London
for World 2015Yes, for all people asking their selfs Have you ever dreamed
to visite World Travel Market 2015 ? we can confirm that now it is a great
time to go to London for World Travel Market 2015Yes, for all people asking
their selfs Have you ever dreamed to visite World 2015 we can confirm that
now it is a great time to go to London for World 2015Yes, for all people
asking their selfs Have you ever dreamed to visite World Travel Market
2015 ? we can confirm that now it is a great time to go to London for World
2015Yes, for all people asking their selfs Have you ever dreamed to visite
World 2015 ? we can confirm that now it is a great time to go to London for
World 2015")
outputs: 290
What does the PHP str_word_count() doesn't count as word, which my JS code does? Also can you suggest what to change so I can get same count for JS and PHP code?
A:
As PHP manual for str_word_count says:
For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with ' and - characters.
So integers are not counted as words. You have ten occurances of 2015 surrounded by spaces. If it's instantly followed with letters, it will still count them, for example: 2015Yes.
You may want to read this question to also count numbers in PHP.
OR
remove numbers in JS.
words = words.replace(/[0-9]/gi,"");
As @Rizier123 pointed out, you can see all words with this:
print_r(str_word_count($string, 1));
|
[
"christianity.stackexchange",
"0000007267.txt"
] | Q:
Why in the Book of Exodus did God let the people travel for exactly 40 years?
What is the symbolic idea behind this number?
Also, what might be His intention behind the travel?
A:
The field of Biblical numerology can be a pretty mirky pond. There are some clear trends (three for completion, seven for perfection, a thousand for a really big number, etc.) and a lot of speculation and conclusions that may or may not be warranted.
In this case however, the answer is pretty much spelled out in another verse. The 40 years of wandering was an exact calculation, one year for one day, based on how long the spies spent looking around the land before they were originally supposed to enter.
Numbers 14:34 (ESV)
34 According to the number of the days in which you spied out the land, forty days, a year for each day, you shall bear your iniquity forty years, and you shall know my displeasure.’
The logical next question is, "Why did the spies spend 40 days on their quest"? To that we are not given any definite clues. It does seem like a reasonable amount of time to get around to a bunch of different places on foot and get an idea of the lay of the land without making your movements too obvious and getting caught.
There are actually quite a few references to 40 in the Bible. The flood. The spies. The wandering in the desert. The reigns of many of the Judges. Moses life has three periods of 40 years each. The temptation of Jesus. The surmised time between the resurrection and the ascension that Jesus spent back on earth. However the connections between these references is faint at best, and I think it is safe to say, since we are not told explicitly that there is any meaning to this number, that it is of no particular consequence that the spies took 40 days to get their spyin' done.
A:
Numbers 14: 26-35
26 The LORD said to Moses and Aaron: 27 “How long will this wicked community grumble against me? I have heard the complaints of these grumbling Israelites. 28 So tell them, ‘As surely as I live, declares the LORD, I will do to you the very thing I heard you say: 29 In this wilderness your bodies will fall—every one of you twenty years old or more who was counted in the census and who has grumbled against me. 30 Not one of you will enter the land I swore with uplifted hand to make your home, except Caleb son of Jephunneh and Joshua son of Nun. 31 As for your children that you said would be taken as plunder, I will bring them in to enjoy the land you have rejected. 32 But as for you, your bodies will fall in this wilderness. 33 Your children will be shepherds here for forty years, suffering for your unfaithfulness, until the last of your bodies lies in the wilderness. 34 For forty years—one year for each of the forty days you explored the land—you will suffer for your sins and know what it is like to have me against you.’ 35 I, the LORD, have spoken, and I will surely do these things to this whole wicked community, which has banded together against me. They will meet their end in this wilderness; here they will die.”
God commanded Israelites to explore the land of Canaan. Indeed, the milk and honey was flowing in that land. However, the people of Israel did not believe in God's powers and refused to march into Canaan and claim the land, except for Joshua and Caleb. God multiplied the number of days the group of explorers took to explore Canaan and multiplied it by a year. Eventually, the entire disbelieving generation died out.
|
[
"stackoverflow",
"0017148544.txt"
] | Q:
Django template - dynamic variable name
Good Afternoon,
How can I use a variable variable name in Django templates?
I have a custom auth system using context, has_perm checks to see if the user has access to the specified section.
deptauth is a variable with a restriction group name i.e SectionAdmin. I think has.perm is actually checking for 'deptauth' instead of the variable value SectionAdmin as I would like.
{%if has_perm.deptauth %}
How can I do that? has_perm.{{depauth}} or something along those lines?
EDIT - Updated code
{% with arg_value="authval" %}
{% lookup has_perm "admintest" %}
{% endwith %}
{%if has_perm.authval %}
window.location = './portal/tickets/admin/add/{{dept}}/'+val;
{% else %}
window.location = './portal/tickets/add/{{dept}}/'+val;
{%endif%}
has_perm isn't an object.. it's in my context processor (permchecker):
class permchecker(object):
def __init__(self, request):
self.request = request
pass
def __getitem__(self, perm_name):
return check_perm(self.request, perm_name)
A:
You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.
I have not tested this, but something along these lines should work. Remember to handle errors properly!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
If you're trying to get a property rather than execute a method, remove those ().
and use it:
{% lookup has_perm "depauth" %}
Note that has_perm is a variable, and "depauth" is a string value. this will pass the string for lookup, i.e. get has_perm.depauth.
You can call it with a variable:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value'.
|
[
"stackoverflow",
"0032936029.txt"
] | Q:
Trying to add numbers from a file into an array then print the array in formatted columns in java
I am new to programming and I am having some trouble taking a file with a list of numbers and converting it to an array of integers that I can then print in formatted columns (5 rows and 10 columns). I think I did the import correct using an ArrayList but when I try to print the columns I run into issues. I think I need to use a for loop to get the columns to print but I'm not 100% sure. Any amount of help would be greatly appreciated! Here is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Numbers {
private List < Integer > data = new ArrayList < Integer > (); //Create ArrayList
public static void main(String[] args) {
String filename = "C/Users/s/Desktop/file4/Input.txt";
Numbers rfe = new Numbers();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
int[] i = input;
for (i; i < null; i++) {
System.out.format("%20s, %10s", i);
}
}
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
} catch (Exception ex) { // Not required, but a good practice
ex.printStackTrace(); //Usually good for general handling
}
}
}
this is what the file contains (each number in a line):
32
73
63
47
72
34
26
84
27
75
95
10
48
88
28
65
71
40
14
11
67
76
77
80
12
15
30
74
13
41
21
22
57
17
99
92
52
38
18
46
62
64
39
16
43
29
79
49
19
60
A:
You have two problems within your code. All of then at this portion:
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
int[] i = input;
for (i; i < null; i++) {
System.out.format("%20s, %10s", i);
}
}
First you did it right, you've added the readed number into your list: data.add(Integer.parseInt(input)); and this is all you need for this requirement add the number from the file to your list so you just need this for your while:
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
}
After that you want to print it, the error you are seeing is because you are making a wrong assignment int[] i = input; forget about this, you don't need it.
You need to loop through your list to print all the numbers
for (int i=0; i<data.size(); i++){
System.out.format("%20s, %10s", i); //here is your another problem
}
You want to print on that line two parameters "%20s, %10s" but you only give one so either print only one or pass the i twice:
System.out.format("%20s, %10s", i, i); //twice
Or
System.out.format("%10s", i); //just once
|
[
"stackoverflow",
"0031684995.txt"
] | Q:
Materialize.toast() doesn't work in pair with tabs content
I can't make it work both Tabs and Toast
It doesnt appeared when content exist
http://screencloud.net/v/jMs4
and Toast shows normal if i delete content from DOM
http://screencloud.net/v/3MS0
A:
I have issue solved. Just investigation by deleting some content from page and call Materialize.toast() again. so i found that in one node somehow exist tag it is appeared here by some copy-paste. this tag was on collapsed content, so toast why Toast wasn't visible
|
[
"stackoverflow",
"0033674415.txt"
] | Q:
Get data from child tag in riot.js
I want to create a tag like this
<mytag>
<p class={ hide: doEdit }>
<a class="icon1" onmousedown={ startEdit }></a>
<input type="text" value={ opts.value } readonly/>
</p>
<p class={ hide: !doEdit }>
<a class="icon2 onmousedown={ endEdit }></a>
<input name="editfield" type="text" value={ opts.value }/>
</p>
this.doEdit = false
startEdit(e){
this.doEdit = true
this.update()
}
endEdit(e){
this.doEdit = false
opts.value = this.editfield.value // this does not change opts.value, unfortunately
this.update()
}
</mytag>
If it would have worked, i could have used it like
var mydatamodel = {"input1":"email","input2":"name"}
<mytag value={ mydatamodel.input1 }></mytag>
<mytag value={ mydatamodel.input2 }></mytag>
Unfortunately, this does not seem to work. mydatamodel.xy does not get updated, i cannot assign a new value to opts.value (there is no exception, opts.value simply won't change its value).
What would a good way be to update the parents model according to the new values of the "editfield" in the children?
It is possible to access the data using this.mytag[i].editfield. But this is no good solution for larger forms.
I also tried using a custom event and trigger it in the child tag. However, i did not yet find a proper generic solution to update the model in the parent tag. This approach led to something clumsy as the "this.mytag[i].editfield"-way.
Is there a method to create the child tags in such a way that it is possible to write
<mytag value={ mydatamodel.input1 }></mytag>
where mydatamodel.input1 is updated as soon as it changes in the child tag?
Thanks for your thoughts.
A:
Set the callback through an attribute:
<my-tag
title={ globalModel.input1.title }
val={ globalModel.input1.val }
onendedit={ endEdit1 }></my-tag>
Then send back the value through callback.
endEdit (e) {
this.doEdit = false
if (opts.onendedit)
opts.onendedit(this.editfield.value)
}
It seems better to add an outer tag. See detail on plunkr
You may have an interest on RiotControll, too. This is a kind of Flux solution for Riot.js, FYI.
Update: rewrote the answer after the information via comment.
|
[
"stackoverflow",
"0006055793.txt"
] | Q:
How to recalculate position, when copy template
I want to ask how to recalculate line number position and other data when I copy template from another xml file if satisfy condition that code should be the same like in lookup.xml.
My programs look like that:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Line-Item[code = document('lookup.xml')/*/*/code]" />
<xsl:template match="Line[not(Line-Item/code[not(. = document('lookup.xml')/*/*/code ) ] )]"/>
</xsl:stylesheet>
xml file:
<document>
<header>
<remarks>test</remarks>
</header>
<Line>
<Line-Item>
<lineNumb>1</lineNumb>
<code>123</code>
<amount>4</amount>
</Line-Item>
<Line-Item>
<lineNumb>2</lineNumb>
<code>444</code>
<amount>2</amount>
</Line-Item>
<Line-Item>
<lineNumb>3</lineNumb>
<code>321</code>
<amount>1</amount>
</Line-Item>
</Line>
<summary>
<total-line>3</total-line>
<total-amount>7</total-amount>
</summary>
</document>
Lookup.xml file:
<lookup>
<Codes>
<code>123</code>
</Codes>
</lookup>
I need recalculate lineNumb in Line-Item, And summary there is total-line and total-amount.
Correct result:
<document>
<header>
<remarks>test</remarks>
</header>
<Line>
<Line-Item>
<lineNumb>1</lineNumb>
<code>444</code>
<amount>2</amount>
</Line-Item>
<Line-Item>
<lineNumb>2</lineNumb>
<code>321</code>
<amount>1</amount>
</Line-Item>
</Line>
<summary>
<total-line>2</total-line>
<total-amount>3</total-amount>
</summary>
</document>
A:
Your work is almost done. You need only XPath count() and sum(). To recalculate the lineNumb, I've counted all previous sibling elements but the ones matching the lookup code.
I think this should work fine on the base of your assumptions.
XSLT 1.0 tested on Saxon-B 9.0.0.4J
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Line">
<xsl:copy>
<xsl:apply-templates select="Line-Item"/>
</xsl:copy>
<xsl:variable name="lines" select="count(Line-Item[not(code = document('lookup.xml')/*/*/code)])"/>
<xsl:variable name="amount" select="sum(Line-Item[not(code = document('lookup.xml')/*/*/code)]/amount)"/>
<summary>
<total-line><xsl:value-of select="$lines"/></total-line>
<total-amount><xsl:value-of select="$amount"/></total-amount>
</summary>
</xsl:template>
<xsl:template match="Line-Item">
<xsl:copy>
<lineNumb>
<xsl:value-of select="count(preceding-sibling::*[not(code = document('lookup.xml')/*/*/code)])+1"/>
</lineNumb>
<xsl:copy-of select="code"/>
<xsl:copy-of select="amount"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Line-Item[code = document('lookup.xml')/*/*/code]|summary" />
</xsl:stylesheet>
|
[
"math.stackexchange",
"0002042912.txt"
] | Q:
Physicist: Need help understanding a line in a derivation
The derivation I'm looking at is the Poisson distribution in M. Fox's "Quantum Optics" Chapter 5.
Now by Stirling's Formula:
$\lim_{N \to \infty} [\ln N!] = N \ln N - N $
we can see that
$\displaystyle\lim_{N \to \infty} \big[\ln \big(\frac{N!}{N^n(N-n)!}\big)\big] = 0$
It's not clear to me why this limit equates to zero. Am I missing something obvious?
A:
$$\begin{align}\log{\left (\frac{N!}{N^n (N-n)!} \right )} &= \log{N!} - n \log{N} - \log{(N-n)!} \\ &\approx N \log{N}-N - n \log{N} - (N-n) \log{(N-n)} + (N-n) \text {[By Stirling's Formula]}\\ &= (N-n) \log{N} - (N-n) \log{(N-n)} - n \\ &= (N-n) \log{\left (\frac{N}{N-n} \right )} - n \\ &= -(N-n) \log{\left (1-\frac{n}{N} \right )} - n \\ &\approx -N \left ( -\frac{n}{N}\right ) - n\end{align}$$
Thus the limit is indeed $0$ as $N \to \infty$.
|
[
"stackoverflow",
"0015710883.txt"
] | Q:
Forcing grunt plugin update
I'm using Grunt with the grunt-contrib-copy plugin. Recently a new version (0.4.1) was committed which has a nice new feature that I'd like to take advantage of. But, when I try to update using npm update grunt-contrib-copy, nothing happens.
Here's my current version:
$ sudo npm list grunt-contrib-copy
[email protected] /Users/username/src/project/UI
└── [email protected]
Here's my update attempt:
$ sudo npm update grunt-contrib-copy
No output -- and npm list still shows 0.4.0.
Verifying the latest version available:
$ sudo npm info grunt-contrib-copy
npm http GET https://registry.npmjs.org/grunt-contrib-copy
npm http 200 https://registry.npmjs.org/grunt-contrib-copy
{ name: 'grunt-contrib-copy',
description: 'Copy files and folders.',
'dist-tags': { latest: '0.4.1' },
versions:
[ '0.2.0',
... other versions snipped ...
'0.4.0',
'0.4.1' ],
maintainers:
[ 'tkellen <[email protected]>',
'cowboy <[email protected]>',
'shama <[email protected]>' ],
time:
{ '0.2.0': '2012-09-10T22:26:15.048Z',
... other versions snipped ...
'0.4.0': '2013-02-18T17:24:36.757Z',
'0.4.1': '2013-03-26T20:08:14.079Z' },
author: 'Grunt Team (http://gruntjs.com/)',
repository:
{ type: 'git',
url: 'git://github.com/gruntjs/grunt-contrib-copy.git' },
version: '0.4.1',
... other config info snipped ...
dist:
{ shasum: 'f0753b40ae21bb706daefb0b299e03cdf5fa9d6e',
tarball: 'http://registry.npmjs.org/grunt-contrib-copy/-/grunt-contrib-copy-0.4.1.tgz' },
directories: {} }
What am I missing here? Why won't npm update this plugin to the currently available version?
A:
Currently there is an open issue in NPM which talks about same thing. npm update does not update devDependencies while npm install works fine.
https://github.com/isaacs/npm/issues/2369
So what I can recommend is try to use npm install instead:
$ sudo npm install grunt-contrib-copy --save-dev
|
[
"english.stackexchange",
"0000320482.txt"
] | Q:
What are the difference between "should open" and "should be opened" and "should be opening"?
I am preparing some document. In this document I need to mention User activity and corresponding expected results. For example
User activity : User clicks on the Submit button.
Expected Results : It should open one new popup window and this pop up window should display the the following message to the user -"Thanks for your feedback".
Can I also write something like this?
Expected Results : It should be opened one new popup window and this pop up window should be displayed the the following message to the user -"Thanks for your feedback".
or
Expected Results : It should be opening one new popup window and this pop up window should be displayed the following message to the user -"Thanks for your feedback".
So my questions are
What is the difference between should open and should be opened and should be opening?
What to use when?
In this case which one is more suitable?
A:
The big difference here is active and passive voice. The original sentence is in active voice. In your suggested options, I think you're trying to use passive voice, but you need to change the order of the words.
When you say “it should be opened,” it is the object of the opening. But the object should be the window. So you want to say “One new popup window should be opened.” Note that in passive voice, you don't say who or what is doing the opening.
The same goes for the message: “the following message should be displayed.” Again, you don't say that the window is doing the displaying.
Putting it together, you could say:
One new popup window should be opened and the following message should be displayed to the user: “Thanks for your feedback.”
Note that you could use active voice for one part and passive for the other, though that is probably more awkward.
Generally, the choice of voice is determined by the style guide, or consistency with the rest of the document. So check whether someone has made a guide for these documents and if not, just pick either active or passive voice and use it throughout.
|
[
"unix.stackexchange",
"0000329324.txt"
] | Q:
ssh login with password impossible - no prompt offered- Too many authentication failures
I am trying to log in to a fresh installation of openSUSE Leap 42.2 on a Raspberry Pi. The setup if completely default, and there are no public keys stored on the pi.
When I try to log in via ssh [email protected] I get an error:
Received disconnect from 192.168.1.56 port 22:2: Too many authentication failures
Connection to 192.168.1.56 closed by remote host.
Connection to 192.168.1.56 closed.
Using ssh -v reveals that lots of public keys are being offered:
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/robert/.ssh/id_rsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Offering DSA public key: /home/robert/.ssh/id_dsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Offering RSA public key: robert@XXX
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Offering RSA public key: robert@yyy
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Offering RSA public key: robert@zzz
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Offering RSA public key: backup-login@xxx
Which I assume count for an authentication attempt each and cause the server to stop talking to me.
Sure enough, when I log in from a different user account, the password prompt appears.
On the server the following error message appears
Dec 09 20:27:18 linux sshd[1020]: error: maximum authentication attempts exceeded for root from 192.168.1.52 port 35088 ssh2 [preauth]
To work around this tried to force password authentication as described at How to force ssh client to use only password auth?:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no [email protected]
which now lead to
Permission denied (publickey,keyboard-interactive).
How can I get password-based login working in this situation?
A:
"password" and "keyboard-interactive" are two different authentication types; the host is offering the later. So you need to use that in your preferred authentication list:
ssh -o PreferredAuthentications=keyboard-interactive …
|
[
"raspberrypi.stackexchange",
"0000039391.txt"
] | Q:
Can't stop script from running at start up
Hope this is the correct forum.
I'm new to Raspberry Pi and programming.
I have been trying to get my script running at startup without any success, until I found an answer on stack overflow.
https://stackoverflow.com/questions/30507243/start-shell-script-on-raspberry-pi-startup
I wrote the code into /etc/rc.local which got the script to run at startup. The script keep on running. I have had the SD card into my PC where i added init=/bin/sh, to cmdline.txt which gives me an command line when starting up my Raspberry. When I write sudo nano /etc/rc.local I can open the file, delete the code from earlier, but I can't save the file.
Any good advice on how to fix this problem so my script ain't running at boot-up in my terminal anymore?
Thanks.
A:
I installed the program Paragon extfs on my PC.
I could then open the rc.local file and delete the code.
I opened the cmdline.txt and deleted the init=/bin/sh
The Raspberry Pi is now starting up normally again.
Thanks
|
[
"stackoverflow",
"0042285895.txt"
] | Q:
File paths for java spark project deployed into Heroku
I have deployed a java spark app onto Heroku but seem to be getting errors such as:
2017-02-16T22:17:35.519937+00:00 app[web.1]: java.io.FileNotFoundException: src/main/resources/csvs/webApp/questions/questions.csv (No such file or directory)
I can't seem to locate my files. When I run the project locally in Eclipse (on windows), all is working well. What about the file paths do i need to change for the app to find the files when it is live. Sample code of the working local code:
String directory = "src/main/resources/csvs/webApp/questions/";
BufferedReader questions = null;
String line;
ArrayList<String> questionList = new ArrayList<String>();
try {
questions = new BufferedReader(new FileReader(directory + "questions.csv"));
while ((line = questions.readLine()) != null) {
if(!(line.equals("Question"))) {
questionList.add(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Thanks for the help.
A:
The heroku deploy:war and heroku deploy:jar commands do not upload your src/ directory by default (the only uploads your WAR or JAR file respectively).
You can add the --includes src option to the heroku deploy:* commands.
|
[
"stackoverflow",
"0034551204.txt"
] | Q:
MySQL query taking a long time on Join
I have the following mysql query which takes long time
SELECT `A`.*, max(B.timestamp) as timestamp2
FROM (`A`)
JOIN `B` ON `A`.`column1` = `B`.`column1`
WHERE `column2` = 'Player'
GROUP BY `column1`
ORDER BY `timestamp2` desc
I have index on TABLE A on column1 and indexes on table B are (column1,timestamp,column2),timestamp,column1.
When i use EXPLAIN it does not use timestamp index.
A:
Try adding an index...
... ON `B` (`column2`,`column1`,`timestamp`)
with the columns in that order.
Without any information about datatype, we're going to guess that column2 is character type (and we're going to assume that the column is in table B, given the information about the current indexes.)
Absent any information about cardinality, we're going to guess that the number of rows that satisfy the equality predicate on column2 (in the WHERE clause) is a small subset of the total rows in B.
We expect that MySQL will use of a "range" scan operation, using an index that has column2 as a leading column.
Given that the new index is a "covering" index for the query, we also expect the EXPLAIN output to show "Using index" in the Extra column.
We also expect that MySQL can use the index to satisfy the GROUP BY operation and the MAX aggregate, without requiring a filesort operation.
But we are still going to see a filesort operation, used to satisfy the ORDER BY.
|
[
"stackoverflow",
"0023851435.txt"
] | Q:
WordPress update_user_meta not saving
I have multiple additional usermeta fields created and working via the backend with WordPress.
However, I'm trying to create a simple form that allows people to click a button that saves a field to their profile. I've been all through StackOverflow, wordpress.stackexchange.com, and the wordpress.org forums. People seem to have this working, but I can't do the same.
Any help anyone can throw my way is much appreciated.
Here's my code, in functions.php:
function my_function() {
if (is_user_logged_in()) {
global $post;
if (has_badge()) {
$current_user = wp_get_current_user();
$badge_ID = get_post_meta($post->ID, 'badge_id', true);
$badge_check = $current_user->$badge_ID;
$badge_id_1289 = get_user_meta( $current_user->ID, 'badge_id_1289', true);
return '<form name="update_badges" action="#" method="POST">
<fieldset>
<label for="'.$badge_ID.'">Badge Name</label>
<input type="text" id="'.$badge_ID.'" name="'.$badge_ID.'" value="'.$badge_ID.'" />
</fieldset>
<button type="submit">Claim Badge</button>
</form>';
update_user_meta( $current_user->ID, 'badge_id_1289', $_POST['badge_id_1289'] );
}
add_shortcode('subscribe','my_function');
$badge_ID is taken from a custom field in the post this shortcode is added to, and I have confirmed it's working correctly (it shows as the value in the input field, the "for" in the label, etc.)
I get nothing. The form submits, the page reloads, but nothing gets saved to the database and therefor nothing shows up in the user's profile.
Any idea what I might need to do additionally with update_user_meta, or if this is a shortcode problem?
A:
@brasofilo was correct, the issue was that I was calling user_update_meta before the return. Here's the correct version:
function my_function() {
if (is_user_logged_in()) {
global $post;
if (has_badge()) {
$current_user = wp_get_current_user();
$badge_ID = get_post_meta($post->ID, 'badge_id', true);
$badge_check = $current_user->$badge_ID;
$badge_id_1289 = get_user_meta( $current_user->ID, 'badge_id_1289', true);
update_user_meta( $current_user->ID, 'badge_id_1289', $_POST['badge_id_1289'] );
return '<form name="update_badges" action="#" method="POST">
<fieldset>
<label for="'.$badge_ID.'">Badge Name</label>
<input type="text" id="'.$badge_ID.'" name="'.$badge_ID.'" value="'.$badge_ID.'" />
</fieldset>
<button type="submit">Claim Badge</button>
</form>';
}
add_shortcode('subscribe','my_function');
|
[
"stackoverflow",
"0004213888.txt"
] | Q:
How to return a DECIMAL(4,0) in TEXT keeping the 0000 format?
I want to return in a Stored Function a value as TEXT but I want to be 0001, and not 1
I have this code fragments:
DECLARE _RESTRICTEDROUTE DECIMAL(4,0);
RETURN(_RESTRICTEDROUTE);
I tried
RETURN(CAST(_RESTRICTEDROUTE AS TEXT));
but failed.
A:
Use LPAD().
This should work:
RETURN(LPAD(_RESTRICTEDROUTE, 4, "0"))
|
[
"stackoverflow",
"0047795522.txt"
] | Q:
Search for overlapping date ranges
I have product collection with a list of date ranges that represent dates when products are rented. So it looks something like this:
"product" : {
...
"RentalPeriods" : [
{
"From" : ISODate("2017-02-11T23:00:00.000Z"),
"To" : ISODate("2017-02-12T23:00:00.000Z")
},
{
"From" : ISODate("2017-10-09T23:00:00.000Z"),
"To" : ISODate("2017-10-21T23:00:00.000Z")
}
]
...
}
I want to create query that will go through all products and to return only products that can be rented for provided date range.
So if I provide something like:
RentalPeriod("2017-03-03", "2017-03-04") - it should return above product
RentalPeriod("2017-02-03", "2017-02-14") - it should not return above product
We tried with LINQ expression, but we got Unsupported filter Exception.
So this is what we tried:
public Expression<Func<Product, bool>> IsSatisfied() =>
product => product.RentalPeriods.All(rentPeriod => !(_fromDate > rentPeriod.FromDate && _fromDate < rentPeriod.MaybeToDate.Value) &&
!(rentPeriod.FromDate > _fromDate && rentPeriod.FromDate < _toDate));
(Above query is partial, but I suppose it is clear what we tried).
Is there any other way how we can achieve this?
Edit 13-12-2017:
public class AvailabilityForRentalPeriodSpecification : ISpecification<Product>
{
private UtcDate _fromDate;
private UtcDate _toDate;
public AvailabilityForRentalPeriodSpecification(RentalPeriod rentalPeriod)
{
_fromDate = rentalPeriod.FromDate;
_toDate = rentalPeriod.MaybeToDate.Value;
}
public Expression<Func<Product, bool>> IsSatisfied() =>
product => product.RentalPeriods.All(rentPeriod => !(_fromDate > rentPeriod.FromDate && _fromDate < rentPeriod.MaybeToDate.Value) &&
!(rentPeriod.FromDate > _fromDate && rentPeriod.FromDate < _toDate));
}
This specification is used in DAO layer as:
public IList<T> GetBy(ISpecification<T> specification)
=> _mongoCollection.Find(specification.IsSatisfied()).ToList();
Possible solution (that I'm trying to avoid) is to retrieve all products from DB and then to filter them in the code.
A:
I changed a query logic to use Any method instead of unsupported All method, so it looks like this now:
public Expression<Func<Product, bool>> IsSatisfied() =>
product => !product.RentalPeriods.Any(dbRentalPeriod => _fromDate >= dbRentalPeriod.FromDate && _fromDate <= dbRentalPeriod.ToDate ||
_toDate >= dbRentalPeriod.FromDate && _toDate <= dbRentalPeriod.ToDate ||
dbRentalPeriod.FromDate >= _fromDate && dbRentalPeriod.ToDate <= _toDate);
Another problem was using Maybe struct for ToDate (rentPeriod.MaybeToDate.Value), which is resolved by creating internal DateTime field next to the MaybeToDate field.
|
[
"stackoverflow",
"0036232101.txt"
] | Q:
Codename One - create small image from big image (and store it)
I have a GUI built app, that manages profiles of clients. When a new profile is created, a picture is taken. The path (String) is saved in a Hashtable along with the other info.
When it displays the list of all clients, each client info is set in a Multibutton, each containing a small picture of the client. That picture is a masked picture that is set every time the form is loaded, making it very slow to load (when I didn't have the small pictures, it loaded faster).
Question
I would like to save the masked small picture right after I take & save the picture of the client. So when I display the list of clients, I would just fetch the small image instead of having to do the masking for all the items. Is this possible?
I am trying this: (my goal is to have a working "smallPhotoPath")
String bigPhotoPath = Capture.capturePhoto(width, -1);
Image bigPhoto = Image.createImage(bigPhotoPath);
...
//masking image
...
bigPhoto = bigPhoto.applyMask(mask);
String smallPhotoPath = bigPhotoPath+"Small";
Image smallPhoto = bigPhoto.scaled(bigPhoto.getWidth()/8, -1);
java.io.OutputStream os = Storage.getInstance().createOutputStream(smallPhotoPath);
ImageIO.getImageIO().save(smallPhoto, os, ImageIO.FORMAT_PNG, 1);
os.close();
A:
After experimenting a lot, I solved the issue. I changed the following line:
java.io.OutputStream os = Storage.getInstance().createOutputStream(smallPhotoPath);
for this one:
OutputStream os = FileSystemStorage.getInstance().openOutputStream(smallPhotoPath);
Now it works fine :)
|
[
"stackoverflow",
"0022374412.txt"
] | Q:
My login codes validate my credentials ,but don't login
I have MVC.Net C# Login page and I decided to make some fancy changes, and all of the sudden my login page stoped working.
I need your help , somebody else to look at my code and may be see what I couldn't find. during debugging, it returns all true but don't go into index page. What do you think ? what is my problem that I can't see!
Here is my controller:
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.EMP_ID, model.EMP_PASSWORD))
{
FormsAuthentication.SetAuthCookie(model.EMP_ID, false);
}
else
{
ModelState.AddModelError("", "The User ID or Password provided is incorrect.");
}
}
return View(model);
}
A:
You are transferring it to any other view, you can use return RedirectToAction("Actionname","controllername","params if any");
// POST: /Account/Login
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.EMP_ID, model.EMP_PASSWORD))
{
FormsAuthentication.SetAuthCookie(model.EMP_ID, false);
//change here
return RedirectToAction("Actionname","controllername","params if any");
}
else
{
ModelState.AddModelError("", "The User ID or Password provided is incorrect.");
}
}
return View(model);
}
|
[
"stackoverflow",
"0046772299.txt"
] | Q:
Spark Apache is not deleting "NULL" values
I have a spark script that is supposed to delete null values in a dataframe build base on data read from a csv file.
This how my csv file look like:
Name,Surname,Age,Class,Categ
John,Snow,30,2nd,NULL
Alfred,Nobel,69,10th,m
Isaac,Newton,55,9th,m
So, I need to delete each row including a "NULL" value. To reach this result, This the code I am wrinting:
rdd = sc.textFile(dataset)
header = rdd.first()
data = rdd.filter(lambda x: x!=header).map(lambda line: line.replace("NULL","").split(","))
columns = header.split(",")
df = spark.createDataFrame(data, columns)
cleanedData = df.na.drop()
cleanedData.coalesce(1).write.option("header", True).option("delimiter", ",").csv('cleanedData')
When I execute my code, it supposed to return a csv file with the following content: (remove the first row)
Name,Surname,Age,Class,Categ
Alfred,Nobel,69,10th,m
Isaac,Newton,55,9th,m
but what I am getting is (just replace the NULL value with an empty string but not deleting the row):
Name,Surname,Age,Class,Categ
John,Snow,30,2nd,
Alfred,Nobel,69,10th,m
Isaac,Newton,55,9th,m
How can I fix this?
A:
When I execute my code, it supposed to ... (remove the first row)
It shouldn't. Empty string is not the same as NULL. In general you should avoid brittle manual parsing and use csv reader specifying nullValue:
spark.read.option("nullValue", "NULL").option("header", "true").csv(dataset)
but if you want to stick to your approach you should use None
lambda line: tuple(x if x != "NULL" else None for x in line.split(","))
|
[
"softwareengineering.stackexchange",
"0000315065.txt"
] | Q:
Version control on standalone (in-house) libraries?
Problem Statement
At our company, we have various application projects that we work on and then we also have libraries that those projects need to utilize. I feel the need (based on some similar question that have been asked) to say that none of these libraries are from a 3rd party, and that we design all of them in-house. Currently we do not control the version of these libraries whatsoever. We just plug all of the libraries that we need into the new application we are developing at the time, and just forget about it.
I don't think that this is the right approach. That being said, we do track the version of all of our application projects regularly through the use of Git. I am thinking that there must be a way to make sure that these stand-alone libraries are properly controlled.
Proposed Plan
What I am thinking to do is, have all of the libraries as there own repositories on our drive then just have a clone of each repository within the application working directory.
Question
Is my proposed plan okay? Or, should I not have revision control on these libraries in a stand-alone manner, then just check them into the application's repository? Something else?
A:
I would keep each library in its own repository. Start keeping track of library versions, for example with git tag.
A big problem with simply checking each library into each application's repository, is that you've essentially done copy and paste, and thus gain all the disadvantages that implies. Bugs fixed in the copy of the library in one application don't necessarily make it to the copies in other applications.
By having a single place for the library to officially live, you can more easily make sure all your applications can take advantage of bug fixes and new features.
For managing how each application gets a copy for actual build purposes, I'd recommend something similar to what the Cargo package manager does. Include a config file (xml, json, toml, etc) in each application's repository. In that config file, specify what libraries it needs, and what versions of those libraries it requires. You may also want to specify the locations of those libraries.
Then, either the developer or, preferably, a package manager, can read the file and clone the appropriate libraries, checkout the correct tag, and build them. You could clone them into a .gitignored subdirectory of the application. A dedicated library directory may be better, as then multiple applications that use the same version of the same library can share one copy.
A:
There are two basic approaches that you can take.
Keep versions on libraries. Track dependencies carefully. You will eventually experience dependency hell.
Keep all libraries up to date all the time. You will need very good unit tests, and a deployment strategy that provides a locked target for production.
I have worked at companies that use both approaches. For example Amazon tracks dependencies carefully, while Google keeps the world up to date.
My biased opinion is that the first approach pushes off your pain points, but in the long run it is more painful than the second approach. If you go with the second approach it is critical to automatically run unit tests, and I strongly recommend a good code review process. If you wish to copy Google, you can use https://www.gerritcodereview.com/about.md for code review and http://bazel.io/ for a build system. See http://googletesting.blogspot.com/2011/06/testing-at-speed-and-scale-of-google.html for a sense of how this scales to a large organization.
|
[
"stackoverflow",
"0012372688.txt"
] | Q:
How to perform this query on a hash in a MongoDB document (using Mongoid)
I am using Mongoid. I have a document that looks like the following:
Pet:
foo: {bar: 1, foobar: 2}
another_attr: 1
In this case, preferably using Mongoid, how would I query for all pets that have a bar value greater than 0 where another_attr is equal to 1?
A:
In mongo shell:
db.pets.find({"foo.bar":{$gt:0}, another_attr:1});
In mongoid:
Pet.where(:'foo.bar'.gt => 0, :another_attr => 1)
|
[
"stackoverflow",
"0042123266.txt"
] | Q:
How to access values of custom objects in an array?
I currently have a custom object
public struct GenreData : Decodable {
public let id : NSNumber?
public let name : String
public init?(json: JSON) {
guard let name : String = "name" <~~ json
else {return nil}
self.id = "id" <~~ json
self.name = name
}
}
I have an array of the custom object and am trying to access the 'id' part of the object so I can plug it in another function :
var genreDataArray: [GenreData] = []
var posterStringArray: [String] = []
var posterImageArray: [UIImage] = []
GenreData.updateAllData(urlExtension:"list", completionHandler: { results in
guard let results = results else {
print("There was an error retrieving info")
return
}
self.genreDataArray = results
for _ in self.genreDataArray {
if let movieGenreID = self.genreDataArray[0].id {//This is where the ID is needed to access the posters
print(movieGenreID)
//Update posters based on genreID
GenrePosters.updateGenrePoster(genreID: movieGenreID, urlExtension: "movies", completionHandler: {posters in
//Must iterate through multiple arrays with many containing the same poster strings
for poster in posters {
//Check to see if array already has the current poster string, if it does continue, if not append to array
if self.posterStringArray.contains(poster){
continue
} else {
self.posterStringArray.append(poster)
//Use the poster string to download the corresponding poster
self.networkManager.downloadImage(imageExtension: "\(poster)",
{ (imageData) //imageData = Image data downloaded from web
in
if let image = UIImage(data: imageData as Data){
self.posterImageArray.append(image)
}
})
}
}
})
}
}
DispatchQueue.main.async {
self.genresTableView.reloadData()
}
})
As of right now all its doing is accessing the first array of the JSON data(there are 19 arrays)and appending every string from that first array to the posterStringArray but instead I need it to go through each array and only append the string if doesn't already exist in the posterStringArray.
A:
I am not 100 percent sure I understood your question, but shouldn't you replace:
for _ in self.genreDataArray {
if let movieGenreID = self.genreDataArray[0].id
with
for item in self.genreDataArray {
if let movieGenreID = item.id
update
to only add one item try adding a break after getting the image:
//Use the poster string to download the corresponding poster
self.networkManager.downloadImage(imageExtension: "\(poster)",
{ (imageData) //imageData = Image data downloaded from web
in
if let image = UIImage(data: imageData as Data){
self.posterImageArray.append(image)
}
})
break
|
[
"stackoverflow",
"0029563788.txt"
] | Q:
How to draw N elements of random indices from numpy array without repetition?
Say, I have a numpy array defined as:
X = numpy.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Now I want to draw 3 elements from this array, but with random indices and without repetition, so I'll get, say:
X_random_draw = numpy.array([5, 0, 9]
How can I achieve something like this with the least effort and with the greatest performance speed? Thank you in advance.
A:
With NumPy 1.7 or newer, use np.random.choice, with replace=False:
In [85]: X = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [86]: np.random.choice(X, 3, replace=False)
Out[86]: array([7, 5, 9])
|
[
"gaming.stackexchange",
"0000065246.txt"
] | Q:
How can I disable my second monitor when game is running?
I have 2 screen setup for my computer... and I think the cold hard fact that the second monitor is running while I'm running games kills my FPS.
So, is there a way to automatically disable my second screen when I start a game on the first screen? And when I'll close it, to automatically reenable the second screen?
A:
It is hard to answer this question generically. Display "Mode Persistence", as it is called in the biz, is a notoriously fickle and config dependent feature. Key factors to consider:
Display mode (Clone, or Extended Desktop)
Graphics adapter (nVidia, ATI, etc)
Version of Windows (generally pre-Win 7 or post-Win 7)
Display modes are handled differently for these different configs. I'd also suspect that the FPS hit for running in these different configs varies.
All that said, if you want an easy way to turn off your second (or third/fourth etc) displays, most modern graphics cards provide it. Look for a "hotkey" menu in the graphics adapter GUI. For example in Catalyst:
Here you can set keystrokes for various display mode switching. I believe you'd be looking for "Disable all non-Primary displays". There many other hotkey-able capabilities you may also find useful, if you are switching between gaming and "regular" computer use.
|
[
"dba.stackexchange",
"0000131844.txt"
] | Q:
What is the minimum privilege required to create a full text index?
I just created a full text catalog on my database. I now have a developer who needs the ability to create full text indexes on the tables in this database.
The suggestion given in a previous question was to grant db owner to the user. I'd really like to avoid giving such a high level of access.
Is there any way to do this without granting dbo? I wasn't able to find anything regarding the permissions aspect on BOL.
A:
From BOL :
User must have REFERENCES permission on the full-text catalog and have ALTER permission on the table or indexed view, or be a member of the sysadmin fixed server role, or db_owner, or db_ddladmin fixed database roles.
If SET STOPLIST is specified, the user must have REFERENCES permission on the specified stoplist. The owner of the STOPLIST can grant this permission.
The public is granted REFERENCE permission to the default stoplist that is shipped with SQL Server.
Suggest you create a role and add the dev to the role. Just grant permissions to the role.
|
[
"stackoverflow",
"0015816927.txt"
] | Q:
bit manipulation: clearing range of bits
I'm preparing for an interview using the text, "Cracking the Coding Interview" by Gayle Laakman McDowell. On the section covering bit manipulation, there are two functions that are provided, but I don't quite understand how it works.
// To clear all bits from the most significant bit through i (inclusive), we do:
int clearMSBthroughI(int num, int i) {
int mask = (1 << i) - 1;
return num & mask;
}
// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
int mask = ~(((1 << (i+1)) - 1);
return num & mask;
}
In the first function, I understand what (1 << i) does of course, but what I'm not sure of is how subtracting 1 from this value affects the bits (i.e., (1 << i) - 1)).
I basically have the same confusion with the second function. To what effects, specifically on the bits, does subtracting 1 from ((1 << (i+1)) have? From my understanding, ((1 << (i+1)) results in a single "on" bit, shifted to the left i+1 times--what does subtracting this by 1 do?
Thanks and I hope this was clear! Please let me know if there are any other questions.
For those who by some chance have the text I'm referencing, it's on page 91 in the 5th Edition.
A:
let's assume i= 5
(1 << i) give you 0100000 the 1 is placed in the 6th bit position
so now if we substract 1 from it, then we get 0011111 ==> only the 5 first bit are set to 1 and others are set to 0 and that's how we get our mask
Conclusion: for a giving i the (1 << i) -1 will give you a mask with the i first bits set to 1 and others set to 0
A:
For the first question:
lets say i = 5
(1 << i ) = 0010 0000 = 32 in base 10
(1 << i ) -1 = 0001 1111 = 31
So a & with this mask clears the most significant bit down to i because all bit positions above and including index i will be 0 and any bellow will be 1.
For the second question:
Again lets say i = 5
(1 << (i + 1)) = 0100 0000 = 64 in base 10
(1 << (i + 1)) - 1 = 0011 1111 = 63
~((1 << (i + 1)) - 1) = 1100 0000 = 192
So a & with this masks clears bits up to index i
A:
First Function:
Let's take i=3 for example. (1 << i) would yield 1000 in binary. Subtracting 1 from that gives you 0111 in binary (which is i number of 1's). ANDing that with the number will clear all but the last i bits, just like the function description says.
Second Function:
For the second function, the same applies. If i=3, then ((i << (i+1)) - 1) gives us 01111. The tilde inverts the bits, so we have 10000. It's important to do it this way instead of just shifting i bits left, because there could be any number of significant bits before our mask (so 10000 could be 8 bits long, and look like 11110000. That's what the tilde gets us, just to be clear). Then, the number is ANDed with the mask for the final result
|
[
"stackoverflow",
"0003083810.txt"
] | Q:
Jsf library with web.xml
Jsf library (that is included in WEB-INF/lib) might contain its own faces-config.xml file.
Is it possible for such a library to include also its own web.xml file?
A:
Not until Servlet 3.0.
There you'll have "web fragments" (see under "Pluggability and Extensibility" from the above article)
|
[
"math.stackexchange",
"0001185853.txt"
] | Q:
can i continue with this. is there an inverse direction of modus tollens?
can i continue with this. is there an inverse direction of modus tollens. Should i end this validation like this ?
A:
You've done well so far! There are two ways to proceed, depending on what rules of inference you're allowed.
If you know about contrapositives, then you know that a statement of the form $a \rightarrow b$ is equivalent to the statement $(\lnot b) \rightarrow (\lnot a)$. Using that on the long axiom will finish the problem quickly for you.
Otherwise, hopefully you know that a statement of the form $a \rightarrow b$ is equivalent to the statement $(\lnot a) \lor b$, or equivalently to $\lnot(a\land\lnot b)$. Using that transformation on the long axiom will allow you to reach the answer in a few more steps.
|
[
"stackoverflow",
"0042575361.txt"
] | Q:
How to make a HTTPS GET request with headers with unsigned Certificate Swift 3?
I'm trying to make a https request to my website api and I'm been working on it for 2days but didn't find a solution to all my needs (it's in iOS 10). My https certificate is unsigned (https://api.example.de/v1/something) with a token as 'Authorization' header. then I want to download the JSON file and parse it. here's my code:
func testDownload(token: String){
let url = URL(string: "https://api.example.de/v1/blabla")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("Token \(token)", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: AnyObject]
let parsed_data = json["data"] as? [[String: AnyObject]] ?? []
let firstName = parsed_data[0]["firstName"] as? String
print("Firstname for first item is: \(firstName)")
self.employeeName.text = firstName
} catch let error as NSError{
print("Sorry there is an Error: \(error)")
}
})
task.resume()
I'm getting this error which seems unrelated:
2017-03-03 10:16:52.636 44 App[1763:34479] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
fatal error: unexpectedly found nil while unwrapping an Optional value
btw, I have already changed the info.plist like This Screenshot
and also have tested this code on two different APIs (one with a certified SSL and one with a normal HTTP protocol) and parsed the data.
What I'm doing wrong? please help me
A:
The problem was only the certificate, if a HTTPS certificate is unsigned then there is no way to make an HTTP request. If it is HTTPS then the certificate must be signed.
The problem was solved as soon as we signed our certificate.
|
[
"stackoverflow",
"0039443897.txt"
] | Q:
Access MySQL Database Of A 'Per Project' Installation of Laravel Homestead
I've installed Laravel Homestead on Vagrant via the 'per project' method outlined here: https://laravel.com/docs/5.3/homestead#per-project-installation
I can access the project database via ssh but want to be able to connect to it via my db editor (Coda).
My project root is ~/Code5
and my ~/Code5/Homestead.yaml file looks like this:
---
ip: "192.168.10.10"
version: "0.3.3"
memory: 2048
cpus: 1
hostname: code5
name: code5
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
- ~/.ssh/id_rsa
folders:
- map: "/Users/me/Code5"
to: "/home/vagrant/code5"
sites:
- map: super.app
to: "/home/vagrant/code5/app/super/public"
databases:
- super_db
Accessing super_db via ssh looks like this...
my-mac:~ me$ cd ~/Code5
my-mac:Code5 me$ vagrant ssh
vagrant@code5:~$ mysql --user=homestead --password=secret
mysql> use super_db;
mysql> show tables;
(tables listed successfully)
But If I try use this login config in Coda to access my database...
Server: 127.0.0.1 (port 33060)
User: homestead
Pass: secret
...I can't get it to connect.
(which is how I would connect on a global Homestead install, as opposed to a 'per project' method)
Also tried...
Server: code5 (port 33060)
User: homestead
Pass: secret
FYI: I needed to install Homestead via the 'per project' approach as I needed to run an older version of Homestead (that runs php5) without messing with my current global installation of homestead box (which runs php7). This way I can vagrant up either the php5 or php7 box and get developing.
A:
Ok, figured it out, used the IP from the Homestead.yaml file and changed the port back to the default (3306, not 33060) e.g.
Server: 192.168.10.10 (port 3306)
User: homestead
Pass: secret
|
[
"ru.stackoverflow",
"0001068886.txt"
] | Q:
Вылет при вводе неподдерживаемой информации в модуль wikipedia (Python3.8)
Пишу макет для работы с википедией на python3 и когда пользователь вводит информацию, которой на википедии нет или просто набор символов, то программа вылетает (файл .py закрывается), можно ли как-то обойти эту проблему.
Используются python3.8 и модуль: wikipedia.
Код:
import wikipedia
Input = input("Запрос?")
Searcher = "Start"
wikipedia.set_lang("RU")
Searcher = wikipedia.summary(Input)
print(Searcher)
Traceback
(Планирую использовать это в своём боте вк, через vk_api).
A:
Модуль wikipedia выбрасывает исключение, и это нормальный способ работы с ошибками - выкидывать исключение определённого типа. Ловите это исключение (через try
except) в своём модуле там, где вызываете функции из модуля wikipedia и делайте что вам нужно в этом случае делать, например, печатайте информацию об ошибке. Пример кода, где ловятся исключения любого типа:
import wikipedia
Input = input("Запрос?")
Searcher = "Start"
wikipedia.set_lang("RU")
try:
Searcher = wikipedia.summary(Input)
print(Searcher)
except:
print('Статья не найдена!')
|
[
"stackoverflow",
"0000979454.txt"
] | Q:
Variables defined and assigned at the same time
A coding style presentation that I attended lately in office advocated that variables should NOT be assigned (to a default value) when they are defined. Instead, they should be assigned a default value just before their use.
So, something like
int a = 0;
should be frowned upon.
Obviously, an example of 'int' is simplistic but the same follows for other types also like pointers etc.
Further, it was also mentioned that the C99 compatible compilers now throw up a warning in the above mentioned case.
The above approach looks useful to me only for structures i.e. you memset them only before use. This would be efficient if the structure is used (or filled) only in an error leg.
For all other cases, I find defining and assigning to a default value a prudent exercise as I have encountered a lot of bugs because of un-initialized pointers both while writing and maintaining code. Further, I believe C++ via constructors also advocates the same approach i.e. define and assign.
I am wondering why(if) C99 standard does not like defining & assigning. Is their any considerable merit in doing what the coding style presentation advocated?
A:
Usually I'd recommend initialising variables when they are defined if the value they should have is known, and leave variables uninitialised if the value isn't. Either way, put them as close to their use as scoping rules allow.
Instead, they should be assigned a default value just before their use.
Usually you shouldn't use a default value at all. In C99 you can mix code and declarations, so there's no point defining the variable before you assign a value to it. If you know the value it's supposed to take, then there is no point in having a default value.
Further, it was also mentioned that the C99 compatible compilers now throw up a warning in the above mentioned case.
Not for the case you show - you don't get a warning for having int x = 0;. I strongly suspect that someone got this mixed up. Compilers warn if you use a variable without assigning a value to it, and if you have:
... some code ...
int x;
if ( a )
x = 1;
else if ( b )
x = 2;
// oops, forgot the last case else x = 3;
return x * y;
then you will get a warning that x may be used without being initialised, at least with gcc.
You won't get a warning if you assign a value to x before the if, but it is irrelevant whether the assignment is done as an initialiser or as a separate statement.
Unless you have a particular reason to assign the value twice for two of the branches, there's no point assigning the default value to x first, as it stops the compiler warning you that you've covered every branch.
|
[
"stackoverflow",
"0017525278.txt"
] | Q:
OutOfMemoryError in LWUIT Table
I am developing an app for S40, focused to work in the Nokia Ahsa 305. In some pages of the app, I show some tables filled with so many data (21 rows with 10 columns, like 210 Label data). When I show that table the memory use, rise a lot and when I try to show again the table, it gives me OutOfMemoryException.
Are there some guidelines that can be carried out for efficient memory management?
Here you can find some images from my memory diagram.
Before showing the table:
When I show the table:
After going back of the Table form
A:
Memory shouldn't rise noticeably on that amount of data. I would doubt a table like this should take more than 200kb of memory unless you use images in some of the labels in which case it will take more.
A Component in Codename One shouldn't take more than 1kb since it doesn't have many fields within it, however if you have very long strings in every component (which I doubt since they won't be visible for a 200 component table).
You might have a memory leak which explains why the ram isn't collected although its hard to say from your description.
We had an issue with EncodedImage's in LWUIT 1.5 which we fixed in Codename One, however as far as I understood the Nokia guys removed the usage of EncodedImage's in Codename One resources which would really balloon memory usage for images.
|
[
"stackoverflow",
"0013710126.txt"
] | Q:
Magento Random Fatal Error
I have a VPS apache server based in a farm.
Recently i sufferd from memory limit errors and i decided to increase the number of the memory limit by changing it in the WHM panel at PHP Configuration to 256MB. after i was presss the button "Save", i got my site (and other wordpress sites i have in my server) all over with random fatal errors and 500 internal server errors on my site: http://amadeus-trade.ru
I can log into the backoffice but, when i tried to go to System -> Configuration i get this error:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, [email protected] and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request
And when i try to add products i get this error:
Fatal error: Out of memory (allocated 19922944) (tried to allocate 1245184 bytes) in /home/amadeus/public_html/app/code/core/Zend/Date.php on line 2423
This error allways jumps from file to file and looks like this scheme:
Fatal error: Out of memory (allocated xxxxxxxx) (tried to allocate xxxxxxx bytes) in /home/amadeus/public_html/xxx/xxxx/xxx/xx/xx.php on line xxxx
Now, It is fresh installation. so far (until 01.11.12) the website worked great without problems.
The team in the hosting company says that this is aproblem of a code in magento but i positivly sure that the problem is on the server!
My WHM version was update by the team in 01.11.12 to v11.30
Can you assist me please how to solve this?
A:
Looking at your error message
Fatal error: Out of memory (allocated 19922944) (tried to allocate 1245184 bytes)
in /home/amadeus/public_html/app/code/core/Zend/Date.php on line 2423
PHP is telling you it tried to allocate 1,245,184 bytes of memory, but that was over the limit allowed. It's also telling you there are currently 19,922,944 bytes allocated.
1,245,184 bytes is 1,216 kilobytes (KB), which is 1.1875 megabytes (MB).
19,922,944 bytes is 19,456 kilobytes (KB), which is about 19 megabytes (MB).
This means one of two things.
PHP thinks it's only allowed to allocate around 19 MB of memory
The operating system PHP is running on ran out of memory
Check your runtime php.ini settings to make sure your memory change stuck (use a single page calling the phpinfo function to do this). Also, make sure it's 256M, and not 256MB. The later won't be recognized by PHP, and "weird things" will happen (including a super low memory limit).
That said, my guess is it's the later. When my version of PHP goes over the limit set in the memory_limit ini, I get a slightly different error.
PHP Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocate 10493952 bytes)
PHP is telling me that it's allowed limit has been violated. Your error
Fatal error: Out of memory
Says PHP has literally used up all the memory avaiable to the server at that point in time.
Beyond that, you host's response show a lack of Magento specific knowledge — any host capable of running the system would be able to the give you the information I just did. I'd start by asking them what the maximum memory limit is for a single PHP request. I'd end by moving to a VPS host that advertising Magento capability and has a good reputation for it.
|
[
"stackoverflow",
"0060763310.txt"
] | Q:
Change underline color of edittext if it is filled with input?
Change underline color of edittext if it is filled with input ?
State :
unfocused : color/1
focused : color/2
unfocused(after input) : color/2
i've try use :
edtText.doAfterTextChanged {
}
but, i can't find attribut "edtText.backgroundTint" in doAfterTextChanged
A:
You can use TextWatcher for this and setBackgroundTintList to change the line color,
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && !(s.toString().isEmpty())) {
//Color when text exists
ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.colorPrimaryDark));
ViewCompat.setBackgroundTintList(et, colorStateList);
} else {
//Default color - color when text does not exist
ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.colorAccent));
ViewCompat.setBackgroundTintList(et, colorStateList);
}
}
@Override
public void afterTextChanged(Editable s) {}
});
Please refer to this link.
|
[
"stackoverflow",
"0015093867.txt"
] | Q:
jQuery: access dropdown menu items via Tab
I'm trying to make a dropdown menu accessible via the keyboard (using only Tab, no access keys). I can't figure out how to make subitems accessible.
The desired behaviour is the following: when "item" is clicked or has the focus, display the list; when "item" loses the focus (on blur), if no "sub item" has the focus (which would mean that it has been accessed via the keyboard), hide the list.
Fiddle: http://jsfiddle.net/DBdbz/
HTML
<p id="ui"><a href="#">Item</a></p>
<ul>
<li><a href="#">Sub item 1</a></li>
<li><a href="#">Sub item 1</a></li>
<li><a href="#">Sub item 1</a></li>
</ul>
JS
$('ul').hide();
$('#ui a').on('focus', function() {
$('ul').show();
});
$('#ui a').on('blur', function() {
$('ul').hide();
});
Thanks for your help.
A:
What about this: http://jsfiddle.net/DBdbz/6/ ?
To get the focus/blur to work on every browser, the only thing that is needed is a tabindex on a given element (no matter which one, see Lee's link):
<p id="ui"><a href="#" tabindex="1">Item</a></p>
<ul>
<li><a href="#">Sub item 1</a></li>
<li><a href="#">Sub item 1</a></li>
<li><a href="#">Sub item 1</a></li>
</ul>
And here comes the JS:
$('ul').hide();
$('#ui a').on('focus', function() {
$('ul').show();
});
$('#ui a').on('keydown', function(e) {
if (e.keyCode == 9) {
$('ul').addClass('tab');
}
});
$('ul').on('mouseover', function() {
$('ul').addClass('mouse');
});
$('ul').on('mouseout', function() {
$('ul').removeClass('mouse').removeClass('tab');
});
$('ul li:last-child a').on('blur', function() {
if ($('ul').hasClass('tab')) {
$('ul').hide().removeClass('tab');
}
});
$('#ui a').on('blur', function() {
if (!$('ul').is('.tab, .mouse')) {
$('ul').hide();
}
});
|
[
"stackoverflow",
"0010378404.txt"
] | Q:
How do I prevent UIScrollView from intercepting touches outside of it's own view hierarchy?
My understanding of touch handling is that when a view is touched, if it itself doesn't handle touches, it 'hands' the touches up the view hierarchy until they are either handled, or you're at the top and they're discarded. (In essence, it's recursion; it hands the touches up to their subview, at which point the same 'upward' direction functions are called to pass it upward).
I'm in an odd situation where a UIScrollView -- which SHOULD intercept and handle any and all touches from it's children -- appears to be intercepting the touches of a UIImageView placed 'on top' of it. Remove the scroll view, and touches work properly. The problem is, the UIImageView in question is NOT a child of the UIScrollView; it's a sibling.
So my question becomes twofold: first, how do I stop it from 'stealing' these touches, and two, how can it be stealing them in the first place?
A:
Try setting userInteractionEnabled to YES on the UIImageView. If userInteractionEnabled is set to NO (which should be the default for a UIImageView), then touches would be passed down to the object below it -- the UIScrollView.
|
[
"emacs.stackexchange",
"0000034274.txt"
] | Q:
gnus, gmail and mbsync..do i need dovecot?
I'm trying to setup using gnus for mail using gmail.
I have a solid mbsync installation which saves my mails in a maildir folder. I've been reading lots of guides, including very up to date ones, and all of them seem to use dovecot in such a setup. Why is dovecot necessary? Other mail apps in emacs can just read a maildir folder (mu4e, notmuch, etc).
Can one just read a maildir directly into gnus?
A:
Why is dovecot necessary?
Dovecot is not necessarily necessary; it depends on your setup, needs and preferences.
Can one just read a maildir directly into gnus?
Of course one can, using the nnmaildir select method. See also the group parameters it recognises and a comparison of Gnus mail backends. Here is an example of my previous configuration:
(setq gnus-secondary-select-methods
'((nnmaildir "personal"
(directory "~/Mail/personal/"))
(nnmaildir "uni"
(directory "~/Mail/uni/"))))
i dont really understand why dovecot is needed for maildit+gnus so would also love to get insight into that
I, too, use mbsync to synchronise multiple Gmail mailboxes with Maildirs under a single parent directory on my system. Up until a couple of days ago I used nnmaildir and was happy with its performance, even in groups containing thousands of articles. The only slow operation was starting Gnus, which on my machine and with 3GB of mail took 9 seconds with the default gc-cons-threshold and 6 seconds with a temporarily increased value. This may be related to mutbuerger's comment; I am not sure. More importantly, though, I never faced any issues like the ones described in this SO question and the discussion thread linked therein (I use the latest version of Gnus in the master branch of the Emacs development tree).
Since then, however, I have configured Dovecot to serve said mbsynced Maildirs, which Gnus reads via the nnimap select method, for two main (possibly related) reasons concerning Gnus (as opposed to unrelated reasons like personal/academic interest):
Sometimes Gmail's special labels like [Gmail] All Mail, [Gmail] Bin, etc. did not behave like other labels/folders (unsure as to the correct terminology here). For example, I sometimes would not be able to select them from the group buffer without first rescanning them for new articles. Or, more annoyingly, I sometimes would not be able to move articles to them from a different summary buffer without first having selected or scanned them. I have no idea why this was the case or who was to blame, and I haven't yet found the time to investigate.
The straw which broke the author's back was nnir. This select method provides excellent OOTB support for nnimap and can even be easily configured to use the Gmail search key X-GM-RAW, in case you connect to their servers directly from Gnus.
nnir supports and can be extended to support multiple search engines for local Maildirs, but I only had time to try one. I picked notmuch because it is the newest and most actively developed project out of the supported engines. I soon discovered, however, that the relevant nnir code has not been updated in years, does not work at all with my multiple-Maildirs-under-single-parent-directory setup and has a few bugs which I will report and attempt to fix when I find the time.
I even resorted to rewriting some of the nnir-run-notmuch code and registering it as a new search engine in my gnus-init-file as an initial foray into debugging and improving the original code.
This is where I discovered that notmuch does not handle the aforementioned special Gmail labels very well OOTB either. In particular, filtering with the folder: keyword on such a label causes the whole query to return nothing. This made it impossible to search across the whole Maildir, let alone be confident in the thoroughness of the results. One day I would like to investigate all this further, but right now I just need a working mail setup.
Which brings me to my main justification for Dovecot. It is a large, mature, feature-rich yet modular and performant, specialised yet configurable and widely used project. I found it quite easy to configure as it has sensible defaults. More importantly, it has and will probably continue to have better IMAP support than Gnus, and IMAP in turn is a more mature and widely supported standard than the Maildir format. I would indeed like to see and help Emacs' IMAP and Maildir support improve, but Dovecot is simply the more stable and hence sensible option for (seemingly) a lot of people at the time of writing.
Having said that, nnmaildir is better than nnimap at filling in threads (i.e. looking up articles in any group by Message-ID), unless you enable the registry, which in turn results in some space and time overhead when selecting groups, etc.
|
[
"math.stackexchange",
"0003131055.txt"
] | Q:
Stability of numerical scheme for heat equation
We want to use the Fourier discrete transform to analyze the stability of leapfrog scheme for 1D diffusion eqn $v_t = \nu v_{xx}$
Thoughts
The leapfrog numerical discretization is given by
$$ \frac{ u_k^{n+1} - u_{k}^{n-1} }{2 \Delta t } = \nu \frac{ u_{k+1}^n - 2 u_k^n + u_{k-1}^n }{\Delta x } $$
With $r = 2 \nu \Delta t / \Delta x$, we can write our numerical scheme
$$ u_{k}^{n+1} = u_k^{n-1} + 2r ( u_{k+1}^n - 2u_k^n + u_{k-1}^n ) $$
(Def:) the discrete Fourier discrete transform of $u \in l_2$ is the function defined in $L_2[- \pi, \pi] $ by
$$ \hat{u}(\xi) = \frac{1}{ \sqrt{2 \pi } } \sum_{k=-\infty}^{\infty} e^{-i k \xi }u_k$$
for $\xi \in [-\pi, \pi]$.
If we apply the discrete Fourier transform to our scheme and then shifting the index $k$ appropriately, one obtains
$$ \hat{u}^{n+1} ( \xi) = \hat{u}^{n-1} ( \xi) + (2 r e^{i \xi} - 4r + 2r e^{- i \xi} ) \hat{u}^n(\xi) $$
And here is where I'm looking for some guidance. I know how to perform Von Neumann analysis for 1-level schemes, but how do we handle these situations when we have 2-level scheme?
A:
The characteristic equation for the recursion in $\hat u^n(ξ)$ is
$$
q^2+4r(1-\cosξ)q-1=0\iff q_\pm(ξ)=q_\pm=-2r(1-\cosξ)\pm\sqrt{1+4r^2(1-\cosξ)^2}.
$$
As both characteristic roots are real and their product is $-1$ with negative sum, the absolute value of the negative one will be larger than $1$. Which means that the resulting sequence $$\hat u^n(ξ)=c_1(ξ)q_+(ξ)^n+c_2(ξ)(-q_+(ξ))^{-n}$$ is almost always unstable. Even if initially $c_2(ξ)$ is very small, the accumulation of numerical errors will add to it in every step, and the alternating exponential term $$(-q_+(ξ))^{-n}\approx(-1)^n\exp(2nr(1-\cosξ))$$ will quickly grow, as the exponent $2nr(1-\cosξ)=(nΔt)\left(\frac{2\sinξ/2}{Δx}\right)^2$ is is positive and grows linearly in time $t_n=t_0+nΔt$.
|
[
"stackoverflow",
"0030847174.txt"
] | Q:
Wait all tasks one by one with the same transaction instance failed c#
I am using the wait all one by one approach inside one transaction instance and I get this error when calling the Commit method on the transaction instance:
What Am I missing here?
This is the code:
.
.
.
using Dapper;
using DapperExtensions;
.
.
.
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var tlis = GetTlis(connection).ToList();
using (var trans = connection.BeginTransaction())
{
var tasks = tlis.Take(10).Select(tli => Task.Factory.StartNew(
(dynamic @params) =>
{
ProcessTli(@params.Connection, @params.Transaction, tli);
},
new { Connection = connection, Transaction = trans }
)).ToList();
var tlisAmount = 0;
while (tasks.Count > 0)
{
//const int timeout = 3600*1000;
var winner = Task.WaitAny(tasks.ToArray());
if (winner < 0)
break;
tlisAmount++;
tasks.RemoveAt(winner);
Cmd.Write("({0}%) ", tlisAmount*100/tlis.Count);
var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(stopWatch.Elapsed.TotalSeconds));
Cmd.Write(timeSpan.ToString("c") + " ");
Cmd.Write("Processing {0} of {1} ", tlisAmount, tlis.Count);
Cmd.Write('\r');
}
try
{
trans.Commit();
}
catch (Exception e)
{
Cmd.WriteLine(e.Message);
trans.Rollback();
}
finally
{
connection.Close();
}
}
}
private static void ProcessTli(IDbConnection connection, IDbTransaction transaction, Tli tli)
{
var quotesTask = Task.Factory.StartNew(() => GetQuotesByTli(connection, transaction, tli));
quotesTask.ContinueWith(quotes =>
{
quotes.Result.ToList().ForEach(quote =>
{
var tliTransaction = new TliTransaction(quote);
connection.Insert(tliTransaction, transaction);
});
});
var billOfLadingsTask = Task.Factory.StartNew(() =>GetBillOfLadings(connection, transaction, tli));
billOfLadingsTask.ContinueWith(billOfLadings =>
{
var bolGroupsByDate = from bol in billOfLadings.Result.ToList()
group bol by bol.Year;
bolGroupsByDate.ToList().ForEach(bolGroupByDate =>
{
var bol = new BillOfLading
{
As400FormatQuoteDate = bolGroupByDate.ElementAt(0).As400FormatQuoteDate,
CommodityCode = tli.CommodityCode,
TariffOcurrenciesAmount = bolGroupByDate.Count(),
TliNumber = tli.TliNumber
};
var tliTransaction = new TliTransaction(tli, bol);
connection.Insert(tliTransaction, transaction);
});
});
Task.WaitAll(quotesTask, billOfLadingsTask);
}
Thanks in advance
A:
I would do something like this (note this shows the process, not the extact code...)
public void ModifyData()
{
using (var connection = new SqlConnection(connectionString))
{
var tlis = GetTlis(connection).ToList();
connection.Open();
Quotes quotes;
BillOfLading billOfLading;
using (var trans = connection.BeginTransaction())
{
quotes = GetQuotesByTli(connection, transaction, tli);
billOfLading = GetBillOfLadings(connection, transaction, tli);
}
}
// Process those items retrieved from the database.
var processedItems = this.Process(/* the items that you want to process */);
using (var connection = new SqlConnection(connectionString))
{
var tlis = GetTlis(connection).ToList();
connection.Open();
using (var trans = connection.BeginTransaction())
{
// do all your inserts.
}
}
}
Then you would run it:
await Task.Run(() => ModifyData());
This resource shows a really good example of running multiple tasks.
|
[
"stackoverflow",
"0057388211.txt"
] | Q:
TSQL: How to get a UNION result from two tables with XML information in T1.Field_A and nvarchar in T2.Field_A
I have two separate data input tables from different sources (one direct insert, one via API). I´m trying to fetch a unified list of tuples out of these two tables using the UNION command. Unfortunately the information of the field SourceEventID has different source types:
In table1, the information for SourceEventID is stored inside an xml in the field IncidentRequest_XML (type=xml).In table2 the data for this field is stored as a string (type = nvarchar).
My questions are:
Is it possible to get the result by using the union command in a different way and if not, how is it possible to get the unified list out of the two tables with the told circumstances?
Thanks a lot!
I tried to get the result using the UNION command but it told me, the following:
The data type xml cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.
SELECT
row_number() OVER (PARTITION BY A.SourceSystem ORDER BY Date) as Row,
IncidentRequest_XML.query('INCIDENT_REQUEST/SourceEventID') as SourceEventID,
'FOO' as Type
FROM dbo.Source_A
INNER JOIN dbo.ConfigTable C ON A.SourceSystem = C.SourceSystem
WHERE C.ReturnStatus = 1
UNION
SELECT
row_number() OVER (PARTITION BY B.SourceSystem ORDER BY Date) as Row,
SourceEventID,
'BAR' as Type
FROM dbo.Source_B
INNER JOIN dbo.ConfigTable C ON B.SourceSystem = C.SourceSystem
WHERE C.ReturnStatus = 1
What I expect is the following result:
ROW SourceEventID Type
1 <SourceEventID>abc12345</SourceEventID> FOO
2 testcall123 BAR
A:
If you look at your expected result you see, that XML and string would be mixed in the same column. This is not possible...
What you can do, is either use .value() instead of .query() to read the SourceEventId as string:
IncidentRequest_XML.value('(INCIDENT_REQUEST/SourceEventID/text())[1]','nvarchar(100)') as SourceEventID
Or you can use a cast, to transform your result of .query() to a string:
CAST(IncidentRequest_XML.query('INCIDENT_REQUEST/SourceEventID') AS NVARCHAR(100)) as SourceEventID
Good to know: .query() returns a XML-typed result, which is the result of a XQuery-expression. On the other hand .value() can deal with a singleton value only (therefore we need the (blah)[1] and the specific type.
|
[
"stackoverflow",
"0018214286.txt"
] | Q:
Javascript synchronous functions - chrome extension
I have a lot of problems in my code because it is not synchronous. Here is an example of problem that i have in a chrome extension. This is my function
function getTranslation(a_data, callback)
{
var apiKey = '####'
var json_object = {};
var url = '###';
var xmlhttp;
var json_parsed = {};
storage.get('data', function(items)
{
json_object = {
'text': a_data,
'from' : items.data.from,
'to' : items.data.to
};
var json_data = JSON.stringify(json_object);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Authorization","##apiKey=" + apiKey);
xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest");
xmlhttp.send(json_data);
json_parsed = JSON.parse(xmlhttp.responseText);
callback(json_parsed.translation);
});
}
This is how i use getTranslation function in another function:
for (counter in toTranslateArray)
{
getTranslation(toTranslateArray[counter],function(callback)
{
translated += callback;
console.log(translated); //this is second and works
});
}
console.log(translated); //this is first and empty
//code depending on translated
Is it something wrong there ?
A:
Since you are using sync XHR, instead of ajax, you need to use a sync function to save data, instead of chrome.storage, which is async.
In the chrome.storage documentation, one of its features is
It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial localStorage API.
But being blocking (and sync) is what you want, so why don't you change to that API instead?
Or even better:
Convert your getTranslation() function to be async. You would only need to add a third parameter that would be a callback, and use it inside the nested callbacks (because if you do this, you can also use ajax instead of sync XHR).
That way is the right thing, but if you feel lazy and want an easier way, just do the former and change chrome.storage to localStorage and you are done.
EDIT: I see you have already changed you function to be async. And it seems it works correctly, but you updated your question and you seem to have problems grasping why this line does not work:
console.log(translated); //this is first and empty
You need to understand how event oriented programming works. You may think that the line
for (counter in toTranslateArray)
which contains getTranslation means "do translation of every counter inside this toTranslateArray", but actually means "fire a translation event for every counter inside this toTranslateArray".
That means when that console.log get executed this tasks have just been fired; it does not wait for it to be finished. Therefore translated is empty in that moment. And that's normal, is executed async.
I don't know what you need to do with the translated var once is finished, but I would try to fire a different event once the last item of the array gets processed.
But anyway, what you need is to do is to study some tutorial or something about event oriented programming so all this makes more sense to you.
About the localStorage, I don't know, I found out about that as an alternative in the chrome.storage documentation, I really don't know how to use it in your case.
But since javascript is event oriented, I really recommend you to learn events instead of just going back to sync. But is up to you.
|
[
"stackoverflow",
"0025731177.txt"
] | Q:
How to list array
I have an array that contains image file names like this
Array ( [0] => first.png [1] => second.png [2] => third.png [3] => anyone.png [4] => all.png [5] => usual.png )
I use foreach to make a list
foreach($use_img as $use_img_result){
$use_img1 .= '<img src="' . $use_img_result . '">' . "\n";
$use_img1 .= '<img scr="spacer.png">' . "\n";
}
echo $use_img1
Result:
<img src="first.png">
<img scr="spacer.png">
(loops thru entire array)
<img src="usual.png">
<img scr="spacer.png">
but what I need is a result without the last "spacer.png" like this:
<img src="first.png">
<img scr="spacer.png">
(loop thru entire array)
<img src="usual.png">
Any Idea how to do this?
A:
Faster approach:
// Use variable to hold use_img`s count
$size = count($use_img);
$images = '';
for ($i = 0; $i < $size; ++$i) {
$images .= '<img src="'.$use_img[$i].'">'.PHP_EOL;
if ($i != ($size - 1)) {
$images .= '<img src="spacer.png">'.PHP_EOL;
}
}
echo $images;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.