text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
php permissions to create a file
I'm running an apache server on lubuntu, and am trying to use php to write a text file that the users can then download. I changed the permissions as so:
sudo chmod 775 /var/www -R
But I still get an error when I execute the script:
Warning: fopen(3): failed to open stream: Permission denied in
/var/www/myPage.php on line 217 Could not open file!
Here is the php code:
$filename = $liste[0][0];
$fh = fopen($filename, "x+") or die("Could not open file!");
fwrite($fh, "foo") or die("Could not write to file");
fclose($fh);
Do I need to change other permissions? Or is there another way to do what I'm trying to do?
Thanks
A:
Writing into a folder requires the Apache user to have writing, reading and executing privileges on that folder.
So, first try to identify the name of the Apache user (often www-data).
Then check if that user is either the owner or in the group of the folder where you want to write files.
Give write, read and execute (7) privileges on that folder for that user. Give everyone else who don't need writing the read and execute privileges (5) on the same folder.
(recommended) Give write and read (6) privileges to your files for the www-data user. Everyone else only need read privileges (4).
If www-data is neither the owner nor in the group of the file, then you should change either one of them. After doing this, you may find yourself unable to access the web folder if you access the server with a user other than www-data and other than root (like "webeditor"), and that user is neither the owner nor in the group.
I recommend:
Set the owner and group to the Apache user/group.
chown -R www-data:www-data /var/www
Add the webeditor user (or whichever you use to connect to the server on ssh or ftp) to the www-data group.
usermod -a -G www-data webeditor
Give folders the write, read and execute privileges to the owner. Avoid the writing privileges on everyone else.
find /var/www -type d -exec chmod 755 {} \;
Files do not require the execution privilege. Only reading and writing is necessary for the www-data user, the rest only need reading privileges, so 644 is enough for our files.
find /var/www -type f -exec chmod 644 {} \;
| {
"pile_set_name": "StackExchange"
} |
Q:
DNN Fresh Install. Cannot get to Homepage
I have installed DotNetNuke 7.03.01 on a Windows 2008 R2 server running IIS 7
The installation went ahead smoothly but when I opened the site and went to Login i got the 404 error page.
So I used the siturl/login.aspx to login to the site. Once I did the getting started popup keeps flashing infinitely and i cannot get further. If I check the console, I get
JQMIGRATE: Logging is active jquery-migrate.js?cdv=23:21
GET http://www.siteurl.org/DesktopModules/InternalServices/API/GettingStarted/GetGettingStartedPageSettings 401 (Unauthorized) jquery.js?cdv=23:8526
GET http://www.siteurl.org/DesktopModules/InternalServices/API/GettingStarted/GetContentUrl 401 (Unauthorized) jquery.js?cdv=23:8526
JQMIGRATE: Logging is active jquery-migrate.js?cdv=23:21
I don't know what could be causing this. I'm sure its a minor issue but unfortunately I cannot pinpoint it and there are not any resources that can help. Hopefully somebody has encountered this issue and has a solution for me.
A:
I got this problem resolved from the following link...
https://dnntracker.atlassian.net/browse/DNN-4264
So the simple solution is to add the following line to the modules node in the web.config file
runAllManagedModulesForAllRequests="true"
So the modules node should look like this.
<modules runAllManagedModulesForAllRequests="true">
<--->
<--->
</modules>
Hopefully this answer should anybody else who encounters this problem
| {
"pile_set_name": "StackExchange"
} |
Q:
Intel Galileo BSP Quark_EDKII error 4063
Building the EDKII Firmware
./buildallconfigs.sh GCC44 QuarkPlatform
I get the errors listed below
after hitting a roadblock and not knowing where to go anyone any ideas?
running on
Python 3.3
CentOS release 6.4 (Final)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
68: Notify (_SB.PCI0.SDIO, 0x02) make: ***
[/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.aml]
Error 255 Error 4063 -
Object does not exist ^ (_SB.PCI0.SDIO)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
69: Notify (_SB.PCI0.URT0, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.URT0)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
70: Notify (_SB.PCI0.USBD, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.USBD)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
71: Notify (_SB.PCI0.EHCI, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.EHCI)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
72: Notify (_SB.PCI0.OHCI, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.OHCI)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
73: Notify (_SB.PCI0.URT1, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.URT1)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
74: Notify (_SB.PCI0.ENT0, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.ENT0)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
75: Notify (_SB.PCI0.ENT1, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.ENT1)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
76: Notify (_SB.PCI0.SPI0, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.SPI0)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
77: Notify (_SB.PCI0.SPI1, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.SPI1)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
78: Notify (_SB.PCI0.GIP0, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.GIP0)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
85: Notify (_SB.PCI0.PEX0, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.PEX0)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
86: Notify (_SB.PCI0.PEX1, 0x02) Error 4063 -
Object does not exist ^ (_SB.PCI0.PEX1)
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
1218: I2cSerialBus (0x20, ControllerInitiated, 0x00061A80,
AddressingMode7Bit, "\_SB.PCI0.GIP0.I2C_", 0, ResourceConsumer,,)
Error 4095 -
syntax error, unexpected PARSEOP_NAMESEG ^
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
1235: I2CSerialBus(0x20, ControllerInitiated, 100000,
AddressingMode7Bit, "\_SB.PCI0.GIP0.I2C_", 0, ResourceConsumer, , )
Error 4095 -
syntax error, unexpected PARSEOP_NAMESEG ^
ASL Input:
/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii
- 1301 lines, 48788 bytes, 568 keywords Compilation complete. 15 Errors, 0 Warnings, 0 Remarks, 31 Optimizations
build.py... : error 7000: Failed to execute command make tbuild
[/home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables]
build.py... : error F002: Failed to build module
/home/mark/Quark_EDKII_v1.1.0/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables.inf
[IA32, GCC44, DEBUG]
Failed - Build end time: 16:35:20, Mar.03 2015 Build total time: 00:00:13
A:
You have issues with compiling ACPI tables. Crucial error message here is next:
ASL Input: /home/mark/Quark_EDKII_v1.1.0/Build/QuarkPlatform/DEBUG_GCC44/IA32/QuarkPlatformPkg/Acpi/AcpiTables/AcpiTables/OUTPUT/Dsdt/Platform.iiii - 1301 lines, 48788 bytes, 568 keywords Compilation complete. 15 Errors, 0 Warnings, 0 Remarks, 31 Optimizations
Probably your ACPICA tools outdated. You need to figure out, which version of ACPI compiler (from ACPICA tools) you should use. It's can be stated in build documentation for project you are building, or you can ask developers on corresponding mailing list. But first just try to update ACPICA tools to most recent version.
| {
"pile_set_name": "StackExchange"
} |
Q:
Static Block And Object Block Access In java
I read about object block that I mention below:
class Check {
static {
System.out.println("hello from Static");
}
//object block
{
System.out.println("This is my object block");
}
public static void main(String args[]) {
}
}
This is the output of program
Hello from Static
But when I make the object of class then object block is execute. I can't understand how this process is done by jvm. Is there any role of garbage collector?
class Check {
static {
System.out.println("hello from Static");
}
//object block
{
System.out.println("This is my object block");
}
public static void main(String args[]) {
System.out.println("hello from main");
Check obj = new check();
}
}
this is the Output:
hello from Static
hello from main
This is my object block
A:
The static blocks are executed whenever a classloader loads the class (this is most commonly done once per JVM instance, but I suppose you could create some very weird situation where you had multiple classloaders that all load the class; that's not a very beginner-level situation, though). The instance initializer blocks are executed every time you create an instance of that class (or one of its subclasses). Your program requires that:
The class is loaded by the JVM; this triggers the static initializer block (hello from Static).
The main static method is executed
A println is executed (hello from main).
You create an instance of Check. This triggers the instance initializer, leading to This is my object block.
The GC doesn't have anything to do with the behavior you're asking about, FTR.
A:
According to the Java Language Specification, the static blocks will be executed when the class is loaded and initialized by the classloader. As for the initialization blocks, they will be executed when the class is instantiated.
Please, refer to sections Static Initializers and Instance Initializers in the Java Language Specification (1.6)
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract number from string and replace?
So right now, my code is working as intended from what I know. But, I am incapable of putting together either a small module or another few lines to extract an integer number from users Input and inflate it by 1.
dictZero = [ "zero", "none", "null", "nil" ]
dictOne = [ "juan", "one", "won" ]
dictTwo = [ "two", "to", "too", "tu" ]
dictThree = [ "three" ]
dictFour = [ "four", "fore", "for" ]
userInput = input ( "Enter your sentence to inflate: " )
for i in userInput.split():
for e in dictFour:
if e in i:
userInput = userInput.replace ( e, "five" )
for d in dictThree:
if d in i:
userInput = userInput.replace ( d, "four" )
for c in dictTwo:
if c in i:
userInput = userInput.replace ( c, "three" )
for b in dictOne:
if b in i:
userInput = userInput.replace ( b, "two" )
for a in dictZero:
if a in i:
userInput = userInput.replace ( a, "one" )
print ( userInput )
Sample Input:
Before we begin to do anything at 1630.
Sample Output:
Befive we begin three do anything at 1631.
Without over-complicating and changing my code significantly, what can I do to simply +1 any number in the input string?
A:
If you ignore the 1630 at the end of the sentence, str.replace can just do replacements for words on the whole line, without needing to split it up by word.
If you want to add decimal numbers as well, you will need to go character by character, which will add some more complexity to the code.
dictZero = [ "zero", "none", "null", "nil" ]
dictOne = [ "juan", "one", "won" ]
dictTwo = [ "two", "to", "too", "tu" ]
dictThree = [ "three" ]
dictFour = [ "four", "fore", "for" ]
userInput = input ( "Enter your sentence to inflate: " )
for i in dictFour:
userInput = userInput.replace(i, 'five')
for i in dictThree:
userInput = userInput.replace(i, 'four')
for i in dictTwo:
userInput = userInput.replace(i, 'three')
for i in dictOne:
userInput = userInput.replace(i, 'two')
for i in dictZero:
userInput = userInput.replace(i, 'one')
output = ''
num = ''
for c in userInput: # Going char by char to find decimal values
if c.isdigit(): # is this char a digit?
num += c # if so remember it
else:
if num: # if we just found a whole number
output += str(int(num) + 1) # add 1 and append the string
num = ''
output += c # Append any non-decimal character
print(output)
Input:
Before we begin to do anything at 1630.
Output:
Befive we begin three do anything at 1631.
Note that this will not add float or negative values in the string, only ints.
| {
"pile_set_name": "StackExchange"
} |
Q:
LinkedIn: Education, Courses, and/or Certifications?
I'm a little confused about how exactly to treat these three sections on LinkedIn: Education, Courses, and Certifications.
It seems easy enough at first, but... Well, I'll give myself as an example.
I'd finished a four-year university course (let's call it Course X) a few years ago now. I put that in my LinkedIn profile under the "Education" section, and at this stage, all is well.
A month ago, I finished a year-long online course (Course Y), complete with project and exam (if it matters), which also gave me a certificate/certification in the field. If it matters, it's in a field which is completely unrelated to Course X.
I detailed Course Y in the "Education" section as well, and then put the certification under the "Certification" section. Seems logical enough.
But I'm wondering... What am I meant to use the LinkedIn "Courses" section for, exactly?
I'm assuming Course X should just stay under "Education". But what about Course Y? Should it stay there too, or should it actually be put under "Courses"?
If it should stay in "Education", then what on earth is meant to go under "Courses" at all? And in either case, I'm planning on continuing to take many more courses related to Course Y in future. Most of these will be shorter than Course Y, some much shorter (i.e. week- or month-long courses), some may be the same or longer. How many of these should I list as I complete them (if not all of them), which of them should go in "Education" (if any), and which of them should go under "Courses"?
Also, I'm assuming that wherever Course Y ends up, the certificate doesn't change anything, and should just stay under "Certifications"?
After all this, I'm sure it doesn't actually matter all that much in the grand scheme of things. But I'm wondering if there is a rule of thumb that I should be following here? Maybe it's as simple as, anything which comes after Tertiary education (or Secondary, if you didn't go on to complete Tertiary education) should go in Courses?
(Sorry if this was asked elsewhere, but after searching, I couldn't find anything here, or elsewhere online, that clears up this particular question for me.)
A:
Courses section is meant for you to highlight coursework you have taken as part of degree program or certification program. Certifications section is meant specifically for certifications.
Course X should go under Courses and its degree goes under Education. Course Y should go under Courses and its certification in Certifications. Course Y should only be under Education if you were admitted to an university/community degree/certification program. For instance, if you took a course on Coursera and got a certificate in the end. This certificate should only go under Courses and Certifications.
I haven't seen a standard on this though. You can experiment with which seems to get you more profile views.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access a drawable resource as an image in a webview
I have a png file in my package, and I just want to use it as the source for an image I am loading via html in a webview.
So far I have tried, this, this and this. None of which have actually worked.
Here is how I am adding the img tag to the html. Can anyone help me? I'm trying to build this for as early of an SDK version as possible (currently 4 [1.6])
String stringPath = "fie:///android_asset/chat_bubble.png";
addOn = String.format("<img src=\"%s\" >", stringPath);
A:
(I assume you copied the code piece from your project.)
There is a typo:
String stringPath = "fie:///android_asset/chat_bubble.png";
should be
String stringPath = "file:///android_asset/chat_bubble.png";
And you didn't closed <img> tag:
addOn = String.format("<img src=\"%s\" >", stringPath);
should be
addOn = String.format("<img src=\"%s\" />", stringPath);
| {
"pile_set_name": "StackExchange"
} |
Q:
Regarding android app development
Can anyone tell me more about the line- android:id = "@+id/enter_message" ?
where enter_message is a string. Why do we use '@+' before the 'id'?
A:
From Android official documentation:
ID
"Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:"
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file)
Read more here:
http://developer.android.com/guide/topics/ui/declaring-layout.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 2 - ngIf - Not a known property of div
So I'm obviously new to ng2, as are a lot of people currently. With the release of the first version I have been learning a little. I am starting to get some of the more "ng2" ways of thinking down.
However, something as simple as ngIf I can't get to work.
This is my view:
<div *ngIf="testVariable" class="checkbox">
<label>
<input type="checkbox" formControlName="rememberMe" value="remember-me"> Remember me
</label>
</div>
In my component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
...
ngOnInit() {
this.loginForm = this._fb.group({
username: ['', [<any>Validators.required]],
password: ['', [<any>Validators.required]],
rememberMe: []
});
this.testVariable = false;
}
Do I have to import something extra? I have seen pre-release ng2 examples importing CORE_COMPONENTS but I can't find a recent example with that in.
My module declaration:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';
@NgModule({
imports: [ ReactiveFormsModule, CommonModule ],
exports: [ LoginComponent ],
declarations: [ LoginComponent ],
providers: [ ],
})
export class LoginModule { }
A:
You have to add CommonModule in your application's @NgModule's imports declaration as below :
@NgModule({
imports : [
CommonModule
]
})
export default class AppModule {}
| {
"pile_set_name": "StackExchange"
} |
Q:
Update Gallery after capture an image android
I try to create an app that can capture image from camera and show the result based on image path. Inside the button which handles capturing image as below
btnImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "Nama_foto_" + waktu + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
intent.putExtra("return-data", true);
getParentFragment().startActivityForResult(intent, CAPTURE_IMAGE);
}catch (ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
});
And as a respon from camera capturing Im writing below code
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == CAPTURE_IMAGE) {
performCrop();
}
else if(requestCode == PIC_CROP){
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
picturePath = file.getAbsolutePath();
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
out.write(bytes.toByteArray());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//retrieve a reference to the ImageView
//ImageView picView = (ImageView)findViewById(R.id.picture);
//display the returned cropped image
imgView.setImageBitmap(thePic);
}
try {
}catch (Exception e) {
Toast.makeText(getActivity(), "Maaf gagal mengambil foto.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Variable picturePath declared outside OnCreateView as an empty string.
The problem is, whenever I run the app and capture the image. The image didnt show immediately in the gallery but instead I need to rerun the app (thru android studio) to see the image in gallery. It seems like something inside oncreateview trigger the event. But I still cant figure out what.
Pls help me fix the issue. Thanks
A:
it seems that your question should be rephrased differently:
this may solve your problem
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
reference :
How can I update the Android Gallery after a photo?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is deadly self defense in Germany legal?
Since I am an American in Germany I have had this discussion with a few Germans but haven't got a concrete answer. If i am at home in Germany and someone breaks into my house and I see that they have a gun am i allowed to use a gun that I have legally or a knife as self defense?
A:
Deadly self-defense is legal in Germany. The self-defense law (in particular Sect. 32 of the Criminal Code) makes no restrictions as far as the type of aggression and the type of defense is concerned. That means that - in principle - you can defend yourself against an attack by any means that is necessary to stop it. The principle behind that is "das Recht muss dem Unrecht nicht weichen", which translates to "the law does not have to yield to the unlawful". That particularily means that:
You do not have to run.
You do not have to yield.
You do not have to wait for help from public authorities (notably the police).
You can defend yourself (against any attack on you, be it life, limb or property), no matter if that would mean commiting a crime (even if that crime is killing a person). This is called "Trutzwehr" or "schneidiges Notwehrrecht", which can be translated to "active defense" or "aggressive defense" as opposed to passive defense.
However...
This regulation is not without pitfalls and limitations. There are quite a few, which means that in practice deadly force could be considered unlawful in self-defense. Books have been written about this subject alone, so it can not be exhaustively handled here. Some examples for corner cases are:
Attackers that clearly can not understand the severity of their actions have to be spared from extreme effects of your self-defense. The classical book case is that you can't shoot little children stealing apples from your tree.
If there is a massive discrepancy between what you want protect and the damage the attacker has to endure (called "qualitativer Notwehrexzess" - translating to "qualitatively eccessive self-defense"). If someone insults you, shooting him might go to far, since while your honour is attacked (which is protected by Sect. 185 Criminal Code), the attacker's life (protected by Sect. 212 Criminal Code) by far outweighs it. Note that, to ensure the effectiveness of the self-defense laws, the discrepancy must be extreme. And it does not mean you can't defend yourself. You just have to choose a less severe measure. So you might get away with knocking the insulter out.
After the attack is over you hit the attacker once too often, which causes his death (called "quantitativer Notwehrexzess" - "quantitatively eccessive self-defense"). The attack was over at the time of the deadly blow, so your right for self-defense had ended. You might get away without punishment, if it was impossible for you to realize that the attack was over.
If you only think an attack is happening, but it is not (for example someone attacking you with a rubber knife on Halloween). In this case there is no attack and so technically there is no right for self defense (called "Putativnotwehr"). Similar to the cases of excessive self-defense, it depends on your individual case (notable if you had a chance to realize the attack was false) if you are punished or not.
To sum it up: You have the right to defend yourself by any means necessary, but you are held responsible if you go to far (not just a little, but really really to far).
A:
This is governed by Sections 32 through 35 of the German Criminal Code which are admittedly a bit vague:
FOURTH TITLE: SELF-DEFENCE, NECESSITY AND DURESS
Section 32 Self-defence
(1) A person who commits an act in self-defence does not act
unlawfully.
(2) Self-defence means any defensive action that is necessary to avert
an imminent unlawful attack on oneself or another.
Section 33 Excessive self-defence
A person who exceeds the limits of self-defence out of confusion, fear
or terror shall not be held criminally liable.
Section 34 Necessity
A person who, faced with an imminent danger to life, limb, freedom,
honour, property or another legal interest which cannot otherwise be
averted, commits an act to avert the danger from himself or another,
does not act unlawfully, if, upon weighing the conflicting interests,
in particular the affected legal interests and the degree of the
danger facing them, the protected interest substantially outweighs the
one interfered with. This shall apply only if and to the extent that
the act committed is an adequate means to avert the danger.
Section 35 Duress
(1) A person who, faced with an imminent danger to life, limb or
freedom which cannot otherwise be averted, commits an unlawful act to
avert the danger from himself, a relative or person close to him, acts
without guilt. This shall not apply if and to the extent that the
offender could be expected under the circumstances to accept the
danger, in particular, because he himself had caused the danger, or
was under a special legal obligation to do so; the sentence may be
mitigated pursuant to section 49(1) unless the offender was required
to accept the danger because of a special legal obligation to do so.
(2) If at the time of the commission of the act a person mistakenly
assumes that circumstances exist which would excuse him under
subsection (1) above, he will only be liable if the mistake was
avoidable. The sentence shall be mitigated pursuant to section 49(1).
In practice, to the extent that you are in genuine fear for the safety of a human being from an intruder armed with a gun, in all likelihood you would be justified in using a deadly weapon in self-defense unless there was some reason that you could protect yourself completely without doing so, for example, by retreating into a panic room.
On the other hand, if your fear is only for property and not harm to a human being, you are probably not justified. Certainly, for example, you would not be justified in shooting and killing a fleeing burglar, or someone rustling your cattle out of your barn.
Germany does not have a "stand your ground" law, or something similar that automatically makes shooting someone who is an intruder in your home lawful. But, if a guy with a gun intrudes and puts some innocent person at genuine risk, it would be justified to defend yourself - and Section 33 gives you the benefit of the doubt in close cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
if search query is met function
I want to create a function for wordpress that display a particular banner only if certain search terms stored in array are entered into the search box.
So for example if i entered the string "yellow" I would get a banner and search results for that string because it is in the array
But if i entered the string "orange" I would only get search terms
not too sure where to start with this so any help would be much appreciated
Cheers
Daniel Wakefield
Web Designer Cheshire
A:
To check if a word exists within a search term, add each searched word into an array using explode(). Then use in_array() to see if that word exists.
$words_array = explode(' ', $_GET['s']);
if(in_array('orange', $words_array)) {
// search contains orange
} else {
// search does not contain orange
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails form select with NULL (no choice) support
How can I add a NULL option to my form select? I have a table:
categories
id
category_id
name
If I'm creating a new category, I want to be able to select the NO_CATEGORY option (NULL value and id).
My view code:
<%= f.collection_select :supercategory_id, Category.all, :id , :name %>
Also, it is a good idea? Isn't it better to have some predefined ROOT category in the database? Thank you.
A:
Try:
<%= f.collection_select :supercategory_id, Category.all, :id , :name, :include_blank => true %>
Its ok to have null. Just have your model logic know that it should create a new category and assign it rather than mass assign from the select. Might be something that happens in a before_validation method
| {
"pile_set_name": "StackExchange"
} |
Q:
Unexpected request: GET in angular jasmine testing
During controller testing I am facing Error: Unexpected request: GET /api/initData,Expected GET /api/empData.For as of now I have two http call in my controller.I have the below issues.
1)After giving $httpBackend.expectGET for both the test cases are passing otherwise I am getting the above error.Here I want to test for one http call
2)In afterEach block again I have to do a $httpBackend.expectGET otherwise the same error it is throwing.
Below is my code snippet for that controller
describe('Manager Controller',function(){
var $scope,
$rootScope,
$injector,
$controller,
$httpBackend,
mockManagerData,
managerController;
beforeEach(module('APP'));
beforeEach(inject(function(_$rootScope_,_$injector_,_$controller_,_$httpBackend_){
$rootScope = _$rootScope_;
$injector = _$injector_;
$controller = _$controller_;
$scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
mockManagerData = {
"manager": [
{
"id": 1,
"name": "Sam",
"department": "IT",
"employee": [
{
"id": 1,
"name": "Mak",
"profile": "developer"
},
{
"id": 1,
"name": "John",
"profile": "QA"
},
{
"id": 1,
"name": "Tom",
"profile": "Dba"
}
]
}
]
}
managerController = $controller('managerCtrl',{
$scope:$scope
});
}));
it('should get manager details',function(){
$httpBackend.expectGET('/api/initData').respond(200,'');
$httpBackend.expectGET('/api/empData').respond(200,mockManagerData);
$scope.getManagerDetails();//click event in controller
$httpBackend.flush();
expect(true).toBe(true);
});
afterEach(function() {
$httpBackend.expectGET('/api/initData').respond(200,'');
$httpBackend.expectGET('/api/empData').respond(200,mockManagerData);
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
})
Below is my controller logic
(function(angular){
'use strict'
angular.module('APP').controller('managerCtrl',managerController);
managerController.$inject=['$scope','$http'];
function managerController($scope,$http){
$scope.getManagerDetails = function(){
$http({
method: 'GET',
url: '/api/empData'
}).then(function successCallback(response) {
//some login
}, function errorCallback(response) {
});
}
$http({
method: 'GET',
url: '/api/initData'
}).then(function successCallback(response) {
//some logic
}, function errorCallback(response) {
});
}
})(window.angular)
The above code is working fine but when I remove any of the http call I am getting the above mentioned erros. Please some one help.Thanks
A:
You can test only for your api/initData or for both requests.The second call in your controller will be always made no matter you call the clickhandler or not. You could move that expectGet to beforeEach function and change it to whenGet. Then, you can unit test only the click function in your first test.
For documentation on httpBackend and difference between whenGet and expectGet refer this.
| {
"pile_set_name": "StackExchange"
} |
Q:
No Activity found to handle Intent { act=android.media.action.IMAGE_CAPTURE (has extras) }
Why I could receive this crash? I check the report in crittercism and the device affected was a GT-I9300 (Samsung S3) in 4.2.2. It's only one report in about 2500 daily users.
java.lang.RuntimeException: Unable to start activity ComponentInfo{co.seahorse.android/co.seahorse.android.views.camera.CameraActivity}: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.media.action.IMAGE_CAPTURE (has extras) }
A:
This exception is thrown when the phone can't find an activity (application) that can handle your intent. On S3 it shouldn't be the case of no camera application but in very rare occasions things that are supposed to always work just fail.
As long as you don't have more frequent reports I wouldn't worry. I'd say that in 99% of the cases, single time reports are not a problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
GZIP compression to a byte array
I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)
Besides: I don't want to generate the .gz file directly like it is done in all examples. I only want to get the compressed
data, so that I can e.g. encrypt it before writting the data to a file.
If I write directly to a file everything works fine:
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
GZIPOutputStream zipStream = null;
FileOutputStream fileStream = null;
try
{
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
zipStream = new GZIPOutputStream(fileStream);
zipStream.write(dataToCompress);
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
But, if I want to 'bypass' it to the byte array stream it does not produce a single byte - compressedData is always empty.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
byte[] compressedData = null;
GZIPOutputStream zipStream = null;
ByteArrayOutputStream byteStream = null;
FileOutputStream fileStream = null;
try
{
byteStream = new ByteArrayOutputStream(dataToCompress.length);
zipStream = new GZIPOutputStream(byteStream);
zipStream.write(dataToCompress);
compressedData = byteStream.toByteArray();
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ byteStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
A:
The problem is that you are not closing the GZIPOutputStream. Until you close it the output will be incomplete.
You just need to close it before reading the byte array. You need to reorder the finally blocks to achieve this.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
try
{
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(dataToCompress.length);
try
{
GZIPOutputStream zipStream =
new GZIPOutputStream(byteStream);
try
{
zipStream.write(dataToCompress);
}
finally
{
zipStream.close();
}
}
finally
{
byteStream.close();
}
byte[] compressedData = byteStream.toByteArray();
FileOutputStream fileStream =
new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
try
{
fileStream.write(compressedData);
}
finally
{
try{ fileStream.close(); }
catch(Exception e){ /* We should probably delete the file now? */ }
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I do not recommend inititalizing the stream variables to null, because it means your finally block can also throw a NullPointerException.
Also note that you can declare main to throw IOException (then you would not need the outermost try statement.)
There is little point in swallowing exceptions from zipStream.close();, because if it throws an exception you will not have a valid .gz file (so you should not proceed to write it.)
Also I would not swallow exceptions from byteStream.close(); but for a different reason - they should never be thrown (i.e. there is a bug in your JRE and you would want to know about that.)
A:
I've improved JITHINRAJ's code - used try-with-resources:
private static byte[] gzipCompress(byte[] uncompressedData) {
byte[] result = new byte[]{};
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
gzipOS.write(uncompressedData);
// You need to close it before using bos
gzipOS.close();
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static byte[] gzipUncompress(byte[] compressedData) {
byte[] result = new byte[]{};
try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPInputStream gzipIS = new GZIPInputStream(bis)) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzipIS.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
A:
If you are still looking an answer you can use the below code to get the compressed byte[] using deflater and decompress it using inflater.
public static void main(String[] args) {
//Some string for testing
String sr = new String("fsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggfsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggg");
byte[] data = sr.getBytes();
System.out.println("src size "+data.length);
try {
compress(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] compress(byte[] data) throws IOException {
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
System.out.println("Original: " + data.length );
System.out.println("Compressed: " + output.length );
return output;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
google cloud endpoints discrepancy between documentation, and what works in my app
The documentation states you should load your api from javascript like this:
var ROOT = 'https://your_app_id.appspot.com/_ah/api';
gapi.client.load('your_app_id', 'v1', function() {
doSomethingAfterLoading();
}, ROOT);
But, what it seems to actually be is
var ROOT = 'https://your_app_id.appspot.com/_ah/api';
gapi.client.load('your_api_name', 'v1', function() {
doSomethingAfterLoading();
}, ROOT);
For example, I can pass "users" as the api name, and now the users object is defined as an attribute of gapi.client.
Just to be clear, my api is defined like this:
@endpoints.api(name='users',version='v1',
description='The user service.')
class UserService(remote.Service):
...
So now, I wonder, am I doing something in an unintended way? And, since /_ah/api/explorer can find all the APIs that are defined, is there a way to have this function add all the apis I define without having to specify all their names in separate gapi.client.load calls?
A:
Thanks for pointing it out, this is a bug in the documentation! We'll try to get if fixed ASAP.
You should check out the fully-baked Tic Tac Toe sample application.
In it, we show how to load multiple APIs (among other things).
google.devrel.samples.ttt.init = function(apiRoot) {
// Loads the OAuth and Tic Tac Toe APIs asynchronously, and triggers login
// when they have completed.
var apisToLoad;
var callback = function() {
if (--apisToLoad == 0) {
google.devrel.samples.ttt.signin(true,
google.devrel.samples.ttt.userAuthed);
}
}
apisToLoad = 2; // must match number of calls to gapi.client.load()
gapi.client.load('tictactoe', 'v1', callback, apiRoot);
gapi.client.load('oauth2', 'v2', callback);
var buttons = document.querySelectorAll('td');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.addEventListener('click', google.devrel.samples.ttt.clickSquare);
}
var reset = document.querySelector('#restartButton');
reset.addEventListener('click', google.devrel.samples.ttt.resetGame);
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Google maps are loaded in Earth view
I am displaying google maps in my android application.
However, I am able to see the maps in earth/satellite mode.
I want to see them in normal mode.
Can anyone tell me where am I going wrong?
A:
According to the documentation you just need to call mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); on a valid GoogleMap instance.
| {
"pile_set_name": "StackExchange"
} |
Q:
android: Execution failed for task ':app:dexDebug' zxing barcode scanner
i am trying to use dm77/barcodescanner zxing from github and i've been trying to use this library but i always get
Error:Execution failed for task ':app:dexDebug'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 2
i've searched to other app:dex:Debug questions and problems and they said that i may have multiple dependencies. i tried to check it but i can't detect what or where these "multiple dependencies" are.
here's my code:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.quest.questsuser"
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dexOptions {
javaMaxHeapSize "4g"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.akexorcist:RoundCornerProgressBar:2.0.3'
compile 'com.github.ksoichiro:Android-ObservableScrollView:v1.6.0'
compile 'com.melnykov:floatingactionbutton:1.0.7'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.easing:library:1.0.1@aar'
compile 'com.daimajia.androidanimations:library:1.1.3@aar'
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.parse:parse-android:1.12.0'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
}
repositories {
maven {
url "https://jitpack.io"
}
}
your help with be greatly appreciated.
A:
I've already found the solution from https://www.youtube.com/watch?v=7uzWEjTVLQ4.
1. I added multiDexEnabled true in the default config build.gradle, added compile 'com.android.support:multidex:1.0.0' in the dependencies and in my Application Class i added a MultiDex.install(this); in the onCreate method
| {
"pile_set_name": "StackExchange"
} |
Q:
Partition theorems for located words
In this paper Bergelson, Blass, and Hindman prove the following
Theorem 1.2 Let $W(\Sigma; v)$ be colored with finitely may colors and let $\bar s$ be an infinite sequence from $W(\Sigma; v)$. Then $\bar s$ has a variable extraction $\bar t$ such that the set of extracted words of $\bar t$ is monochromatic.
I would like to know if there is an easy counter example to the claim that the components of $\bar t$ are obtained concatenating those of $\bar s$ in increasing order. (As stated, the theorem also allows substitution of the variable $v$ with elements of $\Sigma$ as long as all components of $\bar s$ contain at least a variable.)
Notation $W(\Sigma; v)$ is the set of words in the alphabeth $\Sigma\cup\{v\}$ that contain at least one occurrence of the variable $v$.
A:
If I understand the definitions correctly, you can take $\bar s$ to be a constant sequence equal to $v$. Take a coloring that colors words containing only the letter $a$ in red and words containing only the letter $b$ in blue. Then any $\bar t$ obtained by concatenating members of $\bar s$ will be composed of words in which only the letter $v$ is used. Therefore those words can be reduced to words using only $a$ or words using only $b$, which are of different colors. Hence $\bar t$ does not have the required property.
| {
"pile_set_name": "StackExchange"
} |
Q:
NodeJS Passport
I setup passport on nodejs and have it working with mongoose for allowing users to login and create new accounts.
app.js:
var express = require('express')
, app = module.exports = express.createServer()
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, routes = require('./routes/index')(app) //index loads in multiple routes
, MongoDBConnection = require('./database/DatabaseConnector').MongoDBConnection;
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'justdoit' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var mongoDbConnection = new MongoDBConnection();
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
//conditions....
});
});
}
));
app.get('/', function(req, res){
res.render('index', { title: "Index", user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { title: "Account", user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { title: "Login", user: req.user, message: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/account',
failureRedirect: '/login',
failureFlash: true })
);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
My problem is the app.js (which is where the passport code is) file is getting a bit large and I tried to move the passport sections into its own script and have the routes outside the app.js and in its own auth.js route file and then reference the routes via the app.js. It works for other routes but for passport related ones such as login it doesnt appear to fire the passport.authenicate() function.
Is there anyway I can put passport routes and functions into its own file and call it/load it from app.js?
auth.js:
module.exports = function(app){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
));
app.get('/', function(req, res){
res.render('index', { title: "Index", user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
console.log("directing to the account page....");
res.render('account', { title: "Account", user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { title: "Login", user: req.user, message: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/account',
failureRedirect: '/login',
failureFlash: true })
);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
}
A:
This is what I do. Please comment if you need more help tailoring it to your code.
First Step
Put your passport code in a separate file. e.g. pass.js. (I see you have already done that) Then, in that file, put all the code inside this:
module.exports = function(passport, LocalStrategy){
};
Remember to add to the function input anything else that you are using. In your case, besides passport and LocalStrategy, you will probably need to add mongoDbConnection as an input too.
Second Step
In your app.js, include this line. Just before "app.listen" if possible to ensure that everything has been properly defined/declared/included.
require('./pass.js')(passport, LocalStrategy);
Explanation
The "wrapper" in step one defines the chunk of code you will be including into your app. The "require" in step two is the code that actually includes it. You are basically defining the entire "pass.js" file as a function and passing it the tools it needs to carry out the code (passport, LocalStrategy etc)
In your case, you will probably need to modify my code to:
module.exports = function(passport, LocalStrategy, mongoDbConnection){
};
require('./pass.js')(passport, LocalStrategy, mongoDbConnection);
This should works. I googled about this a while ago and this appears to be the "correct" way to break up your app.js (I say this with great trepidation though :) ). Feel free to comment if you need anymore help.
A:
This github repo also has a good example of this.
https://github.com/madhums/nodejs-express-mongoose-demo
The server.js file would be your app.js. And the /config/passport.js is the included passport setup.
A:
For this I'll suggest to do this In app.js
require('./mypassport')(app);
And
mypassport.js
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, MongoDBConnection = require('./database/DatabaseConnector').MongoDBConnection;
module.exports = function(app){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Studio does not launch after installation
I've just downloaded the new Android Studio IDE released today, and installed it. When I double-click the icon to launch it, nothing happens. I've tried every shortcut to it, as well as the .exe in the installation folder.
I've also tried restarting the machine, uninstalling / restarting, and installing to a folder location without spaces. Does someone know why Android Studio won't start?
A:
I set my JDK_HOME environment variable to point to my Java (1.7) JDK path, and it worked.
My JDK path was:
c:\Program Files\Java\jdk1.7.0_21
but it will vary depending on the version of your JDK.
For directions in setting PATH variables for windows see: http://java.com/en/download/help/path.xml
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I build a virtual object cache?
I have a set of objects and I want to be able to use the same syntax to either
build a new object or
load an existing object.
I've built a "cache" that takes the object and the context that the object was created using and uses this data to see if the object has been previously created. So, for example, if I build theObject = new myObject(param1, param2), the cache would save the object as { obj: theObject, context: { param1: param1, param2: param2 } } and would be loaded again if I give it a context with the same values of param1 and param2.
I thought I was being clever and would be able to build the object like this:
myObject = function(param1, param2) {
var context = { param1: param1, param2: param2 };
var cacheHit = this.cache.find(context);
if (cacheHit) return cacheHit; // <-- Doesn't work :(
this.param1 = param1;
this.param2 = param2;
this.cache.save(this, context);
};
myObject.prototype = { cache: new myCacheObject }; // Shared cache in all instances
Sadly, I've learned that the new keyword means that I cannot use a return statement. I'd like for the cache collections to be internalized so that it's possible to build similar objects without a built-in cache and they would work the same. However, I don't think that I can do this with the new keyword.
How would I go about accomplishing this?
Update:
It turns out that this approach actually does work and my problem was stemming from inheritance (particularly since this is JavaScript inheritance). When extending this object, I used the following syntax:
myObject = function(param1, param2) {
if (arguments.length) {
var context = { param1: param1, param2: param2 };
var cacheHit = this.cache.find(context);
if (cacheHit) return cacheHit;
this.param1 = param1;
this.param2 = param2;
this.cache.save(this, context);
}
};
// Extended from myObject
anotherObject = function(foo, bar) {
// Call parent constructor
myObject.call(this, foo, bar);
};
anotherObject.prototype = new myObject;
anotherObject.prototype.constructor = anotherObject;
Since calling the parent constructor can't force the child to return a value, the child has to explicitly denote this.
anotherObject = function(foo, bar) {
return myObject.call(this, foo, bar);
};
Hopefully, I can come up with a cleaner way of doing this since, if the child class performs anything in its constructor, I will have to always check if a value was returned.
anotherObject = function(foo, bar) {
var possibleCacheHit = myObject.call(this, foo, bar);
if (possibleCacheHit) return possibleCacheHit;
// Do stuff
};
A:
I've learned that the new keyword means that I cannot use a return statement.
Lucky you, that's not true. Provided that you return a non-null object reference (see the linked answer for the specifics), the new operator will actually let you do what you want.
A:
Just don't use the new keyword, or at least don't use it outside your caching function
var getObject = function(param, param2) {
var context, cacheHit, obj;
context = { param1: param1, param2: param2 };
cacheHit = this.cache.find(context);
if (cacheHit) {
return cacheHit
}
obj = new myObject(param1, param2);
this.cache.save(obj, context);
return obj;
}
Later:
var someObj = getObject("a","b");
would return an instance of myObject from the cache, if one exists, or create a new one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Suggestion required for Large Database Optimization and performance
We are creating a large database with estimated growth rate 200 million+ records per annum. The database is use for analysis purpose and we will generate different tabular and graphical reports from available data. we've some concerns and require technical input and advices.
What impact we may see in future for very large table? Is there any limitation on number of records in one table or size of table?
What is the best way to index large data tables like this?
Any suggestion for optimization and performance of database is also appreciated.
A:
SQL Server DENALI will have column store indexes but this won't come until the end of this year or early next year but from what I have seen so far (very little), it will definitely help.
In SQL Server partitioning is your best friend here. And to your question abt the limitation of # of rows in a table, it is limited only by storage space.
http://msdn.microsoft.com/en-us/library/ms143432(v=sql.100).aspx
As tables grow, adding and updating the data will take some time and you may want to look at using minimal logging if you are using SQL Server 2008.
http://sqlcat.com/whitepapers/archive/2009/02/15/the-data-loading-performance-guide-2008.aspx
And for large tables, updating indexes frequently can take significant times and have seen cases where updating the statistics will give you a quick boost instead of frequent index rebuilds.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript: Push to Array with unknown key names
I have a small program that returns JSON which I'm then interrogating before pushing it into an array.
An example of the data is as follows:
id=1|owner=Vina San Pedro|brandName=1865 Chilean Wine|variantName=1865 Chilean Wine|quality=Standard|minorRegionName=Nordic Countries|vol02=0|vol07=0|vol08=4.25|vol09=4.25|vol10=0|
I can iterate the above string, pushing the values into the array, but how can I 'name' the key in the array based on the field name from JSON, considering that items such as "Vol02", "Vol07" may be marked as "val02", "val07", or "minorRegionName" can in some cases by "majorRegionName".
edit
var finalSplit = brandDataRow.split('|');
$.each(finalSplit, function (x, y) {
var v = y.split('=');
$.each(v, function (m, n) {
formattedBrandData.push({ m: m }, { n: n });
});
});
In the above example, if my | delimiterred string contains "Owner=??????|Value=????????|Brand=???????" then when I push this into an array, I want the keys to be "Owner", "Value" and "Brand".
BUT, I don't know the key names until after I've returned the data, so sometimes the | delimitered string could be "Owner=??????|Line=???????|Region=??????"
A:
Try this:
var data = "id=1|owner=Vina San Pedro|brandName=1865 Chilean Wine|variantName=1865 Chilean Wine|quality=Standard|minorRegionName=Nordic Countries|vol02=0|vol07=0|vol08=4.25|vol09=4.25|vol10=0|";
var keyVal = data.split("|");
var res = {};
for(var i =0; i< keyVal.length; i++) {
var tmp = keyVal[i].split("=")
res[tmp[0]] = tmp[1];
}
console.log(res);
Yes, it will return an object, but array can contain only numerical indexes. And in most cases you can work with object the same way as with array. Besides, see no reason to use $.each for such a simple task. Just an additional code to execute.
JSFiddle demo - see console output
| {
"pile_set_name": "StackExchange"
} |
Q:
Manually remap HSV to JET colormap
Is it possible to remap an RGB image (RxCx3) which uses an HSV colormap (not format!) to an RGB image using a JET colormap? In other words, is there a "mapping" between the HSV and JET colormaps in Matlab?
I haven't thought about it too hard, but here is a quick and dirty attempt:
function J = remap( I )
n = 256;
X = hsv(n);
Y = jet(n);
t = linspace(0,1,n)';
[r,c,~] = size(I);
I = reshape( I, r*c, 3 );
u = interp3( X(:,1), X(:,2), X(:,3), t, I(:,1), I(:,2), I(:,3) );
J = I;
for k = 1:3
J(:,k) = interp1( t, Y(:,k), u );
end
J = reshape( J, r, c, 3 );
end
Unfortunately this throws an error on the interp3 line saying that "The grid vectors must contain unique points.". I am not sure my code is the correct thing to do (I am basically trying to fit a 1D embedding coordinate to the HSV colormap), but size(unique(hsv(256),'rows'),1)==256 is true so I am not too sure why this error occurs.
NOTE: it might be confusing to some, but this question has nothing to do with the HSV format; all colour images here are stored in RGB format. I am asking about a mapping between colormaps.
A:
The easiest way of doing this would be to use your source colormap to convert your image to an indexed image (using rgb2ind) and then convert this indexed image back into an RGB image using the destination colormap (using ind2rgb)
indexed = rgb2ind(img, source_colormap);
output = ind2rgb(indexed, destination_colormap);
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get user input without receiving an "Unsed Variable" warning?
I'm taking a look at Rust and decided to build a small program that takes a user's input and prints it, but also want to do some math stuff with it for practice. Currently, this is how I am taking user input:
let mut number = String::new();
let input = io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
However, although I do get the correct input this way, Cargo gives me the following warning:
src/main.rs:10:9: 10:14 warning: unused variable: input, #[warn(unused_variables)] on by default
src/main.rs:10 let input = reader.read_line(&mut number)
If I were to just use the input variable, no matter what number I enter I would get a "2" in return when I print the number.
How can I avoid the warning? Is there another way for me to take input without creating 2 variable bindings?
A:
You can simply not write the value to a variable. As long as the type of the value is not marked must_use, you can ignore the value.
let mut number = String::new();
io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
[commercial]
You can use the text_io crate for super short and readable input like
let i: i32 = read!()
let tup: (i32, String) = read!("{}, {}");
[/commercial]
A:
It creates a warning because you are allocating space for a variable that is never used.
When faced with such warning you can either replace offending variable with _
let _ = io::stdin().read_line(&mut number) ...
or as ker noted just remove the variable altogether
io::stdin().read_line(&mut number)...
The _ will also work in other situation like parameters or in match clauses.
One additional option is to add #[allow(unused_variables)] in the module or crate and disable unused variable warnings. Although, I don't recommend it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is properly commented line in vimrc giving error for Missing quote?
I've been trying to add comments to my vimrc file and for some reason it is not allowing me to comment after the execute pathogen line.
4: execute pathogen#infect() "Enable Pathogen
5:
6: syntax on "*Syntax color highlighting*
With vimrc like this, saving and exiting and reentering vim, it gives me an error 'Line 4: Missing quote: "Enable pathogen'
I have syntax highlighting on, and all other comments I make show up as comments, but anything after () on that line doesn't. I don't know if it's something simple I'm missing or if anyone else has seen this, but it seems strange that it's just this one line giving me problems.
I am running Mac OS X 10.13.6 and Vim 8.2.600
A:
Please, read :h :comment carefully
It is not possible to add a comment to a shell command ":!cmd" or to the
":map" command and a few others (mainly commands that expect expressions)
that see the '"' as part of their argument:
...
execute
...
syntax
Also note that if the command does not take "bar" as part of argument (see :h :bar), you still can do
execute pathogen#infect() | "Enable Pathogen
Here you have two commands in a row, and the second one is a pure comment.
However, I suggest always write comments on separate lines and not to mess with this stuff at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
SASS: Why does phpsass remove the css attribute -webkit-box?
I am using PHPSASS in my web project. After running the whole thing I noticed that it removed all occurences of display:-webkit-box in my css. Why that?
A:
the Problem is not with the value (-webkit-box) it's because of the missing space before it!
see: Is there a reason why SASS, a CSS generator, needs to reject lines such as margin:10px ? (no space after colon)
| {
"pile_set_name": "StackExchange"
} |
Q:
Table widths hugging elements
I'm working on a site for one of my in-laws, who insisted on using Joomla so that he could update the content himself in the future. That being said, one of the things that I developed for him was a character generator for a game that he and his brothers created. That is working fine. The issue is that they want a way to print the final sheets off when finished, and to do so without all of the menus, banners, etc. I was told that the simplest way to handle that was to pass ?tmpl=component in the URL to strip everything out, which is also working.
The problem that I am running into is that the CSS in the Joomla template is causing the tables to behave in a way that I cannot figure out how to correct. The page consists of nested tables, with widths defined in terms of % (currently), but it seems that the specifically defined widths are being ignored in favor of the widths hugging the largest cell. To see what I'm talking about:
The trouble page: http://www.basementgames.com/tools/character-generator.html?s=36&tmpl=component
What the page should look like: http://www.basementgames.com/char_gen.php?s=36
This is the exact same code in both places, with the first being inside Joomla, and thus subject to the CSS of the template. I don't know much about CSS, and I'm driving myself crazy trying to figure out what to override to make the first example look like the second. Any thoughts?
A:
You can run this script on the page and it will remove the offending print.css file on page load:
<script>
if (window.location.href.indexOf('/character-generator.html') > 0 &&
window.location.href.indexOf('tmpl=component') > 0) {
(function(){
var links = document.getElementsByTagName('link');
for (var i = 0; i < links.length; i++) {
if (links[i].href.indexOf('/print.css') > 0) {
links[i].href = '';
}
}
})();
}
</script>
http://jfcoder.com/test/character-generator.html?tmpl=component
Note, it only runs on the character-generator.html page with a tmpl=component in the query string. It also has to run after the link elements, as well, so it should be inserted into the body tag or at the very bottom of the head tag. Since you have MooTools available, you could also use DOMReady().
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL auto increment refresh with new ID
I have a table, in MySQL where events are posted by users. Their individual ID is posted, so all the events they post can be related to their account. However, I want to put an auto increment field, that only count the events for 1 user at the time.
Is it possible? If yes, how can I achieve it?
For example, if the user with the ID 544 post 4 events, the 4th one will be marked as 4 in the auto increment column, even if it's the 421 events in the table...
A:
You could put in such a field, but you would need a trigger to keep it up-to-date. Then, if rows are updated or deleted, maintaining becomes challenging.
You can simulate this in a query pretty easily though, using variables:
select e.*,
@rn := if(@userid = userid, 1, @rn + 1) as UserSequenceNumber,
@userid := userid
from events e cross join
(select @rn := 0) const
order by userid;
You can also incorporate this into an update statement, if you want to actually store the values in the table. Once again, let me say, keeping the value up to date requires a bunch of triggers.
Also, the above works in practice. However, MySQL does not guarantee that arguments are processed in order. So, in theory, the @userid could be assigned before @rn, but this doesn't seem to happen in practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to parse numbers from a string using regex
I'm trying to understand why my regex below is failing. I'm trying to retrieve a range of values on both sides of the : but my code always fails to the else. range is coming from a command line arg like this java -jar myprogram.jar -R 50:100.
Is it failing because I'm passing a string to the matches() and looking for integers?
Here is my code:
private int[] parseRangeResults(String range) {
int[] rangeResults = new int[2];
if(range.matches("\\d+:\\d+")) {
String[] numbers = range.split(":")
rangeResults[0] = Integer.parseInt(numbers[0]);
rangeResults[1] = Integer.parseInt(numbers[1]);
} else {
throw new Exception("Invalid Syntax.");
}
return rangeResults;
}
A:
I would write it like this
private static int[] parseRangeResults(String range) {
String[] numbers = range.split(":", -2)
return new int[] {Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1])};
}
If there is no : it will give you an IndexOutOfBoundException: 1
If there is an invalid number like 1abc:234 you will get NumberFormatException: Unable to parse 1abc
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP not support double
I have written one function which is giving diff out put in PHP and Java. Please help me to get same output in PHP too. below are that functions written in both languages.
Function in Java:
public String getLat(String v_str, String strNS){
try
{
double lat = Integer.parseInt(v_str.substring(0, 2));
//System.out.println("lat="+lat);
double lat2 = Float.parseFloat(v_str.substring(2));
lat2 = lat2*10000;
lat2 = lat2/60*10000;
lat2 = lat2/100000000;
//System.out.println("lat2="+lat2);
lat += lat2;
if(strNS.equals("S"))
return ("-"+lat);
else
return (""+lat);
}
catch(Exception e){}
return ("");
}
Call: getLat("5224.09960","N");
Output: 52.40165999730428
Function in PHP:
$deg_coord = '5224.09960';
$lat = (int)(substr($deg_coord,0,2));
$lat2 = (substr($deg_coord,2));
$lat2 = $lat2*10000;
$lat2 = $lat2/60*10000;
$lat2 = $lat2/100000000;
echo $lat += $lat2;
exit;
Output: 52.40166
A:
It looks like your Java answer is incorrect due to a rounding error. This could be because you use Float instead of Double as float's precision is much more limited than double.
public static void main(String[] args) {
System.out.println(getLat("5224.09960","N"));
}
public static double getLat(String v_str, String strNS) {
double lat = Integer.parseInt(v_str.substring(0, 2));
double lat2 = Double.parseDouble(v_str.substring(2));
lat += lat2 / 60;
return strNS.equals("S") ? -lat : lat;
}
prints
52.40166
I suspect using string manipulation is unsafe as latitudes start at 0. i.e. it only happens to work for numbers with 4 digits in front of the decimal point.
This code makes no assumptions about the number of digits. (It does assume you want to round to 6 decimal places)
public static double getLat(String v_str, String strNS) {
double v = Double.parseDouble(v_str);
double lat = ((long) v)/100;
double lat2 = (v - lat * 100) / 60;
double lat3 = lat + lat2;
double rounded = (double)(long) (lat3 * 1000000 + 0.5) / 1000000;
return strNS.equals("S") ? -rounded : rounded;
}
If you want to reproduce the same rounding error in PHP, you could try
$deg_coord = '5224.09960';
$lat = (int)(substr($deg_coord,0,2));
$lat2 = (float) (substr($deg_coord,2));
$lat2 = $lat2*10000;
$lat2 = $lat2/60*10000;
$lat2 = $lat2/100000000;
echo $lat += $lat2;
exit;
| {
"pile_set_name": "StackExchange"
} |
Q:
One HTML file, and Multiple CSS files in Rails how?
I have one HTML file located in app/views/layouts/application.html.erb
I use <%=yield=> to render the HTML code from other models.
The problem is that I don't know how to distinguish the CSS code. I have a universal CSS code, but each html file needs a different one.
here is my CSS line in app/views/layouts/application.html.erb
<%= stylesheet_link_tag "scaffold" %>
<%= stylesheet_link_tag "welcome_screen/my_CSS.css", :media => "all" %>
A:
put a named yield in the head of the layout file, then use content_for in your specific view
# application.html.erb
<head>
<%= stylesheet_link_tag "scaffold" %>
<%= yield(:head) %>
# ...
</head>
<body>
<%= yield %>
# ...
</body>
then your view code
# welcome_screen.html.erb
<% content_for(:head) do %>
<%= stylesheet_link_tag "welcome_screen/my_CSS.css", :media => "all" %>
<% end %>
| {
"pile_set_name": "StackExchange"
} |
Q:
ng-options Key Value pair
есть массив list объектов вида
[
{Key: "key1", Value: "val1"},
{Key: "key2", Value: "val2"},
...
]
при использовании его в операторе ng-repeat
<select ng-repeat="obj.Key as obj.Value for obj in list"></select>
я в качестве значений опций получаю не свои ключи (key1, key2), а порядковые номера элементов в коллекции. т.е. примерно:
<option value='0'>val1</option>
<option value='1'>val2</option>
подозреваю, это связано с именами переменных внутри объектов (Key, Value). Кто-то может разъяснить поподробнее?
UPD: я прошу прощения. в пример кода вкралась ошибка. следует читать ng-repeat как ng-options (в названии запроса указал правильно)...
<select ng-options="obj.Key as obj.Value for obj in list" ng-model="selectRes"></select>
A:
Вам нужно заменить ng-repeat с ng-options. И добавить ng-model:
<select ng-model="selectedKey" ng-options="obj.Key as obj.Value for obj in list"></select>
Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
parse unique string based on a certain line
I have a dhcpd.leases file with the following:
lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;
lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;
lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state free;
next binding state expired;
lease 172.231.100.151 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;
lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state free;
next binding state expired;
As you may know in this file some leases are recorded multiple times. I need a solution to only grep out a unique IP addresses RANGE using the 172.231.100 BUT only the ones that have a binding state of active. I am aware there are scripts out there that do this for you with DHCP but ours is not working atm and a command line solution for this would be great. Note the "binding state " line will always be the 6th line from the "lease" line.
A:
awk solution:
awk '/^lease/ && !($2 in ips){ f=1; ips[$2]=$0; n=NR+5 }
f && NR <= n{
a[++c]=$0;
if (NR == n) {
if ($NF == "active;") {
for (i=1; i<7; i++) print a[i]; print ""
}
c=0
}
}' dhcpd.leases
The output:
lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
lease 172.231.100.151 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41;
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysterious OP_WITH_INVALID_USER_TYPE_EXCEPTION, Operation not valid for this user type: []
I had following situation.
When I tried to edit and save some of custom object CustomObject1__c instance, I received error in the top of the page
Error: Invalid Data.
Review all error messages below to correct your data.
Operation not valid for this user type
When I investigated deeper, so I have found out that this object CustomObject1_c has lookup relation to another object CustomObject2_c for which instance of one more custom object CustomObject3_c have been trying to be inserted.
Object CustomObject3_c also has lookup relation to object CustomObject2_c, so during insert object CustomObject2_c was considered to be updated with new child relationship record.
So when I tried manually to update corresponding instance of CustomObject2__c object, I saw another error instead of page
Can't Perform this Operation
You can't perform this operation with the selected user type.
Click here to return to the previous page.
I was trying to perform this operation under system administrator, so I supposed I had all the permissions to perform any of operations on any object.
Why did I have that error?
A:
You are not allowed to set the OwnerId of an object to an Inactive User or a User with a Chatter Free license. There are a few exceptions for Chatter Free license but such as Files, etc but Custom Objects are not allowed.
A:
So I want to share the answer I have found.
CustomObject2__c has a trigger which tried to modify OwnerId of instance of that object to AssignedUser field value.
I have found out that AssignedUser value for the failing object was inactive user, and it seems inactive user can't own custom object records.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do you estimate RAM size for application server?
I'm wondering what an appropriate way to estimate RAM
size for application server is.
I'm planning to build an application server with Apache as Web server and Django as application framework.
databases exist on different nodes.
at first, I thought finding out all cases that those middlewares use memory and
calculating how much each case would use memory would do the job.
but now I'm lost on how to find those use cases and also wonder this is appropriate to find a suitable RAM size for this server.
if anyone has experience on estimating RAM size for application server, could you tell me how you have done that or suggest me any book that would help me from this situation?
A:
System requirements calculation is more of an art than a science.
For games, it's often done by running through the game on progressively worse and worse hardware (e.g. less ram, slower CPU, less beefy GPU) until you get to around ~30fps (that's "Recommended" apparently), and then keep on going until a point where you can't play it at all (e.g. sub-10fps performance), that's your minimum.
For other software, without actually testing it on hardware, it really often is guesswork in combination with load-testing with some profiling: for example, spamming a web-application with lots of test requests and seeing how much RAM the webserver's process eats-up and how the CPU holds-up.
Be careful to also see how many resources are consumed by other, non-proprietary, components of your system, such as your database server, memcached, and so on. For example, a dedicated database server box will see the DB server eat up all the RAM available: this is intentional, as it can cache more data in-memory and improve performance.
Other things to consider:
Perform load-testing typical of 95% of daily use, if your application won't be handling 10,000 requests a second then you don't need to use that as the basis for your system requirements. If requirements do scale with load, then inform your customers.
Test it in a resource-constrained environment. You don't need a physical machine, just set-up a VM with limited RAM and CPU resources and see how well it handles the load-testing
| {
"pile_set_name": "StackExchange"
} |
Q:
Fluent Interface for a XmlQueryBuilder
In this answer I suggested using a fluent interface "builder" to replace all the hard-coded, repetitive and quite error-prone inline XML string concatenations.
This code might need a bit of tweaking to work perfectly with the OP's code in the question this code is following-up on, but it seems to work as expected. Thoughts?
public enum XmlQueryOperator
{
Equals,
LessThan,
LessThanOrEqual,
GreaterThan,
GreaterThanOrEqual
}
public class XmlQueryBuilder<TEntity>
where TEntity : class
{
private readonly XDocument _xDoc = new XDocument();
private readonly XElement _queryNode = new XElement("query");
public XmlQueryBuilder()
{
var rootNode = new XElement("queryxml");
rootNode.SetAttributeValue("version", "1.0");
var entityNode = new XElement("entity");
entityNode.Value = typeof (TEntity).Name;
rootNode.Add(entityNode);
_xDoc.Add(rootNode);
}
public XmlQueryBuilder<TEntity> Where<TProperty>(Expression<Func<TEntity, TProperty>> property, XmlQueryOperator operation, string value)
{
var xCondition = new XElement("condition");
var xField = new XElement("field");
xField.Value = GetPropertyName(property);
var xExpression = new XElement("expression");
xExpression.SetAttributeValue("op", operation.ToString());
xExpression.Value = value;
xField.Add(xExpression);
xCondition.Add(xField);
_queryNode.Add(xCondition);
return this;
}
public override string ToString()
{
var parent = _xDoc.Element("queryxml");
if (parent == null) throw new InvalidOperationException("root node was not created.");
parent.Add(_queryNode);
return _xDoc.ToString();
}
private string GetPropertyName<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
{
// credits http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression/672212#672212 (modified to return property name)
var type = typeof(TSource);
var member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", propertyLambda));
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", propertyLambda));
if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format("Expresion '{0}' refers to a property that is not from type {1}.", propertyLambda, type));
return propInfo.Name;
}
}
Usage - given a TestEntity:
public class TestEntity
{
public string Test1 { get; set; }
public int Test2 { get; set; }
public DateTime Test3 { get; set; }
}
This program produces the expected output:
class Program
{
static void Main(string[] args)
{
var builder = new XmlQueryBuilder<TestEntity>()
.Where(t => t.Test1, XmlQueryOperator.Equals, "abc")
.Where(t => t.Test2, XmlQueryOperator.GreaterThan, "def")
.Where(t => t.Test3, XmlQueryOperator.LessThanOrEqual, DateTime.Now.ToString());
Console.WriteLine(builder.ToString());
Console.ReadLine();
}
}
Output:
<queryxml version="1.0">
<entity>TestEntity</entity>
<query>
<condition>
<field>Test1<expression op="Equals">abc</expression></field>
</condition>
<condition>
<field>Test2<expression op="GreaterThan">def</expression></field>
</condition>
<condition>
<field>Test3<expression op="LessThanOrEqual">2014-05-05 14:14:57</expression></field>
</condition>
</query>
</queryxml>
A:
ToString() does too many things, it should only be calling _xDoc.ToString(); it has side-effects that make it dangerous to call more than once:
var foo = builder.ToString()
Console.WriteLine(builder.ToString());
Console.ReadLine();
Will not produce the expected output, and will not throw an exception either, resulting in an XML document with _queryNode showing up as many times as ToString() was called.
A:
One thing I really like about LINQ to XML is that it can be very declarative. For example, this code:
var rootNode = new XElement("queryxml");
rootNode.SetAttributeValue("version", "1.0");
var entityNode = new XElement("entity");
entityNode.Value = typeof (TEntity).Name;
rootNode.Add(entityNode);
_xDoc.Add(rootNode);
can be alternatively written as:
_xDoc.Add(
new XElement(
"queryxml",
new XAttribute("version", "1.0"),
new XElement("entity", typeof(TestEntity).Name)));
This approach can be taken too far (e.g. maybe I should have kept the rootNote variable?), but I think that judicious use can make the code more readable, especially since it means the code becomes hierarchical, just like the XML you're building.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to select one whole column in a table to style differently?
Is there a way to select one whole column in a table to style differently? without adding class or id to all those td?
I want to do with HTML and css 2.1 only. with cross browser compatibility
A:
You could try to use <col> element.
| {
"pile_set_name": "StackExchange"
} |
Q:
fragment visible while going back from an activity to other activity
I have 2 activities A and B. A hosts 2 fragments A and B. What I do is from this fragment A, I start Activity B and on finish I go to Activity A and
open Fragment B. In going to Activity A, I see fragment A for a second which should not happen. Here is my code -
From Fragment A -
Intent intent = new Intent(getActivity(), B.class);
intent.putExtra("hi, "bye);
getActivity().startActivityForResult(intent, "performaAction");
In Activity B -
Intent i = new Intent();
i.putExtra("data", data);
setResult(resultId, i);
finish();
Now I am go to Activity A and in Activity A, I open Fragment B. During this process, I see Fragment A for a while which I dont want
In Activity A -
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case resultId:
new Handler().post(new Runnable() {
public void run() {
openFragmentB(); //Fragment transition
}
});
break;
default:
break;
}
}
A:
Just remove the Handler part:
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
switch (resultCode) {
case resultId:
openFragmentB(); //Fragment transition
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
Explanation:
What you see is caused by you calling to switch fragments "sometime in the future", by using:
new Handler().post(new Runnable() {
public void run() {
openFragmentB();
}
});
What that means is your system will open the fragment once it's done with its current queue of actions it already has to do on the same thread.
There should be no reason for switching fragments like that, the current thread already gives you control over what happens right then and there, by calling into your code in onActivityResult.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between edo tensei Madara with rinnegan and Alive Madara with Rinnegan
When madara was revived, he lost his pair of rinnegan ,his reservoir of infinite chakra and not be killed ability (being an edo tensei).
So, I know why madara wanted to be revived, but my question is , how does the ability differ in these 2 cases?
A:
An Edo Tensei cannot be a jinchuuriki, and so, he couldn't complete his plan by becoming the Ten Tails' jinchuuriki. That is the main reason he wanted to be revived.
Also, although very powerful, the power of a "real" Rinnegan is far superior to one of the reanimated "fake" Rinnegan. The "real" Rinnegan can summon and control the Gedo Mazo, use the Rinbo: Hengoku technique etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Ruby, is it possible to move a module up the ancestor chain?
I have a Ruby class C that includes some third-party modules, say A and B.
Module A is included indirectly via C's class inheritance chain; assume I have no control over where A gets incuded. Now, C includes B directly, but B includes another module D which happens to provide functionality that is also provided by A, like this:
class C < Base
# Base includes A
include B # includes D
# methods in A overridden by D
end
The ancestor chain goes something like this (where ... represents zero or more other ancestors that aren't relevant to this discussion):
C ... B ... D ... A
I want the functionality of A to take precdence over D: I want to move A so it is in front of D in the ancestor chain, like this:
C ... A ... B ... D
I have tried simply including A again but this didn't work. Is there a way to do this?
A:
It is impossible to change the mixin hierarchy once it is established. And only the inclusion order determines the hierarchy. You have to include A into C (for the first time) after you include B into C, or, if you prepend A to C instead of including it, then it will have precedence over D even if B is included into C later.
| {
"pile_set_name": "StackExchange"
} |
Q:
Animated sprite from few images
I've been searching for some good tutorial about making simple sprite animation from few images in Python using Pygame. I still haven't found what I'm looking for.
My question is simple: how to make an animated sprite from few images (for an example: making few images of explosion with dimensions 20x20px to be as one but animated)
Any good ideas?
A:
There are two types of animation: frame-dependent and time-dependent. Both work in similar fashion.
Before the main loop
Load all images into a list.
Create three variable:
index, that keeps track on the current index of the image list.
current_time or current_frame that keeps track on the current time or current frame since last the index switched.
animation_time or animation_frames that define how many seconds or frames should pass before switching image.
During the main loop
Increment current_time by the amount of seconds that has passed since we last incremented it, or increment current_frame by 1.
Check if current_time >= animation_time or current_frame >= animation_frame. If true continue with 3-5.
Reset the current_time = 0 or current_frame = 0.
Increment the index, unless if it'll be equal or greater than the amount of images. In that case, reset index = 0.
Change the sprite's image accordingly.
A full working example
import os
import pygame
pygame.init()
SIZE = WIDTH, HEIGHT = 720, 480
BACKGROUND_COLOR = pygame.Color('black')
FPS = 60
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
def load_images(path):
"""
Loads all images in directory. The directory must only contain images.
Args:
path: The relative or absolute path to the directory to load images from.
Returns:
List of images.
"""
images = []
for file_name in os.listdir(path):
image = pygame.image.load(path + os.sep + file_name).convert()
images.append(image)
return images
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, position, images):
"""
Animated sprite object.
Args:
position: x, y coordinate on the screen to place the AnimatedSprite.
images: Images to use in the animation.
"""
super(AnimatedSprite, self).__init__()
size = (32, 32) # This should match the size of the images.
self.rect = pygame.Rect(position, size)
self.images = images
self.images_right = images
self.images_left = [pygame.transform.flip(image, True, False) for image in images] # Flipping every image.
self.index = 0
self.image = images[self.index] # 'image' is the current image of the animation.
self.velocity = pygame.math.Vector2(0, 0)
self.animation_time = 0.1
self.current_time = 0
self.animation_frames = 6
self.current_frame = 0
def update_time_dependent(self, dt):
"""
Updates the image of Sprite approximately every 0.1 second.
Args:
dt: Time elapsed between each frame.
"""
if self.velocity.x > 0: # Use the right images if sprite is moving right.
self.images = self.images_right
elif self.velocity.x < 0:
self.images = self.images_left
self.current_time += dt
if self.current_time >= self.animation_time:
self.current_time = 0
self.index = (self.index + 1) % len(self.images)
self.image = self.images[self.index]
self.rect.move_ip(*self.velocity)
def update_frame_dependent(self):
"""
Updates the image of Sprite every 6 frame (approximately every 0.1 second if frame rate is 60).
"""
if self.velocity.x > 0: # Use the right images if sprite is moving right.
self.images = self.images_right
elif self.velocity.x < 0:
self.images = self.images_left
self.current_frame += 1
if self.current_frame >= self.animation_frames:
self.current_frame = 0
self.index = (self.index + 1) % len(self.images)
self.image = self.images[self.index]
self.rect.move_ip(*self.velocity)
def update(self, dt):
"""This is the method that's being called when 'all_sprites.update(dt)' is called."""
# Switch between the two update methods by commenting/uncommenting.
self.update_time_dependent(dt)
# self.update_frame_dependent()
def main():
images = load_images(path='temp') # Make sure to provide the relative or full path to the images directory.
player = AnimatedSprite(position=(100, 100), images=images)
all_sprites = pygame.sprite.Group(player) # Creates a sprite group and adds 'player' to it.
running = True
while running:
dt = clock.tick(FPS) / 1000 # Amount of seconds between each loop.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.velocity.x = 4
elif event.key == pygame.K_LEFT:
player.velocity.x = -4
elif event.key == pygame.K_DOWN:
player.velocity.y = 4
elif event.key == pygame.K_UP:
player.velocity.y = -4
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
player.velocity.x = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:
player.velocity.y = 0
all_sprites.update(dt) # Calls the 'update' method on all sprites in the list (currently just the player).
screen.fill(BACKGROUND_COLOR)
all_sprites.draw(screen)
pygame.display.update()
if __name__ == '__main__':
main()
When to chose which
Time-dependent animation allows you to play the animation at the same speed, no matter how slow/fast the frame-rate is or slow/fast your computer is. This allows your program to freely change the framerate without affecting the animation and it'll also be consistent even if the computer cannot keep up with the framerate. If the program lags the animation will catch up to the state it should've been as if no lag had happened.
Although, it might happen that the animation cycle don't synch up with the framerate, making the animation cycle seem irregular. For example, say that we have the frames updating every 0.05 second and the animation switch image every 0.075 second, then the cycle would be:
Frame 1; 0.00 seconds; image 1
Frame 2; 0.05 seconds; image 1
Frame 3; 0.10 seconds; image 2
Frame 4; 0.15 seconds; image 1
Frame 5; 0.20 seconds; image 1
Frame 6; 0.25 seconds; image 2
And so on...
Frame-dependent can look smoother if your computer can handle the framerate consistently. If lag happens it'll pause in its current state and restart when the lag stops, which makes the lag more noticeable. This alternative is slightly easier to implement since you just need to increment current_frame with 1 on each call, instead of dealing with the delta time (dt) and passing it to every object.
Sprites
Result
A:
You could try modifying your sprite so that it swaps out its image for a different one inside update. That way, when the sprite is rendered, it'll look animated.
Edit:
Here's a quick example I drew up:
import pygame
import sys
def load_image(name):
image = pygame.image.load(name)
return image
class TestSprite(pygame.sprite.Sprite):
def __init__(self):
super(TestSprite, self).__init__()
self.images = []
self.images.append(load_image('image1.png'))
self.images.append(load_image('image2.png'))
# assuming both images are 64x64 pixels
self.index = 0
self.image = self.images[self.index]
self.rect = pygame.Rect(5, 5, 64, 64)
def update(self):
'''This method iterates through the elements inside self.images and
displays the next one each tick. For a slower animation, you may want to
consider using a timer of some sort so it updates slower.'''
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
def main():
pygame.init()
screen = pygame.display.set_mode((250, 250))
my_sprite = TestSprite()
my_group = pygame.sprite.Group(my_sprite)
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
# Calling the 'my_group.update' function calls the 'update' function of all
# its member sprites. Calling the 'my_group.draw' function uses the 'image'
# and 'rect' attributes of its member sprites to draw the sprite.
my_group.update()
my_group.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
It assumes that you have two images called image1.png and image2.png inside the same folder the code is in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trigger to not delete Data from a table
I have a table called PaperInfo and sample data on the table is:
PaperID Type Description
1 T Level 1
2 S Level 2
3 V Level 3
How can enforce a trigger where no one can delete a record from the above table. When some one tries to delete it for example as below:
Delete from dbo.paperInfo
WHERE PaperID = 1
It should display an error message saying "Cannot Delete Records from Paperinfo Table"
How can i do it?
A:
You should write an INSTEAD OF trigger. This will replace the delete operation:
CREATE TRIGGER td_PaperInfo
ON PaperInfo
INSTEAD OF DELETE
AS
BEGIN
RAISERROR ('Cannot Delete Records from Paperinfo Table', 16, 1)
END
| {
"pile_set_name": "StackExchange"
} |
Q:
Why don't counts using 'LIKE' in SQL match?
I have one table ABC with EMPLID, GRADE, SALARY and DATE as its fields.
I am executing the following 3 statements:
select count(*) from ABC;
Result :- 458
select count(*) from ABC where GRADE LIKE '%def%';
Result :- 0
select count(*) from ABC where GRADE NOT LIKE '%def%';
Result :- 428
My point here is: the result of second query plus the result of third query should be equal to the result of first query, shouldn't it?
A:
Looks like you have 30 records where the GRADE is null.
null values are unknown, so do not match either condition.
A:
Sql uses a three-valued logic: true, false &unknown. If you compare a NULL to any other value the result is unknown. NOT(unknown) is still unknown.
A WHERE clause only returns rows that evaluate to true. So the missing 30 rows in your example have a NULL in the Grade column.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a new instance of some model when instantiating some another model?
I want to instantiate the Blog model when instantiating the User model and associate a new instance of the Blog model with a just created instance of the User model (and save both in database) by the OneToOneField.
I want always create a new instance of the Blog model when I creating a new instance of the User model and associate them by the OneToOneField.
class User(AbstractUser):
# some logic to create a new instance of the Blog model
# and associating it with a just created instance of the User
# by the OneToOneField
class Blog(models.Model):
author = OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
How can I get it?
Thank you in advance!
A:
You can use signals for that (https://docs.djangoproject.com/en/2.2/ref/signals/). So in your case it could look like this:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_blog(sender, instance, created, **kwargs):
if created:
Blog.objects.create(author=instance)
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby: install mysql2
Windows 7 32bits
Hi everyone, how can I install mysql2 properly in windows 7 I have this error:
c:\dev\mysql2>gem install mysql2-0.3.13.gem --no-ri --no-rdoc -- --with-mysql-di r=c:\mysql-connector-c-noinstall-6.0.2-win32
This could take a while...
ERROR: Error installing mysql2-0.3.13.gem:
ERROR: Failed to build gem native extension.
C:/Ruby200/bin/ruby.exe extconf.rb --with-mysql-dir=c:\mysql-connector-c-noi
nstall-6.0.2-win32
Gem files will remain installed in C:/Ruby200/lib/ruby/gems/2.0.0/gems/mysql2-0.
3.13 for inspection.
Results logged to C:/Ruby200/lib/ruby/gems/2.0.0/gems/mysql2-0.3.13/ext/mysql2/g
em_make.out
c:\dev\mysql2>
A:
Try to install using different version, It's happens because sometime binary is not available for specific verion for window.
gem install mysql2 -v 0.2.6
If still you have issues, Try below steps.
1) Download the MySql C Connector from: http://dev.mysql.com/downloads/connector/c/
NOTE Don't download the installer, download the ARCHIVE for your OS
2) Extract the file to C:\mysql-connector
3) Then ran:
gem install mysql2 --platform=ruby -- '--with-mysql-lib="C:\mysql-connector\lib" --with-mysql-include="C:\mysql-connector\include" --with-mysql-dir="C:\mysql-connector"'
It's works for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hear Twilio text to Voice again when press one
In my web application I have used Twilio application for automatic voice calling. Here I used Text to call using Twilio
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Say voice='man'>Hello Welcome.</Say>
<Gather numDigits="1" method="POST">
<Say>
Press 1 to call again.
Press any other key to start over.
</Say>
</Gather>
</Response>
The Recipient will hear "Hello Welcome" as voice. My question is how to hear again if he press 1 and also how to stop he press another digits
A:
Twilio evangelist here.
once the <Gather> completes, which in your case will be when the user presses one number on their keypad, Twilio is going to let you know that its done by make an HTTP request to a URL. You can explicitly tell Twilio what URL to request by using the action parameter.
<Gather
action="http://example.com/yourpage.php"
method="POST"
numDigits="1"
timeout="10"></Gather>
In your case since you have not explicitly specified the action parameter, Twilio is just going to make a request back to the same URl that returned it the <Gather> verb.
When Twilio makes the HTTP request it will include a parameter named Digits that you can check:
$index = (int) $_REQUEST['Digits'];
Now you can use an if statement or a switch statement in your PHP to process change the behavior of your app based on the value of $index
In your case, that logic would look roughly like this in pseudocode:
if Digits does not exist OR digits exists and equals 1
return welcome message TwiML
else
either do nothing or explicitly return the <Hangup> verb
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML Divs, Columns, Horizontal Scroll Bar
I'm trying to display several chunks of data in columns next to each other. I have set the container to display inline, which works great if the columns are relatively thin. As soon as a column exceeds the horizontal screen length, the other columns get appended to the bottom.
My question is this: How can display inline column divs that are placed horizontally, with a horizontal scroll bar?
Note: I actually WANT the scroll bar; I want the elements side by side.
<div class="container">
<div class="child" id="1">Stuff</div>
<div class="child" id="2">Stuff</div>
</div>
---------
.child {
/*float:left;
margin-right:5em;*/
display:inline;
}
.container {
display:inline;
overflow: scroll-x;
white-space: nowrap;
}
Thanks,
Michael
A:
We're trying to keep the browser from doing it's normal job: layouting stuff in such a way that it fits into the current window-size. It doesn't matter if the stuff is block or inline, still the browser will try to fit it inside the window.
You can give your container a fixed width to ensure enough space for all the columns:
.child {
margin-right:50px;
float:left;
width: 100px;
border: 1px black solid;
}
.container {
width: 1520px;
overflow: scroll-x;
border: 1px red solid;
}
example page
screenshot of the example page http://www.users.fh-salzburg.ac.at/~bjelline//css-layout/sidebyside.png
| {
"pile_set_name": "StackExchange"
} |
Q:
.htaccess rules to move a subfolder to a new domain
I need to permanently move everything is in my /blog/ subfolder, into a new domain, keeping the full remaining url.
i.e.:
- from: https//www.example.com/blog/2018/05/07/article1
- to: https://www.newdomain/2018/05/07/article1
In other words, https://www.example.com/blog should redirect to https://www.newdomain.com/ keeping the rest of the url unchanged.
I am getting lost with the .htaccess rules to accomplish this, without loosing SEO ranks and without interfering with other WordPress htaccess rules...
A:
Inside blog/.htaccess you can have this single rule:
RewriteEngine On
RewriteRule .* https://www.newdomain.com/$0 [L,R=301,NE]
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is there no public domain licensing in Europe?
Why are there issues with public domain in Europe, that forces public domain projects to use CC0, 0BSD, Unlicense or other similar licenses?
I.E. why is it that, when someone dedicates a work to the public domain, someone in Europe can still get into trouble for using it? Isn't the copyright holder the only person that can sue? Or is there some other law in Europe?
A:
With respect to my colleague planetmaker, public domain is not a US-specific concept. It dates back to the first copyright law in the world, Britain's 1710 Statute of Anne, where it was referred to as publici juris ("of public right"). French jurists further developed the idea and we see the term "fall into the public domain" entering the discussion in mid-19th Century France, to refer to the fate of a creative work after all the time-limited rights reserved to the creator expire.
The problem to which I think the OP is referring is that of moral rights. Some implementations of copyright law recognise more controlled rights than the economic right - the right to exploit the commercial potential of one's creation. In particular, many jurisdictions recognise the creator's moral rights - the right to be attributed as the creator of the work, and the right to the integrity of one's work (that is, the right not to be attributed as the creator of modifications of one's work of which one does not approve).
The problem is further compounded because in some jurisdictions, primarily civil law ones, the author's moral rights are inalienable. That is, the author cannot lawfully give up those rights, however much (s)he wants to. France and Italy are examples of such jurisdictions.
In those jurisdictions, if an author says "I have no interest in this work, do as you please with it", you cannot know that (s)he intended to waive his/her moral rights. The author might know full well that those rights are inalienable, and intended only that others should have the right to profit from his/her creation. (S)he might well turn out to be very annoyed if an "unsuitable" adaptation appeared, and his/her name was associated with it without even a by-your-leave.
That said, this risk isn't huge. I don't think I've ever heard of it happening in respect of a work where the creator had abandoned his/her economic rights. Secondly, if it does, then it seems to me that changing the name of the project and removing all references to the original author will likely suffice.
But for those seeking clarity, licences like CC0 are specifically intended to implement a simple method of putting a work into the public domain in so far as is legally possible in any given jurisdiction. As Creative Commons note:
many legal systems effectively prohibit any attempt by these owners to surrender rights automatically conferred by law, particularly moral rights, even when the author wishing to do so is well informed and resolute about doing so and contributing their work to the public domain.
CC0 helps solve this problem by giving creators a way to waive all their copyright and related rights in their works to the fullest extent allowed by law
Using a licence like this makes it clear that you, the creator, are relinquishing all legally-relinquishable control of your work, and would like to go the whole way if you were permitted. Anyone who chooses to use your work can then decide for him/herself what sort of jurisdiction (s)he's in, and respect moral rights if that's what the local jurisdiction requires. Anyone using that adaptation can know that the original author intended this to be possible, and is therefore particularly unlikely to start filing suit.
Edit in response to OP's additional questions:
I have seen several people say that certain jurisdictions do not recognize the right to waive copyright and/or moral rights. But who can enforce that?
Nobody has to enforce it. In those jurisdictions, the author simply can't waive those rights, however much (s)he wants to.
Can someone other than the author sue
That will be jurisdictionally-dependent, and is beyond the scope of this site.
can the author act in bad faith claiming that the public domain dedication is legally unenforcable even though the intention is clear?
No bad faith is required. In such jurisdictions the moral rights aspect of the public-domain dedication is indeed invalid, however clearly the intention is expressed.
The utility of CC0 (and similar licences) is to clarify that the author intended to waive even the moral rights wherever possible, and is thus unlikely to sue in those jurisdictions where (s)he retains them. One could argue under the doctrine of promissory estoppel that an undertaking had been given not to enforce those rights, even though they couldn't be waived, and this might well provide a defence if a creator were ever to sue. Failing that, the mitigation measures I outline above aren't exactly painful.
A:
I will give an example specifically for the jurisdiction that I am most familiar with, which is Germany.
Germany doesn't have "copyright". We have "Urheberrecht" (literally translated "Originator's Right" or "Creator's Right", but usually translated as "Author's Right"). In German Author's Right, there is a notion of the work being somehow a "brain child" of the author. There is a connection between the author and their work that goes beyond any form of commercial interest, that is almost metaphysical. (In German literature, this is called the "Band" (roughly "bond") between a creator and his work.)
This is also the reason why it is simply impossible for corporations to be authors and thus hold Author's Rights, whereas it is completely normal for corporations in the US to be copyright holders.
Urheberrecht is split into two distinct subgroups:
Persönlichkeitsrechte (literally "Personal Rights", but usually called "Moral Rights").
Verwertungsrechte ("Exploitation Rights").
The Moral Rights, in particular, are:
Full Control over publication. The author has full control over if, when, and how the work is published. This includes not publishing it at all.
Recognition: The author has the exclusive right to control if and how their name is attached to the work, and which name to use (the real name, a pen name, a pseudonym, "anonymous"). Conversely, the author also has the right to have their name removed from a work.
The work must not be "defaced", and this is interpreted somewhat broadly. The starting assumption is that the work, as created by the creator, is the perfect version of itself, and even an "improvement" is actually worsening it.
These Moral Rights cannot be transferred and cannot be given up. (Remember the "bond" between an author and their works.)
That is the reason why you cannot "put a work in the Public Domain" in Germany.
But there are also limitations on the "Exploitation Rights" (which correspond more closely to e.g. the US idea of copyrights).
There was a landmark case a while ago (I unfortunately don't remember the name, it was a case at the Bundesgerichtshof and it must have been before 2000) that restricted the rights that an author can sign away. Roughly, journals and magazines started to create digital archives with search engines, and sold these archives or access to them. (Seems obvious to us now, but wasn't nearly so in the 1980s.) Journalists typically had contracts with the magazines / journals stating that all exploitation rights for works created in the employ of the magazine belong to the magazine.
The court found that, even though the journalists had signed away "all rights", that actually only meant "rights for usage that commonly existed at the time the contract was signed". Since the lawsuit was about creating archives of old content, the court found that, e.g. for articles written in the 1950s, 60s, 70s, the right to use the articles as part of an electronic database was not included, even though the journalists had explicitly signed away "all rights". The court argued that, since this kind of usage did not exist before, you couldn't have willingly agreed to give up your rights to it.
So, even if you interpret "Public Domain" as "signing away all exploitation rights", that *still doesn't work in Germany", because "all" doesn't actually mean "all", it means "all, as far as we know today".
A:
It's actually very simple:
The term "public domain" is not a legal term, it's strictly US-specific. So it bears no meaning legally outside US. (So in reality US is special here, not "the rest of the world".)
You cannot give up authorship nor copyright. If you want to concede rights for everyone to use your work in perpetuity, use words (a license) which does bear legal meaning - so that they can rely on the words of the license to hold up in court.
So yes, of course you, as author, can write "I put it under public domain". And no-one will be in trouble, if you don't go to court as author. But due to the circumstance that it is not a legally - defined term you can come at any later time and still sue for infringement. That's why people insist on a license to make clear that work can be used under a CC-0 license or similar.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using an analog demultiplexer as a digital demultiplexer
If I want to use an analog de/multiplexer as a digital demultiplexer, do I have to use pull-up / pull-down resistors?
For example when driving a CMOS IC like the 4015 with the CMOS analog 4051, do I have to use pull-down resistors?
A:
Only if an input could be left floating. For example, if you select between several outputs to a single input, all analog inputs are tied to something (or you believe they can never be selected) and the mux is always enabled then you don't need a resistor.
Chances are that if you are using it as a digital de-multiplexer this condition won't be true and you need one resistor per mux output.
Also keep in mind that the switch-off will be relatively sluggish compared to push-pull drive, depending on the resistor value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode 11.2 swift 13.2 An SSL error has occurred and a secure connection to the server cannot be made
i am trying to send remote notification using one signal and i made all certificates right when i run application and check one signal i got this "We haven't detected any subscribed users yet for this platform" and i found this in my log in xcode "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9816, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?" and i have been searching online all the day and i tried every solution i found and it did not work i also done this in info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
A:
it seems that the problem is one signal does not open in my country , thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Application that Always Listen to Specific Port Number
I want to create a python application that is always listening to a parametrized port. Whenever there is a request coming from the port, the application will parse the request and do tasks based on the request.
Is this type of application called services? (I have 0 knowledge on services). Where can I find beginner's tips and guides on this type of development?
A:
This is called a server, there are examples at the bottom of the Python socket documentation page.
HTH.
A:
This is socket programming. Writing sockets is cumbersome, you can use any web server written in python. My recommendation is use werkzeug, it is very simple. Meanwhile have a look at Flask which is built on top of werkzeug.
In case you are trying to build your own protocol engine twisted is one which will help you to achieve that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deleting character from the end of un array
I use this code to display first letters from a string where $atit is an array of that string and results must be something like "R. & B. & T.". But this code displays results like "R. & B. & T. &".
Is it possible to get rid of the last "&"? I tried to use rtrim in echo line but it deleted all "&" while I need to delete only the last one.
foreach ($atit as $ati) {
$pieces = explode(' ', $ati);
$otw = preg_replace('/\W\w+\s*(\W*)$/', '$1', $pieces);
$acronym = "";
foreach ($otw as $w) {
$acronym .= $w[0].'. ';
}
$bla = $acronym.' & ';
echo $bla;
}
I think it's a problem with foreach but I couldn't figure it out. Any suggestions please?
Update:
Each entry in the array is comprised of several words so the code above is designed to display first letters of all words except for the last one in each entry.
Example:
$atit = ["Right now", "Behind you", "This is the time"];
So the code above will first delete the last word in each array entry and then get and display the first letters of the rest words in it, something like this (R. & B. & T. I. T). but the problem is that it adds an additional "&" to the end (R. & B. & T. I. T &).
A:
If you meant formation of an "acronym" comprising of first character of each string from the array of strings - here is complex solution using array_map, array_slice, implode, explode and ucfirst functions:
$atit = ["Right now", "Behind you", "This is the time"];
$acronym = implode(" & ", array_map(function($v) {
$words = explode(" ", $v);
if (count($words) > 2) {
return implode(".", array_map(function($w) {
return ucfirst($w[0]);
}, array_slice($words, 0, -1)));
}
return $words[0][0] . "."; // for simple strings (less/equal two words)
}, $atit));
echo $acronym; // "R. & B. & T.I.T"
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to store data in a spreadsheet application in java
I am creating a spreadsheet application in Java programming language. I need to save my spreadsheets to open later when needed. So, what is the most suitable way to do this? Is it more suitable to use serialization in Java? Or is it suitable to create a database and use JDBC?What are the pros and cons of using these?
A:
Use Apache's POI library which can read and write .xls and .xlsx formatted files
| {
"pile_set_name": "StackExchange"
} |
Q:
Can .NET Task instances go out of scope during run?
If I have the following block of code in a method (using .NET 4 and the Task Parallel Library):
var task = new Task(() => DoSomethingLongRunning());
task.Start();
and the method returns, will that task go out of scope and be garbage collected, or will it run to completion? I haven't noticed any issues with GCing, but want to make sure I'm not setting myself up for a race condition with the GC.
A:
Update:
After I answered this question (a long time ago!) I found out that it's not true that Tasks will always run to completion - there's a small, let's say "corner" case, where tasks may not finish.
The reason for that is this: As I have answered previously, Tasks are essentially threads; but they are background threads. Background threads are automatically aborted when all foreground threads finish. So, if you don't do anything with the task and the program ends, there's a chance the task won't complete.
You should always await on tasks. More information can be found on the excellent answer Jon gave me.
Original:
Task are scheduled to the ThreadPool, meaning that they are essentially threads¹ (actually, they encapsulate threads).
From the Thread documentation:
It is not necessary to retain a
reference to a Thread object once you
have started the thread. The thread
continues to execute until the thread
procedure is complete.
So, no, there is no need to retain a reference to it.
Also, the documentation states that the preferred way to create a Task is to use it's factory:
You can also use the StartNew method
to create and start a task in one
operation. This is the preferred way
to create and start tasks if creation
and scheduling do not have to be
separated (...)
Hope it helps.
¹ Accordingly to the documentation:
A task represents an asynchronous
operation, and in some ways it
resembles the creation of a new thread
or ThreadPool work item, but at a
higher level of abstraction.
A:
The task will run to completion. Even if there aren't any other references to it (not being rooted I believe is the term), the thread pool will still hold a reference to it, and prevent it from being Garbage Collected at least (I say at least, because even after it completes, there is no guarantee that it will be Garbage Collected) until completion.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: split data frame rows by space, remove common elements, put unequal length columns in new df
Suppose, I have df with two rows of strings that I need to split by space, unlist, then find anti-intersection and reuse in a list. I can do it brute force by working with each row individually. Problem is that there can be more than 2 rows etc. My working solution thus far is below, but there must be a simpler way of not accessing each line. Thanks!!
df = structure(list(A = structure(1:2, .Label = c("R1", "R2"), class = "factor"),
B = c("a b c d e f g o l",
"b h i j k l m n o p q"
)), .Names = c("A", "B"), row.names = c(NA, -2L), class = "data.frame")
dat1 = unlist(strsplit(df[1,2]," "))
dat2 = unlist(strsplit(df[2,2]," "))
f <- function (...)
{
aux <- list(...)
ind <- rep(1:length(aux), sapply(aux, length))
x <- unlist(aux)
boo <- !(duplicated(x) | duplicated(x, fromLast = T))
split(x[boo], ind[boo])
}
excl = (f(dat1, dat2))
L <- list(excl[[1]],excl[[2]])
cfun <- function(L) {
pad.na <- function(x,len) {
c(x,rep("",len-length(x)))
}
maxlen <- max(sapply(L,length))
print(maxlen)
do.call(data.frame,lapply(L,pad.na,len=maxlen))
}
a = cfun(L)
What I had:
A B
1 Food a b c d e f g
2 HABA b h i j k l m n o p q
What I got:
c..a....c....d....e....f....g.......... c..h....i....j....k....m....n....p....q..
1 a h
2 c i
3 d j
4 e k
5 f m
6 g n
7 p
8 q
Edit: The goal is to eliminate common elements from all columns. I.e. if "4" is present in row 1 and seen anywhere else - remove. New test set:
df1 = structure(list(A = structure(1:3, .Label = c("R1", "R2", "R3"
), class = "factor"), B = c("1 4 78 5 4 6 7 0", "2 3 76 8 2 1 8 0",
"4 7 1 2")), .Names = c("A", "B"), row.names = c(NA, -3L), class = "data.frame")
Current output from suggested code:
a b c
1 4 2 4
2 78 3 7
3 5 76 2
4 4 8 NA
5 6 2 NA
6 7 8 NA
7 0 0 NA
2, 4, and 7 should not be there as they are seen in more than 1 column. Bottom line - output should consist of unique numbers/elements only in any columns. Thanks!!
A:
Here's one way using base R that avoids a lot of your current code
## split column B on the space character
s <- strsplit(df$B, " ")
## find the intersection of all s
r <- Reduce(intersect, s)
## iterate over s, removing the intersection characters in r
l <- lapply(s, function(x) x[!x %in% r])
## reset the length of each vector in l to the length of the longest vector
## then create the new data frame
setNames(as.data.frame(lapply(l, "length<-", max(lengths(l)))), letters[seq_along(l)])
# a b
# 1 a h
# 2 c i
# 3 d j
# 4 e k
# 5 f m
# 6 g n
# 7 <NA> p
# 8 <NA> q
I presume that's what you are shooting for?
Note that lengths() is a new function in the base package of R version 3.2.0 that is a faster more efficient replacement for sapply(x, length) on a list.
| {
"pile_set_name": "StackExchange"
} |
Q:
What action variable is needed for a Java servlet class?
I have this reverse.html in the root /Reverse directory
<!DOCTYPE html>
<html>
<body>
<h1>Assignment Servlets-2 - Reverse</h1>
<form method='post' action='ReverseServlet'>
Text: <input type='text' name='text' size='50'><br><br>
<input type='submit' value='submit'>
</form>
</body>
</html>
This is the web.xml in the /WEB-INF directory
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet> <servlet-name>ReverseServlet</servlet-name>
<servlet-class>ReverseServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>ReverseServlet</servlet-name>
<url-pattern>/reverse</url-pattern>
</servlet-mapping>
</web-app>
And this is the ReverseServlet.java source which is compiled into a class file in the /classes directory
import java.io.* ;
import javax.servlet.http.* ;
public class ReverseServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) {
String text = request.getParameter("text");
response.setContentType("text/html");
try {
PrintWriter out = response.getWriter();
out.println( new StringBuffer( text ).reverse().toString() );
out.close();
} catch( Exception e ) {
System.out.println( "cannot get writer: " + e );
}
}
}
They are all in the proper directories, and I can load the reverse.html, but the action won't tie to the ReverseServlet class. I'm using Tomcat 7.0 and I've gotten a simple servlet to work, so I know it's installed correctly. It just won't go to the servlet code upon hitting submit...
A:
The problem is you are sending request using post method and trying catch it using get method.
1 way:
try to channge post to get or remove method attribute from form:
<form method='get' action='/reverse'>
OR
2 way:
implement doPost method in your ReverseServlet in order to catch request from post method:
public void doPost( HttpServletRequest request, HttpServletResponse response ){...}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cookie is only set on the initial page
I am setting a cookie in JavaScript (with an ASP.NET app). I can refresh the page and I can verify that the cookie is set with document.cookie. Now if I go to any other page, the cookie is not set, but it should be. I am not setting a path, so I don't see any reason why it isn't showing up. I've tried Chrome, FF, and IE and nothing.
Any ideas what I could be doing wrong?
UPDATE:
Here's the code I used to set the cookie. I also tried jquery.cookie
function Set_Cookie(name, value, expires, path, domain, secure) {
// set time, it's in milliseconds
var today = new Date();
today.setTime(today.getTime());
/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}
Set_Cookie('cookie1', 'value1', 14);
$.cookie('cookie2', 'value2');
A:
I set the path to '/'. I resisted doing that cause it sounded dumb. It should be that by default, right? I guess not.
| {
"pile_set_name": "StackExchange"
} |
Q:
can akka actor capture a specific message in all states without implementing the same code
I have an actor that manages different states e.g:
case object Start
case object Stop
case object Init
class Foo extends Actor {
def receive: Receive = {
case Init =>
doSomeInit()
context become busy
self ! Start
case Stop =>
context stop self
}
}
def busy: Receive = {
case Start =>
doingSomeProcessing()
context become receive
case Stop =>
context stop self
}
}
I want to avoid writing the Stop handling code in every state (similar to whenUnhandled in FSM )
is there idiomatic way to do that without using FSM ?
A:
Use orElse and move the common messages to separate partial function.
receive and busy are partial functions. You can compose partial functions using orElse as shown in the code below.
Order is important. So based on the use case do f1 orElse f2 or f2 orElse f1 f1, f2 are partial functions
case object Start
case object Stop
case object Init
class Foo extends Actor {
def common: Receive = {
case Stop =>
context stop self
}
def receive: Receive = common orElse {
case Init =>
context become busy
self ! Start
}
def busy: Receive = common orElse {
case Start =>
context become receive
}
}
Scala REPL
scala> val f: PartialFunction[Int, String] = { case 1 => "one"}
f: PartialFunction[Int, String] = <function1>
scala> val g: PartialFunction[Int, String] = { case 2 => "two"}
g: PartialFunction[Int, String] = <function1>
scala> val x = f orElse g
scala> f(1)
res9: String = "one"
scala> x(2)
res10: String = "two"
scala> x(1)
res11: String = "one"
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a "Newton differential equation" always have a solution?
One reason why the iteration
$$x_{n+1}=x_n-\tan\;x_n$$
converges quickly for appropriate starting values is that this is nothing more than the Newton-Raphson iteration for $\sin\;x$.
This got me thinking: given some arbitrary function $g(x)$, is there always a function $f(x)$ such that
$$\frac{f(x)}{f^\prime(x)}=g(x)$$
or are there restrictions on the nature of $g(x)$ so that the differential equation has a solution?
A:
The differential equation you have is an example of a first-order separable differential equation.
If you write $y = f(x)$, then you have
$$
\frac{y}{\frac{dy}{dx}} = g(x)
$$
Writing this in terms of differentials (treat $\frac{dy}{dx}$ as a fraction) so that all the $y$'s are on one side and all the $x$'s are on the other gives
$$
\frac{dx}{g(x)} = \frac{dy}{y}
$$
Integrating both sides yields
$$
\int \frac{dx}{g(x)} + C = \ln |y|
$$
where $C$ is an arbitrary constant. Then
$$
\exp(\int \frac{dx}{g(x)} + C) = |y|
$$
and so
$$
y = \pm \exp(\int \frac{dx}{g(x)} + C)
$$
This works as long as $\frac{1}{g(x)}$ has an antiderivative. For this purpose, it is sufficient to have $g$ continuous and not everywhere zero.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python game over client server
Below is the Python code for a simple game i had to create now i am having difficulty seperating the code to play the game over a client and server using sockets. any help would be appreciated
import random
rannum = random.randrange(0,10,1)
print rannum
counter = 0
a=0
while(a==0):
guess = int(raw_input("What is your guess?: "))
counter = counter + 1
diff = abs(guess - rannum)
if(diff >5):
print "Way Off!"
elif(diff >2):
print "Close!"
elif (diff>1):
print "Closer!"
elif(diff >0):
print "Even Closer!"
elif (diff==0):
print "Correct"
name = str(raw_input("What is your name?: "))
print name + " Your score is: "
print counter
f = open('high_scores.txt', 'a')
score = str(counter)
f.write(name + " " + score + "\n")
f.close()
break
A:
The client interface in your code is just the raw_input function and print statements. Effectively, all you need to do is turn those into recv and send calls on a socket, and you've got a server. Or, more simply, wrap the socket in makefile and just write and read lines:
import random
import socket
rannum = random.randrange(0,10,1)
print rannum
counter = 0
a=0
sock = socket.socket()
sock.bind(('127.0.0.1', 12345))
sock.listen(5)
clientsock, addr = sock.accept()
client = clientsock.makefile('r+')
while(a==0):
client.write('What is your guess?: ')
guess = int(client.readline())
counter = counter + 1
diff = abs(guess - rannum)
if(diff >5):
client.write("Way Off!\n")
…
You can test this without even writing a client, just using nc localhost 12345. (If you're on Windows, you don't have nc built-in; google "netcat Windows" and get yourself a copy.) Then just look at the docs for socket.connect and you should be able to write the client side.
Now, you may want to reorganize your interface a bit. Maybe the client should provide the prompts and format the results (so, e.g., you can have separate English and Spanish clients with the same server—or, even better, a nice GUI client). To do that, you need to design some kind of protocol for the client and server to use for communication. (In fact, even the trivial example above has an implicit protocol: every prompt, response, etc. is separated by newlines. I "cheated" by using makefile and readline to handle that automatically. But figuring out how to separate messages—newlines, length-prefixing, etc.—is just the first step.)
You also may want to consider whether you really want to design a "raw" protocol that sits on top of TCP, or use something that takes care of the low-level stuff for you (a web service, JSON-RPC over sockets, etc.) so you only need to write the application-specific stuff yourself.
Finally, this is a very, very bad server. It only accepts one client, and it does everything synchronously, so if the client screws up the server can't recover. A real server needs what's called a "reactor" or a "proactor" (you can built your own with select.select, or use asyncore or something third-party like twisted), or needs to spawn a new thread or process for each accept.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can a mathematician interested in the foundation of mathematics be satisfied by an always partial knowledge of the mathematics?
I don't study Mathematics at university, and I probably will never understand of what mathematics consists of in all its aspects. But I love to find structures and links betwen ideas, and to ask myself philosophical questions about foundations of mathematics. If I have understood well is what is happening with the "categorical" point of view, there is some kind of great unification of the mathematics from a structural point of view.
Obviously I understand that for humans it is impossible to reach a total understanding of something, and that what moves me is a mirage. I must give up until I'm sane and study modestly mathematics, in a relaxed way: playing with easy problems, reading books, and learning from the basics all I can, without excessive demands on myself.
More I understand and more new interesting mathematical topics I discover... but the facts that overwhelm me are the acceleration of this process and the fact that there are a lot of new theories; and that this implies that this growth will be even faster.
Probably I, as an amateur mathematician, don't have a chance to come at new ideas in the foundational research (or even understand the actual point of view since it is changing so fast)... but
Q1: From your experience how can mathematicians deal (or how they usually chose to behave) with this huge mathematical universe and be satisfied from a philosophical point of view?
Q2: How can a mathematician interested in the foundation of mathematics be satisfied by an always partial knowledge of the mathematics?
Is maybe possible that in 100 years tha amount of mathematical knowledge will be so huge that even Mathematicians will be totally overwhelmed from it? In other words, is possible that will be impossible for anyone to research new things because the knowledge required will take like 80 or 90 years of hard study? I say this because I think that humans has a limit to the speed of learning.
If this is possible, should mathematicians abandon the hope of understanding mathematics?
I remember a quote of John von Neumann:
"Young man, in mathematics you don't understand things. You just get used to them."
I have read many stories about his math skills, and how he was a genius... anyways from my point of view... I feel very sad when I read this quote.
Is really this the ultimate nature of mathematics?
Notes
I'm searching for human experience of real mathematicians, that is very important for me in this moment, I asked this question on SEMath but it was closed in 40 seconds...is a soft question, as many others questions, but it has philosophical contenents too and I think it deserves at least a chance, thanks in advance.
(Link to a closed crosspost on SE Mathematics)
A:
Consider that quotation by John von Neumann.
"Young man, in mathematics you don't understand things. You just get used to them."
What does it mean to "understand" something? Consider a simple example, of understanding what someone has said, or written: you have taken some sensory data, and incorporated it into your body of experiences — you develop your idea of who the person is, or the subject that they describe; and you connect it to other things that you know, securely enough that you will remember. Understanding consists of having those links in place.
When you learn something entirely new, there is little that you can link it to in your mind, precisely because it is entirely new. There is nothing to do but to reinforce by repetition, until it becomes something which remains by sheer force of weight — or possibly because eventually you manage to retain it long enough that you can start to connect it to other things that you have been learning in the meantime.
It's a question of quantity over quality. If your primary aim is to understand a piece of mathematics, you may have to spend a lot of time on the mathematics which motivated it, to build the links. It is not an efficient way to learn as much mathematics as possible; it is at best a route to understand all of the mathematics as well as possible, as one is learning it. The alternative is to learn things by rote — which we often do; the names of the numbers 1, 2, 3, our addition and multiplication tables, how to multiply matrices and vectors, and so forth. We may come to understand them later, but the understanding only secures the knowledge, while the memorization allowed us to use the knowledge before we had a secure foundation to understand why it could be useful. (Of course, knowing why it might be useful is not necessarily important, so long as one knows that it is useful.)
This is true of any subject. What does it mean to understand that tomatoes start green, and then turn red? It's just a simple fact; one learns it and moves on. Perhaps if one studies horticulture or biochemistry, one can actually come to understand why tomatoes turn red; but there will be other simple facts of the world which are left unexplained. Can a gardener be interested in biology, and still be content to plan and plant their garden without understanding every cellular process in each plant that they cultivate? Yes. However, understanding the plants better may give them more insight as to better approaches to gardening. Because they can never obtain complete knowledge, they will always have some things about which they are curious — something more to work on to understand.
The world is big with many things in it, and mostly must be taken as it is; perhaps with some investigation if one is curious about details, if one has the time. This is true of mathematics, music, history, poetry — and when for some reason one needs to know something quickly and use it without necessarily understanding it (which is often the case), getting used to it is the best one can hope for, until it has embedded itself into your brain so that you forget what it was like not to know it, or until you can forge connections with other things that you know.
A:
The planet Earth is too large for one man to explore fully in one lifetime. Yet its relatively straight forward to get some idea of what it looks like from an atlas; and similarly its geology; its weather; and its flora and fauna.
Similarly although the mathematical universe is too large for one mathematician to explore fully its possible to get a feel for the shape of it, what are the currently important research programmes and movements and thus to find an important question which can advance knowledge and secure his reputation.
For example, an important research 'idea' is the Langlands programme - it occupies the energies of a large number of mathematicians. What is it? Class Field Theory in Number Theory which is about describing abelian galois extensions is now seen as beginning of a ladder of such theories. The interest is describing this ladder more properly. This is the Langlands programme.
A similar strategy is seen in higher-dimensional category theory where ordinary category theory is seen as the simplest case. Again the interest is in describing this ladder of theories.
Without understanding any of the technicalities there, one should be able to see that there is a common pattern here. An important theory is described as the simplest case, and one climbs and describes a ladder of such theories.
The simplest place where this idea occurs is of course the integer: 1,2,3...
What I've described is simply doing this with more sophisticated objects. Its already been done for vector spaces and manifolds - the higher dimensional objects reveal new phenomena unavailable in lower dimensions.
One could say mathematicians are always learning to count!
| {
"pile_set_name": "StackExchange"
} |
Q:
invalid conversion from const char * to char * in Linux with Ternary Operator
Example 1:
char* message = ( m_message != NULL ? m_message : "" );
above line gives compiler error as invalid conversion from const char* to char*. in g++ compiler. but the below piece of code works.
Example 2:
char* message;
if(m_message)
message = m_message;
else
message = "";
Why do I get a compiler error with g++ in the first example but not the second? Both ways work fine in Windows.
A:
The string literal -> char* conversion is allowed (but deprecated) only if it is direct - you can't let the value "pass through" somewhere else to decay into a const char*.
Your second code is a conversion directly from a string literal to a char*, which is "only" deprecated.
The first one is first a pointer decay to const char* - the result of m_message != NULL ? m_message : "" is a const char* - and then an attempt to convert the resulting const char* to a char*, which isn't allowed.
This code also produces an error, for the same reason:
const char* empty() { return ""; }
char* message;
if(m_message)
message = m_message;
else
message = empty();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to stop for loop from printing results in R
I'm trying to loop through integers 1:1000 comparing the result of a function I've created with an R function. Specifically, I have:
floor.log2 = function(n) {
x = 1
i = 0
while (x <= n) {
x = 2*x
i = i + 1
}
print(i-1)
}
And I want to compare with:
floor(log(n, base = 2))
Every comparison loop I've created ends up printing each index 1:1000 - what is a succinct way to compare results for 1:1000 in these functions without R printing the indices?
A:
I would modify the existing function you wrote to:
floor.log2 = function(n) {
x = 1
i = 0
while (x <= n) {
x = 2*x
i = i + 1
}
return(i-1)
}
To test:
iter <- 100 # How long you would like to test for
vec1 <- c() # Container of your custom function
vec2 <- c() # Container for the comparison function
for(i in 1:iter) {
vec1[i] <- floor.log2(i)
vec2[i] <- floor(log(i, base = 2))
}
Finally:
all(vec1 == vec2)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to grid.arrange() in grid.newpage()
I have the following grid of plots
library(ggplot2)
library(gridExtra)
df1 <- data.frame(Var1 = rnorm(100), Var2 = rnorm(100) )
df2 <- data.frame(Var1 = rnorm(100), Var2 = rnorm(100, sd = 1000000) )
wide1 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()
wide2 <- ggplot(df2, aes(x=Var1, y=Var2)) + geom_point()
wide3 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()
narrow1 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()
grid.newpage() # Open a new page on grid device
pushViewport(viewport(layout = grid.layout(5, 3)))
print(wide1, vp = viewport(layout.pos.row = 3, layout.pos.col = 1:3))
print(wide2, vp = viewport(layout.pos.row = 4, layout.pos.col = 1:3))
print(wide1, vp = viewport(layout.pos.row = 5, layout.pos.col = 1:3))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 1))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 2))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 3))
which correctly plots
Nevertheless the second plot from the bottom is compressed due to the Y-axis labels and is not aligned with the other two wide plots. Normally I would proceed as following to make sure the three wide plots are aligned
gp1<- ggplot_gtable(ggplot_build(wide1))
gp2<- ggplot_gtable(ggplot_build(wide2))
gp3<- ggplot_gtable(ggplot_build(wide3))
maxWidth = unit.pmax(gp1$widths[2:3], gp2$widths[2:3],gp3$widths[2:3])
gp1$widths[2:3] <- maxWidth
gp2$widths[2:3] <- maxWidth
gp3$widths[2:3] <- maxWidth
grid.arrange(gp1,gp2,gp3)
which produces
yet when I try to grid.arrange() within a grid.newpage() it doesn't produce what I hoped...
grid.newpage() # Open a new page on grid device
pushViewport(viewport(layout = grid.layout(5, 3)))
print(grid.arrange(gp1,gp2,gp3), vp = viewport(layout.pos.row = 3:5, layout.pos.col = 1:3))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 1))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 2))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 3))
A:
print(arrangeGrob(gp1,gp2,gp3), vp=..., newpage=FALSE)
| {
"pile_set_name": "StackExchange"
} |
Q:
Swapping control position in TableLayoutPanel
EDIT:
Okay so for clarity I will improve my information a bit more:
I have a TableLayoutView (I will call this tlv) that has 5 fixed columns, and x + 2 rows. The first row of tlv contains labels in each cell for header purposes. I dynamically add more rows onto tlv and so that it why it has a variable amount of rows (plus the initial header row which is never removed).
As another tiny small complication, I also keep an empty row entry at the bottom of tlv which I must keep because I use it for other functionality.
To visualise what I have just said, this is an example of tlv consisting with 4 entries (numbered), the header row (H's) and the placeholder row (P's).
HHHHH
11111
22222
33333
44444
PPPPP
I want to go from that, to say, if I wanted to swap entry 2 and 3 the output would be:
HHHHH
11111
33333
22222
44444
PPPPP
The code I have so far is as follows:
for (int j = 0; j < 5; j++)
{
TableLayoutPanelCellPosition tablePosition1 = new
TableLayoutPanelCellPosition(j, rowIndex + 1);
Control moveControl1 = queuedFiles.GetControlFromPosition(j, rowIndex);
queuedFiles.SetCellPosition(moveControl1, tablePosition1);
TableLayoutPanelCellPosition tablePosition2 = new
TableLayoutPanelCellPosition(j, rowIndex);
Control moveControl2 = queuedFiles.GetControlFromPosition(j, rowIndex + 1);
queuedFiles.SetCellPosition(moveControl2, tablePosition2);
if (j.Equals(0))
{
moveControl1.Text = (rowIndex + 1).ToString();
moveControl2.Text = (rowIndex).ToString();
}
}
However this code doesn't work and for the example above it produces:
HHHHH
11111
33222
22333
44444
PPPPP
What I believe is happening is tlv is automatically organising it's contents itself during the process of moving them around (maybe to fill vacant spaces?).
rowIndex above is the index of the target row which must be swapped with the row below it. I don't need to worry about checking if there is only 1 row or if it is the last row because I have done that already. Ignore changing the text too, I just need a pointer as to how I can achieve the intended result!
Thank you for absolutely any help you can give :)
A:
The following code does the job:
Code
using System;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// some content
var panel = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 5,
RowCount = 2
};
for (var y = 0; y < 2; y++)
for (var x = 0; x < 5; x++)
{
var control = new Button {Text = $@"X = {x}, Y = {y}"};
panel.Controls.Add(control, x, y);
}
// swap button
var button = new Button
{
Dock = DockStyle.Fill,
Text = @"Clicky !"
};
button.Click += (o, args) =>
{
var dictionary = panel.Controls
.Cast<Control>()
.ToDictionary(k => k, v => panel.GetCellPosition(v));
foreach (var pair in dictionary)
{
var position = pair.Value;
position.Row ^= 1; // simple row swap
panel.SetCellPosition(pair.Key, position);
}
};
// add to form
var container = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Horizontal,
SplitterWidth = 5,
BorderStyle = BorderStyle.Fixed3D
};
container.Panel1.Controls.Add(panel);
container.Panel2.Controls.Add(button);
Controls.Add(container);
}
}
}
Before
After
Note
Next time you ask a question, post a Minimal, Complete, and Verifiable example to maximize your chances of getting an answer !
As on why your code didn't work, see previous sentence, e.g what was rowIndex etc ?
Edit
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
const int cols = 5;
const int rows = 6;
// setup layout
var tlp = new TableLayoutPanel
{
ColumnCount = cols,
RowCount = rows,
Dock = DockStyle.Fill,
GrowStyle = TableLayoutPanelGrowStyle.FixedSize
};
for (var i = 0; i < cols; i++)
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100.0f / cols));
// add header
var label = new Label
{
Text = @"My Header",
BackColor = Color.Red,
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleCenter
};
tlp.Controls.Add(label);
tlp.SetColumn(label, 0);
tlp.SetRow(label, 0);
tlp.SetColumnSpan(label, cols);
// add some cells
var yMin = 1;
var yMax = 5;
var xMin = 0;
var xMax = cols;
for (var y = yMin; y < yMax; y++)
for (var x = xMin; x < xMax; x++)
{
var color = Color.FromArgb(
255 / (xMax - xMin) * (x - xMin),
128,
255 / (yMax - yMin) * (y - yMin)
);
var label1 = new Label
{
Text = $@"X = {x}, Y = {y}",
BackColor = color,
ForeColor = Color.White,
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleCenter,
Margin = DefaultMargin
};
tlp.Controls.Add(label1, x, y);
}
// add swapper
var button = new Button
{
Text = @"Clicky !",
Dock = DockStyle.Fill
};
button.Click += (o, args) =>
{
var srcRow = 2;
var tgtRow = 3;
var controls = tlp.Controls.Cast<Control>().ToArray();
var array1 = controls.Where(s => tlp.GetRow(s) == srcRow).ToArray();
var array2 = controls.Where(s => tlp.GetRow(s) == tgtRow).ToArray();
foreach (var control in array1)
tlp.SetCellPosition(control, new TableLayoutPanelCellPosition(tlp.GetColumn(control), tgtRow));
foreach (var control in array2)
tlp.SetCellPosition(control, new TableLayoutPanelCellPosition(tlp.GetColumn(control), srcRow));
};
// pack things up
var sc = new SplitContainer
{
Orientation = Orientation.Horizontal,
BorderStyle = BorderStyle.Fixed3D,
Dock = DockStyle.Fill
};
sc.Panel1.Controls.Add(tlp);
sc.Panel2.Controls.Add(button);
Controls.Add(sc);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Binary search tree
Present an algo to start with an initially empty BST and make 'n' random insertions.Use a uniform random number generator to obtain the values to be inserted.Measure the height of the resulting BST and divide this height by log2n.Do this for n=100,500,1000,2000,3000....,10000.Plot the ratio height/log2n as a function of n.The ratio should be approximately constant(around 2).Verify that this is so.
My understanding:Now we all know that the height of a BST is log2n where 'n' is the number of elements in the tree.If it is a left skewed/right skewed tree,then the height is equal to 'n'. So,if we measure the height here,what height should we assume for the insertions are random.I mean,how could the ratio be always around 2.I am banging my head against this one.
A:
If it is a left skewed/right skewed tree,then the height is equal to 'n'. So,if we measure the height here,what height should we assume for the insertions are random
The height for such binary tree is n. You don't have to assume anything here. Moreover, height of perfectly balanced BST is log(n) (not in general)
Coming to your question, I assume you are asking to find height of randomly build binary tree. In that case you don't have to calculate height of any specific binary tree.
Even if the height of skewed tree is n, the probably of it being generated in uniform random distribution is very less. So, if you calculate the height of random BST, it will come out to be O(log n).
For accurate calculation, refer Randomly build BST has logarithmic height
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ preprocessor removes whitespace in calls to variadic macros (Solaris Studio 12.3)
The C++ preprocessor of Oracle Solaris Studio 12.3 removes whitespace completely when expanding __VA_ARGS__.
Can anybody confirm this behaviour on their system? Is it a known compiler bug? Are there any workarounds for this problem?
To illustrate, here is a simple test program, vaargs.c:
#include <stdio.h>
#define PRINT(...) printf("%s\n", #__VA_ARGS__)
int main()
{
PRINT(hello world);
return 0;
}
The C preprocessor works as expected:
$ cc vaargs.c -o vaargs && ./vaargs
hello world
$ cc -V
cc: Sun C 5.12 SunOS_i386 2011/11/16
But the C++ preprocessor removes the space between "hello" and "world":
$ CC vaargs.c -o vaargs && ./vaargs
helloworld
$ CC -V
CC: Sun C++ 5.12 SunOS_i386 2011/11/16
A:
This is a compiler bug, as per N3337 16.3.2 (cpp.stringize) p2 (the rest of the quote is snipped):
A character string literal is a string-literal with no prefix. If, in the replacement
list, a parameter is immediately preceded by a # preprocessing token, both are replaced
by a single character string literal preprocessing token that contains the spelling of the
preprocessing token sequence for the corresponding argument. Each occurrence of white space
between the argument’s preprocessing tokens becomes a single space character in the
character string literal.
| {
"pile_set_name": "StackExchange"
} |
Q:
QueryPerformanceCounter returning negative number
Hey im trying to count how long the function takes to execute
I am doing it like this:
Timer.cpp
long long int Timer :: clock1()
{
QueryPerformanceCounter((LARGE_INTEGER*)&time1);
return time1;
}
long long int Timer :: clock2()
{
QueryPerformanceCounter((LARGE_INTEGER*)&time2);
return time2;
}
main.cpp
#include "Timer.h" //To allow the use of the timer class.
Timer query;
void print()
{
query.clock1();
//Loop through the elements in the array.
for(int index = 0; index < num_elements; index++)
{
//Print out the array index and the arrays elements.
cout <<"Index: " << index << "\tElement: " << m_array[index]<<endl;
}
//Prints out the number of elements and the size of the array.
cout<< "\nNumber of elements: " << num_elements;
cout<< "\nSize of the array: " << size << "\n";
query.clock2();
cout << "\nTime Taken : " << query.time1 - query.time2;
}
Can anyone tell me if i am doing this correctly?
A:
You are substracting ending time from starting time.
cout << "\nTime Taken : " << query.time1 - query.time2;
should be
cout << "\nTime Taken : " << query.time2 - query.time1
| {
"pile_set_name": "StackExchange"
} |
Q:
IOnic angular prod compiler error Property 'md' does not exist on type
Hi for the following code
<ion-segment value="{{selectedWor}}" (ionChange)="worshipTypeChanged($event)" [mode]="md">
I am getting the following error when i run: ionic build --prod. (no compiler error without --prod)
ERROR in src/app/pages/map/map.html(38,85): Property 'md' does not exist on type 'MapPage'.
[ERROR] An error occurred while running subprocess ng.
ng.cmd run app:build:production exited with exit code 1.
Re-running this command with the --verbose flag may provide more information.
Any ideas? The documentation says i can do it..
Here is my ionic info.
Ionic:
Ionic CLI : 5.4.6
(C:\Users\ginil\AppData\Roaming\npm\node_modules\ionic) Ionic
Framework : @ionic/angular 5.0.4
@angular-devkit/build-angular : 0.803.24 @angular-devkit/schematics
: 8.3.20 @angular/cli : 8.3.20
@ionic/angular-toolkit : 2.2.0
Cordova:
Cordova CLI : 8.1.2 ([email protected]) Cordova Platforms
: not available Cordova Plugins : not available
Utility:
cordova-res : 0.5.1 native-run : 0.2.7
System:
NodeJS : v11.11.0 (C:\Program Files\nodejs\node.exe) npm :
6.7.0 OS : Windows 10
A:
You are using mode as two way binding variable so you have to declare md in ts file.
There are two way to use mode property
1)
<ion-segment value="{{selectedWor}}" (ionChange)="worshipTypeChanged($event)" mode="md">
2)
html
<ion-segment value="{{selectedWor}}" (ionChange)="worshipTypeChanged($event)" [mode]="md">
ts
md = 'md'
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that $9\vert F_{n+24}$ iff $9\vert F_n$.
Prove that $9\vert F_{n+24}$ iff $9\vert F_n$.
This can be proved if in some way we can establish $F_{n+24}\equiv F_{n}(mod 9)$.
It is given in hint to use identity $F_{m+n}=F_{m-1}F_{n}+F_{m}F_{n+1}$.
Using the above identity for $F_{n+24}$,we get $F_{n+24}=F_{n-1}F_{24}+F_{n}F_{25}$,from here how to find the direction leading to $F_{n+24}\equiv F_{24}(mod 9)$?
A:
Just note that $F_{24} \equiv 0 \bmod 9$ and $F_{25} \equiv 1 \bmod 9$, and so $F_{n+24} = F_{n-1}F_{24}+F_{n}F_{25} \equiv F_{n} \bmod 9$.
In particular, $9 \mid F_{n+24}$ iff $9 \mid F_n$.
Actually, we have $9 \mid F_{n+12}$ iff $9 \mid F_n$ because $F_{12} \equiv 0 \bmod 9$ and $F_{13} \equiv -1 \bmod 9$ gives $F_{n+12} = F_{n-1}F_{12}+F_{n}F_{13} \equiv -F_{n} \bmod 9$.
More generally, take a divisor $d$ of $F_m$. Then, $d \mid F_{n+m}$ iff $d \mid F_n$.
Indeed, $F_{n+m}=F_{m+n}=F_{m-1}F_{n}+F_{m}F_{n+1} \equiv F_{m-1}F_{n}\bmod d$. But $F_{m-1}$ is invertible mod $d$ because $\gcd(F_{m-1},F_m)=1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter async with akka-stream
Is there an equivalent to the mapAsync() method, but for filter?
Here is an example using pseudo code:
val filter: T => Future[Boolean] = /.../
source.filter(filter).runWith(/.../)
^^^^^^
Thanks
A:
I don't think there is a direct method of Flow or Source that has the capability you're looking for, but a combination of the available methods will get you what you want:
def asyncFilter[T](filter: T => Future[Boolean], parallelism : Int = 1)
(implicit ec : ExecutionContext) : Flow[T, T, _] =
Flow[T].mapAsync(parallelism)(t => filter(t).map(_ -> t))
.filter(_._1)
.map(_._2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Entity Translation Should be in the Data Layer or Business Layer
From my understanding I though the data layer should isolate the Data Technology from the rest of the application, for me this also include the schema in this case the data entity. Recently I've been looking at the Silk project from Patterns & Practices http://silk.codeplex.com/, and noticed that data entities are translated in the business layer rather than in the data layer.
I think the advantage is that it avoid the data layer to reference an assembly containing the business model. However the fact that it expose data entities publicly is from my understanding a disadvantage because external components may be dependent of the data schema.
I would like to understand why they translate data entities in the business layer and what are the advantages?
I know that they use code first entity framework, so that the entities doesn't have data technology related dependency, however there responsibility is still to structure the data model not the business model.
Thanks
A:
I imagine the conversion is done in the Business Layer as opposed to the Data Layer so that the Data Layer doesn't need to know every case of its use.
With the current approach it is the responsibility of the calling code to know how to use the Data Layer. If the conversion happened in the Data Layer, then it would need to be aware of all the calling code cases.
This may be pretty straight forward at first because you probably have a close to 1:1 mapping between Business Objects/Entities and the storage schema, but that won't necessarily always be the case.
Take the example of two Departments in a business working with a similar concept... let's say an Approval Workflow. Dept A calls each step in the workflow a Bla. Dept B likes that Dept A has its workflow automated and wants the same, but it calls its workflow steps BongoBlas. It is a fundamental fact of the business domain that the two workflows are identical and will always be, but the business process is such that the steps have different names (and some of the metadata fields have different names as well).
In this case you could develop a second Business Entity which uses the same persistence as the first.
If the Data Layer was responsible for conversions then it would now need to be extended to handle BongoBla conversions as well as its existing Bla conversions. This seems a bit odd because as far as the Data Layer is concerned this is none of its concern.
The Data Layer is consumer agnostic.
This is why it makes more sense for the consumers of the Data Layer to be responsible for the data conversions. When new consumers are added then only the consumer code needs to be written. The Data Layer can remain untouched. And this makes sense because the concerns of the Data Layer haven't actually changed.
Note: Sorry for the lame example scenario above. If I think of anything better I'll update the answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I fix this error with location, adapters and ListView in Android?
Hi guys I have a tricky error that I can't solve. I'm working on a listview and when location services are active I wanna that if location is turned on I watch time to go in a place, and when location services are off I will display a message instead of time. Nothing special. But I have a tricky error like, if I have GPS, so fine location, works, if I have all location turned off, works, but If I have coarse location active, the app crash...this is really tricky. Below my code and my logcat. Thanks guys.
Full class code:
package com.example.findmyclients;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListviewActivity extends Activity{
private ListView lista;
private ListView listaNOGPS;
private List<InterestPoint> listaInteressPoint;
private List<InterestPoint> listaInteressPointNOGPS;
private InterestPoint ip;
private CustomListAdapter adapter;
private CustomListAdapter adapterNOGPS;
public String [][]ArrayTime = new String[1000][6]; //La matrice che conterrà tutti i dati relativi alla lista
public String [][]Dati_history = new String[100][10];
public String [][]Dati_restaurant = new String[100][10];
public String [][]Dati_hotel = new String[100][10];
public String [][]Dati_souvenir = new String[100][10];
public String pathdirectory = "/sdcard/PredappioLiving/";
String[]file_names={"markers_history.xml", "markers_hotel.xml", "markers_restaurant.xml", "markers_souvenir.xml"};
String[]Array_Cat={"Monumenti","Alloggi","Ristoranti","Negozi"};
int nome_luogo = 0;
int categoria = 1;
int auto = 2;
int piedi = 3;
int latitude = 4;
int longitude = 5;
int gps_on= 0;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final Activity thiz = this;
//Get ListView Object from xml
lista = (ListView) thiz.findViewById(R.id.lista);
listaNOGPS = (ListView) thiz.findViewById(R.id.lista);
GPSTracker gpstrack = new GPSTracker(this);
if (gpstrack.canGetLocation() ) {
gps_on = 1;
}
/* - - - Costruzione della matrice dall'xml - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - -*/
int file_choice=-1;
int n = 0; //mi serve per riempire bene tutta la matrice
for (int i = 0; i<file_names.length; i++)
{
String file_path = pathdirectory+file_names[i];
int indice_riempimento = n;
int returnhistory = file_names[i].compareTo("markers_history.xml");
int returnhotel = file_names[i].compareTo("markers_hotel.xml");
int returnrestaurant = file_names[i].compareTo("markers_restaurant.xml");
int returnsouvenir = file_names[i].compareTo("markers_souvenir.xml");
if (returnhistory == 0){
file_choice = 0;
}
if (returnhotel == 0){
file_choice = 1;
}
if (returnrestaurant == 0){
file_choice = 2;
}
if (returnsouvenir == 0){
file_choice = 3;
}
// Inizio lettura da XML e popolazione della matrice
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(file_path));
doc.getDocumentElement().normalize();
NodeList nodi = doc.getElementsByTagName("marker");
for (int c = 0; c<nodi.getLength(); c++)
{
Element item = (Element) nodi.item(c);
String nome = item.getAttribute("name");
String destLat = item.getAttribute("lat");
String destLong = item.getAttribute("long");
Double lat = Double.valueOf(destLat);
Double lon = Double.valueOf(destLong);
GPSTracker gpsTracker = new GPSTracker(this);
String stringMyLatitude = String.valueOf(gpsTracker.latitude);
String stringMyLongitude = String.valueOf(gpsTracker.longitude);
double currentLat = Double.parseDouble(stringMyLatitude);
double currentLong = Double.parseDouble(stringMyLongitude);
final float[]distanzadouble = new float[3];
Location.distanceBetween(currentLat, currentLong, lat, lon, distanzadouble);
float metri = distanzadouble[0];
float km = Math.round((double)metri/1000);
int minuti_persona = (int)Math.round(metri/125); //125 metri al minuto -> velocità media di 2,5 m/s
int minuti_auto = (int)Math.round(km/0.7); //700 metri al minuto -> velocità media di 42 km/h
String string_min_a_piedi;
String string_min_in_auto;
if(minuti_persona <=0) // Stampa tempo per coprire la distanza
{
string_min_a_piedi="meno di un minuto";
}else
{
string_min_a_piedi=String.valueOf(minuti_persona);
}
if(minuti_auto <= 0)
{
string_min_in_auto="meno di un minuto";
}else
{
string_min_in_auto= String.valueOf(minuti_auto);
}
ArrayTime[c+n][nome_luogo] = nome;
ArrayTime[c+n][categoria] = Array_Cat[file_choice];
ArrayTime[c+n][auto] = string_min_in_auto;
ArrayTime[c+n][piedi] = string_min_a_piedi;
}
n = n+nodi.getLength();
}catch(Exception e)
{
e.printStackTrace();
}
}
//Arrays.sort(ArrayTime, new ColumnComparator(0));
//Stampa dell'array sulla lista - - -
/*
for(int i = 0; i<6; i++)
{
ip = new InterestPoint();
ip.nome = "pippo"+i;
ip.categoria ="cat pippo"+i;
ip.apiedi = "25";
ip.inauto = "10";
listaInteressPoint.add(ip);
}
*/
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (gps_on == 1) {
listaInteressPoint = new ArrayList<InterestPoint>();
for(int i = 0; i<n;i++)
{
ip = new InterestPoint();
ip.nome = ArrayTime[i][nome_luogo];
ip.categoria = "Categoria: "+ArrayTime[i][categoria];
ip.inauto = "In auto: " +ArrayTime[i][auto]+ " minuti";
ip.apiedi = "A piedi: " +ArrayTime[i][piedi]+ " minuti";
listaInteressPoint.add(ip);
}
//Ordinamento
Collections.sort(listaInteressPoint, new Comparator<InterestPoint>(){
@Override
public int compare(InterestPoint elem1, InterestPoint elem2) {
return elem1.inauto.compareTo(elem2.inauto);
}
});
}else
{
listaInteressPointNOGPS = new ArrayList<InterestPoint>();
for(int i = 0; i<n;i++)
{
ip = new InterestPoint();
ip.nome = ArrayTime[i][nome_luogo];
ip.categoria = "Categoria: "+ArrayTime[i][categoria];
ip.inauto = "In auto: Attiva la posizione per la distanza";
ip.apiedi = "A piedi: in auto e a piedi";
listaInteressPointNOGPS.add(ip);
}
//Ordinamento
Collections.sort(listaInteressPointNOGPS, new Comparator<InterestPoint>(){
@Override
public int compare(InterestPoint elem1, InterestPoint elem2) {
return elem1.nome.compareTo(elem2.nome);
}
});
}
/*
//ListView Item Click Listener
listaNOGPS.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//ListView Clicked item index
int itemPosition = position;
InterestPoint item = adapter.getItem(position);
Intent piu_info = new Intent(thiz, MoreInfoActivity.class);
piu_info.putExtra("nome", item.nome);
startActivity(piu_info);
//ListView clicked item value
//int itemValue = (int) lista.getItemAtPosition(position);
//Show Alert
Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
}
});
*/
//ListView Item Click Listener
lista.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (gps_on == 1){
//ListView Clicked item index
int itemPosition = position;
InterestPoint item = adapter.getItem(position);
Intent piu_info = new Intent(thiz, MoreInfoActivity.class);
piu_info.putExtra("nome", item.nome);
startActivity(piu_info);
//ListView clicked item value
//int itemValue = (int) lista.getItemAtPosition(position);
//Show Alert
Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
}else
{
//ListView Clicked item index
int itemPosition = position;
InterestPoint item = adapterNOGPS.getItem(position);
Intent piu_info = new Intent(thiz, MoreInfoActivity.class);
piu_info.putExtra("nome", item.nome);
startActivity(piu_info);
//ListView clicked item value
//int itemValue = (int) lista.getItemAtPosition(position);
//Show Alert
Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);
if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
lista.setAdapter(adapter);
}else
{
listaNOGPS.setAdapter(adapterNOGPS);
}
}
}
Logcat:
10-28 10:53:53.106: E/AndroidRuntime(445): FATAL EXCEPTION: main
10-28 10:53:53.106: E/AndroidRuntime(445): Process: com.example.findmyclients, PID: 445
10-28 10:53:53.106: E/AndroidRuntime(445): java.lang.RuntimeException: Unable to resume activity {com.example.findmyclients/com.example.findmyclients.ListviewActivity}: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3076)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3105)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.access$900(ActivityThread.java:175)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.os.Looper.loop(Looper.java:146)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.main(ActivityThread.java:5602)
10-28 10:53:53.106: E/AndroidRuntime(445): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 10:53:53.106: E/AndroidRuntime(445): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
10-28 10:53:53.106: E/AndroidRuntime(445): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
10-28 10:53:53.106: E/AndroidRuntime(445): at dalvik.system.NativeStart.main(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445): Caused by: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.widget.ListView.setAdapter(ListView.java:486)
10-28 10:53:53.106: E/AndroidRuntime(445): at com.example.findmyclients.ListviewActivity.onResume(ListviewActivity.java:356)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1198)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.Activity.performResume(Activity.java:5530)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3066)
10-28 10:53:53.106: E/AndroidRuntime(445): ... 12 more
10-28 10:53:53.161: I/Process(445): Sending signal. PID: 445 SIG: 9
P.S.: With coarse location variable "gps_on" is set to "1" correctly
A:
1.
if (gps_on == 1) {
listaInteressPoint = new ArrayList<InterestPoint>();
//rest of the code
} else {
listaInteressPointNOGPS = new ArrayList<InterestPoint>();
//rest of the code
}
2. P.S.: With coarse location variable "gps_on" is set to "1" correctly
So
3. from your onResume()
adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);
if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
lista.setAdapter(adapter);
}else
{
listaNOGPS.setAdapter(adapterNOGPS);
}
The error you get is for the getCount() of a list which is initialized but empty, not populated. In this case, gps_on==1 so listaInteressPointNOGPS isn't accessed.
You can change the if in onResume() and check with an or condition maybe... in the case of coarse location active specifically.
Important lines from your logcat:
10-28 10:53:53.106: E/AndroidRuntime(445): Caused by: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
10-28 10:53:53.106: E/AndroidRuntime(445): at android.widget.ListView.setAdapter(ListView.java:486)
10-28 10:53:53.106: E/AndroidRuntime(445): at com.example.findmyclients.ListviewActivity.onResume(ListviewActivity.java:356)
Check which one is line 356 from ListviewActivity.java
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have nested trigger in sql?
i have a After insert/update trigger. It should gets a field value (lets call it "CurrentState") from inserted record. check CurrentState value in another table, then find another value for this field and then update the newly added or updated record with this value. so after a record update, the currentstate might be updated several times.
Does SQL support nested update trigger?! actually it doesn't work now, i didn't found any mistake in my code. so i get suspicious about sql support.
here is my code
create TRIGGER [dbo].[ASI_trigBPMIAutomaticState]
ON [dbo].[ASI_TblBPMForm]
AFTER INSERT, Update
AS
BEGIN
select @CurrentState = CurrentState from inserted;
select @FormID = FormID from inserted;
DECLARE curflow CURSOR
LOCAL SCROLL STATIC
for select w.WorkflowID
from ASI_TblBPMWorkflow w
where w.FromState = @CurrentState
OPEN curflow
FETCH first FROM curflow
INTO @WorkflowID
WHILE @@FETCH_STATUS = 0
BEGIN
select @ToState = StateID
from TblStates
where r.ResponseID = @WorkflowID
if (@ToState =1)
breake;
FETCH next FROM curflow
INTO @WorkflowID
END -- While Cursor
CLOSE curflow
DEALLOCATE curflow
if (@QID > 0)
begin
update ASI_TblBPMForm
set CurrentState = @ToState
where FormID = @FormID
end;
end
A:
Does SQL support nested update trigger?!
Yes.
Create Nested Triggers
Both DML and DDL triggers are nested when a trigger performs an action
that initiates another trigger. These actions can initiate other
triggers, and so on. DML and DDL triggers can be nested up to 32
levels. You can control whether AFTER triggers can be nested through
the nested triggers server configuration option. INSTEAD OF triggers
(only DML triggers can be INSTEAD OF triggers) can be nested
regardless of this setting.
There are nested triggers and recursive triggers.
ALTER DATABASE AdventureWorks2012
SET RECURSIVE_TRIGGERS ON;
GO
[Please take note of @marc_s's comments.] I would strongly suggest you do not use cursors in triggers, and make sure your trigger can handle multiple rows.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add n rows (not a single row) in a dataframe?
I have some dataframes and i want to add some empty rows in each one. The number of the added empty rows depend of the lenght of maxdf minus the lenght of the dataframe itself.
I tried this code:
control1.loc[control1.index.max() + (len(maxdf)-len(control1))] = None
control2.loc[control2.index.max() + (len(maxdf)-len(control2))] = None
control3.loc[control3.index.max() + (len(maxdf)-len(control3))] = None
control4.loc[control4.index.max() + (len(maxdf)-len(control4))] = None
control5.loc[control5.index.max() + (len(maxdf)-len(control5))] = None
But it only adds one empty row in each df. Can anyone help me please?
A:
To add n empty rows - you can do:
n=10
control1=control1.append(pd.DataFrame([[None]*len(control1.columns)]*n, columns=control1.columns, index=np.arange(n)+control1.index.max()+1))
Using @Raphaele Adjerad sample data output:
# Before:
A B C D
0 510 365 382 322
1 988 98 742 17
2 595 106 123 569
# After:
A B C D
0 510 365 382 322
1 988 98 742 17
2 595 106 123 569
3 None None None None
4 None None None None
5 None None None None
6 None None None None
7 None None None None
8 None None None None
9 None None None None
10 None None None None
11 None None None None
12 None None None None
| {
"pile_set_name": "StackExchange"
} |
Q:
Connecting a Switch to a Relay
I am trying to connect 2 motor boats with a relay to a switch. I received a drawing, but I am not understanding how the wires connect into the illuminated switch.
Here is the switch and the drawing.
Can you help me with this ?
A:
Granted, I don't read German, and it took a bit of guess work, but considering they are standardish parts, this should be correct. Your switch is not the same kind of illuminated switch used in the circuit you show. But it can be wired the same.
Battery positive to the C (Common) pin. Connect the + on the switch to the NO pin. Connect the relay pin 85 to the NO pin as well. The battery negative should go to the Relay Pin 86 AND the switch pin -.
The rest of the circuit is as normally connected (Battery Positive to the Switch's C pin and the Relay pin 30, etc etc.
simulate this circuit – Schematic created using CircuitLab
| {
"pile_set_name": "StackExchange"
} |
Q:
Joomla menu css
I wanted to create a menu in the top of the page, because of the specific layout in the css i thought this is a solution to do this using the following code in my template (the index.php)
$item_active = $menu->getActive();
for($i = 0; $i > count($menu_items); $i++){
$item = $menu_items[$i];
if($item_active->id == $item->id)
echo '<a href="'.$this->baseurl.'/'.$item->route.'"><div id="button_pressed"><div id="button_text">'.$item->title.'</div></div></a>';
else
echo '<a href="'.$this->baseurl.'/'.$item->route.'"><div id="button"><div id="button_text">'.$item->title.'</div></div></a>';
}
But isnt there a better way, i think im missing a link here
A:
This shouldn't be in your template. The menu should be in a module. Most menu modules have active highlighting built in. Even the core Joomla mod_menu supports active highlighting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Update data from server periodically design
I had a problem about how to design updater for my program. Which the best order to update data from the server? (absolutely multithreading)
Thread {
Timer {
result = downloaddata(url)
}
}
or
Timer {
Thread {
result = downloaddata(url)
}
}
A:
And who manges the timer in the second solution? Should it be again the main thread? I would suggest the first option.
In android the Thread will be implemented in a Service.
Also, think of whether you really need periodic updates. If the changes are relatively rare, then push notifications from the server might be better solution for your needs (they will greatly reduce the number of calls to the server, thus consumed resources).
| {
"pile_set_name": "StackExchange"
} |
Q:
ImagesTabViewController' does not conform to protocol 'UITableViewDataSource'
I know this question has been asked a million times, but I can't find a resolution to this specific issue. I'm using Xcode 6.3 beta 4 with Swift 1.2 and since the last update I haven't been able to get a regular UITableView with the supporting datasource and delegate protocols working.
I am getting the above error and "Definition conflicts with previous value" for the numberOfRowsInSection function. At this point I don't know if it's a Swift change or I am missing something. The tableview is connected properly..
Thanks for any help.
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}}
A:
There is a bracket missing and didReceiveMemoryWarning must be overridden. Here is the revised code:
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
} // <- Was missing!
// Override!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Inkscape Mac: how to organize objects in the same layer
If I understand if I want to create a mask all the objects must be in the same layer. (if previously are in different layers, they move to one layer only). I find difficult to keep organized when I have many objects in the same layer. For instance, I have shadows behind some objects and I cannot even select them and make changes. My question is what is the best way to organize different objects in the same layer in Inkscape? How to select an object that is in the bottom of the layer and it's very close to other objects?
A:
The answer of @Billy Kerr is right in Windows. I have a mac and it does not work.
I have a Mac, so I have to go first to XQuartz (general menu up left) > Preferences > Input > "Option keys send Alt_L and Alt_R"
With that, Alt + click will select the top object, the second click will select the object behind and so on.
If you have a Mac Mouse (Magic Mouse) it also works alt + finger up and down to the surface (that's the equivalent of the scroll wheel in other mouses)
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails: sending an array of hashes from form to server
In my parameters hash, I am trying to achieve something like the following:
{"utf8"=>"✓", "authenticity_token"=>"6A14fVUEWQSB83j2BsYKn", "search"=>{"keywords"=>[{"keyword_names"=>"color", "keyword_conditions"=>"is not", "keyword_values"=>"red"}, {"keyword_names"=>"size", "keyword_conditions"=>"is", "keyword_values"=>"3"}] , "assignee_id"=>"", "begin_date"=>"", "end_date"=>""}, "commit"=>"search"}
Notice the following:
"keywords"=>[{"keyword_names"=>"color", "keyword_conditions"=>"is not", "keyword_values"=>"red"}, {"keyword_names"=>"size", "keyword_conditions"=>"is", "keyword_values"=>"3"}]
However, this is what is currently being sent:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6A14fVUEWQSB83j2BsYKn", "keyword_names"=>["name", "name"], "keyword_conditions"=>["is", "is"], "keyword_values"=>["dan", "john"], "search_add"=>"and", "search"=>{"assignee_id"=>"", "begin_date"=>"", "end_date"=>""}, "commit"=>"search"}
Notice keyword_names, keyword_conditions, and keyword_values is not part of the search hash. How can I make it part of the search hash?
This is what I have:
<%= link_to "Add", "#", class: 'add_search' %>
<div class="search_container">
<%= text_field_tag "keyword_names[]" %><%= select_tag "keyword_conditions[]", options_for_select(["is", "is not","is like"]) %><%= text_field_tag "keyword_values[]" %>
</div>
A:
Following this structure of the params:
keywords:
[
{ keyword_names: 'color', keyword_conditions: 'is not', keyword_values: 'red' }
]
You should name your input like this:
0..3.each do |index|
text_field_tag "keywords[#{index}][keyword_names]"
select_tag "keywords[#{index}][keyword_conditions]", options_for_select(['is', 'is not', 'is like'])
text_field_tag "keywords[#{index}][keyword_values]"
end
Where the 0..3.each do |index| is a loop defining 4 different sets of 3 inputs for each keyword. So params[:keywords].size should return 4
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues in resolving placeholders in bootstrap.properties after upgrading to Springboot 2
Spring dependency:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Spring-cloud dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Error on startup -
2018-03-09 19:41:35.096 WARN 97916 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'propertySourceBootstrapConfiguration': Unsatisfied dependency expressed through field 'propertySourceLocators'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configServicePropertySource' defined in org.springframework.cloud.config.client.ConfigServiceBootstrapConfiguration: Unsatisfied dependency expressed through method 'configServicePropertySource' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'configClientProperties': Could not bind properties to 'ConfigClientProperties' : prefix=spring.cloud.config, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.cloud.config.password' to java.lang.String
bootstrap.properties:
spring.cloud.config.failFast=true
spring.profiles.active=${ACTIVE_PROFILES:dev}
spring.cloud.config.uri=${CLOUD_CONFIG_URL:http://domainname/cloud-config}
spring.cloud.config.username=${CLOUD_CONFIG_USERNAME}
spring.cloud.config.password=${CLOUD_CONFIG_PASSWORD}
A:
Figured this out:
spring.cloud.config.username=${CLOUD_CONFIG_USERNAME}
spring.cloud.config.password=${CLOUD_CONFIG_PASSWORD}
needs to be changed to -
spring.cloud.config.username=${CLOUD_CONFIG_USERNAME:}
spring.cloud.config.password=${CLOUD_CONFIG_PASSWORD:}
Notice the colon at the end. This used to work earlier though.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I save clicked node in cytoscape.js?
I want to show the details about a selected node in a side panel in my AngularJS application. How can I dynamically bind the selected Node with the data in the side panel?
A:
I designed this to use with a pretty old Cytoscape.js version (2.0.2), but as far as I could check in the documentation, it stills the same. Below you can find a minimal example.
You could do something like this:
var cy = cytoscape({
container: document.getElementById('cy'),
showOverlay: true,
minZoom: 1,
maxZoom: 1,
layout: {
fit: true
},
elements: {
// nodes
"nodes": [{
"data": {
"id": "n1",
"name": "node 1",
"description": "Ars Gratia Artis 1"
}
}, {
"data": {
"id": "n2",
"name": "node 2",
"description": "Ars Gratia Artis 2"
}
}],
"edges": [{
"data": {
"source": "n1",
"id": "e1",
"target": "n2",
"type": "belongs-to"
}
}]
},
ready: function() {
var stringStylesheet = "node {"
+"content: data(name);"
+"text-valign: center;"
+"color: white;"
+"text-outline-width: 2;"
+"text-outline-color: #888;"
+"}"
+"edge {"
+" target-arrow-shape: triangle;"
+"content: data(type);"
+"text-outline-color: #FFF;"
+"text-outline-opacity: 1;"
+" text-outline-width: 2;"
+" text-valign: center;"
+" color: #777;"
+"width: 2px;"
+"}"
+":selected {"
+"background-color: black;"
+"line-color: black;"
+"target-arrow-color: black;"
+"source-arrow-color: black;"
+"color: black;"
+"}"
+".faded {"
+" opacity: 0.25;"
+"text-opacity: 0;"
+"}";
cy = this;
cy.style( stringStylesheet );
//You can have different panels for editing edges and nodes.
var nodeClicked = cy.on('tap', 'node', function(e) {
//var edgeClicked = cy.on('tap', 'edge', function(e) {
//Here I use pure jQuery to hide the edge-edition panel
//and show the node-edition one.
//$('div.edge-edition').hide();
$('div.node-edition').show();
//if you click in a specific node, unselect any other
//previously selected element from the graph
cy.elements().unselect();
//* identify which node was clicked
var node = e.target;
console.log("node clicked: " + node.data('name'));
//finally, fullfills forms of the panel with node data
$('.node-name').val(node.data('name'));
$('.node-description').val(node.data('description'));
});
}
});
html {
height: 98%;
}
body {
font-family: Verdana, Arial, Times New Roman;
font-size: 11px;
height: 100%;
}
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cy {
height: 85%;
width: 60%;
float: left;
position: relative;
top: 10px;
left: 0px;
border: 1px solid #aaa;
border-radius: 5px;
-webkit-border-radius: 5px;
padding: 0px;
display: block;
z-index: 1;
}
#edition {
float: right;
height: 85%;
width: 39.5%;
position: relative;
top: 10px;
border: 1px solid #aaa;
border-radius: 5px;
-webkit-border-radius: 5px;
padding: 0px;
display: block;
z-index: 1;
}
input,
textarea {
border: 1px solid #aaa;
border-radius: 5px;
-webkit-border-radius: 5px;
padding: 5px;
z-index: -1;
}
.node-name,
.node-description {
max-width: 350px;
width: 250px;
}
<script src="https://rawgit.com/cytoscape/cytoscape.js/master/dist/cytoscape.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-us">
<head>
</head>
<body>
<div id="cy"></div>
<div id="edition">
<div class="node-edition">
<form>
<table>
<tr>
<td>Name</td>
<td>
<input type="text" class="node-name">
</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea class="node-description"></textarea>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Immutable Properties That Shouldn't Be
I've come across a very strange problem, which I am trying to understand. It appears that instance variables are not working like they should...
self.imageView.setImage(image) // This works.
self.imageView.image = image // This does not.
With the second method, I get the following error. Cannot assign to property: self is immutable.
This is the first time it happens to me: I am not doing anything special.
My image view is declared like follows,
@IBOutlet var imageView: UIImageView!, and is connected in the storyboard.
The only think I can think of is that I've recently included an Objective-C bridging header; it was working fine yesterday, although I can't seem to make it work normally by removing the bridging header from the build settings.
All this is happening from a UIViewController subclass, and I mean class, not struct...
Thank you for your help.
A:
I found the reason behind all this. It's stupid, and I thank Nicklas Ridewing for pointing me in the right direction.
I've included https://github.com/mindbrix/UIImage-PDF (UIImage+PDF).
This code extends UIView with a method defined as
- (NSImage *) image.
I renamed it, pdf_image and all was fixed, after changing all calls to it in the library. Maybe I'll do a pull request...
| {
"pile_set_name": "StackExchange"
} |
Q:
Firefox not properly displaying inset box-shadow with border-radius
I have several buttons at the top of a sidebar. The first and last buttons have a rounded corner to match the edges of the sidebar. When .active, the buttons should have an inset box-shadow. In Chrome, this works properly. In Firefox, however, the box-shadow doesn't follow the border-radius and instead has a sharp corner. Am I doing something wrong, or is this a bug in the way Firefox renders the shadow? This is Firefox 41.0.1 for Ubuntu, by the way.
I can't post a screenshot (company policies) but I have put up a fiddle (link at end of post) where you should be able to see the problem.
I've searched for a couple of days and haven't found any other questions describing this same behavior.
Here's the HTML:
<div class="sidebar">
<div class="sidebar-nav">
<a class="menu-item active" href="#" onclick='toggleNav(this)'>
My Page
</a>
<a class="menu-item" href="#" onclick='toggleNav(this)'>
Your Page
</a>
<a class="menu-item" href="#" onclick='toggleNav(this)'>
Our Page
</a>
</div>
<div class="sidebar-main">
<div class="sidebar-row">
<div class="sidebar-h1">User Info</div>Phasellus blandit nulla ante, non tempus sem imperdiet sagittis. Vivamus condimentum et est eu iaculis. Nam semper nunc quis rhoncus viverra. Nam lorem nulla, feugiat at sodales sit amet, tempor quis nisi. Sed dictum in tortor et dapibus. Aliquam erat volutpat. Vivamus venenatis faucibus justo vitae rutrum. Sed in viverra ipsum. Duis et metus at metus euismod fermentum sed eu dolor.</div>
<div class="sidebar-row">
<div class="sidebar-h1">User Settings</div>
<label>
<input type="checkbox" />Settings</label>
<br>
<select>
<option>Words</option>
<option>Things</option>
<option>Stuff</option>
</select>
</div>
</div>
</div>
And the CSS:
.sidebar {
text-align: center;
border: 1px solid #ddd;
border-radius: 8px;
color: #888;
background: #eee;
width: 250px;
height: 100%;
}
.sidebar-nav {
padding: 0px;
display: table;
width: 100%;
border-bottom: 1px solid #ccc;
border-collapse: collapse;
}
.sidebar-nav > .menu-item {
color: #888;
padding: 10px;
vertical-align: top;
display: table-cell;
cursor: pointer;
text-decoration: none;
}
.sidebar-nav > .menu-item:first-child {
border-radius: 8px 0 0 0;
}
.sidebar-nav > .menu-item:last-child {
border-radius: 0 8px 0 0;
}
.sidebar-nav .menu-item + .menu-item {
border-left: 1px solid #ccc;
}
.sidebar-nav > .menu-item:not(.active):hover {
background-color: #ddd;
}
.sidebar-nav > .active {
color: white;
box-shadow: inset 0px -2px 4px 2px #888;
background-color: #aaa;
}
.sidebar-main {
padding: 10px;
}
.sidebar-h1 {
font-size: 1.2em;
font-weight: bold;
margin: 5px;
}
.sidebar-row {
padding: 15px;
position: relative;
}
.sidebar-row:after {
content:'';
width: 50%;
height: 1px;
background: #ddd;
position: absolute;
left: 25%;
bottom: -1px;
}
And the JSFiddle (note that the fiddle also includes a little jQuery to make the buttons clickable).
A:
This is because of display: table-cell; in your .sidebar-nav > .menu-item {} selector. Fix it by adding display: block; to your .sidebar-nav > .active class:
function toggleNav(elem) {
$('a').removeClass('active');
$(elem).addClass('active');
}
.sidebar {
text-align: center;
border: 1px solid #ddd;
border-radius: 8px;
color: #888;
background: #eee;
width: 250px;
height: 100%;
}
.sidebar-nav {
padding: 0px;
display: table;
width: 100%;
border-bottom: 1px solid #ccc;
border-collapse: collapse;
}
.sidebar-nav > .menu-item {
color: #888;
padding: 10px;
vertical-align: top;
display: table-cell;
cursor: pointer;
text-decoration: none;
outline: none;
}
.sidebar-nav > .menu-item:first-child {
border-radius: 8px 0 0 0;
}
.sidebar-nav > .menu-item:last-child {
border-radius: 0 8px 0 0;
}
.sidebar-nav .menu-item + .menu-item {
border-left: 1px solid #ccc;
}
.sidebar-nav > .menu-item:not(.active):hover {
background-color: #ddd;
}
.sidebar-nav > .active {
color: white;
box-shadow: inset 0px -2px 4px 2px #888;
background-color: #aaa;
display: block;
}
.sidebar-main {
padding: 10px;
}
.sidebar-h1 {
font-size: 1.2em;
font-weight: bold;
margin: 5px;
}
.sidebar-row {
padding: 15px;
position: relative;
}
.sidebar-row:after {
content:'';
width: 50%;
height: 1px;
background: #ddd;
position: absolute;
left: 25%;
bottom: -1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="sidebar">
<div class="sidebar-nav">
<a class="menu-item active" href="#" onclick='toggleNav(this)'>
My Page
</a>
<a class="menu-item" href="#" onclick='toggleNav(this)'>
Your Page
</a>
<a class="menu-item" href="#" onclick='toggleNav(this)'>
Our Page
</a>
</div>
<div class="sidebar-main">
<div class="sidebar-row">
<div class="sidebar-h1">User Info</div>Phasellus blandit nulla ante, non tempus sem imperdiet sagittis. Vivamus condimentum et est eu iaculis. Nam semper nunc quis rhoncus viverra. Nam lorem nulla, feugiat at sodales sit amet, tempor quis nisi. Sed dictum in tortor et dapibus. Aliquam erat volutpat. Vivamus venenatis faucibus justo vitae rutrum. Sed in viverra ipsum. Duis et metus at metus euismod fermentum sed eu dolor.</div>
<div class="sidebar-row">
<div class="sidebar-h1">User Settings</div>
<label>
<input type="checkbox" />Settings</label>
<br>
<select>
<option>Words</option>
<option>Things</option>
<option>Stuff</option>
</select>
</div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Few questions regarding Polymer best practices
I'm bulding my first Polymer single page app and I have few questions.
1) In many views I need to show a dialog (various confirmations etc.) and I tried to centralize the dialogs by creating a dialog in a parent. The content of the dialog is switched by iron-pages. Here is what the code in parent looks like:
<paper-dialog id="main_dialog" with-backdrop entry-animation="scale-up-animation"
exit-animation="fade-out-animation">
<iron-pages id="dialogpages" selected="login" attr-for-selected="name">
<login-view name="login"></login-view>
<registration-view name="registration"></registration-view>
<emaildialog-view name="emaildialog"></emaildialog-view>
<actionerror-view name="actionerror"></actionerror-view>
<actionconfirm-view name="actionconfirm"></actionconfirm-view>
<passreset-view name="passreset"></passreset-view>
<emailinput-view name="emailinput"></emailinput-view>
</iron-pages>
</paper-dialog>
And the javascript:
showDialog: function (path, pageName, open) {
this.$.dialogpages.selected = pageName;
this.importHref("/views/dialog_views/" + path + pageName + "-view.html", function () {
if (open) {
this.$.main_dialog.toggle();
}
}.bind(this), null, true);
},
However as the app grows the code is getting messy. Do you think it would be better to import paper-dialog in subviews and show them from there?
2) I am not sure what is the most effective way to pass the data between views. I have a registration-view which contains iron-pages. In iron-pages there is a step1, step2 and step3 view. In the last step I need to save the data into the database.
I was thinking I could save the data in a parent view (for example by using this.domHost.step1 = data) and process them in the last step. Or would it be better to pass the data directly from view to view or maybe to use the iron-meta tag?
3) SOLVED: Event firing vs direct function call.
I wonder if it's better to just call the function in parent element (for example by calling this.domHost.showDialog()) or if I should fire the event and catch it when needed.
I think that from a performance perspective the direct function call would be better (no event bubbling) but the code seems to be less clear and the advantage of event firing is that I don't need to pass the reference to a children deeper in a DOM tree.
EDIT:
I found an answer for the 3rd question. I should have searched better.
Thanks in advance, Jan
A:
What I have tended to do is make pairs of elements. For instance I have a <file-location> element and a <file-location-dialog> element. I am using <file-location> in dom-repeat templates and so there are many copies of this element and I then locate the <file-location-dialog> is some surrounding element at the top, so there is only one of them.
These elements communication with each other via custom events, the <file-location> element dispatches a file-location-request bubbling event on itself. The <file-location-dialog> listens to this event on its domHost and sets an internal dialogs positionTarget property to event.path[0] of the event. Any data a need to use to populate the dialog comes in that event.
When the dialog closes with an affirmative action I dispatch a non bubbling event back at the positionTarget with updated data.
I do need a lock to prevent two elements opening the same dialog at the same time.
I have only tested this with Polymer 1.0, but the events pierce the shadow dom in both directions without problems - and my reading of the web components v1.0 spec seems that I might need to change event.path[0] to event.composedPath()[0] and ensure the shadow doms are "open" (recommended anyway)
By making them in pairs, I can use a similar design model for each pair, but have custom data pass between them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to load balancing between AWS and Rackspace?
I have a SaaS product hosted on AWS and I would like to have the same infrastructure hosted on Rackspace (or any other host) to offer a high availability (eventually load balancing) for my users in case AWS becomes out.
Someone has any tips to do it? The best way is use a DNS load balancer?
Thank you all in advance
A:
A variety of methods can be used to achieve this. Usually a combination of DNS load balancing and load balancers is the approach that is applied. Allows you to have multiple layers of redundancy, my simple flow diagram:
User -> DNS Response (multiple IPs, makes sure you get a response from a respective cloud provider) -> Load Balancer (such as ELB or HAproxy, makes sure your cloud servers are up) -> cloud server
simple example of a walkthrough: http://blog.rightscale.com/enterprise-cloud-strategies/dns-load-balancing-and-using-multiple-load-balancers-cloud
A solution I have also used before is using CDN to handle DNS responses and dynamically manage traffic across multiple data centers or cloud providers. Akamai does this using global traffic management: http://www.akamai.com/html/solutions/gtm.html
edit: I did forget to mention that with DNS load balancing can provide some interesting behavior based on how upstream servers cache DNS responses, sometimes ISPs (cough comcast, at&t cough, they have gotten better) and other client DNS servers don't follow TTLs you define (the blog I linked mentioned this, but I can't hammer this home enough). Usually this isn't a major problem, but something to consider if you actually run into an issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET MVC models when using external web services
I'm getting started on a new MVC project where there are some peculiar rules and a little bit of strangeness, and it has me puzzled. Specifically, I have access to a database containing all of my data, but it has to be handled entirely through an external web service. Don't ask me why, I don't understand the reasons. That's just how it is.
So the CRUD will be handled via this API. I'm planning on creating a service layer that will wrap up all the calls, but I'm having trouble wrapping my head around the model... To create my model-based domain objects (customers, orders, so on..) should I:
Create them all manually
Create a dummy database and point an ORM at it
Point an ORM at the existing database but ignore the ORM's persistence in lieu of the API.
I feel like I've got all the information I need to build this out, but I'm getting caught up with the API. Any pointers or advice would be greatly appreciated.
A:
Depending on the scale of what you're doing option 3 is dangerous as you're assuming the database model is the same as that exposed by the external service. Options 1 and 2 aren't IMHO much different from each other - in either case you'll have to decide what your objects, properties and behaviours are going to be - it just boils down to whether you're more comfortable doing it in classes or database tables.
The key thing is to make sure that the external service calls are hidden behind some sort of wrapper. Personally I'd then put a repository on top of that to handle querying the external service wrapper and return domain objects.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up a many-to-many relationship based off of two other many-to-many relationships
I have 3 main top level entities:
Project (PK: Id)
Owner (PK: Id)
Product (PK: Id)
Here are the rules:
A Project can have many Owners. An Owner can have many Projects.
A Project can have many Products. A Product can have many Projects.
This is the part that is confusing me:
A ProjectOwner can have many ProjectProducts and a ProjectProduct can have many ProjectOwners.
Here is how I currently have it setup (w/ two additional tables besides the ones above):
ProjectOwner (PK: ProjectId, PK: OwnerId)
ProjectProductOwner (PK: ProjectId, PK: ProductId, PK: OwnerId)
I am trying to figure out if I am following best practice with this because something seems strange. For some reason I feel like I should have this broken out into 3 tables (ProjectOwner, ProjectProduct, ProjectOwnerProduct).
Just to give you an idea of how things will be saved in the application it will be as follows:
User creates a Project. User creates Owners and during this process they add them to the project. User adds multiple Products to the Project and associates them with Project Owners from the previous step.
A:
It looks like you're almost where you want to be. I typically design those linking tables a bit differently, as well, because I don't like compound PKs and that may not be a "best practice" as much as a personal preference:
Primary Tables:
Create Table Projects (
ProjectID int not null identity(1,1) primary key,
ProjectName nvarchar(2000) not null,
StartDate datetime2,
FinishDate datetime2
-- Other fields here
)
Create Table People (
PersonID int not null identity(1,1) primary key,
PersonName nvarchar(2000) not null,
CreateDate Datetime2
--other fields here
)
Create Table Products (
ProductID int not null identity(1,1) primary key,
ProductName nvarchar(2000) not null,
CreateDate datetime2
--other fields here
)
Linking Tables:
Create Table ProjectManagers (
ProjectManagerID int not null identity(1,1) primary key,
ProjectID int not null,
PersonID int not null, --this is the manager
-- other fields here
Constraint FK_ProjectManager_Project Foreign Key (ProjectID) References Projects (ProjectID),
Constraint FK_ProjectManager_Owner Foreign Key (PersonID) References People (PersonID)
)
Create Table ProjectProducts (
ProjectProductID int not null identity(1,1) primary key,
ProjectID int not null,
ProductID int not null,
-- other fields here
Constraint FK_PRojectProduct_Project Foreign Key (ProjectID) References Projects (ProjectID),
Constraint FK_PRojectProduct_Product Foreign Key (ProductID) References Products (ProductID)
)
Create Table ProductOwners (
ProductOwnerID int not null identity(1,1) primary key,
ProductID int not null,
PersonID int not null, --the owner
-- other fields...
Constraint FK_ProductOwner_Owner Foreign Key (PersonID) References People (PersonID)
)
And now let's put some data in...
Insert into projects (ProjectName, StartDate) values ('Project 1', SYSDATETIME());
Insert into projects (ProjectName, StartDate) values ('Project 2', SYSDATETIME());
Insert into projects (ProjectName, StartDate) values ('Project 3', SYSDATETIME());
insert into People (PersonName, CreateDate) values ('Alan Alda', SYSDATETIME());
insert into People (PersonName, CreateDate) values ('Ben Bova', SYSDATETIME());
insert into People (PersonName, CreateDate) values ('Claire Collins', SYSDATETIME());
Insert into Products (ProductName, CreateDate) values ('1 product', SYSDATETIME());
Insert into Products (ProductName, CreateDate) values ('2 product', SYSDATETIME());
Insert into Products (ProductName, CreateDate) values ('3 product', SYSDATETIME());
Insert into Products (ProductName, CreateDate) values ('4 product', SYSDATETIME());
And now let's link these together.
Insert Into ProjectManagers (ProjectID, PersonID) values (1, 1);
Insert Into ProjectManagers (ProjectID, PersonID) values (1, 2);
Insert Into ProjectManagers (ProjectID, PersonID) values (2, 1);
Insert Into ProjectManagers (ProjectID, PersonID) values (3, 3);
Insert into projectproducts (projectid, productid) values (1, 1)
Insert into projectproducts (projectid, productid) values (2, 1)
Insert into projectproducts (projectid, productid) values (3, 1)
Insert into projectproducts (projectid, productid) values (2, 2)
Insert into projectproducts (projectid, productid) values (3, 3)
Insert into projectproducts (projectid, productid) values (1, 4)
Insert into projectproducts (projectid, productid) values (2, 4)
Insert into projectproducts (projectid, productid) values (3, 4)
Insert Into ProductOwners (ProductID, PersonID) values (1, 1)
Insert Into ProductOwners (ProductID, PersonID) values (1, 3)
Insert Into ProductOwners (ProductID, PersonID) values (3, 1)
Insert Into ProductOwners (ProductID, PersonID) values (1, 2)
So now you can link a product up to a project and from there down to the owners or vice versa.
select proj.ProjectName, peMgr.PersonName [Proj Manager], prod.ProductName, peOwn.PersonName [Product Owner]
from projects proj
left join ProjectManagers pm on pm.ProjectID = proj.ProjectID
left join ProjectProducts pp on pp.ProjectID = proj.ProjectID
left join people peMgr on peMgr.personID = pm.personID
left join Products prod on prod.ProductID = pp.ProductID
left join ProductOwners po on po.ProductID = prod.ProductID
left join people peOwn on peOwn.PersonID = po.PersonID
order by 1, 2, 3
This gives us :
ProjectName | Proj Manager | Product | Product Owner
Project 1 | Alan Alda | 1 product | Alan Alda
Project 1 | Alan Alda | 1 product | Alan Alda
Project 1 | Alan Alda | 1 product | Ben Bova
Project 1 | Alan Alda | 1 product | Ben Bova
Project 1 | Alan Alda | 1 product | Claire Collins
Project 1 | Alan Alda | 1 product | Claire Collins
Project 1 | Ben Bova | 1 product | Alan Alda
Project 1 | Ben Bova | 1 product | Alan Alda
Project 1 | Ben Bova | 1 product | Ben Bova
Project 1 | Ben Bova | 1 product | Ben Bova
Project 1 | Ben Bova | 1 product | Claire Collins
Project 1 | Ben Bova | 1 product | Claire Collins
Project 2 | Alan Alda | 2 product | NULL
Project 2 | Alan Alda | 2 product | NULL
Project 2 | Alan Alda | 2 product | NULL
Project 3 | Claire Collins | 3 product | Alan Alda
Project 3 | Claire Collins | 3 product | Alan Alda
Project 3 | Claire Collins | 3 product | Alan Alda
Similar queries can reverse that to show the owners and their products or other combinations. Some XML work can be used to turn this into comma-separated lists instead of more rows...
| {
"pile_set_name": "StackExchange"
} |
Q:
One way among different expressions of "subset()" function failed in R
I found in the Help file of subset() that different syntax occur for the "selection" or "inverse selection". Specifically, in "selection" example, the columns's name are surrounded by c(), but in "inverse selection", there is no c(). In addition, they both don't have quatation mark. So I tried some different syntax:
## For `selection`
# standard usage in Help
subset(airquality, select = c(Temp))
# some different syntax
# (1a) add quotation mark: worked
subset(airquality, select = c("Temp"))
# (2a) remove "c()": worked
subset(airquality, select = Temp)
## For `inverse selection`
# standard usage in Help
subset(airquality, select = -Temp)
# some different syntax
# (1b) add "c()": worked
subset(airquality, select = -c(Temp))
# (2b) add quotation mark: failed
# Error in -c("Temp") : invalid argument to unary operator
subset(airquality, select = -c("Temp"))
These non-standard usage all worked, except the last example. The last example generated an error: Error in -c("Temp") : invalid argument to unary operator
I have two questions:
(1) Why does this error occur? Because in (1a) and (2b), these two non-standard usage seems the same, but (1a) succeeded, while (2b) failed.
(2) Could someone tell me when should I use c(), or "" in c()?
A:
So I dug into the source function of subset:
subset <- function(df, vars) {
vars <- substitute(vars)
var_pos <- setNames(as.list(seq_along(df)), names(df))
pos <- eval(vars, var_pos)
df[, pos, drop = FALSE]
}
The key issue here is how pos is evaluated inside subset function.
In our case, we have df = airquality, vars = c(Temp), vars = c("Temp"),vars = Temp, vars = -Temp, vars = -c(Temp) and vars = -c("Temp")
Let's explicitly evaluate function subset line-by-line for vars = "Temp" and vars = -"Temp":
vars <- substitute("Temp")
> vars
[1] "Temp"
var_pos <- setNames(as.list(seq_along(airquality)), names(airquality))
> var_pos
$Ozone
[1] 1
$Solar.R
[1] 2
$Wind
[1] 3
$Temp
[1] 4
$Month
[1] 5
$Day
[1] 6
pos <- eval(vars, var_pos)
> pos
[1] "Temp"
df <- airquality[, pos, drop = FALSE]
> head(df)
Temp
1 67
2 72
3 74
4 62
5 56
6 66
This evaluated fine since there is no operation applied on "Temp". However, if we try with input -"Temp", we get the following:
vars <- substitute(-"Temp")
> vars
-"Temp"
var_pos <- setNames(as.list(seq_along(airquality)), names(airquality))
> var_pos
$Ozone
[1] 1
$Solar.R
[1] 2
$Wind
[1] 3
$Temp
[1] 4
$Month
[1] 5
$Day
[1] 6
pos <- eval(vars, var_pos)
Error in -"Temp": invalid argument to unary operator
We receive this error because eval should be an operation with only one operand, that is it requires a single input while in this case, we basically supply two operands, i.e. mathematically speaking we do: f:(-1) x 'Temp' -> var_pos.
So one might ask why then input -Temp works.
Let's see what the output of pos is in that case:
vars <- substitute(-Temp)
> vars
-Temp
var_pos <- setNames(as.list(seq_along(airquality)), names(airquality))
pos <- eval(vars, var_pos)
> pos
[1] -4
Here we have pos which is -4 so we can drop the fourth column from our data frame.
df <- airquality[, pos, drop = FALSE]
> head(df)
Ozone Solar.R Wind Month Day
1 41 190 7.4 5 1
2 36 118 8.0 5 2
3 12 149 12.6 5 3
4 18 313 11.5 5 4
5 NA NA 14.3 5 5
6 28 NA 14.9 5 6
| {
"pile_set_name": "StackExchange"
} |
Q:
Extending relation to be transitive
I am lookign for an easy "algorithm" to extend relation (add some elements to it) to be transitive, say I use matrix representation of relation is there any trick that can help me to say if it is transitive or not?
A:
I am assuming you have a finite set $\{x_1,\dots,x_n\}$ and your matrix is $(m_{ij})$ where $m_{ij}=1$ if $x_i \sim x_j$ and $0$ otherwise. Consider squaring the matrix. You end up with the matrix $(n_{ij})$ where
$$n_{ij} = \sum_{k=1}^n m_{ik}m_{kj}.$$
The term $n_{ij}$ will be zero unless there exists at least one $k$ such that $m_{ik}=m_{kj}=1$. In this case, $n_{ij}\geq 1$. The fact that $m_{ik}=m_{kj}=1$ means $x_i \sim x_k$ and $x_k \sim x_j$. If you want to extend your relation to be transitive, this means you need to add the relation $x_i\sim x_j$. So to figure out which relations need to be added, square the matrix and add relations corresponding to any nonzero entries in the squared matrix (unless they are already in the relation). Since this adds elements to the relation, the process must be repeated for the new relation matrix to account for additional relations that will then need to be added. Eventually you'll reach a step where there is nothing new to add (all the nonzero elements of the squared matrix correspond to elements already in the relation), and then you know you're done.
| {
"pile_set_name": "StackExchange"
} |
Q:
are needsDisplayForKey/actionForKey overrides working correctly?
I'm trying to convert some code that works in Objective-C to Swift. The problem I'm running into is that needsDisplayForKey/actionForKey aren't getting called the same way. As far as I can tell, the custom key values aren't getting passed in correctly. Here is what I get when I debug it:
default value:
(String!) event = {
core = {
_baseAddress = Builtin.RawPointer = 0x00feee51 "onOrderIn"
_countAndFlags = 1073741833
_owner = Some {
Some = (instance_type = Builtin.RawPointer = 0x01026348 @"onOrderIn")
}
}
}
custom value (empty string passed in):
(String!) event = {
core = {
_baseAddress = Builtin.RawPointer = 0x0b418f79
_countAndFlags = 1073741833
_owner = Some {
Some = (instance_type = Builtin.RawPointer = 0x0b418f70 -> 0x006e38f0 (void *)0x006e38c8: __NSCFString)
}
}
}
I'm not sure what the relevant code might be. I'll just ask - has anyone else was able to define a custom implicit animation in Swift? Is there anything I need to keep in mind when moving over from Objective C?
override class func needsDisplayForKey(key: String!) -> Bool{
if key == "angleFrom" || key == "angleTo" {
return true;
}
return super.needsDisplayForKey(key)
}
override func actionForKey(event: String!) -> CAAction!{
if event == "angleFrom" || event == "angleTo" {
return self.makeAnimationForKey(event)
}
return super.actionForKey(event)
}
A:
I got this working in Swift by using @NSManaged attribute in front of the variable declaration (where you would use the the @dynamic attribute in Objective-C)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to turn a git repository into a subdirectory of a new repo?
It turns out a git repo I created betters suits as subdirectory, say module x, of a more general repository. How can I copy the original history (no signed commits) over such that now all the paths have the prefix module x\?
I could of course simply make moving everything into that subdirectory a new commit, but I'd prefer a solution that makes history look as if the former repo was always in the subdirectory.
I tried git subtree add --prefix="module x" ../module_x master from a temporary parallel folder with a fresh repository (since otherwise git subtree complains about the already existing prefix), but end up with
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
Working tree has modifications. Cannot add.
This seems to be due to the lack of an initial commit, because if I
touch .gitignore
git add .gitignore
git commit -m"Init"
it works, but I end up with the original history in a separate branch plus a commit of moving, so just the manual solution I mentioned before...
A:
git filter-branch --tree-filter 'mkdir -p module_x; mv all the files and* module_x/' HEAD
Did the trick. I'm using msysgit, but I guess in Linux shopt -s extglob; mv !(module_x) module_x/ should work even better...
If the files explicitly mentioned have not existed through the entire history, you may have to trick a bit and append ; true to the --tree-filter such that mv's non-zero exit code is ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java fails to parse a hex string as an int
Can someone tell me why this code throws an Exception?
int value = 0xabcdef01;
System.out.println(value); // prints -1412567295
String hex = Integer.toHexString(value);
System.out.println(hex); // prints abcdef01
// why does this line fail?
Integer.parseInt(hex, 16);
This code throws the following exception:
java.lang.NumberFormatException: For input string: "abcdef01"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
I'm running on Windows 7 with the following JDK
java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)
A:
As you are using Java 8, consider the Integer.parseUnsignedInt method:
Integer.parseUnsignedInt(hex, 16);
| {
"pile_set_name": "StackExchange"
} |
Q:
Product filtering like shopping sites
I want to make a filter for my products like we do in shopping sites as like for prices, type etc.
Code i am using:
if($_GET['fname'] == "") {
$url = "try5.php?fname=".$_POST['getme'];
header("Location:$url");
}
else {
$url = "try5.php?fname=".$_GET['fname'].",".$_POST['getme'];
header("Location:$url");
}
And also want to be that item selected by getting its name from url, but didint get good results.
A:
That'll have to be done in your SQL.
if(isset($_POST['getme']))
{
$item_name = mysql_real_escape_string($_POST['getme']);
$sql = "SELECT * FROM items WHERE `itemname`='$item_name';";
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Will changing class make any difference when importing a character?
Will importing a Mass Effect 2 character and changing class (e.g. ME2:Soldier -> ME3:Engineer) make any difference? Will it be without any penalties?
A:
The answer is it makes no difference if you change class. When you land on Mars you start with a clean ability slate and can spend your imported ability points on whichever skills your want.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.