text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: UML-XMI to XML conversion using XSLT I am trying to convert .UML (in XMI format) file to XML file by writing xslt code. I am novice at this and would be happy if you can help me understand better. Currently I am only trying to read 1 or 2 elements the input and print an XML output with those elements.
XMI-UML input file
<?xml version="1.0" encoding="UTF-8"?>
<uml:Model xmi:version="20110701" xmlns:xmi="http://www.omg.org/spec/XMI/20110701" xmlns:uml="http://www.eclipse.org/uml2/4.0.0/UML" xmi:id="_OlYJkC9-EeWyX7UKkcyxiw" name="model">
<packagedElement xmi:type="uml:Activity" xmi:id="_OlYJkS9-EeWyX7UKkcyxiw" name="Activity1" node="_XjLyEC9-EeWyX7UKkcyxiw _ZfIhYC9-EeWyX7UKkcyxiw _cK4V8C9-EeWyX7UKkcyxiw _fE2zwC9-EeWyX7UKkcyxiw _F67sgC9_EeWyX7UKkcyxiw">
<edge xmi:type="uml:ControlFlow" xmi:id="_jzMLIC9-EeWyX7UKkcyxiw" name="ControlFlow" source="_XjLyEC9-EeWyX7UKkcyxiw" target="_ZfIhYC9-EeWyX7UKkcyxiw"/>
<edge xmi:type="uml:ControlFlow" xmi:id="_lieXcC9-EeWyX7UKkcyxiw" name="ControlFlow1" source="_ZfIhYC9-EeWyX7UKkcyxiw" target="_cK4V8C9-EeWyX7UKkcyxiw"/>
<node xmi:type="uml:InitialNode" xmi:id="_XjLyEC9-EeWyX7UKkcyxiw" name="Start" outgoing="_jzMLIC9-EeWyX7UKkcyxiw"/>
<node xmi:type="uml:OpaqueAction" xmi:id="_ZfIhYC9-EeWyX7UKkcyxiw" name="Load and Enable Timer" visibility="package" outgoing="_lieXcC9-EeWyX7UKkcyxiw" incoming="_jzMLIC9-EeWyX7UKkcyxiw"/>
<inputValue xmi:type="uml:ActionInputPin" xmi:id="_82lIMDRBEeWdiarL2UAMaQ" name="interrupt">
<upperBound xmi:type="uml:LiteralInteger" xmi:id="_82lIMTRBEeWdiarL2UAMaQ" value="1"/>
</inputValue>
</node>
<node xmi:type="uml:ActivityFinalNode" xmi:id="_F67sgC9_EeWyX7UKkcyxiw" name="ActivityFinalNode" incoming="_Hcj3UC9_EeWyX7UKkcyxiw"/>
</packagedElement>
</uml:Model>
XSLT code
<xsl:stylesheet version="1.0" xmlns:UML="org.omg.xmi.namespace.UML" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<root>
<xsl:apply-templates />
</root>
</xsl:template>
<xsl:template match="/uml:Model/packagedElement/edge/">
<xsl:element name="uml:ControlFlow">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
Expected output (Only an example.. It can also contain the "node" from input)
<?xml version='1.0' encoding='UTF-8'?>
<sdf3 type='sadf' version='1.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='uri:sadf' xsi:schemaLocation='some_random_location'>
<sadf name='RandomGraphName'>
<structure>
<edge name='ControlFlow1' source='_ZfIhYC9-EeWyX7UKkcyxiw' target='_cK4V8C9-EeWyX7UKkcyxiw' />
</structure>
</sadf>
</sdf3>
A: From the looks of it, an "UML-XMI" is still an XML document, but as mentioned in the comments, it is not well-formed. The issue is with this node element
<node xmi:type="uml:OpaqueAction" xmi:id="_ZfIhYC9-EeWyX7UKkcyxiw" name="Load and Enable Timer" visibility="package" outgoing="_lieXcC9-EeWyX7UKkcyxiw" incoming="_jzMLIC9-EeWyX7UKkcyxiw"/>
<inputValue xmi:type="uml:ActionInputPin" xmi:id="_82lIMDRBEeWdiarL2UAMaQ" name="interrupt">
<upperBound xmi:type="uml:LiteralInteger" xmi:id="_82lIMTRBEeWdiarL2UAMaQ" value="1"/>
</inputValue>
</node>
If you scroll to the right, the node tag is self-closed (i.e, it ends with />), this means the closing </node> tag doesn't actually match anything.
But assuming it was well-formed, the first issue with your XSLT is with namespaces. In your XML the namespace is defined like this:
xmlns:uml="http://www.eclipse.org/uml2/4.0.0/UML"
But in your XSLT you have defined it like this
xmlns:UML="org.omg.xmi.namespace.UML"
The prefix don't have to match between XML and XSLT, but the namespace URI does. Additionally, if your XSLT when you use the namespace prefix, you are using it in lower-case
<xsl:template match="/uml:Model/packagedElement/edge/">
It is case-sensitive though, so uml won't correspond to the UML which you have defined. The prefix doesn't need to match the XML, but it does need to match the one defined in the XSLT.
Additionally, that template match is also not syntactically correct because it ends with an / symbol. That needs to be removed.
Although I am not quite clear what output you actually want, try this XSLT to get you on your way:
<xsl:stylesheet version="1.0" xmlns:UML="http://www.eclipse.org/uml2/4.0.0/UML" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns='uri:sadf' exclude-result-prefixes="UML">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/UML:Model">
<sdf3 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='some_random_location' type='sadf'>
<sadf name='RandomGraphName'>
<xsl:apply-templates />
</sadf>
</sdf3>
</xsl:template>
<xsl:template match="packagedElement">
<structure>
<xsl:apply-templates select="edge" />
</structure>
</xsl:template>
<xsl:template match="edge">
<edge name="{@name}" source="{@source}" />
</xsl:template>
</xsl:stylesheet>
Note the use of a default namespace in the XSLT xmlns='uri:sadf'. This means all elements, which don't have a namespace, will be output in that namespace.
Also note, you don't necessarily need to code the full path to child elements such as packagedElement and edge.
But given the following well-formed input:
<uml:Model xmi:version="20110701" xmlns:xmi="http://www.omg.org/spec/XMI/20110701" xmlns:uml="http://www.eclipse.org/uml2/4.0.0/UML" xmi:id="_OlYJkC9-EeWyX7UKkcyxiw" name="model">
<packagedElement xmi:type="uml:Activity" xmi:id="_OlYJkS9-EeWyX7UKkcyxiw" name="Activity1" node="_XjLyEC9-EeWyX7UKkcyxiw _ZfIhYC9-EeWyX7UKkcyxiw _cK4V8C9-EeWyX7UKkcyxiw _fE2zwC9-EeWyX7UKkcyxiw _F67sgC9_EeWyX7UKkcyxiw">
<edge xmi:type="uml:ControlFlow" xmi:id="_jzMLIC9-EeWyX7UKkcyxiw" name="ControlFlow" source="_XjLyEC9-EeWyX7UKkcyxiw" target="_ZfIhYC9-EeWyX7UKkcyxiw"/>
<edge xmi:type="uml:ControlFlow" xmi:id="_lieXcC9-EeWyX7UKkcyxiw" name="ControlFlow1" source="_ZfIhYC9-EeWyX7UKkcyxiw" target="_cK4V8C9-EeWyX7UKkcyxiw"/>
<node xmi:type="uml:InitialNode" xmi:id="_XjLyEC9-EeWyX7UKkcyxiw" name="Start" outgoing="_jzMLIC9-EeWyX7UKkcyxiw"/>
<node xmi:type="uml:OpaqueAction" xmi:id="_ZfIhYC9-EeWyX7UKkcyxiw" name="Load and Enable Timer" visibility="package" outgoing="_lieXcC9-EeWyX7UKkcyxiw" incoming="_jzMLIC9-EeWyX7UKkcyxiw">
<inputValue xmi:type="uml:ActionInputPin" xmi:id="_82lIMDRBEeWdiarL2UAMaQ" name="interrupt">
<upperBound xmi:type="uml:LiteralInteger" xmi:id="_82lIMTRBEeWdiarL2UAMaQ" value="1"/>
</inputValue>
</node>
<node xmi:type="uml:ActivityFinalNode" xmi:id="_F67sgC9_EeWyX7UKkcyxiw" name="ActivityFinalNode" incoming="_Hcj3UC9_EeWyX7UKkcyxiw"/>
</packagedElement>
</uml:Model>
The following is output
<sdf3 xmlns="uri:sadf" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="some_random_location"
type="sadf">
<sadf name="RandomGraphName">
<structure>
<edge name="ControlFlow" source="_XjLyEC9-EeWyX7UKkcyxiw"/>
<edge name="ControlFlow1" source="_ZfIhYC9-EeWyX7UKkcyxiw"/>
</structure>
</sadf>
</sdf3>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32009214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restrict character/string/word in input My function, addthisTxt, is not checking the length. It should not exceed 11. Below is what I have tried so far; I'd like to keep on adding text until it reaches the max length, otherwise it should restrict the user from adding more.
HTML
<input type="checkbox" name="chkbxr" value="add this offer on wrapper"
(change)="addthisTxt($event.target.getAttribute('txt'), $event.target.checked)">
JavaScript
addthisTxt(txt, checked): void {
if (checked) {
if((this.v.offerName.length +txt.length) >= 55){
this.v.offerName = this.v.offerName + txt;
}
this.v.offerName = this.v.offerName;
}
}
A: You are setting the value on this.v.offerName. The UI element is not bound to this JavaScript variable and you need to set the value of the UI input element to restrict the value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45080436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twitter iframe widget remove scrollbar Been trying to figure out how to remove the scrollbar in the iframe twitter widget. I know I can't do it with css so my next look was with jquery tried the following but doesn't seem to work
$("iframe").ready(function () {
$(".stream", this).css("overflow-x", "hidden");
});
A: You can use css to disable it. I used this plug in (https://github.com/kevinburke/customize-twitter-1.1) to override twitters css and then just added:
.timeline .stream {overflow:hidden;}
I also hide the scrollbars by adding the same css directly into a locally stored copy of the twitter widget.js (around line 30).
A: Simple solution
Set the scrolling attribute to no in your iframe tag. like this:
scrolling="no"
Full iframe example:
<iframe scrolling="no" title="Twitter Tweet Button" style="border:0;overflow:hidden;" src="https://platform.twitter.com/widgets/tweet_button.html" height="28px" width="76px"></iframe>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15626846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: UIPanGestureRecognizer manually start gesture I have a bunch of views setup on the screen and by using touchesBegan: and touchesMoved: overrides in my main view, I let the user drag around the screen and track the position. When a user hovers over one of the views, I want that view to start a pan gesture recognizer from it's center.
From testing I've seen that when a pan gesture is active, the touchesBegan: and touchesMoved: methods don't get called, which is perfect for my case where I want them to drag over to the view and then that view handles the gesture.
Everything works fine except I can't seem to find a way to start the pan gesture when the user hovers over the view. Even if I call touchesBegan: on that view it doesn't get fooled into thinking the user just tapped and it should start the gesture recognizer.
Do you guys know any way of manually triggering the start of a pan gesture recognizer?
By start I mean manually making the pan gesture think the user just tapped and for the pan gesture to start tracking the touches and movement
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24913019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to show a message text on the chart of Billboard.js? I'm working with Biilboard.js, a library which is based on D3.
I created a chart and I want to be able to show a message on it, for example if Y-axis is greater than 100 or anything like this, doesn't matter the condition.
This is an example of what I want which is done with pure D3 (I guess):
Basically, if that condition is fulfilled, that message box appears over the chart.
Do you have any ideas of to do this?
A: There're several ways to do that.
*
*1) Add y Axis grid text
*2) Simply, add some normal DOM element(ex. div, etc.) and handle it to be positioned over chart element
I'll try put some example using the first one and check for the ygrids() API doc.
// variable to hold min and max value
var min;
var max;
var chart = bb.generate({
data: {
columns: [
["sample", 30, 200, 100, 400, 150, 250]
],
onmin: function(data) {
min = data[0].value;
},
onmax: function(data) {
max = data[0].value;
}
}
});
// add y grids with deterimined css classes to style texts added
chart.ygrids([
{value: min, text: "Value is smaller than Y max", position: "start", class: "min"},
{value: max, text: "Value is greater than Y max", position: "start", class: "max"}
]);
/* to hide grid line */
.min line, .max line{
display:none;
}
/* text styling */
.min text, .max text{
font-size:20px;
transform: translateX(10px);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css" />
<script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.pkgd.min.js"></script>
<title>billboard.js</title>
</head>
<body>
<div id="chart"></div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48784703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bootstrap-Table loading by Json I'm trying to reproduce it this example, but when I download files and try to play in local, not shown me the table, only show me the header, the title an two buttons (learn more and delete)
http://issues.wenzhixin.net.cn/bootstrap-table/index.html
HTML:
<table id="table"
data-side-pagination="server"
data-sort="desc"
data-url="json/data1.json"
>
</table>
JS:
$('#table').bootstrapTable({
url: 'json/data1.json',
columns: [{
field: 'id',
title: 'Item ID'
}, {
field: 'name',
title: 'Item Name'
}, {
field: 'price',
title: 'Item Price'
}, ]
});
JSON
[
{
"id": 0,
"name": "Item 0",
"price": "$0"
},
{
"id": 1,
"name": "Item 1",
"price": "$1"
},
{
"id": 2,
"name": "Item 2",
"price": "$2"
},
{
"id": 3,
"name": "Item 3",
"price": "$3"
},
{
"id": 4,
"name": "Item 4",
"price": "$4"
},
{
"id": 5,
"name": "Item 5",
"price": "$5"
}
]
I copied the folder bootstrap-table the bootstrap-table.js file because when I download the example was not in that folder.
someone could help me to know how to show table please
thanx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34771466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this the "good" way to implement a 6502 CPU emulator in JAVA? Wanting to make sure I won't have to go back and redo large chunks of code... I have each opcode as a value in an enum that implements Runnable. Is there a more efficient way that I should do this or am I on the write track to getting something that runs a testsuite rom accurately?
package com.codeblox.nes.cpu;
public class CPU {
private byte x, y, ac, pcl, pch;
private short pc;
private boolean debugEnabled = false, isGood = true;
private static byte [] mainMem = new byte [0x10000];
public Opcode opcode;
CPU(boolean debugEnabled){
opcode =Opcode.nop;
pc = 0;
this.debugEnabled = debugEnabled;
}
public enum Opcode implements Runnable{
adc(){public void run(){System.out.println("adc");}},
and(){public void run(){System.out.println("and");}},
asl(){public void run(){System.out.println("asl");}},
bcc(){public void run(){System.out.println("bcc");}},
bcs(){public void run(){System.out.println("bcs");}},
beq(){public void run(){System.out.println("beq");}},
bit(){public void run(){System.out.println("bit");}},
bmi(){public void run(){System.out.println("bmi");}},
bne(){public void run(){System.out.println("bne");}},
bpl(){public void run(){System.out.println("bpl");}},
brk(){public void run(){System.out.println("brk");}},
bvc(){public void run(){System.out.println("bvc");}},
bvs(){public void run(){System.out.println("bvs");}},
clc(){public void run(){System.out.println("clc");}},
cld(){public void run(){System.out.println("cld");}},
cli(){public void run(){System.out.println("cli");}},
clv(){public void run(){System.out.println("clv");}},
cmp(){public void run(){System.out.println("cmp");}},
cpx(){public void run(){System.out.println("cpx");}},
cpy(){public void run(){System.out.println("cpy");}},
dec(){public void run(){System.out.println("dec");}},
dex(){public void run(){System.out.println("dex");}},
dey(){public void run(){System.out.println("dey");}},
eor(){public void run(){System.out.println("eor");}},
inc(){public void run(){System.out.println("inc");}},
inx(){public void run(){System.out.println("inx");}},
iny(){public void run(){System.out.println("iny");}},
jmp(){public void run(){System.out.println("jmp");}},
jsr(){public void run(){System.out.println("jsr");}},
lda(){public void run(){System.out.println("lda");}},
ldx(){public void run(){System.out.println("ldx");}},
ldy(){public void run(){System.out.println("ldy");}},
lsr(){public void run(){System.out.println("lsr");}},
nop(){public void run(){System.out.println("nop");}},
ora(){public void run(){System.out.println("ora");}},
pha(){public void run(){System.out.println("pha");}},
php(){public void run(){System.out.println("php");}},
pla(){public void run(){System.out.println("pla");}},
plp(){public void run(){System.out.println("plp");}},
rol(){public void run(){System.out.println("rol");}},
ror(){public void run(){System.out.println("ror");}},
rti(){public void run(){System.out.println("rti");}},
rts(){public void run(){System.out.println("rts");}},
sbc(){public void run(){System.out.println("sbc");}},
sec(){public void run(){System.out.println("sec");}},
sed(){public void run(){System.out.println("sed");}},
sei(){public void run(){System.out.println("sei");}},
sta(){public void run(){System.out.println("sta");}},
stx(){public void run(){System.out.println("stx");}},
sty(){public void run(){System.out.println("sty");}},
tax(){public void run(){System.out.println("tax");}},
tay(){public void run(){System.out.println("tay");}},
tsx(){public void run(){System.out.println("tsx");}},
txa(){public void run(){System.out.println("txa");}},
txs(){public void run(){System.out.println("txs");}},
tya(){public void run(){System.out.println("tya");}},
;
public String mnemonic = "";
public String addressMode;
public byte code;
public byte data;
Opcode(){
this.mnemonic = new String();
}
public void print(){
System.out.printf("Opcode: %02X %s %s\n",
this.code,
this.mnemonic.toUpperCase(),
this.addressMode);
}
public String getMode00(byte opcode){
switch(opcode){
case 0x00: return "Immediate";
case 0x04: return "ZeroPaged";
case 0x0C: return "Absolute";
case 0x14: return "IndexedZeroPagedX";
case 0x1C: return "IndexedAbsoluteX";
default: return "Type 0 undefined";
}
}
public String getMode01(byte opcode){
switch(opcode){
case 0x00: return "InirectIndexedZeroPagedX";
case 0x04: return "ZeroPaged";
case 0x08: return "Immediate";
case 0x0C: return "Absolute";
case 0x10: return "IndrectedZeroPagedY";
case 0x14: return "IndexedZeroPagedX";
case 0x18: return "IndexedAbsoluteY";
case 0x1C: return "IndexedAbsoluteX";
default: return "Type 1 Undefined";
}
}
public String getMode02(byte opcode){
switch(opcode){
case 0x00: return "Immediate";
case 0x04: return "ZeroPaged";
case 0x08: return "Accumulator";
case 0x0C: return "Absolute";
case 0x14: return "IndexedZeroPagedX";
case 0x1C: return "IndexedAbsoluteX";
default: return "Type 2 Undefined";
}
}
public String getMode03(byte opcode){ return "";}
public void decode(){
switch(this.code & 0x03){
case 0x00: this.addressMode = getMode00((byte)(this.code & 0x1C)); break;
case 0x01: this.addressMode = getMode01((byte)(this.code & 0x1C)); break;
case 0x02: this.addressMode = getMode02((byte)(this.code & 0x1C)); break;
case 0x03: this.addressMode = getMode03((byte)(this.code & 0x1C)); break;
default: break;
}
}
}
public void init(){
pc = 0;
}
public void start(){
while(isGood){
opcode.code = readMem(pc++);
CPU.Opcode.valueOf(opcode.mnemonic).run();
}
if(!isGood){
System.err.println("isGood == false");
}
}
public byte readMem(short ptr){
return mainMem[ptr];
}
public byte readMem(short ptr, byte addressMode){
return mainMem[ptr];
}
public void exec(){
opcode.decode();
switch(opcode.code & 0xFF){
case 0x69: case 0x65: case 0x75:
case 0x6D: case 0x7D: case 0x79:
case 0x61: case 0x71: opcode.mnemonic = "adc"; break;
case 0x29: case 0x25: case 0x35:
case 0x2D: case 0x3D: case 0x39:
case 0x21: case 0x31: opcode.mnemonic = "and"; break;
case 0x0A: case 0x06: case 0x16:
case 0x0E: case 0x1E: opcode.mnemonic = "asl"; break;
default: opcode.mnemonic = null;
}
//Opcodes.valueOf(this.mnemonic).run();
}
public void testOpcodes(){
opcode.code = 0;
while((opcode.code & 0xFF) < 0xFF){
//System.out.printf("PC = 0x%04X \n", PC);
exec();
if(opcode.mnemonic != null)
opcode.print();
//Opcode.valueOf(opcode.mnemonic).run();
opcode.code++;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CPU cpu = new CPU(true);
cpu.init();
cpu.testOpcodes();
}
}
A: Well, I think that's the start of a good way to write a 6502 CPU emulator. But it needs some work ...
Ask yourself: What is an enum in Java? And what is it good for?
It's basically a class with a fixed number of instances, so it's great for representing static data (and behaviour) and grouping that - with associated methods - to be easily visible, testable, modifiable.
In various methods you have switch statements that break out the different addressing modes and operations for each opcode:
switch(opcode) {
case 0x00: return "Immediate";
case 0x04: return "ZeroPaged";
case 0x0C: return "Absolute";
case 0x14: return "IndexedZeroPagedX";
case 0x1C: return "IndexedAbsoluteX";
default: return "Type 0 undefined";
}
And we would have to add more switch statements if we wanted instructions times etc.
But this is static data. Those cases constants should be enum properties. Isn't this the kind of data that should be encoded in the enum? I think so, and so did Brendan Robert, who wrote JACE, the Java Apple Computer Emulator. His code is a great example of a well thought-out Java enum.
Here are the first few lines of his 6502 CPU's OPCODE enum:
public enum OPCODE {
ADC_IMM(0x0069, COMMAND.ADC, MODE.IMMEDIATE, 2),
ADC_ZP(0x0065, COMMAND.ADC, MODE.ZEROPAGE, 3),
ADC_ZP_X(0x0075, COMMAND.ADC, MODE.ZEROPAGE_X, 4),
// ...
}
All the static data is grouped together nicely, easily visible, ready to be used in case statements etc.
A: I can't speak best or worst, I can only speak to what I did.
I have an OpCode class, and I create an instance of this class for each opcode (0-255, undefined opcodes are NOPs on my machine).
My OpCode contains two methods. One represents the addressing mode, the other the actual instruction.
Here's my execute method:
public void execute(CPU cpu) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Integer value = (Integer) addrMethod.invoke(cpu);
opMethod.invoke(cpu, value);
}
I build up my list of OpCodes with a list of strings, such as ORA abs. ORA is mapped to a logic method in my CPU class, and abs is mapped to another addressing method. I use reflecting to lookup the methods and stuff them in to my OpCode instances.
public void ORA(int value) {
acc = acc | value;
setFlagsNZ(acc);
}
public int fetchAbsolute() {
int addr = addrAbsolute();
return fetchByte(addr);
}
addrAbsolute will pull the 2 bytes from memory, and increment the PC by 2, among other things. fetchByte gets the value at the address. The value is then passed in to ORA, which acts on the accumulator.
In the end, I have 256 opcodes with a method for the logic, and a method for the addressing.
The core of my simulator is simply setting the initial address, fetching the opcode from that address, increment the address, the execute the opcode.
int code = mem.fetchByte(pc++);
OpCode op = Instructions.opCodes[code];
op.execute(this);
(this being the CPU instance).
Mind, mine is a soft simulator, it doesn't strive for cycle parity or anything like that. It doesn't simulate any specific hardware (like a C64). It's a raw 6502 with a few dedicated memory locations that I/O to a terminal.
But this is what came out of my little head. I didn't study other simulators, I wasn't motivated to go sussing out bit patterns within the instructions. I just make a table for every possible opcode and what it was supposed to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40708150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is jQuery toggleClass not removing a class? I have made a Skills accordion but I now want to create a button to toggle all the skill sections. When I am doing this, the jQuery isn't removing/adding the class when it needs to on the .accordion-trigger-all.
I originally use .click() but then I changed to .on("click", function) but still no luck.
$(document).ready(function() {
$(".accordion .accordion-trigger.accordion-trigger-single:not(.open) + .skill-container").hide()
$(".accordion .accordion-trigger.accordion-trigger-single").click(function() {
$(this).next(".skill-container").slideToggle()
$(this).toggleClass("open")
allOpen()
})
function allOpen() {
if ($(".skill-container").is(":hidden")) {
$(".accordion .accordion-trigger.accordion-trigger-all h3").html("Open All")
$(".accordion .accordion-trigger.accordion-trigger-all").removeClass("open")
} else {
$(".accordion .accordion-trigger.accordion-trigger-all h3").html("Close All")
$(".accordion .accordion-trigger.accordion-trigger-all").addClass("open")
}
}
allOpen()
//
$(".accordion .accordion-trigger.accordion-trigger-all:not(.open)").on('click', function() {
$(".accordion .accordion-trigger.accordion-trigger-single:not(.open) + .skill-container").slideDown()
$(".accordion .accordion-trigger.accordion-trigger-single:not(.open)").toggleClass("open")
$(".accordion .accordion-trigger.accordion-trigger-all.open h3").html("Close All")
$(".accordion .accordion-trigger.accordion-trigger-all").addClass("open")
allOpen()
})
$(".accordion .accordion-trigger-all.open").on("click", function() {
$(".accordion .accordion-trigger-single.open + .skill-container").slideUp()
$(".accordion .accordion-trigger-single.open").toggleClass("open")
$(".accordion .accordion-trigger.accordion-trigger-all h3").html("Open All")
$(".accordion .accordion-trigger.accordion-trigger-all").removeClass("open")
})
})
.accordion .accordion-trigger {
cursor: pointer;
text-align: left;
width: 100%;
border: none;
color: #9CA3AF;
border-bottom: 3px solid #9CA3AF;
background-color: #F9FAFB;
}
.accordion .accordion-trigger:not(:first-of-type) {
margin-top: 30px;
}
.accordion .accordion-trigger.open {
border-bottom: #059669 3px solid;
background-color: #ECFDF5;
}
.accordion .accordion-trigger h3 {
padding: 6px;
font-weight: initial;
margin: 0;
color: #9CA3AF;
}
.accordion .accordion-trigger.open h3 {
color: #059669;
}
.accordion .skill-container * {
box-sizing: border-box;
}
.accordion .skill {
display: inline-block;
text-align: left;
color: white;
padding: 10px 0 10px 4px;
border-radius: 5px;
background-color: lightgray;
white-space: nowrap;
margin: 10px 0;
overflow: hidden;
position: relative;
z-index: 0;
width: 100%;
}
.accordion .skill::before {
content: "";
position: absolute;
background-color: #312E81;
border-radius: inherit;
z-index: -1;
top: 0;
bottom: 0;
left: 0;
animation: animateLeft 1s ease-out;
width: var(--l);
}
.accordion .skill:nth-child(even)::before {
background-color: #374151;
}
@keyframes animateLeft {
from {
left: -100%
}
to {
left: 0
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordion">
<div class="accordion-trigger accordion-trigger-all">
<h3>Close All</h3>
</div>
<div class="accordion-trigger accordion-trigger-single open">
<h3>Web Essentials</h3>
</div>
<div class="skill-container">
<span class="skill" style="--l:100%;">HTML</span>
<span class="skill" style="--l:70%">CSS</span>
<span class="skill" style="--l:60%">Responsive</span>
</div>
<div class="accordion-trigger accordion-trigger-single open">
<h3>JavaScript Skills</h3>
</div>
<div class="skill-container">
<span class="skill" style="--l:90%">Vanilla JavaScript</span>
<span class="skill" style="--l:80%">jQuery</span>
<span class="skill" style="--l:30%">Google Maps</span>
</div>
<div class="accordion-trigger accordion-trigger-single open">
<h3>Server-Side</h3>
</div>
<div class="skill-container">
<span class="skill" style="--l:50%">PHP</span>
<span class="skill" style="--l:30%">MySQL</span>
</div>
<div class="accordion-trigger accordion-trigger-single open">
<h3>Tools of the Trade</h3>
</div>
<div class="skill-container">
<span class="skill" style="--l:100%">PHPStorm</span>
<span class="skill" style="--l:90%">MAMP</span>
<span class="skill" style="--l:90%">OSX</span>
<span class="skill" style="--l:60%">Git Version Control</span>
</div>
</div>
A: I've figured out the answer for this:
When jQuery loads, it assigns an event handler to the $(".accordion .accordion-trigger-all.open").on('click', function() so at the beginning it only finds whichever is open. However when it searches again it doesn't find the element with the class removed.
Simple solution: $(".accordion").on('click','.accordion-trigger-all.open', function()
which will add the event handler to the whole element, instead of the only the element with the class .open
The same should be done for the opposite: $(".accordion").on('click','.accordion-trigger-all:not(.open)', function()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65850916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Compiler error for lambda expression public ICommand ChangeLangCommand => new DelegateCommand(this.ChangeLangClick);
I get this compiler error, marked on the => arrow:
Error 1 ; expected
Am I using the wrong compiler version somehow? How can I check this?
A: This is a C# 6.0 feature called expression bodied property
public ICommand ChangeLangCommand => new DelegateCommand(this.ChangeLangClick);
You can either upgrade your compiler (install latest release version of VS2015) or don't use it, as it's equal to getter-only property:
public ICommand ChangeLangCommand
{
get
{
return new DelegateCommand(this.ChangeLangClick);
}
}
I have feeling, what creating new instance of the command every time property is accessed is wrong, correct code may/would be
public ICommand ChangeLangCommand { get; }
// in constructor
ChangeLangCommand = new DelegateCommand(this.ChangeLangClick);
I think this is also a new feature (to initialize getter-only property from constructor), if this is true, then you can use older syntax:
ICommand _changeLangCommand;
public ICommand ChangeLangCommand
{
get
{
return _changeLangCommand;
}
}
// in constructor
_changeLangCommand = new DelegateCommand(this.ChangeLangClick);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39225846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to stop the location of one grid element from changing due to the update of the content of another grid element in python tkinter? I have written code for a small python tkinter application which goes as follows
import tkinter as tk
from tkinter import *
import tkinter.filedialog as fdialog
class karl(Frame):
def __init__(self):
tk.Frame.__init__(self)
self.pack(fill = tk.BOTH)
self.master.title("Image Selector")
self.master.geometry("500x500")
self.master.resizable(0, 0)
self.pack_propagate(0)
self.label_button_1 = Label(self, text="Select directory for picking images")
self.label_button_1.grid(row = 0, column = 1, rowspan = 1, columnspan = 2, sticky = W)
self.button_1 = tk.Button(self, text="CLICK HERE", width=25, command=self.open_dialog_box_to_select_folder)
self.button_1.grid(row=0, column=20, rowspan=1, columnspan=2, sticky=E)
self.label_for_label_directory = Label(self, text="Current chosen directory")
self.label_for_label_directory.grid(row=20, column=1, rowspan=1, columnspan=2, sticky=E)
self.label_directory = Label(self, text="")
self.label_directory.grid(row=20, column=5, rowspan=1, columnspan=2, sticky=W)
self.label_for_entry_for_class_label_values = Label(self, text="Enter text")
self.label_for_entry_for_class_label_values.grid(row = 24, column = 1, rowspan = 1, columnspan = 2, sticky = W)
self.entry_for_class_label_values = Entry(self)
self.entry_for_class_label_values.grid(row = 24, column = 5, rowspan = 1, columnspan = 2, sticky = E)
def open_dialog_box_to_select_folder(self):
self.chosen_directory_name = fdialog.askdirectory()
self.label_directory.config(text = self.chosen_directory_name)
def main():
karl().mainloop()
if __name__ == '__main__':
main()
As soon as button_1 is clicked and the label_directory gets updated with the string for directory, the position of button_1 gets pushed towards the right and goes outside the application window. How can I stop this from happening?
A: The problem is that when you are selecting a folder and updating self.label_directory with the String of the path to the selected folder it is manipulating the grid and expanding your Click Here Button.
To fix this issue, firstly button_1 should have a its sticky option set to W, so then it doesn't move to the right side of it's grid cell, when it's grid cells width is manipulated.
Another issue you have is that you are increasing you rows and columns of your grid placement too much, you should only increment by the needed spaces, for example, you should start at row 1 and then place your next row at row 2, this helps make sure it is easy to understand where each element is placed.
With that all said I believe this code will fix the issue suitably:
import tkinter as tk
from tkinter import *
import tkinter.filedialog as fdialog
class karl(Frame):
def __init__(self):
tk.Frame.__init__(self)
self.pack(fill = tk.BOTH)
self.master.title("Image Selector")
self.master.geometry("500x500")
self.master.resizable(0, 0)
self.pack_propagate(0)
self.label_button_1 = Label(self, text="Select directory for picking images")
self.label_button_1.grid(row = 0, column = 0, columnspan = 1, sticky = W)
self.button_1 = tk.Button(self, text="CLICK HERE", width=25, command=self.open_dialog_box_to_select_folder)
self.button_1.grid(row=0, column=1, columnspan=2, sticky=W)
self.label_for_label_directory = Label(self, text="Current chosen directory")
self.label_for_label_directory.grid(row=1, column=0, rowspan=1, columnspan=1, sticky=W)
self.label_directory = Label(self, text="")
self.label_directory.grid(row=1, column=1, rowspan=1, columnspan=2, sticky=W)
self.label_for_entry_for_class_label_values = Label(self, text="Enter (+) seperated class labels\nto be assigned to the images")
self.label_for_entry_for_class_label_values.grid(row = 2, column = 0, rowspan = 1, columnspan = 2, sticky = W)
self.entry_for_class_label_values = Entry(self)
self.entry_for_class_label_values.grid(row = 2, column = 1, rowspan = 1, columnspan = 1, sticky = W)
def open_dialog_box_to_select_folder(self):
self.chosen_directory_name = fdialog.askdirectory()
self.label_directory.config(text = self.chosen_directory_name)
def main():
karl().mainloop()
if __name__ == '__main__':
main()
I changed the elements previously mentioned to accomplish this, if you have any questions about my solution feel free to ask :)
Here is your tkinter program converted to an excel file, to visualize how the grid system works, the light blue is where your path string will be put when you select a folder.
When you select a long file path, the path_label expands (the light blue section of the excel, this will push the click me button to the right. So far right that it will push the button of the windows view-able area like so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56199270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload error I wrote a code to upload images of music and it works ,but when I try to edit older posts (I hadn't add img field yet) It shows following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload
Models.py
class add_music(models.Model):
name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
nation = models.CharField(max_length=100)
language = models.CharField(max_length=100)
year = models.DecimalField(max_digits=4,decimal_places=0,null=True)
genre = models.TextField()
duration = models.DecimalField(max_digits=3,decimal_places=2,null=True)
upload = models.DateTimeField(auto_now_add=True)
img = models.ImageField(blank=True,null=True,upload_to='images/')
def __str__(self):
return self.name.title()+" by "+self.artist
views:
def edit_music_view(request,music_id):
my_object = add_music.objects.get(id=music_id)
if request.method != 'POST':
form = add_music_form(instance=my_object)
else:
form = add_music_form(instance=my_object,data=request.POST)
if form.is_valid():
form.save()
context={'form':form,'my_object':my_object}
return render(request,'pages/edit_music.html',context)
Template file:
{% extends 'pages/base.html' %}
{% block content %}
<p>{{ my_object }}</p>
<form action="{% url 'pages:edit_music' my_object.id %}" method='post' enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="yes">save</button>
</form>
{% endblock %}
What's wrong with it?
A: You can always change that field to:
upload = models.DateTimeField(auto_now_add=True, null=True)
that should fix that problem.
PS you should not name classes with snake_case. It's bad habit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72341413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get data from XML file with javascript I'm learning how to do this with the help of some tutorials but this code is not working. The browser is not displaying anything from the XML file. Is there anything wrong with my code?
Here are the codes:
<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>
<!DOCTYPE html>
<html>
<body>
<div>
<b>FirstName:</b> <span id="FirstName"></span><br>
<b>LastName:</b> <span id="LastName"></span><br>
<b>ContactNo:</b> <span id="ContactNo"></span><br>
<b>Email:</b> <span id="Email"></span>
</div>
<script>
if (window.XMLHttpRequest) {
//if browser supports XMLHttpRequest
// Create an instance of XMLHttpRequest object. code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sets and sends the request for calling "node.xml"
xmlhttp.open("GET","company.xml",false);
xmlhttp.send();
// sets and returns the content as XML DOM
xmlDoc=xmlhttp.responseXML;
//parsing the DOM object
document.getElementById("FirstName").innerHTML=xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue;
document.getElementById("LastName").innerHTML=xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue;
document.getElementById("ContactNo").innerHTML=xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0].nodeValue;
document.getElementById("Email").innerHTML=xmlDoc.getElementsByTagName("Email")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
A: You need to move the xml code into another file. I think you code is correct. I have just moved the xml to a new .xml file named company.xml in the site root directory and it is working fine.
<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>
A: if (window.XMLHttpRequest){ //if browser supports
XMLHttpRequest
{
xmlhttp = new XMLHttpRequest();
}
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
a pair of curly brace missing.
A: I tried the following code, and it is working fine. Hope your code is correct.
You can move the XML data to some other file and check once.
I hope your code should work fine.
function loadFile() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","popup.xml",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
responseData = xmlhttp.responseText;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26836946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create Mojave Cocoa window programmatically in Objective-C I'm trying to create a minimal application in order for me to start a game engine from scratch. Here is the code:
#import <Cocoa/Cocoa.h>
int main (int argc, const char * argv[]){
NSWindow *window = [[NSWindow alloc] init];
[window makeKeyAndOrderFront:nil];
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, false)
while (1);
return 0;
}
I would how to display a window without calling CFRunLoopRunInMode().
Xcode 10.1
MacOS 10.14.3
A: I think I have found the answer myself. The window does not appear unless it receives the nextEventMatchingMask: message. This is probably what triggers the window in a CFRunLoop and is what I wanted to know, although it would be nice if I could dig deeper. For now, I'm happy with the following solution.
#import <Cocoa/Cocoa.h>
int main (int argc, const char * argv[]){
@autoreleasepool {
// Create a default window
NSWindow *window = [[NSWindow alloc] init];
// Make it blue just for better visibility
[window setBackgroundColor:[NSColor blueColor]];
// Bring to front and make it key
[window makeKeyAndOrderFront:nil];
// Custom run loop
NSEvent* event;
while(1) {
do {
event = [window nextEventMatchingMask:NSEventMaskAny]; //window shows now
if ([event type] == NSEventTypeLeftMouseDown) {
NSLog(@"Mouse down");
}
else {
NSLog(@"Something happened");
}
} while (event != nil);
}
}
return 0;
}
I don't have a reference for that. I can only refer to this article: Handmade Hero for mac in which the window appears due to a similar method. That was not good enough for me because such a method involves NSApp, which I would like to avoid, if possible.
A: What you have is not a Cocoa app.
You need to use the Xcode template to create a simple, one window, Cocoa app. That template will include a main() that starts the AppKit (NSApplicationMain(argc,argv);). This function performs the (approximately) 5,000 little things that make a Cocoa app run.
In the app bundle's Info.plist you either define a custom subclass of NSApplication to run your app or, much more commonly, in MainMenu.xib you define a custom NSApplicationDelegate object.
Once the AppKit has initialized and is ready to start your application, both of those objects will receive a message that you can override and add your custom startup code.
The standard template does all of that, so just use it to create a new project and then add your code to -applicationDidFinishLaunching:.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54750924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should and be avoided at all costs in web design? I continuously find places where I need to use the <br /> tag because CSS can't do what I need. Isn't the <br /> considered part of the "design" and not part of document structure? What is the acceptable usage for it? Should the same rules also apply to the <hr />?
Here is an example of where I feel forced to use the <br /> tag:
I want to display this:
<address>1234 south east Main St. Somewhere, Id 54555</address>
like this:
1234 south east main st.
Somewhere, Id 54555
A: There is nothing wrong with using <br /> or <hr />. Neither of them are deprecated tags, even in the new HTML 5 draft spec (relevant spec info). In fact, it's hard to state correct usage of the <br /> tag better than the W3C itself:
The following example is correct usage of the br element:
<p>P. Sherman<br>
42 Wallaby Way<br>
Sydney</p>
br elements must not be used for separating thematic groups in a paragraph.
The following examples are non-conforming, as they abuse the br element:
<p><a ...>34 comments.</a><br>
<a ...>Add a comment.<a></p>
<p>Name: <input name="name"><br>
Address: <input name="address"></p>
Here are alternatives to the above, which are correct:
<p><a ...>34 comments.</a></p>
<p><a ...>Add a comment.<a></p>
<p>Name: <input name="name"></p>
<p>Address: <input name="address"></p>
<hr /> can very well be part of the content as well, and not just a display element. Use good judgement when it comes to what is content and what is not, and you'll know when to use these elements. They're both valid, useful elements in the current W3C specs. But with great power comes great responsibility, so use them correctly.
Edit 1:
Another thought I had after I first hit "post" - there's been a lot of anti-<table> sentiment among web developers in recent years, and with good reason. People were abusing the <table> tag, using it for site layout and formatting. That's not what it's for, so you shouldn't use it that way. But does that mean you should never use the <table> tag? What if you actually have an honest-to-goodness table in your code, for example, if you were writing a science article and you wanted to include the periodic table of the elements? In that case, the use of <table> is totally justified, it becomes semantic markup instead of formatting. It's the same situation with <br />. When it's part of your content (ie, text that should break at those points in order to be correct English), use it! When you're just doing it for formatting reasons, it's best to try another way.
A: <hr /> and <br />, much like everything else, can be abused to do design when they shouldn't be. <hr /> is meant to be used to visually divide sections of text, but in a localized sense. <br /> is meant to do the same thing, but without the horizontal line.
It would be a design flaw to use <hr /> across a site as a design, but in this post, for instance, it would be correct to use both <br /> and <hr />, since this section of text would still have to be a section of text, even if the site layout changed.
A: <hr/> and <br/> are presentational elements that have no semantic value to the document, so from a purist perspective yes, they ought to be avoided.
Think about HTML not as a presentational tool but rather as a document that needs to be self-describing. <hr/> and <br/> add no semantic value - rather they represent a very specific presentation in the browser.
That all being said, be pragmatic in your approach. Try to avoid them at all cost but if you find yourself coding up the walls and across the ceiling to avoid them then its better to just go ahead and use them. Semantics are important but fringe cases like this are not where they matter the most.
A: I believe absolutely avoiding usage of a commonly accepted solution (even it is outdated) is the same thing as designing a table with <div> tags instead of <table> tags, just so you can use <div>.
When designing your website, you probably won't require the use of <br /> tags, but I can still imagine them being useful where user input is needed, for example.
I don't see anything wrong with using <br /> but have not come across many situation where I required using them. In most cases, there probably are more elegant (and prettier) solutions than using <br /> tags if this is what you need for vertically seperating content.
A: No. Why? They're useful constructs.
Adding this addendum (with accompanying HR), in case my brief answer is construed as lacking appropriate consideration. ;)
It can be, and often is, an incredible waste of time -- time someone else is usually paying for -- trying to come up with cross-browser CSS-limited solutions to UI problems that BR and HR tags, and their likes, can solve in two seconds flat. Why some UI folks waste so much time trying to come up with "pure" ways of getting around using tried-and-true HTML constructs like line breaks and horizontal rules is a complete mystery to me; both tags, among many others, are totally legitimate and are indeed there for you to use. "Pure," in that sense, is nonsense.
One designer I worked with simply could not bring himself to do it; he'd waste hours, sometimes days, trying to "code" around it, and still come up with something that didn't work in Opera. I found that totally baffling. Dude, add BR, done. Totally legal, works like a charm, and everyone's happy.
I'm all for abstracting presentation, don't get me wrong; we're all out do to the best work we can. But be sensible. If you've spent five hours trying to figure out some way to achieve, in script, something that BR gives you right now, and the gods won't rain fire down on you for doing it, then do it, and move on. Chances are if it's that problematic, there might be something wrong with your solution, anyway.
A: I put in a <hr style="display:none"> between sections. For example, between columns in a multi-column layout. In browsers with no support for CSS the separation will still be clear.
A: Just so long as you don't use <br/> to form paragraphs, you're probably alright in my book ;) I hate seeing:
<p>
...lengthy first paragraph...
<br/>
<br/>
...lengthy second paragraph...
<br/>
<br/>
...lengthy third paragraph...
</p>
As for an address, I would do it like this:
<address class="address">
<span class="street">1100 N. Wullabee Lane</span><br/>
<span class="city">Pensacola</span>, <span class="state">Florida</span>
<span class="zip">32503</span>
</address>
But that's likely because I love jQuery and would like access to any of those parts at any given moment :)
A: Interesting question. I have always used <br/> as a carriage return (and hence as part of content, really). Not sure if that is the right way of going about it, but its served me well.
<hr/> on the other hand...
A: I'd not say at all costs but if you want to be purist, these tags have nothing to do with structure and everything to layout but HTML is supposed to separate content from presentation. <hr /> can be done through CSS and <br/> through proper use of otehr tags like <p>.
If you do not want to be a purist, use them :)
A: I think you should seldom need the BR tag in your templates. But at times it can be called for in the content, user generated and system generated. Like if you want to keep a piece of text in the paragraph but need a newline before it.
What are the occasions where you feel you are forced to use BR tags?
A: <br> is the HTML way of expressing a line break, as there is no other way of doing it.
Physical line breaks in the source code are rightfully ignored (more correctly: treated as a single white space), so you need a markup way to express them.
Not every line break is the beginning of a new paragraph, and packing text into <div>s (for example) just to avoid <br>s seems overly paranoid to me. Why do they bother you?
A: BR is fine, since a hard line-break could be part of the content, for example in code blocks (even though you'd probably use the PRE-element for that) or lyrics.
HR on the other hand is purely presentational: a horizontal rule, a horizontal line. Use border-top/bottom for neighbouring elements instead.
A: I personally feel that, in the interest of true separation of content and style, both <br /> and <hr /> should be avoided.
As far as doing away with <br /> tags in my own markup, I use <div> in conjunction with the css margin property to handle anything that needs a line break, and a <span> for anything that would be inline, but of a different "content class" (obviously distinguishing them with the class attribute).
To replace an <hr /> tag with css, I simply create a <div> with the border-top-style css property set to solid and the other three sides set to none. The margin and the padding properties of said <div> then handle the actual placement/positioning of the horizontal line.
Like I said, I'm no expert, my web design experience is mostly a side effect of my work with JSP pages (I am a Java programmer), but I came upon this question during some research and wanted to put my two cents in...
A: You can use <br> but don't use <hr>.
<BR> — LINE BREAK— This is display information. Still in
common use, but use with restraint.
<HR> — HORIZONTAL RULE— Display info with no semantic value –
never use it. “Horizontal”, by definition, is a visual attribute.
Source: Proper Use Guide for HTML Tags
A: That's bad usage if you're going Strict.
<br/> and <hr/> are not part of the content. For instance the <hr/> is commonly used to separate blocks of text. But isn't possible to that with border-bottom? And <br/> is seen in many cases as a way to limit text to a certain form, which couldn't be accomplished with css?
Of course you aren't going Strict don't worry to much.
A: HR has some hacky uses right now in preventing mobile browsers' font inflation algorithms from kicking in.
Also if you have lots of small content separated by HRs, the Googlebot will currently see it as 'N separate entries', which might be useful to you.
BRs should really only be used as a line break within a paragraph, which is a pretty rare typographical usage (except perhaps within a table cell), and I'm not aware of any hacky reason to use them.
A: Here is an excerpt from a course that helps you learn html.
<form>
<p>Choose your pizza toppings:</p>
<label for="cheese">Extra cheese</label>
<input id="cheese" name="topping" type="checkbox" value="cheese">
<br>
<label for="pepperoni">Pepperoni</label>
<input id="pepperoni" name="topping" type="checkbox" value="pepperoni">
<br>
<label for="anchovy">Anchovy</label>
<input id="anchovy" name="topping" type="checkbox" value="anchovy">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/462619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Firebase getDownloadURL From Storage Unable To Set Img Src I am trying to replicate the results of this question here. I am able to call getDownloadURL() on a valid database child, but the result it returns cannot seem to be set to an IMG's src.
This is the code I am currently using to try and grab the download URL:
var storage = firebase.storage();
var storageRef = storage.ref();
var imgRef = storageRef.child('profile-pictures/1.jpg');
var pulledProfileImage = imgRef.getDownloadURL();
I then push pulledProfileImage into an array by doing this:
dataArray.push(pulledProfileImage)
Send the array (along with other information) off to a function that populates a table with data. The image itself is referenced using this code here:
cell1.innerHTML = '<img id="profileImage" src="'+dataArray[0]+'">';
When I check the source code after the code executes, the src is set to [Object, Object]. I also have the script logging the result which, when it does so, looks like this:
0:C
Hc:false
N:2
Pa:null
Wb:false
ja:null
na:"https://firebasestorage.googleapis.com/v0/b/app-name-da7a1.appspot.com/..."
s:null
The strange thing is if I have the console print out a different property say, Wb from the list above by calling console.log(Array[0].Wb)it prints false out PERFECTLY.... every boolean seems to be just fine, just not strings or numbers.
For reference, my storage structure looks like this:
----root
|
|------profile-pictures
|---------------------- img1.png <--the console is trying to print this one
|
|---------------------- img2.png
And my database structure to find the names of the images to pull is like so:
----root
|
|----folder1
|
|
|----subfolder1
|
|
|----subfolder2
|
|
|--------img1.png
|
|--------img2.png
Basically my code navigates to subfolder two, pulls the child values, then goes into storage and tried to pull them from there.
A: The trick here is that getDownloadURL is an async function that happens to return a promise (as per the docs):
var storage = firebase.storage();
var storageRef = storage.ref();
var imgRef = storageRef.child('profile-pictures/1.jpg');
// call .then() on the promise returned to get the value
imgRef.getDownloadURL().then(function(url) {
var pulledProfileImage = url;
dataArray.push(pulledProfileImage);
});
That will work locally, but that list of URLs won't be synchronized across all browsers. Instead, what you want is to use the database to sync the URLs, like how we did in Zero To App (video, code).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41326493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fix "invalid key format" while read public or private key from file? I have created the public and private key . The public and private key generated from php code :
<?php
require __DIR__ . '/vendor/autoload.php';
use phpseclib\Crypt\RSA;
$rsa = new RSA();
extract($rsa->createKey());
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_PKCS8);
file_put_contents("privateKey.pem",$privatekey);
file_put_contents("publicKey.pem", $publickey);
The java source code to read those keys:
import java.io.*;
import java.security.*;
import java.security.spec.*;
public class PublicKeyReader {
public static PublicKey get(String filename)
throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec =
new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
public static void main (String [] args) throws Exception {
PublicKeyReader publicKeyReader = new PublicKeyReader();
PublicKey publicKey = publicKeyReader.get("key/testPub.pem");
System.out.println(publicKey);
}
}
It produces java.security.InvalidKeyException: invalid key format.
Need help on this. Thanks in advance.
A: First of all, as noted in the comments, there is no such thing as a PKCS#8 public key. That means that the PHP library doesn't know what it is talking about. Instead, what you seem to get, if neubert is correct, is a structure defined for X.509 certificates called X509EncodedKeySpec. And in the Java code, you are indeed trying to use that to read in the public key.
However, what you forget is that X509EncodedKeySpec is a binary format, specified in ASN.1 DER. What you receive is a PEM encoded key that uses ASCII armor. In other words, the binary has been encoded to base64 and a header and footer line has been added. This is done to make it compatible with text interfaces such as mail (Privacy Enhanced Mail or PEM).
So what you do is to remove the armor. You can best do this using a PEM reader such as the one provided by Bouncy Castle.
PemReader reader = new PemReader(new FileReader("spki.pem"));
PemObject readPemObject = reader.readPemObject();
String type = readPemObject.getType();
byte[] subjectPublicKey = readPemObject.getContent();
System.out.println(type);
X509EncodedKeySpec spec = new X509EncodedKeySpec(subjectPublicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(spec);
System.out.println(pubKey);
which prints
PUBLIC KEY
followed by
Sun RSA public key, 1024 bits
params: null
modulus: 119445732379544598056145200053932732877863846799652384989588303737527328743970559883211146487286317168142202446955508902936035124709397221178664495721428029984726868375359168203283442617134197706515425366188396513684446494070223079865755643116690165578452542158755074958452695530623055205290232290667934914919
public exponent: 65537
For the skeptics - hi neubert ;) - here is the definition of SubjectPublicKeyInfo from the X.509 specification:
SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING }
where subjectPublicKey contains the encoded public key in PKCS#1 format - in the case of an RSA public key, of course.
And here is the decoded version of neubert's key so you can compare. The parsed key in Java is the same key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59263160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: css floating divs minwidth without overlapping Well I am making a "simple 3 column layout", the basic setup are two fixed width columns and a (center) column that stretches to fill the remaining width.
Now there is a small "addon" to that simple layout: I wish to have a defined minimum width for the center column, css has an attribute for that so it seemed easy:
.content div {
border:1px solid #bbb;
box-sizing: border-box;
}
.content-left {
float: left;
width: 200px;
}
.content-main {
margin-left: 200px;
margin-right: 200px;
min-width: 200px
}
.content-right {
float: right;
width: 200px;
}
However this gave an important problem: the moment the main column hits the "minimum width" (test it by dragging the dividers in the test link below), it starts overlapping with the left and right column. - I would actually like it to stretch the page introducing a horizontal scrollbar.
fiddle to test it
A: This should do it:
[layout] {
display: flex;
}
#left {
flex: 0 0 180px;
background-color:#f00;
margin-right: 20px;
}
#right {
flex: 1 0 300px;
background-color:#0ff;
}
<div layout>
<div id="left">
left
</div>
<div id="right">
right
</div>
</div>
See flex for details. It's flex-shrink and flex-grow that do the heavy lifting in this case. And the default value of flex-wrap, which is nowrap.
Don't forget to prefix.
Also note the 300px value of flex-basis (third value in flex shorthand of #right element. In this case, it's the minimum width of that element. When it gets under that size, the scrollbar appears.
And here it is with 3 columns:
[layout] {
display: flex;
}
[layout] > * {
padding: 1rem;
}
#left, #right {
flex: 0 0 180px;
}
#left {
background-color:#f00;
}
#right {
background-color:#0ff;
}
#middle {
flex: 1 0 300px;
margin: 0 10px;
border: 1px solid #eee;
}
<div layout>
<div id="left">
left
</div>
<div id="middle">
middle
</div>
<div id="right">
right
</div>
</div>
Side note: nobody seems to have told you the horizontal bar you're trying to achieve was what the rest of the world was trying to avoid when they invented responsive layouts. It's considered really bad user experience and Google lowers the rank of websites that do not feature responsive layouts.
Long story short, it will be losing you (or the client) serious money. The more important the website, the more important the loss. A better user experience would be to transform left and right sidebars into swipe-able drawers on small devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47191629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter : Weird SystemUIOverlayStyle bug I used SystemChrome & AnnotatedRegion to change some default colors for the status & navigation bars but both didn't work and two problems are found now :
First : The navigation bar background color never changes whatever I do. I thought that the phone I am testing my app on doesn't support changing that color but I opened some chess app on it and it changed that
Two : The status bar icons colors turn from white to black after I use Navigator.pushReplacement even after using the annotated region as a parent for the another route....
Code :
import 'package:myapp/pages/loading_page.dart';
import 'package:myapp/statics/statics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: AppStyles.setDefaultSystemLayout(),
child: MaterialApp(
title: 'My App',
debugShowCheckedModeBanner: false,
home: LoadingPage(),
),
);
}
}
class AppStyles {
static SystemUiOverlayStyle setDefaultSystemLayout() {
SystemChrome.setEnabledSystemUIOverlays(
[SystemUiOverlay.bottom, SystemUiOverlay.top],
);
SystemChrome.setPreferredOrientations(
[
DeviceOrientation.portraitUp,
],
);
SystemUiOverlayStyle myStyle = SystemUiOverlayStyle(
statusBarColor: AppColors.background,
systemNavigationBarColor: AppColors.background,
systemNavigationBarIconBrightness: Brightness.light,
);
SystemChrome.setSystemUIOverlayStyle(myStyle);
return myStyle;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58542818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xcode: show documentation for my custom classes How can I force Xcode to show my own documentation for custom classes, methods, etc.? I'm used to Java and Eclipse, which shows me documentation for my classes as shown here:
How can I achieve the same in Xcode? Are there special comments that Xcode can recognize and display?
A: It is also possible to add some code snippet in documentation like the following
by adding the following code
* @code
* - (UIButton*) createButtonWithRect:(CGRect)rect
{
// Write your code here
}
* @endcode
For more details of documenting methods of a custom class you can have a look on my blog Function Documentation in Xcode.
A: To get Xcode to show documentation for your classes, you must create a documentation set for your classes using a tool like Doxygen or HeaderDoc. After creating the documentation set, you must install it using Xcode's documentation preferences. Apple has an article on using Doxygen, but it covers Xcode 3, not 4.
Using Doxygen to Create Xcode Documentation Sets
A: As of Xcode 5.0, Doxygen and HeaderDoc formatting for variables and methods is automatically parsed and rendered in the Quick Help popover. More information about it here, but here's some key bits:
/**
* Add a data point to the data source.
* (Removes the oldest data point if the data source contains kMaxDataPoints objects.)
*
* @param aDataPoint An instance of ABCDataPoint.
* @return The oldest data point, if any.
*/
- (ABCDataPoint *)addDataToDataSource:(ABCDataPoint *)aDataPoint;
renders in Xcode as:
As for properties, it's as easy as:
/// Base64-encoded data.
@property (nonatomic, strong) NSData *data;
When option-clicked, this lovely popover appears:
A: Well, it seems that for the classes the question hasn't still been answered, so I'll post my suggestions.
Just before the @interface MyClass : NSObject line in the MyClass.h file you use the comment like you did in your example, but adding some tags to display the text. For example the code below:
/**
* @class GenericCell
* @author Average Joe
* @date 25/11/13
*
* @version 1.0
*
* @discussion This class is used for the generic lists
*/
will produce the following output:
the output of the code above http://imageshack.com/a/img18/2194/kdi0.png
A: Appledoc is the best option for generating xcode documentation at the moment. Doxygen is great, but it does not generate docsets that work very well for the popups you're talking about. Appledoc isn't perfect, but we moved over to it and have been really happy with the results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6958413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: try/catch is not catching exception I'm using the google_sign_in package and I'm a bit new to error handling. I surrounded two lines in a try/catch statement and I get the exception in VSCode even though I check for PlatformExceptions. The line that gives me the error is where I set the googleSignInAccount variable. I tried using Future#catchError but no luck their either. What am I doing wrong?
Code:
GoogleSignInAccount googleSignInAccount;
GoogleSignInAuthentication googleSignInAuthentication;
try {
googleSignInAccount = await userRepository.googleSignIn.signIn();
googleSignInAuthentication = await googleSignInAccount.authentication;
} on PlatformException catch (e) {
if (e.code == 'sign_in_canceled') {
print('sign in canceled');
return Future.error(e);
}
rethrow;
} on Exception {
print('an exception has occured');
}
final credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60608407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Github CLI or API, can I see which commit a Github Action workflow was run on? Using Github's CLI tool, I can see a Github Action workflow's log by
gh run view [ID] --log
Submitting the ID of a run, this returns the run's log. Now, if I don't have the ID, is there any way to find out from a commit SHA, if there are any GH Action runs associated with it (as in: They were run from a branch whose tip was that commit) and retrieve their IDs remotely, through Github's API or CLI?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75295118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sql query, how to select the clients that has never stayed on a room that cost 5000? This is the database
room(room_id, price)
client(client_id, name)
stayed(StartDate, EndDate, room_id, client_id)
I want to select all the clients' names that have never stayed in a room that has a price above 5000.
I tried this code:
select client.name
from client
inner join stayed on client.client_id = stayed.client_id
inner join room on stayed.room_id = room.room_id
Group by name
having room.price < 5000
It prints me the values of the clients that have stayed in a room < 5000 but some of them may have stayed on a room > 5000 at some other time.
A: You can use the aggregate function MAX in having:
select client.name from client inner join stayed
on client.client_id = stayed.client_id inner join
room on stayed.room_id= room.room_id
Group by name
having MAX(room.price) < 5000
A: I recommend not exists for this:
select c.name
from client c
where not exists (select 1
from stayed s join
room r
on s.room_id = r.room_id
where c.client_id = s.client_id and
r.price >= 500
);
This is almost a directly translation of your question. Note: If you attempt inner joins for this, then you will miss clients who have stayed in no rooms at all. According to your question, you would miss these clients in the result set.
A: This is another approach
SELECT c.Name
FROM client
WHERE c.client_id NOT IN (
SELECT s.client_id
FROM stayed s INNER JOIN room r
ON s.room_id = r.room_id
WHERE r.price > 5000)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58261210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I know the IP address of my iPhone simulator? How can I know the IP address of my iPhone simulator?
A: It will have the same IP addresses as the computer you’re running it on.
A: Jep, like Todd said, the same as your machines IP. You can also simply visit http://www.whatismyip.com with mobile Safari or your Mac's web browser ;-)
A: I think the by visiting the website http://www.test-ipv6.com/ is also a good choice. As the site tells you both the ipv4 and ipv6 global-unicast address
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5667802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Escape dash sign of bash history command On my Ubuntu system, I would like to use bash history command to remember some commands, but when I enter command like:
history -s "-t tag_name"
bash report error:
bash: history: -t: invalid option
history: usage: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]
It seems the argument of -s option cannot start with dash sign, because when I enter something like
history -s "echo test"
it works fine.
How can I make history to remember a command starts with dash sign? (Without adding leading white spaces)
A: You can signal history that you are done passing arguments, so it does not try to evaluate -t, like so:
history -s -- "-t tag_name"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35480054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to expand div in a HTML page I'm working on a browser app. I have read about a couple of dozen pages about the DIV tag. I just can not get it to work. I know I should use CSS but I will incorporate that at the end after I get some other things done.
Basically I want a header and a footer. Then a fixed width side bar and the rest to be filled with a content area. I almost got it but the sidebar starts too low (it should be the same height of the content) and the content does not expand to fit the width of the browser.
Here is what I have got:
<header style='background-color:#013499; height:60'>
<br>
<span style='color:white'>    Whole Number</span>
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</header>
<div>
<div style='display:inline-block; background-color:#7690C5; width:200'>
Task1
<br>Task2
<br>
</div>
<div style='display:inline-block; background-color:#F2F2F2'>
Top
<br>Content
<br>Bottom
</div>
</div>
<footer style='background-color:#013499; height:60'>
<br>
<form name="Actions" action="test.html" method="post">
   
<input type="submit" name="send_button" value="Save">   
<input type="submit" name="send_button" value="Cancel">
</form>
</footer>
I found this post which helped a lot. But it is still not right. I cant seem to find any documentation that explains how these things work together.
I cant figure out how to get the content to fill up the remaining space. It ends up too short (sizing to the actual content) or extending beyond the screen size because at 100% it includes the width of the sidebar. I know whats going wrong but I do not know how to make it right.
I moved the styles out of the HTML now.
html, body {
height: 100%;
margin: 0;
}
header {
width: 100%;
height: 60px;
background-color: #013499;
margin: 0;
}
#wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 0 -60px 0; /* the bottom margin is the negative value of the footer's height */
position: relative;
}
#sidebar {
background-color: #7690C5;
width: 300px;
height: auto !important;
bottom: 60px;
top: 60px;
display: inline-block;
position: absolute;
}
#content {
background-color: #F2F2F2;
width: 100%;
height: auto !important;
bottom: 60px;
top: 60px;
margin-left: 300px;
display: inline-block;
position: absolute;
}
footer {
margin: -60px 0 0 0;
width: 100%;
height: 60px;
background-color: #013499;
}
#buttons {
margin-right: 20px;
text-align: right;
}
<!DOCTYPE HTML>
<html>
<head>
<title>Viewer test</title>
<link rel=Stylesheet Type='text/css' href=ERP.css>
</head>
<body>
<div id="wrapper">
<header>
<br>
<span style='color:white'>    Whole Number</span>
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</header>
<div id="sidebar">
Task1<br>
Task2<br>
</div>
<div id="content">
Content
</div>
</div>
<footer>
<br>
<form id='buttons' name="Actions" action="test.html" method="post">
<input type="submit" name="send_button" value="Save">   
<input type="submit" name="send_button" value="Cancel">
</form>
</footer>
</body>
</html>
A: Firstly, don't use inline styles. Anyone that touches your code will hate you and when you want to apply a change to 100 elements that are the same at once you will equally hate yourself.
Also, HTML is the bread, CSS is the butter. On their own they're rubbish but together they're super awesome.
The only reason your "sidebar" isn't full height is because the content of the element next to is has more content. You need to incorporate CSS to stop this from happening.
A: See the fiddle
The reason why the sidebar was a little bit down was because of the inline-block that you had in the style.In the fiddle that i have made i have replaced the display:inline-block; with float:left;. Kindly see the fiddle
The new markup is as follows
<header style='background-color:#013499; height:60px'>
<br> <span style='color:white'>    Whole Number</span>
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</header>
<div>
<div style='float:left; background-color:#7690C5; width:200px;'>Task1
<br>Task2
<br>
</div>
<div style='float:left; background-color:#F2F2F2;'>Top
<br>Content
<br>Bottom</div>
</div>
<footer style='clear:both;background-color:#013499; height:60px'>
<br>
<form name="Actions" action="test.html" method="post">   
<input type="submit" name="send_button" value="Save">   
<input type="submit" name="send_button" value="Cancel">
</form>
</footer>
A: Try using fixed (or absolute) positions perhaps. Try this, for example:
<header style="background-color:#013499; height:60; right: 0;left: 0;top: 0;position: fixed;">
<div style="display:inline-block; background-color:#F2F2F2;float: right;top: 60px;position: fixed;right: 0;">
<footer style="background-color:#013499; height: 62px;position: fixed;width: 100%;left: 0;bottom: 0;">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29306366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unify and simplify MySQL commands I did some MySQL commands, however it was a bit slow to execute because there are three commands executed at the same time.
How can I unite all in just one command and simplify the code to make it faster?
UPDATE bidbutler b
LEFT JOIN auction a on b.auc_id=a.auctionID
LEFT JOIN auc_due_table c on b.auc_id=c.auction_id
SET b.butler_status=0
WHERE b.auc_id=a.auctionID
AND b.auc_id=c.auction_id
AND b.butler_status<>0
AND a.auc_status=3
AND c.auc_due_price<>a.auc_final_price
AND c.auc_due_time=a.total_time;
DELETE t1
FROM won_auctions t1
LEFT JOIN auc_due_table t2 ON t1.auction_id = t2.auction_id
LEFT JOIN auction t3 ON t1.auction_id = t3.auctionID
WHERE t1.auction_id = t2.auction_id
AND t1.auction_id = t3.auctionID
AND t2.auc_due_price<>t3.auc_final_price
AND t2.auc_due_time=t3.total_time
AND t3.auc_status=3;
UPDATE auction a
LEFT JOIN auc_due_table b on a.auctionID=b.auction_id
SET a.auc_status=2
WHERE a.auc_status=3
AND a.auctionID=a.auctionID
AND b.auc_due_price<>a.auc_final_price
AND b.auc_due_time=a.total_time;
The three commands will be executed at the same time through a database procedure, which is executed every second by an event.
NEW DELETE UPDATED:
DELETE t1
FROM won_auctions t1
JOIN auction t2
ON t1.auction_id = t2.auctionID
LEFT JOIN auc_due_table t3
ON t3.auction_id = t1.auction_id
AND t3.auction_id = t2.auctionID
AND t3.auc_due_price<>t2.auc_final_price
AND t3.auc_due_time=t2.total_time
WHERE t2.auc_status=3;
A: preamble
repeating notes I left as a comment on the question, because I'm not sure there was enough emphasis placed on these points:
"I don't think the slowness is due to three separate statements."
"It looks like the statements have the potential to churn through a lot of rows, even with appropriate indexes defined."
"Use EXPLAIN to see the execution plan, and ensure suitable indexes are being used, ..."
answer
The DELETE statement can't be combined with an UPDATE statement. SQL doesn't work like that.
It might be possible to combine the two UPDATE statements, if those are visiting the same rows, and the conditions are the same, and the second UPDATE is not dependent on the preceding UPDATE and DELETE statement.
We see the first UPDATE statement requires a matching row from bidbutler table. The second UPDATE statement has no such requirement.
We notice that the predicates in the WHERE clause are negating the "outerness" of the LEFT JOIN. If the original statements are correctly implemented (and are performing the required operation), then we can eliminate the LEFT keyword.)
We also find a condition a.auctionID=a.auctionID which boils down to a.auctionID IS NOT NULL. We already have other conditions that require a.auctionID to be non-NULL. (Why is that condition included in the statement?)
We also see a condition repeated: b.auc_id=c.auction_id appearing in both the ON clause and the WHERE clause. That condition only needs to be specified once. (Why is it written like that? Maybe something else was intended?)
The first UPDATE statement could be rewritten into the equivalent:
UPDATE auction a
JOIN auc_due_table d
ON d.auction_id = a.auctionID
AND d.auc_due_time = a.total_time
AND d.auc_due_price <> a.auc_final_price
LEFT
JOIN bidbutler b
ON b.auc_id = a.auctionID
AND b.auc_id = d.auction_id
AND b.butler_status <> 0
SET b.butler_status = 0
WHERE a.auc_status = 3
The second UPDATE statement can be rewritten into an equivalent:
UPDATE auction a
JOIN auc_due_table d
ON d.auction_id = a.auctionID
AND d.auc_due_time = a.total_time
AND d.auc_due_price <> a.auc_final_price
SET a.auc_status = 2
WHERE a.auc_status = 3
The difference is the extra outer join to bidbutler table, and the SET clause.
But before we combine these, we need to decipher whether the operations performed in the first UPDATE or the DELETE statement) influence the second UPDATE statement. (If we run these statements in a different order, do we get a different outcome?)
A simple example to illustrate the type of dependency we're trying to uncover:
UPDATE foo SET foo.bar = 1 WHERE foo.bar = 0;
DELETE foo.* FROM foo WHERE foo.bar = 0;
UPDATE foo SET foo.qux = 2 WHERE foo.bar = 1;
In the example, we see that the outcome is (potentially) dependent on the order the statements are executed. The first UPDATE statement will modify the rows that won't be removed by the DELETE. If we were to run the DELETE first, that would remove rows that would have been updated... the order the statements are executed influence the result.
Back to the original statements in the question. We see auc_status column being set, but also a condition on the same column.
If there are no dependencies between the statements, then we could re-write the two UPDATE statements into a single statement:
UPDATE auction a
JOIN auc_due_table d
ON d.auction_id = a.auctionID
AND d.auc_due_time = a.total_time
AND d.auc_due_price <> a.auc_final_price
LEFT
JOIN bidbutler b
ON b.auc_id = a.auctionID
AND b.auc_id = d.auction_id
AND b.butler_status <> 0
SET b.butler_status = 0
, a.auc_status = 2
WHERE a.auc_status = 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50054410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pyspark to connect to postgresql I'm trying to connect to a Posgresql database in Databricks and I'm using the following code:
from pyspark.sql import SparkSession
spark = SparkSession.builder.config("spark.jars", "path_to_postgresDriver/postgresql_42_2_14.jar").getOrCreate()
driver = "org.postgresql.Driver"
database_host = "my_host"
database_port = "5432"
database_name = "db_name"
table = "db_table"
user = "my_user"
password = "my_pwd"
url = f"jdbc:postgresql://{database_host}:{database_port}/{database_name}"
remote_table = (spark.read
.format("jdbc")
.option("driver", driver)
.option("url", url)
.option("dbtable", table)
.option("user", user)
.option("password", password)
.load()
)
Unfortunately I get back the following error:
Any idea what might be happening?
Thank you in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75327651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Microsoft SQL Server stuck at "Install_SQLSupport_CPU64_Action" While installing SQL Server 2017 Developer Edition, I got stuck at "Install_SQLSupport_CPU64_Action", this happened to me for the second time, once at work and once at home.
After searching online I found no solution.
A: The solution:
You will need to browse to this installation path:
C:\SQLServer2017Media\<YOUR_SQL_ENU>\1033_ENU_LP\x64\Setup
Then while the setup is stuck at “Install_SQLSupport_CPU64_Action” run
SQLSUPPORT.msi
And follow the installation procedure.
Once installed, run the following command in cmd:
taskkill /F /FI "SERVICES eq msiserver"
The SQL Server setup will continue and succeed.
Edit:
according to @snomsnomsnom, it seems that SQL Server 2019 unpacks to C:\SQL2019...
if the error code is 0x851a001a, then you need to change the sector size of the hard drives. Here is the guideline for that.
https://learn.microsoft.com/en-us/troubleshoot/sql/admin/troubleshoot-os-4kb-disk-sector-size
A: I had this issue when installing sql server 2016, the taskkill solution not work for me. Therefore, I tried do uninstallation for SQL Server 2012 Native Client, and install the one in the setup\x64\sqlncli.msi and reinstall the sql server again, and no more issue anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54380363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Convert reference to item to slice of length 1 I have a &X. How can I convert this to a &[X] of length 1? std::slice::from_raw_parts should work, but it is unsafe. Is there a safe function that I can use to do this conversion?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44629021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Wrap if long not working in android studio I have custom settings for my android projects.
I cannot get my code to wrap, whether I use wrap if long or always wrap.
I have included screenshots.
I have used the settings for the android xml, the xml, the java, the margin.
The Margin:
It still extends past the margin line and does not wrap.
It's frustrating, as I want to be able to view all the code without using the scrollbar.
A: I worked it out. It doesn't seem to automatically format as being typed on on save (there may be a format on save option somewhere).
Using reformat code:
Crt+Alt+L
Or go to Code in the menu bar, find Reformat Code in the drop down list as shown in the image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30963489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XHR request for Image Fails On Second Request in Safari I am storing image assets on S3 and requesting them using an XHR. I have a CORS policy file on S3 that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
<MaxAgeSeconds>3000</MaxAgeSeconds>
</CORSRule>
</CORSConfiguration>
Everything is working great in Chrome and Firefox, but I've got problems in Safari ...
If I clear my cache and request an image, there is no problem and the image loads successfully, however if I then refresh the page, the image fails to load and I get the following error:
XMLHttpRequest cannot load
http://s3-eu-west-1.amazonaws.com/my.bucket.com/photographs/example.jpg?1369324610.
Origin http://example.dev is not allowed by
Access-Control-Allow-Origin.
Using Charles to watch the network, I can see that on this second request, no request is made to S3.
So the problem seems related to Safari's cache.
Does anyone have any idea why I'm getting this error in Safari?
The loading code is part of a library called PreloadJS and the class responsible for loading is here. p_createXHR starting on Line 370 contains the XHR creation code. However, having kept a close eye on this function, the XHR request appears to be identical between succeeding and failing requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16760570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails ajax form, does its job but still tries to redirect I have a remote form for @vote, which submits a choice id. I simply want to render a partial instead of redirect it after the successful create action.
The action is successful, the vote is created, my create.js.erb is not reached and it gives a RoutingError. Server window looks to me like its processing html format. Any help appreciated!
Form:
= form_for Vote.new, url: poll_votes_path(@model), remote: true do |f|
%ul
- choices.each do |choice|
%li
%label
= radio_button_tag 'choice', choice.id, false, required: true
= choice.body
.submit
= f.submit "Stemmen", class: "send-vote", id: "poll_#{@model.id}"
Controller:
def create
@poll = Poll.find(params[:poll_id])
vote = Vote.new(poll: @poll, choice_id: params[:choice], ip: request.remote_ip, email: params[:email])
if vote.save
# cookies["#{@poll.id.to_s.crypt('lenniskink')}"] = {value: params[:choice], expires: 1.year.from_now}
end
respond_to do |format|
format.js
end
end
routes:
resources :polls, path: 'peilingen' do
member do
get :results
put :sort
end
resources :votes, path: 'stemmen', only: [:create, :index]
end
create.js
Browser:
ActionController::RoutingError at /peilingen/581/stemmen
Not Found
Server:
Started POST "/peilingen/581/stemmen" for ::1 at 2017-02-18 14:08:53 +0100
Processing by Admin::VotesController#create as HTML
Parameters: {"utf8"=>"✓", "choice"=>"2711", "commit"=>"Stemmen", "poll_id"=>"581"}
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 461 ORDER BY login ASC LIMIT 1
(0.3ms) BEGIN
SQL (2.0ms) UPDATE `users` SET `last_request_at` = '2017-02-18 13:08:53', `perishable_token` = 'ouUIlXRADq3WTnrysQGC', `updated_at` = '2017-02-18 13:08:53' WHERE `users`.`id` = 461
(1.0ms) COMMIT
Organization Load (0.6ms) SELECT `organizations`.* FROM `organizations` INNER JOIN `organizations_users` ON `organizations`.`id` = `organizations_users`.`organization_id` WHERE `organizations_users`.`user_id
` = 461
User Store (29.8ms) {"id":461}
Poll Load (0.6ms) SELECT `polls`.* FROM `polls` WHERE `polls`.`id` = 581 LIMIT 1
(1.0ms) BEGIN
Choice Load (0.5ms) SELECT `choices`.* FROM `choices` WHERE `choices`.`id` = 2711 LIMIT 1
SQL (24.5ms) INSERT INTO `votes` (`poll_id`, `choice_id`, `ip`, `created_at`) VALUES (581, 2711, '::1', '2017-02-18 13:08:53')
SQL (0.8ms) UPDATE `choices` SET `votes_count` = COALESCE(`votes_count`, 0) + 1 WHERE `choices`.`id` = 2711
(0.8ms) SELECT COUNT(*) FROM `votes` WHERE `votes`.`poll_id` = 581
SQL (2.7ms) UPDATE `polls` SET `votes_count` = 157, `updated_at` = '2017-02-18 13:08:53' WHERE `polls`.`id` = 581
(1.6ms) COMMIT
Completed 404 Not Found in 139ms (Searchkick: 29.8ms | ActiveRecord: 37.1ms)
ActionController::RoutingError - Not Found:
app/controllers/application_controller.rb:26:in `not_found'
Routes:
results_poll GET /peilingen/:id/results(.:format) admin/polls#results
sort_poll PUT /peilingen/:id/sort(.:format) admin/polls#sort
poll_votes GET /peilingen/:poll_id/stemmen(.:format) admin/votes#index
POST /peilingen/:poll_id/stemmen(.:format) admin/votes#create
polls GET /peilingen(.:format) admin/polls#index
POST /peilingen(.:format) admin/polls#create
new_poll GET /peilingen/new(.:format) admin/polls#new
edit_poll GET /peilingen/:id/edit(.:format) admin/polls#edit
poll GET /peilingen/:id(.:format) admin/polls#show
PATCH /peilingen/:id(.:format) admin/polls#update
PUT /peilingen/:id(.:format) admin/polls#update
DELETE /peilingen/:id(.:format) admin/polls#destroy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42315737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to open hyperlinks in excel without mouse-click; is there any shortcut key/Keys I have many hyperlinks in a column of excel-sheet.
Is/Are there any shortcut key/Keys so that after going to each cell(using keyboard) I can open those in browser without using mouse-click?
A: Press the menu key and then press 'O' or 'o'.
More about Menu Key: http://en.wikipedia.org/wiki/Menu_key
A: Create a macro with the following. The cell with the link should only include text of the hyperlink (and not use the Excel function hyperlink with an embedded link). Note that the "... chrome.exe " has a [space] between exe and quote (").
Sub ClickHyperlnk()
'
' ClickHyperlnk Macro
'
' Keyboard Shortcut: Ctrl+d
'
With Selection.Interior
URL = ActiveCell.Value
Shell "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " & URL, vbNormalNoFocus
End With
End Sub
A: To open a hyperlinked file in excel, try the following
Select the cell.
Press application key (menu key).
Press O key twice.
Press enter key.
This works well for me.
A: Sub hyhperlink()
'
' hyhperlink Macro
' opens hyperlink
'
' Keyboard Shortcut: Ctrl+Shift+X
'
With Selection.Interior
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End With
End Sub
or record a macro for this operation
A: go in excel view tab
*
*Click on micro
*Click Record micro
*type text in shortcut key i.e.(Ctr+Q or q)
*enter OK
*Press the menu key and then press 'O' or 'o' in excel Where is your hyper link data & Enter
*again go in view > micro > click on stop micro
Now you can use your short cut key i.e. Ctr+Q or q
For hyperlink cells in excel
A: This is an old post but maybe it could help someone searching for this shortcut. To open a link without going through "Edit Links" follow these couple of steps:
*
*click on a cell that is linked to another file
*then press Ctrl + [
This will open the linked file. Hope this helps.
A: In Excel 2016 (English version), I would say that the simplest way to do this is to
*
*press the menu key (that has a similar effect to a right click)
*press "o" twice
*press "Enter".
The first "o" goes to "sort" ; the second "o" goes to "Open Hyperlink", and "Enter" then opens the hyperlink.
On a keyboard that does not have a menu key, one can press Shift + F10 instead.
A: I found out this command doesn't work for me with the 'o' twice, maybe because i have a column of hyperlinks? who knows.
What I do is:
*
*Select cell
*Menu key
*Up_Arrow
*Enter
Opening the link is the last proposition of the menu, so going up goes to the last option. Pressing enter activates it.
Chears
Ben
A: You can make keyboard shortcut for hyperlinks formula / function.
Just press ALT + F11 copy and paste the script below:
Sub OpenHyp()
Workbooks.Open "FOLDER ADDRESS\" & ActiveCell.Value & "FILE EXTENSION"
End Sub
replace the FOLDER ADDRESS = you can find it on address bar of the file location just copy, paste and add "\" at the end of file address.
no need to replace ActiveCell.Value = this is the filename of your file which is usually the content of cell.
replace the FILEEXTENSION = for pdf used ".pdf", for normal excel file used ".xlsx" and so on.
Then, go to developer tab, click Macros, select the code we make which is "OpenHyp" and click "Option". Now you can put the shortcut key
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28188425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How can I make matplotlib mark_inset display line on top of the graph? I have this code
ax = plt.subplot(222)
plt.plot(time_list, data[1], color='red')
plt.plot(time_list, y_offset, color='blue')
plt.axvline(x=0, color='black')
plt.axhline(y=0, color='black')
axins = zoomed_inset_axes(ax, 4.5, loc=4)
axins.plot(time_list, data[1], color='red')
axins.plot(time_list, y_offset, color='blue')
axins.axvline(x=0, color='black')
axins.axhline(y=0, color='black')
axins.axis([2, 3, -0.01, 0.01])
plt.yticks(visible=False)
plt.xticks(visible=False)
mark_inset(ax, axins, loc1=3, loc2=1, fc="none", ec="0.0")
which plot the graph like this
as you can see the zoom box line is behind the red plot but the link line is on top of the plot so how can I make the zoom box line become on top of the plot?
A: You can cause the box to appear on top of the graphed line by using Z-order. Artists with higher Z-order are plotted on top of artists with lower Z-order. The default for lines is 2, so add zorder = 3 to mark_inset.
Full code:
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
fig, ax = plt.subplots()
time_list = np.linspace(0, 7, 1000)
data = np.random.random(1000) - .5
plt.plot(time_list, data, color='red')
plt.axvline(x=0, color='black')
plt.axhline(y=0, color='black')
axins = zoomed_inset_axes(ax, 4.5, loc=4)
axins.plot(time_list, data, color='red')
axins.axvline(x=0, color='black')
axins.axhline(y=0, color='black')
axins.axis([2, 3, -0.01, 0.01])
plt.yticks(visible=False)
plt.xticks(visible=False)
mark_inset(ax, axins, loc1=3, loc2=1, fc="none", ec="0.0", zorder = 3)
plt.show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32423187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 8 bit floating point binary to decimal This question is similar to the question asked here: Floating point conversion for 8-bit floating point numbers. The marked answer is good but I am missing what a few of the symbols mean and some of the math completed in between the lines. If you could, please walk me through the process for converting the following 8-bit binary floating point to it's decimal counterpart with IEEE 754-2008.
Where is this formula derived and what are the variables in this formula, specifically 2**:
bias = emax = 2**(k - p - 1) - 1
Please show me the steps with math to convert 0010 0110 to it's decimal representation.
A: I found this webpage with a detailed explanation on how to make the conversion:
http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html
The following is a copy-paste of one 8-bit example that breaks the binary string as 0 010 0110:
Convert the 8-bit floating point number 26 (in hex) to decimal.
Convert and separate: 2616 = 00100110 2
Exponent: 0102 = 210; 2 − 3 = -1.
Denormalize: 1.0112 × 2-1 = 0.1011.
Convert:
Exponents 20 2-1 2-2 2-3 2-4
Place Values 1 0.5 0.25 0.125 0.0625
Bits 0 . 1 0 1 1
Value 0.5 + 0.125 + 0.0625 = 0.6875
Sign: positive
Result: 26 is 0.6875.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30249620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle pl/sql reference(return?) cursor/declared cursor Is there a way to do something like this? Output a cursor's fetched data into a refcursor without stuffing it into a table first?
create or replace procedure someprocedure
(
rc1 in out adv_refcur_pkg.rc) -- this is defined below
as
v_class_year varchar(10);
cursor c1
is
select distinct e.pref_class_year
from entity e
where e.pref_class_year between i_start_class and i_end_class;
begin
open c1;
loop
fetch c1 into v_class_year;
EXIT WHEN c1%NOTFOUND;
end loop;
close c1;
open rc1 for select v_class_year from dual;
end;
here is the refcursor's declaration
CREATE OR REPLACE PACKAGE ADVANCE.adv_refcur_pkg
AS
TYPE RC IS REF CURSOR;
END adv_refcur_pkg;
A: According with this example, yes, it's possible:
https://forums.oracle.com/thread/696634
A: Why go to the trouble of doing that when you can simply pass the cursor itself?
create or replace procedure someprocedure
(
rc1 in out adv_refcur_pkg.rc) -- this is defined below
as
begin
open rc1 for
select distinct e.pref_class_year
from entity e
where e.pref_class_year between i_start_class and i_end_class;
end;
When you call "someprocedure", you have an open cursor you can then fetch from:
BEGIN
...
someprocedure(TheCursor);
LOOP
fetch TheCursor into v_class_year;
exit when TheCursor%NOTFOUND;
...
END LOOP;
CLOSE TheCursor;
...
END;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19427897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DocumentViewer GoToPage() Issue I have a little a problem with the WPF DocumentViewer.
I'm displaying an XPS file using the DocumentViewer.
I want to navigate the XPS document to a certain Page but it navigates to the wrong page number during the initializing of the window.
This is my code:
public partial class Window : Window
{
private string _XPSpath;
public Window()
{
InitializeComponent();
_XPSPath = @"C:\TestFolder\TestDocument.xps";
MyDocViewer.Document = new XpsDocument(_XPSpath, FileAccess.Read).GetFixedDocumentSequence();
DocViewer.GoToPage(100); // Navigates to wrong page !!!!!!!!!
}
private void GoToPageButton_Click(object sender, RoutedEventArgs e)
{
DocViewer.GoToPage(100); //this one is ok.
}
}
Is there any way to solve this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19791017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the mathematical way to determine an angle from two given true bearings? Given that I have two true bearings as a start bearing 315 degrees and an end bearing 45 degrees, is there a better way to determine the angle between the two true bearings? The complication comes in when the start bearing is greater than the end bearing. I have the following that works but I figure there is a better/mathematical way.
double tStartBearing = 315;
double tEndBearing = 45;
double tAngle;
if (tStartBearing > tEndBearing) {
tAngle = tStartBearing - tEndBearing - 180;
} else {
tAngle = tEndBearing - tStartBearing;
}
Expect the resulting value of tAngle to be 90. Consider a start bearing of 0 and an end bearing of 359.9, the resulting value of tAngle should be 359.9, not 0.1.
A: The (signed) angle is always end - start. Assuming the start and end angles are both in the same range [n, n + 360), their difference will be between (-360, 360).
To normalize the difference to a positive angle in the range [0, 360), use:
tAngle = (tEndBearing - tStartBearing + 360) % 360;
To normalize the difference to a signed angle in the range [-180, 180), instead, use:
tAngle = (tEndBearing - tStartBearing + 360 + 180) % 360 - 180;
The above work whether the start angle is smaller than the end one, or the other way around.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61900967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable the input value I have an input field. In which I want to fix a value. I am able to fix the value by putting readonly but it's not passing the value which I have put as fixed.
what I am doing is:-
<input name="txt_zip_code" class="z-con-input adj-z-con-input" style="background:#eee" type="text" maxlength="13" field="txt_zip_code" value="98052" readonly="readonly" />
I want to make the value same for every user.
Can I get any help in this.
A: You have not included what back end system you are using, which is relevant information. However, with PHP and ASP.NET MVC I've discovered a similar behavior. I believe you are describing disabled/readonly inputs sending null values to the back end controller. In the past, I've found that I had to re-enable inputs with Javascript before submitting them to the controller. The jquery to do this is:
$("input[type='submit']").click(function(e){
e.preventDefault();
$("input").removeProp('readonly');
$("form").submit();
});
However, if the field is always static, you may just want to hard code it on the back end.
I'd also recommend you check out the w3 specification on disabled elements to make sure the readonly attribute is the correct attribute for you. You are currently using the readonly attribute incorrectly, as it is a boolean attribute.
<input readonly="readonly">
should be:
<input readonly>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26894349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TYPO3 Inline Relational Record Editing (IRRE) I created a new content element which adds a field called heroslider to tt_content.
The TCA looks like this:
'heroslider' => [
'config' => [
'type' => 'inline',
'allowed' => 'tx_ext_domain_model_heroslider_item',
'foreign_table' => 'tx_ext_domain_model_heroslider_item',
'foreign_field' => 'tt_content_uid',
'foreign_sortby' => 'sorting',
'foreign_label' => 'header',
'maxitems' => 99,
'appearance' => [
'collapseAll' => 1,
'expandSingle' => 1,
],
],
],
Now when I add a heroslider_item in the BE, it gets stored properly, except for the field tt_content_uid. This fields contains a zero instead of the uid of the content element.
Do you have any idea what I am missing?
Thanks in advance!
A: In your table tx_ext_domain_model_heroslider_item you miss a field for the reverse table name. at least you have not declared it in your relation:
foreign_table_field = parent_table
You know that your parent records always are tt_content, but TYPO3 needs some help.
ANFSCD:
why do you have
'allowed' => 'tx_ext_domain_model_heroslider_item',
I can not find any documentation about an option allowed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53522268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TYPO3 9.5 Speaking URL - How to rewrite/redirect former RealUrl pages suffixed .html How can I permanently rewrite or redirect former from realurl suffixed .html pages to the new implemented URL?
So far I didn't see any solution in the API Overview -> Site Handling. Or do I have to do this in the .htaccess file?
I just upgraded my website from TYPO3 8.7 LTS to 9.5 LTS.
In 8.7 I used realurl for Speaking URLs with the configuration:
'www.mydomain.local' =>
array (
'init' =>
array (
'appendMissingSlash' => 'ifNotFile,redirect[301]',
'emptyUrlReturnValue' => '/',
),
'pagePath' =>
array (
'rootpage_id' => '1',
),
'fileName' =>
array (
'defaultToHTMLsuffixOnPrev' => true,
'acceptHTMLsuffix' => 1,
So, all my pages got a .html suffix, e.g. https://resterland.ch/webatelier.html.
After upgrading to TYPO3 9.5 LTS with the new implemented Speaking URLs Out of the Box, all pages ending without any suffix by default, e.g. https://resterland.ch/webatelier.
So far so good. However, if someone like to link to a bookmarked page with the .html suffix, they of course get an "Oops, an error occurred!".
And in the Administration log ERRORs like this:
Exception handler (WEB): Uncaught TYPO3 Exception: #1544172838: Error handler could not fetch error page "https://resterland.ch/", reason: cURL error 7: Failed to connect to resterland.ch port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) | RuntimeException thrown in file /var/www/vhosts/resterland.ch/typo3_src-9.5.3/typo3/sysext/core/Classes/Error/PageErrorHandler/PageContentErrorHandler.php in line 77. Requested URL: https://resterland.ch/webatelier.html
A: realurl is no longer supported. you have to use the new site be modul. or for extension: https://docs.typo3.org/typo3cms/extensions/core/Changelog/9.5/Feature-86365-RoutingEnhancersAndAspects.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53882462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stata calculate % change between years I have the following columns in my data
Firm - revenue - industry - year
I want to calculate the percentage change in total revenue for each industry between 2008 and 2015.
I tried:
by industry: egen tot_2008 = sum(revenue) if year == 2008
by industry: egen tot_2015 = sum(revenue) if year == 2015
gen change = (tot_2015-tot_2008)/tot_2008
But this doesn't work as the ifs restrict which years the egen creates values for as well as which years are included in each sum.
A: As you realise, the problem with your code is that 2008 and 2015 values will be non-missing values only for those years respectively, and hence never not missing on both variables. Here is one way to spread values to all years for each industry:
by industry: egen tot_2008 = total(revenue / (year == 2008))
by industry: egen tot_2015 = total(revenue / (year == 2015))
gen change = (tot_2015-tot_2008)/tot_2008
That hinges on expressions such as year == 2008 being evaluated as 1 if true and 0 if false. If you divide by 0, the result is a missing value, which Stata ignores, which is exactly what you want. Taking totals over all observations in an industry ensures that the same value is recorded for each industry.
Here is another way that some find more explicit:
by industry: egen tot_2008 = total(cond(year == 2008, revenue, .))
by industry: egen tot_2015 = total(cond(year == 2015, revenue, .))
gen change = (tot_2015-tot_2008)/tot_2008
which hinges on the same principle, that missings will be ignored.
Note the use of the egen function total() here. The egen function sum() still works, and is the same function, but that name is undocumented as of Stata 9, in an attempt to avoid confusion with the Stata function sum().
To avoid double (indeed multiple) counting, use
egen tag = tag(industry)
to tag just one observation for each industry, to be used in graphs and tables for which you want that.
For discussion, see here, sections 9 and 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41122322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make visual studio always view commit details in a new tab in git changes? It opens commit details in a small window inside git history and it's very inconvenient, because it's too small to see anything. Clicking "open in a new tab" every time is annoying. Is there a way to make visual studio always open it in a new tab?
A: There is currently no way to open Commit Details straight to a new tab. This is feedback that we've heard a few times since we built the Git Repository window and embedded the commit details, so it is on our radar to improve the window handling in a future update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69378782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: in robot framewerk text edit using selenium library This is an issue I'm facing while automating my test case via robot framework, I'm trying to click on the Action column of 3rd row in the below table (screenshot below)
The Xpath I'm using is as below
Click element xpath=.//table[id="mylogiusers"]/tbody/tr[3]/td[37]
${table_cell} Get Table Cell xpath=//table[contains(@id,'mylogiusers')]
Click Link ${table_cell}
Note - there are multiple hidden columns in the table, so though the Action column appears to be 10th but in the html table it's number 37, so added td[37] in above xpath.
This is a bootstrap table, please let me know where I'm going wrong, tried multiple options in xpath but none seems to be working here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48704750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to implement CDN in ASP.NET I need to implement CDN in an ASP.NET project. The best Idea I could come up with is creating a custom HttpModule which will handle the PostRequestHandlerExecute event. I'm replacing all the static URLs domain with the CDN's zone url before the response is sent to the client.
Here's my module code:
using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
public class CdnModule : IHttpModule
{
public static string CdnUrl;
public CdnModule()
{
CdnUrl = ConfigurationManager.AppSettings["CdnUrl"];
}
public String ModuleName
{
get { return "CdnModule"; }
}
// register handlers
public void Init(HttpApplication app)
{
app.PostRequestHandlerExecute += PostRequestHandlerExecuteHandler;
}
private void PostRequestHandlerExecuteHandler(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.ContentType == "text/html")
{
response.Filter = new UrlFilter(response.Filter);
}
}
public void Dispose() { }
}
public class UrlFilter : Stream
{
private Stream _responseStream;
StringBuilder _responseHtml;
public UrlFilter(Stream inputStream)
{
_responseStream = inputStream;
_responseHtml = new StringBuilder();
}
#region Filter overrides
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Close()
{
_responseStream.Close();
}
public override void Flush()
{
_responseStream.Flush();
}
public override long Length
{
get { return 0; }
}
public override long Position { get; set; }
public override long Seek(long offset, SeekOrigin origin)
{
return _responseStream.Seek(offset, origin);
}
public override void SetLength(long length)
{
_responseStream.SetLength(length);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _responseStream.Read(buffer, offset, count);
}
#endregion
//Here I'm replacing URLs
public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.UTF8.GetString(buffer, offset, count);
//replace relative UploadFile urls with absolute CDN zone
html = html.Replace("\"/UploadFile/", "\"" + CdnModule.CdnUrl + "/UploadFile/");
buffer = Encoding.UTF8.GetBytes(html);
_responseStream.Write(buffer, 0, buffer.Length);
}
#endregion
}
Below piece of code is responsible for intercepting and modifying the response text:
public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.UTF8.GetString(buffer, offset, count);
//replace relative UploadFile urls with absolute CDN zone
html = html.Replace("\"/UploadFile/", "\"" + CdnModule.CdnUrl + "/UploadFile/");
buffer = Encoding.UTF8.GetBytes(html);
_responseStream.Write(buffer, 0, buffer.Length);
}
Am I doing it right? or is there any better way of doing this?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32007306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery ajax to retrive php get variable I would like to take the $id variable from an ajax form (input.php) and make it usable on the main page so I can .submit() the form using this variable in the action='ask.php?q='.
Main Page:
<script type='text/javascript'>
$(document).ready(function(){
$('#questionSubmit').click(function(){
$.post("input.php", { question: questionForm.question.value , detail: questionForm.detail.value }, );
});
});
</script>
<form method='POST' action='ask.php?q=<?php echo $id ?>' name='questionForm'>
<p>Question:</p>
<p><input type='text' name='question' id='question'></p>
<p><textarea id='detail' name='detail'></textarea></p>
<p>Tags:</p>
<p><input type='button' value='submit' name='questionSubmit' id='questionSubmit'></p>
</form>
Input.php:
<?php
include '../connect.php';
if (isset($_POST['questionSubmit'])){
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
$put=mysql_query("INSERT INTO questions VALUES ('','$question','$detail','$date','$time','$user','subject','0')");
$result=mysql_query("SELECT * FROM questions WHERE user='$user' AND time='$time'");
while ($row = mysql_fetch_assoc($result)){
$id=$row['id'];
}
}
?>
A:
$.post("input.php", { question: questionForm.question.value , detail: questionForm.detail.value },
function(data) {
//add the id to question input, or any other input element you want
$("#question").val(data);
});
//and your input.php, echo the $id
while ($row = mysql_fetch_assoc($result)){
$id=$row['id'];
}
echo $id;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8651849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error message seems ambiguous without any descriptive clue I am new to transcrypt. I created a test python file,test.py
def test_def(a: list):
for i in range(len(a)):
print(i)
xx = [2, 3, 4]
test_def(xx)
I have python 3.9. If I run the python file, it runs and prints as expected.
Running transcrypt gives following error
> python -m transcrypt -b -m -n .\test.py
Error while compiling (offending file last):
File 'test', line 2, namely:
Error while compiling (offending file last):
File 'test', line 2, namely:
Aborted
I am not sure what it expects and why is it giving the error, any help would be appreciated.
A: What version of Transcrypt are you using? Wasn't able to replicate the error using Python 3.9.0 and Transcrypt 3.9.0. You can check like this (Win):
> transcrypt -h | find "Version"
# and may as well double check that the right version of python was used:
> python --version
The Python and Transcrypt versions should match, as Transcrypt uses Python's AST that may change between versions.
Another aspect is that I first installed Transcrypt into a virtual env as follows (Win):
> py -3.9 -m venv wenv
> wenv\Source\activate.bat
> pip install transcrypt
> python -m transcrypt -b -m -n test.py
It sometimes happens that one inadvertently uses the wrong version of Python. 'py' is the Python launcher on Windows and useful to launch the right version if you have multiple versions installed. On Linux there are typically binaries in /usr/bin such as 'python3.9' or a symlink such as 'python3' that links to the most recent 3 version. Installing into a virtual env as demonstrated is also helpful, as various problems can come about otherwise.
The above compiled test.py without error (Win 10 cmd.exe). Fwiw, the file was saved as utf-8 and compile worked with and without a BOM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68582595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ORA-00001 Unique constraint (string.string) violated I have two tables that are identical to each other t1 and t2, but t2 has more data than t1.
I'm using this query to insert the missing data from t2 to t1.
insert into t1
select * from t2
where not exist ( select * from t1
where t1.key1 = t2.key1
and t1.key2 = t2.key2)
When this query is run I get the: ORA-00001 Unique constraint (string.string) violated error.
The two tables have key1 and key2 as keys.
Since the only constraint is the two keys I don't understand why I'm getting that error.
EDIT: I noticed now in "Indexes" that there are 2 constraints both are of type unique.
The first one is: key1, random_column
The second one is: key2
sorry for the inconvenience.
A: Just in case there is a different understanding about the unique constraint, I am assuming that the unique constraint is one unique index on both fields. If you have a unique constraint on key1 and a unique constraint on key2, then this will fail when there is a record in t1 with the same t2.key1 value, but a different t2.key2 value, because adding the record would result in two records in t1 with the same key1 value, which is forbidden by a unique constraint on key1.
If this is what you have, you need a unique index with both fields, rather than column constraints.
One possibility is that a value in t2 has a NULL key1 or a NULL key2.
In an expression, a NULL input always results in a NULL result which is considered false.
So, if t2 has a record with NULL key1 and a value of 'value2' for key2, then the where clause is evaluating
select * from t1
where t1.key1 = NULL and t1.key2 = 'value2'
This is not equivalent to
select * from t1
where t1.key1 is NULL and t1.key2 = 'value2'
instead t1.key1 = NULL will be untrue, the select will fail to ever return a result, the exist will be false and NOT(exist) will be true. But if t1 already has a record like this, the unique constraint will fail.
So use this insert statement.
insert into t1
select * from t2
where not exist ( select * from t1
where (t1.key1 = t2.key1 or (t1.key1 is null and t2.key1 is null))
and (t1.key2 = t2.key2 or (t1.key2 is null and t2.key2 is null)))
A: ideal case for use of MINUS result set operation
insert into t1
select * from t2
minus
select * from t1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15412976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting error while running rails server I am migrating my web app to Microsoft Azure. When I do rails s, I am getting this log:
/home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activesupport-4.0.0/lib/active_support/values/time_zone.rb:282: warning: circular argument reference - now
/home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/defaults.rb:465: warning: duplicated key at line 466 ignored: :queue_type
/home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor/safe_yaml/lib/safe_yaml/syck_node_monkeypatch.rb:42:in `<top (required)>': uninitialized constant Syck (NameError)
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor/safe_yaml/lib/safe_yaml.rb:197:in `<module:YAML>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor/safe_yaml/lib/safe_yaml.rb:132:in `<top (required)>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor/require_vendored.rb:4:in `<top (required)>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor.rb:40:in `require_libs'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet/vendor.rb:53:in `load_vendored'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet.rb:172:in `<module:Puppet>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/puppet-3.7.3/lib/puppet.rb:29:in `<top (required)>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:76:in `require'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:72:in `each'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:72:in `block in require'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:61:in `each'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler/runtime.rb:61:in `require'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.10.0/lib/bundler.rb:133:in `require'
from /home/mnpatel0611/mapial-stage/mapial/config/application.rb:7:in `<top (required)>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.0.0/lib/rails/commands.rb:76:in `require'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.0.0/lib/rails/commands.rb:76:in `block in <top (required)>'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in `tap'
from /home/mnpatel0611/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Anyone face this error?
A: Puppatlabs describe that Puppet 3.7.3 is not supported on Ruby 2.2 but now thay change status to resolved. So you should go more into this and find rid of this problem. You can show this issue from puppatlabs ticket Puppet 3.7.3 is not supported on Ruby 2.2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30522126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Order by a value returned from function called in Stored Procedure MYSQL I want to order by dist : dist is a double value returned from function called isNeighbour It throws error as dist is undefined : Unknown column 'dist' in field list
DELIMITER $$
DROP PROCEDURE IF EXISTS `connectarabs`.`maxEdges` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `maxEdges`(id int,lat double,lon double,rad double)
BEGIN
if lat is null then
set lat=(select a.latitude from account a where a.id=id);
end if;
if lon is null then
set lon=(select a.longitude from account a where a.id=id);
end if;
SELECT friends.* FROM account friends left join account_friendTest me on (friends.id=me.second_account)
or (friends.id=me.first_account) where (me.first_account=id OR me.second_account=id) AND friends.id <> id AND
( ((select isNeighbour(lat,lon,friends.latitude,friends.longitude,rad) as dist )<rad) ) order by dist;
END $$
DELIMITER ;
A: This is because you can't alias column used in WHERE clause and use that in ORDER BY clause. Instead you need to SELECT that column and use HAVING clause to filter it:
SELECT friends.*,
isNeighbour(lat,lon,friends.latitude,friends.longitude,rad) AS dist
FROM account friends
LEFT JOIN account_friendTest me
ON (friends.id=me.second_account)
OR (friends.id=me.first_account)
WHERE (me.first_account=id OR me.second_account=id) AND
friends.id <> id
HAVING dist < rad
ORDER BY dist;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12140287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Return data from nested array I'm trying to get some data from Wikipedia API. I found this project https://github.com/donwilson/PHP-Wikipedia-Syntax-Parser but I cannot figure out how to output the infobox entries in a loop, because the array is in an array which is in an array.
The array code
[infoboxes] => Array
(
[0] => Array
(
[type] => musical artist
[type_key] => musical_artist
[contents] => Array
(
[0] => Array
(
[key] => name
[value] => George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>
)
[1] => Array
(
[key] => image
[value] => George Harrison 1974 edited.jpg
)
[2] => Array
(
[key] => alt
[value] => Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.
)
[3] => Array
(
[key] => caption
[value] => George Harrison at the White House in 1974.
)
)
)
)
This is what I tried (returns the value but not the key)
$values=$parsed_wiki_syntax["infoboxes"][0]["contents"];
$keys = array_keys($values);
for($i=0; $i<count($values); $i++){
foreach ($values[$keys[$i]] as $key=>$value)
echo "<b>".$key."</b>: ".$value."<br><br>";
}
A: Let's just see what happens when we simplify everything a little bit:
$firstBox = reset($parsed_wiki_syntax['infoboxes']);
if($firstBox) {
foreach($firstBox['contents'] as $content) {
$key = $content['key'];
$value = $content['value'];
echo "<b>" . $key . "</b>: " . $value . "<br><br>";
}
}
The use of array_keys() and the for/foreach loops get a little confusing quickly, so I'm not sure exactly what your error is without looking more. The big trick with my code above is the use of reset() which resets an array and returns (the first element). This lets us grab the first infobox and check if it exists in the next line (before attempting to get the contents of a non-existent key). Next, we just loop through all contents of this first infobox and access the key and value keys directly.
A: You if want to access both keys and values, a simple good ol' foreach will do. Consider this example:
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$contents = $values['infoboxes'][0]['contents'];
foreach($contents as $key => $value) {
echo "[key => " . $value['key'] . "][value = " . htmlentities($value['value']) . "]<br/>";
// just used htmlentities just as to not mess up the echo since there are html tags inside the value
}
Sample Output:
[key => name][value = George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>]
[key => image][value = George Harrison 1974 edited.jpg]
[key => alt][value = Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.]
[key => caption][value = George Harrison at the White House in 1974.]
Sample Fiddle
A: As an exercise in scanning the given array without hardcoding anything.
It doesn't simplify anything, it is not as clear as some of the other answers, however, it would process any structure like this whatever the keys were.
It uses the 'inherited' iterator, that all arrays have, for the 'types' and foreach for the contents.
<?php
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$typeList = current(current($values));
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), '...', '<br />';
foreach(current($typeList) as $content) {
$key = current($content);
next($content);
echo 'content: ', $key, ' => ', current($content), '<br />' ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23896210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to forecast few periods ahead,a univariate timeseries using support vector regression I have the following data:
head(df)
pce pop psavert uempmed unemploy
507.8 198712 9.8 4.5 2944
510.9 198911 9.8 4.7 2945
516.7 199113 9.8 4.6 2958
513.3 199311 9.8 4.9 3143
518.5 199498 9.8 4.7 3066
I am trying to use SVM - regression to fit the data like this
svmRbftune <- train(unemploy ~ pce + pop + psavert + uempmed,
data = EconomicsTrain, method = "svmRadial",
tunelength = 14, trControl = trainControl(method = "cv"))
svmRbfPredict <- predict(svmRbftune, EconomicsTest)
What i would like is to forecast say 3 periods ahead.....i am stuck as to how i can do that..literature is quite vague regarding it....
A: You need new feature values to make predictions.
For example:
svmRbftune <- train(unemploy ~ pce + pop + psavert + uempmed,
data = head(EconomicsTrain,-3), method = "svmRadial",
tunelength = 14, trControl = trainControl(method = "cv"))
svmRbfPredict <- predict(svmRbftune, tail(EconomicsTest,3))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42268035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Group like JSON objects into arrays I have a model returned by a library in the following format:
var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]
How do I group the "fName" together and add '[]' to get:
{ 'fName[]': ['john','mike'],'country[]': ['USA'] };
**Note country and fName are not related at all.
A: You can iterate over the array and push the date to the desired field.
var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]
var result = {
'fName[]': [],
'country[]': []
};
givenData.forEach(function (data) {
if (data.fName) {
result['fName[]'].push(data.fName);
}
if (data.country) {
result['country[]'].push(data.country);
}
});
console.log(result);
A: You could take the key and build an object with the key and arrays as properties.
var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}],
grouped = givenData.reduce(function (r, o) {
var key = Object.keys(o)[0] + '[]';
r[key] = r[key] || [];
r[key].push(o[Object.keys(o)[0]]);
return r;
}, Object.create(null));
console.log(grouped);
A: Suggestion (using ES6 syntax)
const transformData = (data) => {
const newData = {}
data.forEach( (item) => {
for (let key in item) {
const newKey = key + "[]"
if (!newData.hasOwnProperty(newKey)) newData[newKey] = []
newData[newKey].push(item[key])
}
})
return newData
}
/* added some extra keys just to test */
let givenData = [
{"fName": "john", "country": "England"},
{"fName": "mike"},
{"country": "USA"},
{"language": "English"}
]
console.log(transformData(givenData))
/*
{
"fName[]": ["john","mike"],
"country[]": ["England","USA"],
"language[]":["English"]
}
*/
A: In ES6:
const newData = givenData.reduce(function (r, o) {
const key = `${Object.keys(o)[0]}[]`;
return { ...r, [key]: [ ...r[key], o[key] ] }
}, {});
This doesn't modify your original data and is very clean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42077841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to update users that have 'old' banners? In the past users have uploaded banners freely without validation. Just recently we rolled out validation with banners. How do we update user records that have OLD banners?
class User < ActiveRecord::Base
require 'carrierwave/orm/activerecord'
mount_uploader :banner, BannerUploader
validate :banner_size_validation, :if => :banner?
validate :check_banner_dimensions, :if => :banner?
def banner_size_validation
errors.add :banner, 'should be less than 1mb' if banner.size > 1.megabytes
end
def check_banner_dimensions
tmp_banner = MiniMagick::Image.open(banner)
errors.add :banner, 'height must be no more than 400px.' if tmp_banner[:height] > 400
end
end
For example. User with ID 3 uploaded a banner at the time our validations were not enforced.
User.find(3).update_attributes!(:artist_name => 'vanilla')
# ActiveRecord::RecordInvalid: Validation failed: Banner height must be no more than 400px.
Deleting banners might disappoint users. Resizing existing banners will make some banners look 'stretchy'. Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9598548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Automating file upload using Selenium and pywinauto I am trying to automate a file uplad in a form. The form works as follows:
- some data insert
- click on add attachment button
- windows dialogue window appears
- select the file
- open it
I am using python, Selenium webdriver and pywinauto module.
Similar approach was described here but it only deals with file name and not with path to it.
Sending keys to the element with Selenium is not possible because there is no textbox that would contain the path. I have tried using AutoIT with the followin code:
$hWnd = WinWaitActive("[REGEXPTITLE:Otev.*|Op.*)]")
If WinGetTitle($hWnd) = "Open" then
Send(".\Gandalf")
Send("{ENTER}")
Else
Send(".\Gandalf")
Send("{ENTER}")
EndIf
The code basically waits for window with title Open or Otevrit (in CZ) to appear and then do the magic. This code is compiled into an .exe and ran at appropriate moment.
The code works fine and does the upload, but I can not alter the path to file. This is neccessary if I want run my code on any computer. The mobility of the code is neccessary because it is a part of a desktop application for running Selenium tests.
The window which I am trying to handle is:
Basically I would like to input my path string and open the file location. After that I would input the file name and open it (perform the upload). Currently my code looks like:
# click on upload file button:
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@class=\"qq-upload- button-selector qq-upload-button\"]"))).click()
# wait two seconds for dialog to appear:
time.sleep(2)
# start the upload
dialogWindow = pywinauto.application.Application()
windowHandle = pywinauto.findwindows.find_windows(title=u'Open', class_name='#32770')[0]
window = dialogWindow.window_(handle=windowHandle)
# this is the element that I would like to access (not sure)
toolbar = window.Children()[41]
# send keys:
toolbar.TypeKeys("path/to/the/folder/")
# insert file name:
window.Edit.SetText("Gandalf.jpg")
# click on open:
window["Open"].Click()
I am not sure where my problem is. Input the file name is no problem and I can do it with:
window.Edit.SetText("Gandalf.jpg")
But For some reason I can't do the same with the path element. I have tried setting focus on it and clicking but the code fails.
Thank you for help.
BUTTON HTML:
<div class="qq-upload-button-selector qq-upload-button" style="position: relative; overflow: hidden; direction: ltr;">
<div>UPLOAD FILE</div>
<input qq-button-id="8032e5d2-0f73-4b7b-b64a-e125fd2a9aaf" type="file" name="qqfile" style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0; height: 100%;"></div>
A: Try following code and let me know in case of any issues:
WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//input[@type="file"][@name="qqfile"]'))).send_keys("/path/to/Gandalf.jpg")
P.S. You should replace string "/path/to/Gandalf.jpg" with actual path to file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40040564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Convert double to string quickly observing given precision I have a C++ program using SDL. During rendering, I need to draw some graphics components. I sometimes need to convert double variables, rounded to one decimal, to std::string.
For this, I'm currently using a ostringstream object and it works fine.
std::ostringstream ss;
ss << std::fixed << std::setprecision(1) << x;
However, I'm wondering if this way of converting variables is a good idea with regards to performance.
I've tried to round the double variables with std::to_string(std::round(x * 10) / 10)), but it didn't work -- I still got output like 2.500000000.
*
*Is there another solution?
*Does ostringstream incur a heavy cost?
A: You can't specify the precision with std::to_string as it is a direct equivalent to printf with the parameter %f (if using double).
If you are concerned about not allocating each time the stream, you can do the following :
#include <iostream>
#include <sstream>
#include <iomanip>
std::string convertToString(const double & x, const int & precision = 1)
{
static std::ostringstream ss;
ss.str(""); // don't forget to empty the stream
ss << std::fixed << std::setprecision(precision) << x;
return ss.str();
}
int main() {
double x = 2.50000;
std::cout << convertToString(x, 5) << std::endl;
std::cout << convertToString(x, 1) << std::endl;
std::cout << convertToString(x, 3) << std::endl;
return 0;
}
It outputs (see on Coliru) :
2.50000
2.5
2.500
I didn't check the performance though... but I think you could even do better by encapsulating this into a class (like only call std::fixed and std::precision once).
Otherwise, you could still use sprintf with the parameters that suits you.
Going a little further, with an encapsulating class that you could use as a static instance or a member of another class... as you wish (View on Coliru).
#include <iostream>
#include <sstream>
#include <iomanip>
class DoubleToString
{
public:
DoubleToString(const unsigned int & precision = 1)
{
_ss << std::fixed;
_ss << std::setprecision(precision);
}
std::string operator() (const double & x)
{
_ss.str("");
_ss << x;
return _ss.str();
}
private:
std::ostringstream _ss;
};
int main() {
double x = 2.50000;
DoubleToString converter;
std::cout << converter(x) << std::endl;
return 0;
}
Another solution without using ostringstream (View on Coliru) :
#include <iostream>
#include <string>
#include <memory>
std::string my_to_string(const double & value) {
const int length = std::snprintf(nullptr, 0, "%.1f", value);
std::unique_ptr<char[]> buf(new char[length + 1]);
std::snprintf(buf.get(), length + 1, "%.1f", value);
return std::string(buf.get());
}
int main(int argc, char * argv[])
{
std::cout << my_to_string(argc) << std::endl;
std::cout << my_to_string(2.5156) << std::endl;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34744591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: confusion about array and object in JavaScript I want format like that
"attechent":[{
"name":xyz,
field: [
{ title: 'a' },
{ title: 'b' }
]
}
]
code->>
var field=[]
var obj1={"title":"a"}
var obj2={"title":"b"}
field.push(obj1)
field.push(obj2)
console.log(field)
var outerfiled={}
outerfiled.field=field
out.name="xyz"
console.log(outerfiled)
var list=[outerfiled]
console.log(list)
problem is like my code is working according to desire output format but after
output is [ { field: [ [Object], [Object] ], name: 'xyz' } ]
A: The output which you're seeing is the standart Node output when printing and Object. It shows that it has an Object, but does not print it out in detail.
JSON.stringify will allow you to format your object as required. It takes three arguments - the object to format, an optional replacer function, and an optional indent level. Note that the order of properties is not guaranteed.
In your case, you do not need to use the replacer function, so pass null as the second argument. The required indent level is 4 spaces, so you can pass the number 4 as the third argument.
var field=[]
var obj1={"title":"a"}
var obj2={"title":"b"}
field.push(obj1)
field.push(obj2)
var outerfiled={}
outerfiled.field=field
outerfiled.name="xyz"
var list=[outerfiled]
var result = {attechent: list}
// Extra args for JSON.stringify:
// no replacer function required - pass null, indent level of 4 spaces required
console.log(JSON.stringify(result, null, 4))
A: You need the right variable for the name.
outerfiled.name = "xyz";
// ^^^^^^^
and later an assignment to the result, like
var result = { attechent: list };
var field = [];
var obj1 = { title: "a" };
var obj2 = { title: "b" };
field.push(obj1);
field.push(obj2);
var outerfiled = {};
outerfiled.field = field;
outerfiled.name = "xyz";
var list = [outerfiled];
var result = { attechent: list };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A: console.log doesn't print the whole object. You can use util.inspect() if you want to print the whole object. Here is the code
var utl = require("util");
var field=[]
var obj1={"title":"a"}
var obj2={"title":"b"}
field.push(obj1)
field.push(obj2)
console.log(field)
var outerfiled={}
outerfiled.field=field
outerfiled.name="xyz"
console.log(outerfiled)
var list=[outerfiled]
console.log(utl.inspect(list, false, null))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42607050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Pseudo-random Lognormal values I'm trying to generate pairs of random values from two lognormal distributions - the catch is that one of them must be less than the other. For example:
a1 <- log(47.31)
b1 <- sqrt(2*log(50.84/47.31))
a2 <- log(47.31)
b2 <- sqrt(2*log(59.34/47.31))
x1 <- rlnorm(1,a1,b1)
x2 <- rlnorm(1,a2,b2)
I need some way of ensuring that x1 < x2. Is there any slick way to do this?
A: Well, yes and no. The simplest way is to check if the condition is met, and if not, regenerate the randoms. But the result of this is your variables are no longer characterized by the statistical distributions you started with: the filtering process biases x1 low and x2 high. But if you're okay with this, then just loop until the desired condition is met... in theory this could take an infinite number of iterations, but I assume you're not that unlucky :).
If the two distributions are the same, it's simpler: just swap them if x1 > x2 (I assume they're not equal!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11146488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is which in Perl? When I run
perl -e 'which("clang")'
in Windows Command Prompt I get an empty line, but on Linux I get:
Undefined subroutine &main::which called at -e line 1.
I am asking because I am trying to figure out why which does not work in OpenSSL build script:
# see if there is NDK clang on $PATH, "universal" or "standalone"
if (which("clang") =~ m|^$ndk/.*/prebuilt/([^/]+)/|) { ... }
where the condition is always false even if clang is in the PATH.
A: which is not a Perl builtin function.
% perl -we 'print which("clang")'
Undefined subroutine &main::which called at -e line 1.
Keep in mind the Windows command line does not use the same quoting rules as the Linux command line, unless you're using something like WSL or bash for Windows.
The subroutine which is defined at https://github.com/openssl/openssl/blob/master/Configure#L3264 (or a similar line in other versions of the code). You'll need to make sure you've got all the build dependencies installed, all the application paths and library/include paths configured correctly, that you're following the installation directions accurately, and that you're doing things in the proper order.
You'll especially want to look in https://github.com/openssl/openssl/blob/af33b200da8040c78dbfd8405878190980727171/NOTES-WINDOWS.md and https://github.com/openssl/openssl/blob/master/NOTES-PERL.md to make sure you're following the OpenSSL project's recommendations for their build system on Windows if native Windows is where you intend to do the builds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74098951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Capybara feature test (js: true, React) fails because image element forced to make request I have a form page that renders react components. These components render images that have been uploaded to the local environment (normally they are uploaded to s3).
Originally, I setup my test environment path to point to inside my spec folder (as advised in the paperclip documentation):
```
Paperclip::Attachment.default_options[:path] =
"#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension"
Paperclip::Attachment.default_options[:url] =
"#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension"
When capybara visits a page with the components, the page gets rendered properly if I remove the img element from the component, but if I include the img element, a request is made to the server based on the value specified in the image source field. The above path and url aren't public, so this causes a routing exception and my test fails. If I change spec to public, it works.
If the image is not actually being rendered, why does react/capybara/phantomjs make the request? Is there a way I can configure this stack to not make requests to the image source (for example, if I just wanted to just dummy values)?
Stack:
Rails 4
React
Capybara
Phantomjs
Poltergesit
Rspec
Paperclip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50032430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery on hover out the element still retains the hovered class. This class styles should be removed when the mouse is hovered out I want the login-btn to remain in its hover state when mouse is hovered over .login-content. I have already attempted at this, and for now it shows and hides the div on hover, but the login-btn loses its hover state when the .login-content is hovered, and the the .login-content disappears when it is hovered.
Update:
Current Issue is that the if the mouse is hovered over login and then directly hovered off.. instead of hovering over the child elements, the .hovered styles stays. This shouldnt be this way.
The HTML is as follows:
<li><a href="#" class="login-btn">Login</a>
<div class="login-content">
<form name="login-form" action="" method="post">
<input type="email" name="email" value="" placeholder="E-mail" />
<input type="password" name="password" value="" placeholder="Password" />
<input type="submit" name="login" value="Login" class="form-login" />
</form>
</div>
</li>
The jQuery code is as follows:
$(document).ready(function () {
$(".login-btn").hover(
function() {
clearTimeout($(this).data('hoverTimeoutId'));
$(".login-content").show();
$(this).addClass('hovered');
},
function() {
clearTimeout($(this).data('hoverTimeoutId'));
$(this).data('hoverTimeoutId', setTimeout(function () {
$(this).removeClass('hovered');
$(".login-content").hide();
} ,500));
});
$('.login-content').hover(
function(){
clearTimeout($(".login-btn").data('hoverTimeoutId'));
},
function(){
$(".login-content").hide();
$(".login-btn").removeClass('hovered');
});
});
The webpage can also be found at http://www.domainandseo.com/portfolio/1may/index.html if any further debugging is needed.
Thanks
A: Try
$(".login-btn").hover(
function() {
clearTimeout($(this).data('hoverTimeoutId'));
$(".login-content").show();
$(this).addClass('hovered');
},
function() {
clearTimeout($(this).data('hoverTimeoutId'));
$(this).data('hoverTimeoutId', setTimeout(function () {
$(".login-content").hide();
$(this).removeClass('hovered');
} ,500));
});
$('.login-content').hover(
function(){
clearTimeout($(".login-btn").data('hoverTimeoutId'));
},
function(){
$(".login-content").hide();
$(".login-btn").removeClass('hovered');
});
Instead of using :hover psedoclass use a class like hover assign the hovered state to
login-btn as shown in the demo
Demo: Fiddle
A: Use setTimeout
$(".login-btn").hover(
function() {
clearTimeout($(this).data('animator'));
$(this).data('animator', setTimeout(function () {
$(".login-content").show();
} ,1000));
},
function() {
clearTimeout($(this).data('animator'));
$(this).data('animator', setTimeout(function () {
$(".login-content").hide();
} ,1000));
});
http://jsfiddle.net/uDm64/
A: If you don't want to worry about the user having the cursor away for a moment, then I would suggest a little more state checking.
Also, if you want your button to appear as hovered, in your CSS selector '.login-btn:hover', change it to: '.login-btn:hover, .login-btn.hover'
Fiddle: http://jsfiddle.net/qhAus/
(function() {
var timer = 0,
open = false,
loginBtn = $('.login-btn'),
loginContent = $('.login-content'),
startTimeout = function(state, duration) {
timer = setTimeout(function() {
timer = 0;
loginContent[state]();
open = state === 'show';
if(!open) {
// If it's closed, remove hover class
loginBtn.removeClass('hover');
}
}, duration || 1000);
};
loginBtn.hover(function(e) {
$(this).addClass('hover');
if(open && timer) {
// If about to close but starts to hover again
clearTimeout(timer);
}
if(!(open || timer)) {
// Don't start to open again if already in the process
startTimeout('show');
}
}, function() {
// When not hovering anymore, hide login content
startTimeout('hide', 2000);
});
loginContent.mousemove(function(e) {
// If cursor focus on the login content, stop any closing timers
if(timer) {
clearTimeout(timer);
}
});
loginContent.mouseleave(function(e) {
// When cursor leaves login content, hide it after delay
startTimeout('hide');
});
})();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16311239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exiting program for any input that is not a list My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.
After assigning the variable ‘angle’ to both values of the input. The angle variable becomes a list type.
In norther to exit program with no error message I write this:
'if angle is not list():break'.
The problem is when I do that it exits the program for any type of command entered as an input.
here is my code:
import numpy as np
while 1:
angle=input("Please enter the angle you want to convert,\n\n"\
"If you wish to convert degrees in radiant or vise-versa,\n"\
"follow this format: 'angle/D or R'").split('/')
if angle is not list():break
angle[0]=float(angle[0])
radiant= (angle[0]*(np.pi))/180
degre=((angle[0]*180)/np.pi)
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D' :
print(radiant,'radiants')
elif angle[1] is 'R':
print(degre,'degrés')
else:break
A: You can use isinstance(angle, list) to check if it is a list. But it won't help you achieve what you really want to do.
The following code will help you with that.
question = """Please enter the angle you want to convert.
If you wish to convert degree in radiant or vice-versa.
Follow this format: 'angle/D or R'
"""
while 1:
angle=input(question).split('/')
if not isinstance(angle, list): break # This will never happen
# It will never happen because string.split() always returns a list
# Instead you should use something like this:
if len(angle) != 2 or angle[1] not in ['D', 'R']:
break
try:
angle[0]=float(angle[0])
except ValueError:
break
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D':
# You could also improve this by taking modulo 360 of the angle.
print((angle[0]*np.pi)/180, 'radiants')
else:
# Just an else is enough because we already checked that angle[1] is either D or R
print((angle[0]*180)/np.pi, 'degrees')
A: What you want:
if not isinstance(angle, list): break
What you've done: if angle is not list():break will always evaluate to True as no object will ever have the same identity as the list list(); since is is a check for identity.
Even this:
>>> list() is not list()
True
A: break statements are used to get out of for and while loops. Try using a while loop after the input statement to evaluate the input. Use a possible set as a conditional. You do not need to break from an if statement because it will just be bypassed if the the conditional is not met.
Sometimes you might see an if statement followed by a break statement. The break statement, however, is not breaking from the if statement. It is breaking from a previous for or while loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37886159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with "extra_context" in a login view I'm looking at login views rn but have troubles trying to redirect using the "next" variable that I'm trying to assign a value to inside of "extra_context" dictionary. Overriding "extra_context" in a custom view that inherits from "LoginView" also doesn't work. Redirecting with "next_page" or when hardcoding a value for GET's "next" field works fine. Here's my code.
HTML
<form class="" action="{%url 'luecken:login'%}" method="post">
{% csrf_token %}
<table>
<tr>
<td>Username: </td>
<td>{{form.username}}</td>
</tr>
<tr>
<td>Password: </td>
<td>{{form.password}}</td>
</tr>
</table>
<button type="submit" name="logInBtn">Log in</button>
<input type="hidden" name="next" value="{{next}}/">
</form>
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('c_tests/', include('luecken.urls')),
]
luecken/urls.py
from django.urls import path, include
from . import views
from django.contrib.auth.views import LoginView
# Custom urls
app_name = 'luecken'
urlpatterns = [
path('', views.homepage, name = 'homepage'),
path('login', LoginView.as_view(extra_context={'next':'/c_tests/'}), name='login')
Solved
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72006025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add buttons to the windows taskbar thumbnail JavaFX? This question has been inactive for over a year now. I still don't have a solution for my problem. I edited this to clarify my problem and bring new attention to it.
If you use Windows you probably know the small preview image (thumbnail) that is shown when you hover the icon of the programm on the taskbar.
Some programms manage (e. g. Spotify, previous versions of Git Extension) to add a button to that popup (where the red line is).
For Example: Spotify added some buttons to pause/unpause, skip, etc. I wanted to do something similar for my app.
The question is if this can be done with JavaFX and how this can be done?
I have searched the internet for a solution but I couldn't find any for JavaFX. For example: here is a solution for C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57117955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Returning arbitrary data types in golang I have a simple golang routine that uses database/sql to open a connection to my Postgres DB and does some stuff
package main
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
"log"
)
const (
DB_USER = "my_user"
DB_NAME = "my_postgres_db"
)
// The return type here is wrong - what should it be?
func establish_db_connection() sql.DB {
dbinfo := fmt.Sprintf(
"user=%s password=%s dbname=%s sslmode=disable",
DB_USER, nil, DB_NAME)
db, err := sql.Open("postgres", dbinfo)
if err != nil { log.Fatal(err) }
return db
}
func main() {
// Get a connection to the DB
db := establish_db_connection()
// Do other stuff
// ...
// ...
}
I'm having trouble writing the signature for the establish_db_connection function -
func establish_db_connection() sql.DB {
The documentation suggests it returns a sql.DB instance. So should this not be the return type?
I'm super new to golang, so just figuring most of this out for the first time.
Thanks!
A: Open returns a *sql.DB, a pointer to a sql.Db. Change the function signature to also return a *sql.DB:
func establish_db_connection() *sql.DB {
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37108480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Borders of text boxes not getting painted after validation fails I am just following a ASP.NET MVC book example and for validation we have added those [Required] attributes to the model and it works but now it has added a style sheet to highlight the fields that have issues as well.
Here is how it looks in my IE:
Notice the "red" style is being applied but the borders are not red, and this is how the book screen shot says it should look like:
and here is the CSS I have just copied from the book, so why mine doesn't make the text box border red?
.field-validation-error {color: #f00;}
.field-validation-valid { display: none;}
.input-validation-error { border: 1px solid #f00; background-color: #fee; }
.validation-summary-errors { font-weight: bold; color: #f00;}
.validation-summary-valid { display: none;}
A: For client side validation use jquery and jquery validation. Also enabled client side validation from the web.config:
add key="UnobtrusiveJavaScriptEnabled" value="true"
** Also ensure your styles are being applied using the IE developer toolbar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24471092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I display errors on login modal form when a user enters invalid credentials in Laravel 5.6? In Laravel 5.6 I am using it's default authentication feature. However I have implemented a modal to replace the default login form. I am trying to keep a login modal form open and display errors upon failed login attempt. My login modal form looks like this:
<!-- Modal HTML Markup -->
<div id="login-modal" class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h1 class="modal-title">Login</h1>
</div>
<div class="modal-body">
<div class="cs-login-form">
<form role="form" method="POST" action="{{ url('/login') }}">
<div class="input-holder">
{{ csrf_field() }}
<div class="form-group">
<label for="email" class="control-label">E-Mail Address</label>
<div>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" autofocus>
</div>
</div>
</div>
<div class="input-holder">
<div class="form-group">
<label for="password" class="control-label">Password</label>
<div>
<input id="password" type="password" class="form-control" name="password">
</div>
</div>
</div>
<div class="form-group">
<div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ url('/password/reset') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
Currently when a user enters invalid credentials the modal disappears and the user is redirected back to the home page with no errors. My login controller has not been altered and it looks like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
A: you can submit your credentials using an ajax call, then inside your success method, you can check whether it's successful or not & show error if not ok. If it's ok, you can hide modal manually & redirect user to home page.
A: You would need to setup a function manually as Laravel's documentation explains. You will also need a route and an ajax request to make the login.
Custom Login route:
Route::post('/login', 'LoginController@authenticate');
In your view you will first need to setup a meta tag with the csrf token to protect yourself from attacks:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in your ajax you could do this:
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
url: '/login',
data: [email: '', password: ''],
success: function(controllerResponse) {
if (!controllerResponse) {
// here show a hidden field inside your modal by setting his visibility
} else {
// controller return was true so you can redirect or do whatever you wish to do here
}
}
});
Custom controller method could be something like this:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return true;
} else {
return false;
}
}
*Important note: Please note that I haven't fully coded evrything since stackoverflow is about solving problems not coding for others, so you will need to figure out how to select form data with js, and create the error msg and show it when controller returns false.
Also the controller is really basic, you can improve it with features such as controlling max-login attemps from a certain user, etc..*
A: You can use session variable $_SESSION['error']. And write a if condition over your login form like
if(isset($_SESSION['error']) echo "Your error message.")
And just unset the session variable just after that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50664441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to decompress gzipstream with zlib Can someone tell me which function I need to use in order to decompress a byte array that has been compressed with vb.net's gzipstream. I would like to use zlib.
I've included the zlib.h but I haven't been able to figure out what function(s) I should use.
A: You can take a look at The Boost Iostreams Library:
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
std::ifstream file;
file.exceptions(std::ios::failbit | std::ios::badbit);
file.open(filename, std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_stream<boost::iostreams::input> decompressor;
decompressor.push(boost::iostreams::gzip_decompressor());
decompressor.push(file);
And then to decompress line by line:
for(std::string line; getline(decompressor, line);) {
// decompressed a line
}
Or entire file into an array:
std::vector<char> data(
std::istreambuf_iterator<char>(decompressor)
, std::istreambuf_iterator<char>()
);
A: You need to use inflateInit2() to request gzip decoding. Read the documentation in zlib.h.
There is a lot of sample code in the zlib distribution. Also take a look at this heavily documented example of zlib usage. You can modify that one to use inflateInit2() instead of inflateInit().
A: Here is a C function that does the job with zlib:
int gzip_inflate(char *compr, int comprLen, char *uncompr, int uncomprLen)
{
int err;
z_stream d_stream; /* decompression stream */
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = (unsigned char *)compr;
d_stream.avail_in = comprLen;
d_stream.next_out = (unsigned char *)uncompr;
d_stream.avail_out = uncomprLen;
err = inflateInit2(&d_stream, 16+MAX_WBITS);
if (err != Z_OK) return err;
while (err != Z_STREAM_END) err = inflate(&d_stream, Z_NO_FLUSH);
err = inflateEnd(&d_stream);
return err;
}
The uncompressed string is returned in uncompr. It's a null-terminated C string so you can do puts(uncompr). The function above only works if the output is text. I have tested it and it works.
A: Have a look at the zlib usage example. http://www.zlib.net/zpipe.c
The function that does the real work is inflate(), but you need inflateInit() etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14688296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: memcpy() not working as expected when copying pointers I want to copy the content of a char **pointer to another pointer. My attempt was:
void test(char **arr, int len) {
printf("1: ");
printArr(arr, len);
char ***res = malloc(sizeof(char **));
res[0] = malloc(sizeof(char *) * len);
memcpy(&res[0], arr, len);
printArr(res[0], len);
Here I just wanted to copy the contents of arr, which holds several strings, to r[0] whereby len denotes the number of elements in arr. However, when inspecting res[0] I realised that it only stores two times null. As one can tell I'm a very beginner and have been learning C since a few days, so onc can expect simple mistakes.
A: char ***res = malloc(sizeof(char **));
res[0] = malloc(sizeof(char *) * len);
memcpy(&res[0], arr, len);
The first line allocates space for a single char ** and makes res point at it
The second line allocates space for an array of len pointers to char and makes res[0] point at it.
The third line copies len byes from arr over the top of the memory pointed at by res, overwriting the result of the second malloc call and then scribbling over memory after the block allocated by the first malloc call.
You probably actually want something like
mempy(res[0], arr, len * sizeof(char*));
which will copy an array of len pointers (pointed at by arr) into the memory allocated by the second malloc call.
A: If this is an array of C strings that you need deep copied:
char** array_deep_copy(char **arr, int len) {
// calloc() makes "allocation of N" calculations more clear
// that this is N allocations of char* becoming char**
char **res = calloc(len, sizeof(char*));
for (int i = 0; i < len; ++i) {
// Use strdup() if available
res[i] = strdup(arr[i]);
}
return res;
}
Note that this needs a proper release function that will go through and recursively free() those cloned strings or this leaks memory.
If you only need a shallow copy:
char** array_shallow_copy(char **arr, int len) {
char **res = calloc(len, sizeof(char*));
// memcpy(dest, src, size) is usually more efficient than a loop
memcpy(res, arr, sizeof(char*) * len);
return res;
}
This one doesn't need a recursive free(), you can just free() the top-level pointer and you're done. This one shares data with the original, so if any of those pointers are released before this structure is then you'll have invalid pointers in it. Be careful!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66646357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading the data from socket is currupted in following condition? I am reading data from a socket packet by packet and writing into another buffer to combined all the data.
BOOL _ReadPacket(PBYTE BufferRead, DWORD &Length, SOCKET Socket)
{
WSABUF Buffer;
DWORD Flags = 0;
int Result = 0;
FILE *file;
Buffer.buf = (char *)BufferRead;
Buffer.len = Length;
Flags = 0;
Result = WSARecv(Socket, &Buffer, 1, &Length, &Flags, NULL, NULL);
// if ((file=fopen("D:/test/test1/test1.txt","a+") ) != NULL)
//{
//UINT val = Buffer.len;
//fprintf(file, "%d\n", val);
//
//fflush(file);
//fclose(file);
//}
return(Result != SOCKET_ERROR);
}
Uncommenting the commented code fixes the problem. Why do I get corrupt data when I leave the code commented out?
A: The fourth argument of WSARecv should be a pointer to the number of bytes received. However, you are passing the address of a pointer to the length of your buffer.
If you were passing the pointer, and not a pointer to a pointer, then it would be weird but it should work fine (as it won't corrupt anything). As it is now, however, it is probably writing where it shouldn't.
In short: Check and fix the fourth parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17730052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The module 'app' is an Android project without build variants I am getting below error while importing android project.
Error:The module 'app' is an Android project without build variants, and cannot be built.
Please fix the module's configuration in the build.gradle file and sync the project again.
Gradle file code.
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.djalel.android.bilal"
minSdkVersion 9
targetSdkVersion 25
versionCode 4
versionName "1.3"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt')
}
}
aaptOptions {
cruncherEnabled = false
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:25.3.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:25.3.1'
implementation 'com.android.support:support-v4:25.3.1'
implementation 'com.google.android.gms:play-services-location:12.0.1'
implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1'
implementation 'com.jakewharton.timber:timber:3.1.0'
}
repositories {
mavenCentral()
}
I checked with working gradle file as well but getting same error in this project.
A: Just install the Android SDK platform package through SDK Manager in Android Studio, relevant to your Compile SDK version. It will prompt you to install the package as well as to accept the license. After that just sync the gradle, it will resolve the issue.
A: Above gradle file code seems to be perfect. Probably its nothing to do with app/build.gradle (Module:app). Just open other build.gradle (Project:Android) file in Project window and verify your Android Studio version it must be same as yours.
I replaced from:
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
to my Android Studio v3.0.1 in my case:
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Press "Try Again" to Sync gradle file. This resolved my problem with a successful build.
A: For me, this issue appeared when I updated Android Studio to version 3.3.
Disabling experimental feature "Only sync the active variant" fixes it:
A: Try use command line to run gradlew tasks to see why the build would fail.
In my case:
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-27 Android SDK Platform 27
build-tools;27.0.3 Android SDK Build-Tools 27.0.3
So I just ran Go to Android\sdk\tools\bin sdkmanager --licenses to accept licenses and then the build passed in command line.
I think Android Studio is crying for the wrong issue. So you may check the real output in command line and find what is happening.
A: You must update your dependencies in build.grade in the buildscript block:
classpath 'com.android.tools.build:gradle:3.1.0'
to:
classpath 'com.android.tools.build:gradle:3.4.2'
A: If this error occurs for other module than 'app'
Remove gradle variable from that module's build.gradle like
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
& replace it actual value
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.71"
Clean Project -> Rebuild Project
A: I had this issue in my library project. I solved it by adding
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
To the beginning of build.gradle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49834961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: AFrame and three.js lookat function for child object I want to make a child object to look at the camera position.
In my code, the a-text object is child object of a-entity that is a sphere.
I set the lookat for a-text object to camera position. but it works wrong behavior.
I found the reason but no idea for how to solve it.
According to three.js explains (https://threejs.org/docs/#api/en/core/Object3D.lookAt)
This method does not support objects having non-uniformly-scaled parent(s).
But I don't have any idea what is uniformly-scaled parent...
A: I think it means that if you look at the parents of the object they all have the same scale.
Just to be clear, the two entities below would not work right
<a-entity scale="1 2 1">
<a-entity scale="2 2 2">
</a-entity>
</a-entity>
https://aframe.io/docs/1.0.0/components/scale.html#sidebar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62861439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Crystal Reports Cross-tab overlapping issue I need some assistance to diagnose an issue with crystal reports overlapping occurs in one of my reports where Cross tab is being used inside sub-report , the crosstab overlaps the next section, this happen just when we run the report through our web site, while it is working fine in Crystal report designer ,our current version of Crystal run time is 13_0_7 it run in 32 bit mode , the report was working fine in Crystal 2008 runtime SP3 before we upgrade our system to use the 13_0_7 version.
Thanks in advance !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32585625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Variables set of three? I'm starting to learn Python from a tutorial and I'm not sure how this bit of code works. So we have a return for jelly_beans, jars, crates in the function; however, a little below we see a new set of variables named beans, jars, crates. Does this mean that jelly_beans, jars, crates from the return can be replaced with any combo of three? Can someone break this down for me?
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
A: The function returns a tuple
return jelly_beans, jars, crates
or more explicitly
return (jelly_beans, jars, crates)
The next part is called tuple unpacking
sometuple = secret_formula(start_point)
beans, jars, crates = sometuple
since your function returns a tuple of 3,it can be unpacked to 3 variables
you can also do this in one step
beans, jars, crates = secret_formula(start_point)
A: formula = secret_formula(start_point)
print type(formula) # <type 'tuple'>
So when you are returning its return a tuple.
beans, jars, crates = secret_formula(start_point)
by this you are initialising these variables with data in tuple like this:-
In [6]: a, b, c = (1, 2, 3)
In [7]: a
Out[7]: 1
In [8]: b
Out[8]: 2
In [9]: c
Out[9]: 3
so if you do something like this even storing in a single variable it works fine,
print "We'd have {!r} formula" .format(formula)
A: def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
breakdown:
*
*Define start_point as 10,000
*Pass that into secret_formula()
*Inside secret_formula is a new 'scope' - a place where variables can exist. It's like being in a house with one-way glass windows. You can see variables in the scope outside, but the outside cannot see in. {Scope exists in part so you can have different functions using the same variable names like x and y without clashes}.
*In the secret_formula scope, create the variables jelly_beans and jars and crates and do calculations, and link (bind) the resulting numbers to those names.
*Inside secret_formula, combine these three into a tuple. That's what jelly_beans, jars, crates is doing by having them with commas between them. A tuple is a collection of a few things grouped together and treated as one thing for convenience. You can only return one thing, so this is a workaround to return three-numbers-as-one-thing. The tuple contains the numbers, not the names.
*Inside secret_formula, return the tuple and finish.
*Python clears up the secret_formula scope and removes the jelly_beans and jars and crates names that were running inside it somewhen around now. The function is no longer running and all the names used inside it have "fallen out of scope" and get cleaned up.
*The tuple coming out of the function is a group of three numbers, in order. Create three new variable names, split the three numbers up, and bind the numbers to those new names, in this outer scope.
Does this mean that jelly_beans, jars, crates from the return can be replaced with any combo of three?
Yep. NB. When print prints "%d" it's looking for a whole number, so you would have to replace them with any three numbers 3,55,100 or number variables.
A: One interesting difference between python with other languages such as java and C# is python can return several results, that is what we called tuple
So to your question:
Does this mean that jelly_beans, jars, crates from the return can be replaced with any combo of three?
My answer is yes,
after the code: the three variable would be initialized, and know the type of themselves...
beans, jars, crates = secret_formula(start_point)
if the secret_formula() function returns as:
return 1, 'a', {'key':'value'}
that also make senses, beans, jars, crates will know they are int, string and dict type respectively
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27033161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiplying a certain element in a dataframe, given that certain element is the same as the filename of a CSV file in R I am trying to solve big data problems and this involves 2 different CSV files.
If the filename of CSV1 matches a certain element in CSV2, I will multiply each element of CSV1 to that certain element of CSV2. I am using R by the way.
Let's take these as data samples:
CSV1 filename is: 318
01/01/2005 00:00 0.1
01/01/2005 01:00 0.4
01/01/2005 02:00 0.5
CSV2:
hey 318 0.08
sol 497 0.22
mat 498 0.06
thus 0.1. 0.4 and 0.5 of CSV1 must be multiplied by 0.08
A: You could do get all the filenames for which you want to apply this using list.files, loop over each filename, read it, match it with csv2 dataframe and get corresponding value to multiply.
filenames <- list.files('path/of/files', full.names = TRUE, pattern = "\\.csv$")
list_df <- lapply(filenames, function(x) transform(read.csv(x, header = FALSE),
V3 = V3 * csv2$V3[match(
tools::file_path_sans_ext(basename(x)), csv2$V2)]))
This will return you updated list of dataframes that can be accessed like list_df[[1]], list_df[[2]] etc.
where csv2 is
csv2 <- structure(list(V1 = structure(c(1L, 3L, 2L), .Label = c("hey",
"mat", "sol"), class = "factor"), V2 = c(318L, 497L, 498L), V3 = c(0.08,
0.22, 0.06)), class = "data.frame", row.names = c(NA, -3L))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60824792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Submitting request to https returns http I'm creating and angular app that uses a django backend accessed as a Api. The link for my backend is https, and one of its main purposes is to act as a database for image storage.
I am trying to grab the URLs in the backend by using http calls from my front end. It's not working because the GET calls only return Http urls not Https. This means that when the front end tries to access the url it can't be found :(
Does anyone know how I can change my code so Https is returned or can suggest me some type of workaround?
Here is my API call:
export class ImageService {
baseUrl = 'https://link.com';
constructor(private httpClient: HttpClient) { }
getBebidas() {
return this.httpClient.get(`${this.baseUrl}/bebidas`);
}
And this is an example of the return (an array of json objects):
[{image_url: "http://link.com/image}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53767491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I am having a trouble for insert an csv file data to mysql table I want to insert an csv file data to mysql database.The data is inserted but the values are in readable format.So please help me to insert an original csv data to mysql databse.
These are my php content:
<?php
include "config.php";
if($_FILES[csv][size]>0)
{
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
while ($data = fgetcsv($handle,1000,","))
{
$insert= mysql_query("INSERT INTO contacts(contact_first,contact_last,contact_email) VALUES('$data[0]','$data[1]','$data[2]')");
if($insert) { header('Location: csv_upload.php?msg=success'); }
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_REQUEST['msg'])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" size="1" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
I am getting the result is:
Your file has been imported.
contact_id firstname lastname email
1
2 ÇcÌxLÚÞœHïÚÖûï]Å›*$A°>–›¸í…J%›•ŠôaËËACMÒÛʈ÷¼ÆJꟉ&Mœ;žÖ4BÎe— tˆYÛ>c~4$”‡–
3 &Ú^Õü¼ÊÖÕ
4 [A+Mû×áœ[XK¯52áÀ‹ËÃ`Þ%p‘„ôØÿ¨ð™ýà¡7Ô!?€ÚŠàû…&aQ}É6HH;8‚ÆÉÚ`Ò¤¬iÓÖI[-Û¬/¸ÓÍùž0¶–ì þ>§±óæÌeçäâE;µ°ck;¶ÒÔàÙ“)
5 C“ì cc¾”?fñÑ}pô|6˜1%M0Á§*¡‡˜<€ä·ÍÒ¿ÿÿPK!sÛª@<#xl/worksheets/_rels/sheet1.xml.rels¼”ÁJ1†ï‚ï°än²Z¥4íTèÁ‹Öˆ›ÙÝØM²LR·}{§BÁ–.Z)KNÃÿÿ˜ÉŸÉlmëä0ï$ð”%àr¯+%{[<]ݳ$Då´ª½É6Ølzy1yZEº*Ó„„T¬Š±ò
6 ¬
7 Ü7à¨Sx´*R‰¥hT¾T%ˆašŽþÔ`Ó=Íd®%ù¾fÉbÓóïÚ¾(L>_Ypñˆ…¨H kã–$ª°„(™U¦Ž~šyîí®ùì5ù>®# S5ÇïÎ Ø qd÷
8 úå–ÕòÌVf·Ð•Dìöõ]ÆË+V0õfH}¯Ì&Ï›Š²*°î׸O²3·ùxG_²LpÉ×*]h…¾_ó8‡`šOs†è´{‚®gþC5ùùÅèQ^Ì=EV/´ ™¢9Êä{:ý+ÎwøŒ¿"0JÐŒ$Sì@´(@œ ‚lŒD]„Ëù9Ú“)Ø7áåtMö…úÎ_(Ûl¦H€ÎÃ$[R™¡$©fÍx
9 ½%’r…{„• þDRóØ6“Bˆ:žsÁ]°0’Åê¦VÚÐÕýtF‹v8¼€—¼0ÚêÊ]ÑUÅö’å’
10 xl/workbook.xmlPK-!ûb¥m”§³
A: 10 xl/workbook.xmlPK-!ûb¥m”§³
That says you're uploading an XML workbook
You would first need to convert the file to a comma delimited CSV
A: *
*Have yout tried with another csv file? Maybe it's a formating error
*Do you have to strictly do that trough php? Why not just run directly a sql query like this?
*Read this:
*
*Save CSV files into mysql database
*PHP script to import csv data into mysql
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25581163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.security.cert.CertificateException when connecting to server with multiple certificates I'm trying to create SSL connection to a website (https://www.otten-markenshop.de/), and using browser or curl it works, but neither wget, no Java manages to connect. I am mostly interested in why does Java code fail.
Here are the error details:
Using WGET:
wget https://www.otten-markenshop.de/
results in
Resolving www.otten-markenshop.de... 217.24.213.167
Connecting to www.otten-markenshop.de|217.24.213.167|:443... connected.
ERROR: certificate common name “www.plentymarkets.eu” doesn’t match requested
host name “www.otten-markenshop.de”.
Using Java:
public static void main(String[] args) throws IOException
{
URL url = new URL("https://www.otten-markenshop.de");
URLConnection connection = url.openConnection();
connection.getInputStream();
}
results in:
Exception in thread "main" javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No subject alternative DNS
name matching www.otten-markenshop.de found.
What else I have noticed is that certificate I receive in browser is different from the certificate I receive when running Java program:
in browser:
Common Name (CN):
www.otten-markenshop.de
Subject Alternative Name:
DNS Name=www.otten-markenshop.de
DNS Name=otten-markenshop.de
in Java:
Common Name (CN):
www.plentymarkets.eu
Subject Alternative Name:
And the certificate I get in Java is the same as I would receive in browser if I try to access the host by IP address: https://217.24.213.167
Thus it appears that server has multiple certificates installed and uses virtual hosts to detect which certificate should be used. But for some reason this detection does not work when client is Java or wget.
Any ideas why is this happening?
P.S. I don't have access to the destination server to see how it is configured.
P.P.S. I am interested more in understanding why the simple Java code does not work, rather than making it work by, for instance, disabling the SSL verification. After all I can connect to the mentioned URL over HTTP without any issues.
A: Having multiple certificates on the same IP address and port relies on Server Name Indication.
Your server supports it, but your client needs to support it too.
Client-side support for SNI was only introduced in Java in Java 7 (see release notes)(*). I guess you're using Java 6 or below, otherwise your simple example with URLConnection should work out of the box like this.
(You may also need additional settings if you're using another client library, such as Apache HTTP Client, depending on the version.)
(*) And this was introduced on the server side in Java 8, but that's not really your problem here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24061279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App.config Data Source Relative Path? This is the connection string to a local database on my pc:
<connectionStrings>
<add name="DataEntities"
connectionString="metadata=res://*/Data.csdl|res://*/Data.ssdl|res://*/Data.msl;
provider=System.Data.SqlServerCe.4.0;provider connection string="
Data Source=C:\Users\User\Documents\GitHub\incidentapp\incidentapp\Database\Data.sdf""
providerName="System.Data.EntityClient"/>
</connectionStrings>
However I want to move the project back-and-forth between computers. How can I set a relative path to my database if the database is in the project location which is incidentapp.
A: I got it. It's because I'm running debug, therefore the 'default' location is at the debug folder. So I just needed to move the database location to the debug folder when I'm developing.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31733056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to open String class to rewrite to_s method I want to rewrite the to_s method so that I can print the money in number_to_currency format. How do I do it? Is there any way to print all Integer or Float variables in number_to_currency format without calling number_to_currency method?
I ran this code in the console:
require 'pry'
require 'action_view'
include ActionView::Helpers
class String
def to_s(x)
number_to_currency(x)
end
end
sum = 0
0.upto(one_fifth-1) do |line_no|
sum += lo_to_hi[line_no].last
end
ap("bottom #{one_fifth} sum:#{sum}, average #{sum/one_fifth}")
and got this exception: in `to_s': wrong number of arguments (0 for 1) (ArgumentError).
A: I don't think to_s should have an argument (because the definition in the parent class (probablyObject) doesn't.). You can either use to_s as it is (no arguments) or create a new method which takes an argument but isn't called to_s
In other words, if you want to override a method you have to keep the exact same method signature (that is, its name and the number of arguments it takes).
What if you try:
class String
def to_s_currency(x)
number_to_currency(x)
end
end
A: First, the to_s method has no argument. And it's dangerous to call other methods in to_s when you don't know if that method also calls the to_s. (It seems that the number_to_currency calls the number's to_s indeed) After several attempts, this trick may work for your float and fixnum numbers:
class Float
include ActionView::Helpers::NumberHelper
alias :old_to_s :to_s
def to_s
return old_to_s if caller[0].match(':number_to_rounded')
number_to_currency(self.old_to_s)
end
end
class Fixnum
include ActionView::Helpers::NumberHelper
alias :old_to_s :to_s
def to_s
return old_to_s if caller[0].match(':number_to_rounded')
number_to_currency(self.old_to_s)
end
end
Note that in this trick, the method uses match(':number_to_rounded') to detect the caller and avoid recursive call. If any of your methods has the name like "number_to_rounded" and calls to_s on your number, it will also get the original number.
A: As, you want to print all int and float variables in number_to_currency, you have to overwrite to_s function in Fixnum/Integer and Float class, something like following:
As pointed out by Stefan, Integer and Float have a common parent class: Numeric, you can just do:
class Numeric
def to_s(x)
number_to_currency(x)
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23320876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does gets work even when I have not allocated memory to it? I recently answered a question here in SO where the problem was to input a few sentences of code and print it. My code is this:
#include<stdio.h>
int main() {
clrscr();
int line, i;
char (*string)[100];
printf("How many line?\n");
scanf("%d",&line);
getchar();
for(i=0;i<line;i++) {
gets(string[i]);
}
printf("You entered:\n");
for(i=0;i<line;i++) {
puts(string[i]);
}
return 0;
}
As you see, I haven't allocated any memory to individual strings i.e, s[0],s[1] ,....... but surprisingly my compiler didn't give me any warnings or errors for it and it works perfectly.
So I posted this code and frankly got quite a few of downvotes for it (I know I deserved it). Can you please explain why this code works and not give a segmentation error?
My output is as shown:
A: char (*string)[100];
OK, string represents a pointer to 100 char, but it's not initialized. Therefore, it represents an arbitrary address. (Even worse, it doesn't necessarily even represent the same arbitrary address when accessed on subsequent occasions.)
gets(string[i]);
Hmm, this reads data from standard input to a block of memory starting at the random address, plus i*100, until a NUL byte is read.
Not very robust. Not guaranteed to produce an error, either. If you didn't get one, the random address must have been mapped to writable bytes.
As you see, I haven't allocated any memory to individual strings i.e, s[0],s[1] but surprisingly my compiler didn't give me any warnings or errors for it and it works perfectly.
Time to reduce your expectations, or increase the diagnostic level of the compiler. Try -Wall -Wextra, if it takes options in that style. It should be warning you that string is used without being initialized first. A warning that gets has been deprecated would also be a good idea, although my compiler doesn't mention it.
C and C++ allow you to manage memory yourself. You are responsible for validating pointers. In C, this is a major source of problems.
In C++, the solution is to use alternatives to pointers, such as references (which cannot be uninitialized) and smart pointers (which manage memory for you). Although the question is tagged C++ and compiles as a C++ program, it's not written in a style that would be called C++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30961881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: why console.log(window) in js not working on regular visual studio's console? when I try to implement the below code, and I try to run on chrome. It gives me the answers what I expected. But when I compiled it inside my IDE(visual studio code), it gives me error
console.log(window) // or console.log(this)
/// Above code gives me output on the browser but not on IDE's console
////
///now again If I try to run the Below code on the IDE's console
function test(){
return this
}
console.log(test()) // it gives me the whole window object
console.log(window) // but not this
console.log(this) // output is: {}
A: Presumably, you have configured VS Code to run the code through Node.js and not through a remote debug session on a Chrome instance.
Node.js isn't a web browser. It doesn't have a window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57209716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are C++ recursive type definitions possible, in particular can I put a vector within the definition of T? For one of my projects, what I really wanted to do was this (simplifying it to the bare minimum);
struct Move
{
int src;
int dst;
};
struct MoveTree
{
Move move;
std::vector<MoveTree> variation;
};
I must admit that I assumed that it wouldn't be possible to do this directly, I thought a vector of MoveTree s within a MoveTree would be verboten. But I tried it anyway, and it works beautifully. I am using Microsoft Visual Studio 2010 Express.
Is this portable ? Is it good practise ? Do I have anything to worry about ?
Edit: I've asked a second question hoping to find a good way of doing this.
A: MoveTree is an incomplete type inside its definition. The standard does not guarantee instantiation of STL templates with incomplete types.
A: Use a pointer to the type in the Vector, this will be portable.
struct Move
{
int src;
int dst;
};
struct MoveTree;
struct MoveTree
{
Move move;
std::vector<MoveTree*> variation;
};
A: The C++ Standard (2003) clearly says that instantiating a standard container with an incomplete type invokes undefined-behavior.
The spec says in §17.4.3.6/2,
In particular, the effects are undefined in the following cases:
__ [..]
— if an incomplete type (3.9) is used as a template argument when instantiating a template component.
__ [..]
Things have changed with the C++17 standard, which explicitely allows this types of recursion for std::list, std::vector and std::forward_list. For reference, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4510.html and this answer: How can I declare a member vector of the same class?
A: The MoveTree elements in std::vector are in an allocated (as in new []) array. Only the control information (the pointer to the array, the size, etc) are stored within the std::vector within MoveTree.
A: No, it's not portable. codepad.org does not compile it.
t.cpp:14: instantiated from here
Line 215: error: '__gnu_cxx::_SGIAssignableConcept<_Tp>::__a' has incomplete type
compilation terminated due to -Wfatal-errors.
A: You should define copy constructors and assignment operators for both Move and MoveTree when using vector, otherwise it will use the compiler generated ones, which may cause problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6517231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: How to update two models? I have a select option and a list and I want to update the list when the option is selected. I've tried something but without success. The request to update the notes doesn't fire. See the code below.
<select
ng-change="timeline.selectNote()" ng-model="timeline.selectedNote" ng-options="opt as opt.NoteContent for opt in timeline.noteOptions">
<option value="">-- save note --</option>
</select>
<ul>
</select>
<ul ng-change="timeline.selectNote()" ng-model="timeline.updateNotes"
ng-repeat="note in timeline.notes">
<table border=4 bordercolor=#778899">
<tr>
<td>
{{note.Date_id}}<br>
{{note.NoteContent}}
</td>
</tr>
</table>
<br><br>
</url>
</td>
</tr>
</table>
and JS
crmControllers.controller('TimelineCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('http://local.sx.com:8080/timeline/API?emailsId=' + $routeParams.emailsId, {withCredentials: true})
.success(function(timelines) {
$scope.timelines = timelines;
angular.forEach(timelines, function(timeline) {
$http.get('http://local.sx.com:8080/note/noteAPI?&email='
+timeline.Email+ '&emailsId=' + $routeParams.emailsId, {withCredentials: true}).
success(function(note) {
timeline.noteOptions = note.NoteOptions;
timeline.notes = note.Notes;
timeline.selectNote = function() {
$http.get('http://local.sx.com:8080/note/addNoteAPI?&email='
+timeline.Email+ '¬eContent=' + timeline.selectedNote.NoteContent+
'&emailsId=' +$routeParams.emailsId, {withCredentials: true}).
success(function(addNoteRsp) {
timeline.updateNotes = function(){
$http.get('http://local.sx.com:8080/note/noteAPI?&email='
+timeline.Email+ '&emailsId=' + $routeParams.emailsId, {withCredentials: true}).
success(function(note) {
timeline.noteOptions = note.NoteOptions;
timeline.notes = note.Notes;
});
};
console.log(addNoteRsp);
});
console.log(timeline.noteOptions);
};
});
});
});
Btw does my code looks quite ugly or this is just how all js looks like ?(i.e. never never ending brackets)
A: there are few things which i am not able to understand...
<ul ng-change="timeline.selectNote()" ng-model="timeline.updateNotes"
ng-repeat="note in timeline.notes">
why ng-change and ng-model on the ul
ng-model="timeline.updateNotes"
timeline.updateNotes = function(){
updateNotes is a function, it can not be used as ng-model
given that you are you want notes for each timeline, you can just directly call the function, why wait for change??
EDIT
just to answer you comment...
if you have provided some way of saving the notes either button or form, you can do it as below
<button ng-click="updateNotes()" text="save"></button>
or
<form ng-submit="updateNotes()">
<button type="submit" text="submit"></button>
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24970779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: build elements hierarchy with jquery I need to set deep for each ul. I do
$('.topnav').find('ul').each(function(){
$(this).attr('deep', $(this).index());
})
html
<ul class="topnav dropdown" >
<li class="expand">
<a href="/posluhy">Top</a>
<ul class="subnav">
<li class="expand">
<a href="/posluhy/metalocherepycja">Sub cat 1</a>
<ul class="subnav">
<li >
<a href="/posluhy/metalocherepycja/dsafsadf">Sub Sub cat 1</a>
</li>
</ul>
</li>
<li class="expand">
<a href="/posluhy/metalocherepycja">Sub cat 2</a>
<ul class="subnav">
<li >
<a href="/posluhy/metalocherepycja/dsafsadf">Sub Sub cat 2</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
but this make deep='1' for each ul. I would like to get something like
1
2
1
2
Is that possible with jquery? Fiddle is here http://jsfiddle.net/GLjZt/1/
A: Index won't give you what you want, as it will only tell you where the element lies within a given set of elements; $(this).index() will always return 0. You need to calculate the depth based on the parent ul's:
$('.topnav').find('ul').each(function(){
$(this).attr('deep', $(this).parents('ul').length);//set attr deep
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21664994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Search for partial strings Is there a setting (or snippet) I can use to perform searches for partial string matches using apostrophe-search? For example: a search for "blue" should return the item with the title "Learning Management Blueprint".
A: Looks like adding a RegExp is what is needed. In case anyone else needs this, here is the relevant lib\modules\apostrophe-search\index.js code:
module.exports = {
perPage: 15,
construct: function(self, options) {
self.indexPage = function(req, callback) {
req.query.search = req.query.search || req.query.q;
var allowedTypes;
var defaultingToAll = false;
var cursor = self.apos.docs.find(req, { lowSearchText: new RegExp(req.query.search, 'i') } )
.perPage(self.perPage);
if (self.filters) {
var filterTypes = _.filter(
_.pluck(self.filters, 'name'),
function(name) {
return name !== '__else';
}
);
A: As you know I am the lead developer of Apostrophe at P'unk Avenue.
Your solution does work, however one serious concern with it is that you are not escaping the user's input to prevent regular expression meta-characters like . and * from being interpreted as such. For that you can use apos.utils.regExpQuote(s), which returns the string with the dangerous characters escaped via \.
There is a better way to do this though: just use req.query.autocomplete instead. Apostrophe has a built-in autocomplete cursor filter that works differently from the search filter. The autocomplete filter allows partial matches (although only at the start of a word) and then it feeds the words it finds through the regular search so that results are still sorted by match quality. It also maintains much of the performance benefit of using search.
A regular expression search like yours will scan the entire mongodb collection (well, at least all docs of the relevant type), which means you'll have performance problems if you have a lot of content.
One caveat with autocomplete is that it only "sees" words in high-priority fields like title, tags, etc. It does not see the full text of a doc the way your regex search (or the search filter) can. This was a necessary tradeoff to keep the performance up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40477498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: R: Sort data by most common value of a column I am following this stackoverflow post over here: Sort based on Frequency in R
I am trying to sort my data by the most frequent value of the column "Node_A".
library(dplyr)
Data_I_Have <- data.frame(
"Node_A" = c("John", "John", "John", "John, "John", "Peter", "Tim", "Kevin", "Adam", "Adam", "Xavier"),
"Node_B" = c("Claude", "Peter", "Tim", "Tim", "Claude", "Henry", "Kevin", "Claude", "Tim", "Henry", "Claude"),
" Place_Where_They_Met" = c("Chicago", "Boston", "Seattle", "Boston", "Paris", "Paris", "Chicago", "London", "Chicago", "London", "Paris"),
"Years_They_Have_Known_Each_Other" = c("10", "10", "1", "5", "2", "8", "7", "10", "3", "3", "5"),
"What_They_Have_In_Common" = c("Sports", "Movies", "Computers", "Computers", "Video Games", "Sports", "Movies", "Computers", "Sports", "Sports", "Video Games")
)
sort = Data_I_Have %>% arrange(Node_A, desc(Freq))
Could someone please show me what I am doing wrong?
Thanks
A: Before sorting the data you need to count the data. You can try :
library(dplyr)
Data_I_Have %>%
count(Node_A, sort = TRUE) %>%
left_join(Data_I_Have, by = 'Node_A')
# Node_A n Node_B X.Place_Where_They_Met Years_They_Have_Known_Each_Other What_They_Have_In_Common
#1 John 5 Claude Chicago 10 Sports
#2 John 5 Peter Boston 10 Movies
#3 John 5 Tim Seattle 1 Computers
#4 John 5 Tim Boston 5 Computers
#5 John 5 Claude Paris 2 Video Games
#6 Adam 2 Tim Chicago 3 Sports
#7 Adam 2 Henry London 3 Sports
#8 Kevin 1 Claude London 10 Computers
#9 Peter 1 Henry Paris 8 Sports
#10 Tim 1 Kevin Chicago 7 Movies
#11 Xavier 1 Claude Paris 5 Video Games
Or we can use add_count instead of count so that we don't have to join the data.
Data_I_Have %>% add_count(Node_A, sort = TRUE)
You can remove the n column from the final output if it is not needed.
A: As the last answer of the post you mentionend :
Data_I_Have %>%
group_by(Node_A) %>%
arrange( desc(n()))
# Node_A Node_B X.Place_Where_They_Met Years_They_Have_Known_Each_Other What_They_Have_In_Common
# <chr> <chr> <chr> <chr> <chr>
# 1 John Claude Chicago 10 Sports
# 2 John Peter Boston 10 Movies
# 3 John Tim Seattle 1 Computers
# 4 John Tim Boston 5 Computers
# 5 John Claude Paris 2 Video Games
# 6 Peter Henry Paris 8 Sports
# 7 Tim Kevin Chicago 7 Movies
# 8 Kevin Claude London 10 Computers
# 9 Adam Tim Chicago 3 Sports
# 10 Adam Henry London 3 Sports
# 11 Xavier Claude Paris 5 Video Games
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64707943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't change modes with dynamic FormView templates I have an ASP.NET page with a FormView data-bound to an ObjectDataSource that uses dynamically generated templates to render the UI based on layout information from the application's database. I've been able to get the templates to render correctly and everything seems fine until I click one of the buttons to change modes - nothing changes.
My code is based on the explanations provided in the following articles/posts:
http://www.codeproject.com/KB/aspnet/DynamicFormview.aspx
http://msdn.microsoft.com/en-us/library/ms227423.aspx
http://msdn.microsoft.com/en-us/library/y0h809ak(vs.71).aspx
http://forums.asp.net/p/1379371/2911424.aspx#2911424?Data+Binding+with+Dynamically+Created+controls+not+working+both+ways
In a nutshell, in the Page.OnInit method I assign an instance of my templates to the FormView EditItemTemplate, EmptyDataTemplate, InsertItemTemplate and ItemTemplate properties (a different instance for each property with the appropriate controls, layout, etc for that template). I see that the InstantiateIn method of the template corresponding to the default mode is called, the control hierarchy is created correctly and the UI rendered as expected.
I have a set of button controls in each of my templates that enable the mode switches. So, for instance, in the ItemTemplate, I have a button with CommandName="New". I expect that clicking this button will cause the FormView to change into the Insert mode. Instead, I get the postback and InstantiateIn is called on my ItemTemplate. The handlers I've attached to the FormView's ModeChanging and ModeChanged events do not fire.
When I step through the control hierarchy, I see the same object model as the page I created in markup - with one exception. I am using the HtmlTable, HtmlTableRow and HtmlTableCell controls to construct the layout whereas the markup uses <table>, <tr> and <td> elements.
Any thoughts on what I'm missing? I'd really like to get this working with the automatic binding (through event bubbling) to change modes rather than have to manually create and code the buttons and their actions.
Here is the code used to generate the template:
public class FormViewTemplate : INamingContainer, ITemplate
{
private Boolean _childControlsCreated;
private Panel _panel;
public FormViewTemplate(TemplateMode mode) { Mode = mode; }
public TemplateMode Mode { get; private set; }
private void CreateChildControls()
{
_panel = new Panel();
_panel.Controls.Add(CreateButtons());
switch (Mode)
{
case TemplateMode.Edit:
_panel.Controls.Add(new LiteralControl("Edit Mode"));
break;
case TemplateMode.Empty:
_panel.Controls.Add(new LiteralControl("Empty Mode"));
break;
case TemplateMode.Insert:
_panel.Controls.Add(new LiteralControl("Insert Mode"));
break;
case TemplateMode.ReadOnly:
_panel.Controls.Add(new LiteralControl("Read-Only Mode"));
break;
}
}
private Panel CreateButtons()
{
var panel = new Panel();
var table = new HtmlTable()
{
Border = 0,
CellPadding = 2,
CellSpacing = 0
};
panel.Controls.Add(table);
var tr = new HtmlTableRow();
table.Rows.Add(tr);
var td = new HtmlTableCell();
tr.Cells.Add(td);
var addButton = new ASPxButton()
{
CommandName = "New",
Enabled = (Mode == TemplateMode.ReadOnly),
ID = "AddButton",
Text = "Add"
};
td.Controls.Add(addButton);
return panel;
}
private void EnsureChildControls()
{
if (!_childControlsCreated)
{
CreateChildControls();
_childControlsCreated = true;
}
}
void ITemplate.InstantiateIn(Control container)
{
EnsureChildControls();
container.Controls.Add(_panel);
}
}
(Note that the template is cached so the control hierarchy is only built once.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4970563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PrimeNg V6 confirmationService in loop I am trying to call the confirmation service within a loop, but only the last call is being executed. Is there something that I need to change in this?
for (let x of y) {
if (conditionIsMet) {
this.confirmationService.confirm({
message: 'Question Text',
header: 'Confirmation',
icon: 'fa fa-refresh',
accept: () => {
//DO Accept Work
},
reject: () => {
//Do Rejection Work
}
});
} else {
//Do something else
}
}
A: The component is a single instance and so each time you push a new instance to the ConfirmationService you are overwriting the previous one. To call one after the other, you need to add in some way of waiting for one confirmation to be concluded before making your next call.
I did a quick test of this and got it to work by creating a 'confirmationQueue' array and then calling the service recursively like this:
this.confirmQueue = [];
for (let x of y) {
if (conditionIsMet) {
this.confirmQueue.push(x);
} else {
//Do something else
}
this.displayNextConfirm();
}
<snip>
private displayNextConfirm(): void {
if (this.confirmQueue && this.confirmQueue.length > 0) {
setTimeout(() => {
let x = this.confirmQueue[0];
this.confirmQueue = this.confirmQueue.slice(1);
this.confirmationService.confirm({
message: 'Question Text',
header: 'Confirmation',
icon: 'fa fa-refresh',
accept: () => {
//DO Accept Work
this.displayNextConfirm();
},
reject: () => {
//Do Rejection Work
this.displayNextConfirm();
}
});
}, 1);
}
}
(Note that the setTimeout(() => {...}, 1) allows the current confirm dialog to clear before the service tries to open the next one.)
Obviously there are other ways to implement this, but the key is to only submit one call to the ConfirmationService at a time and wait for that to complete before submitting the next one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55165569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Count number of Paragraphs excluding spaces I am currently working on a code to count the number of paragraphs. The only issue I have not been able to resolve is that spaces inbetween each paragraphs is also been counted. For instance, below example should return 3 but rather it returns 5 because of the empty carriage returns.
sentence 123
sentence 234
sentence 345
Full Fiddle
Is there a regex combination that can resolve this or must I write a conditional statement. Thanks
A: You can change your regexp a liitle:
.split(/[\r\n]+/)
+ character in regexp
matches the preceding character 1 or more times. Equivalent to {1,}.
Demo: http://jsfiddle.net/ahRHC/1/
UPD
Improved solution would use another regexp using negative lookahead:
`/[\r\n]+(?!\s*$)/`
This means: match new lines and carriage returns only if they are not followed by any number of white space characters and the end of line.
Demo 2: http://jsfiddle.net/ahRHC/2/
UPD 2 Final
To prevent regexp from becoming too complicated and solve the problem of leading new lines, there is another solution using $.trim before splitting a value:
function counter(field) {
var val = $.trim($(field).val());
var lineCount = val ? val.split(/[\r\n]+/).length : 0;
jQuery('.paraCount').text(lineCount);
}
Demo 3: http://jsfiddle.net/ahRHC/3/
A: Exclude blank lines explicitly:
function nonblank(line) {
return ! /^\s*$/.test(line);
}
.. the_result_of_the_split.filter(nonblank).length ..
Modified fiddle: http://jsfiddle.net/Qq38a/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22272590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Action attribute that restrict action method by url pattern Is there an action attribute that allows restricting action method by url pattern?
In my controller, I would like to to have two SearchOrder actions. One for editing order and one for viewing order. If the url path is /Order/EditOrder/SearchOrder/1, I would want it to execute this action.
[HttpGet]
[ActionName("SearchOrder")]
public ActionResult EditOrderSearchOrder()
{
. . . .
}
But if the url path is /Order/ViewOrder/SearchOrder/1, I would want it to execute this action.
[HttpGet]
[ActionName("SearchOrder")]
public ActionResult ViewOrderSearchOrder()
{
. . . .
}
A: There are many ways. Some of them are
Write in RouteConfig.cs
routes.MapRoute(
name: "Properties",
url: "Order/EditOrder/SearchOrder/{action}/{id}",
defaults: new
{
controller = "YourControllerName",
action = "SearchOrder",\\ bcoz you have given action name attribute otherwise your method name
id = UrlParameter.Optional \\ you can Change optional to Fixed to make passing Id parameter compulsory
}
);
If using Mvc5, you can do Attribute Routing by following a simple syntax:
[Route("Order/EditOrder/SearchOrder/{id?}")] // ? For optional parameter
public ActionResult EditOrderSearchOrder(){}
And
To enable attribute routing, call MapMvcAttributeRoutes in RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38018661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Define a static constexpr member of same type of a template class A similar question of non-templated class
For a template class,
template <typename T>
struct Test {
T data;
static const Test constant;
};
it's fine when defining a static constexpr member variable of specialized type:
template <>
inline constexpr Test<int> Test<int>::constant {42};
https://godbolt.org/z/o4c4YojMf
While results are diverged by compilers when defining a static constexpr member directly from a template class without instantiation:
template <typename T>
inline constexpr Test<T> Test<T>::constant {42};
https://godbolt.org/z/M8jdx3WzM
GCC compiles.
clang ignores the constexpr specifier in definition.
MSVC... /std:c++17 works well, but /std:c++20 rejects due to redefinition.
I have learnt that constexpr can be applied to the definition a variable or variable template
And in this example, which one is right? Why?
A: I think GCC is correct in accepting the given example. This is because the static data member named constant is an ordinary data member variable(although it is still considered a templated entity).
And since constant is an ordinary data member variable, dcl.constexpr#1.sentence-1 is applicable to it:
The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template.
(emphasis mine)
Thus, as the construct that you have provided after the class template is nothing but an out-of-class definition for the ordinary static data member constant, the given example is well-formed.
template <typename T>
constexpr Test<T> Test<T>::constant {42}; //this is an out-of-class definition for the ordinary static data member variable `constant`
Note
Note that dcl.constexpr#1.sentence-1 doesn't mention templated entity, but instead only mention "variable" and "variable template" and since constant is a variable(ordinary), the same should be applicable to constant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72409091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Improve performance of slow sub query in SQL Server I have a table with 1.3 million rows.
Query #1 takes 29 seconds to run in SQL Server 2016 Management Studio.
Query #1:
select
*,
(select Count(*)
from [dbo].[Results] t2
where t2.RaceDate < t1.RaceDate
and t1.HorseName = t2.HorseName
and t2.Position = '1'
and t1.CourseName = t2.CourseName
and t2.CountryCode = 'GB') as [CourseDistanceWinners]
from
[dbo].[Results] t1
But query #2 takes takes several hours with the only difference being t1.HorseName = t2.HorseName vs t1.TrainerName = t2.TrainerName. There will be many more matches but on TrainerName than HorseName but I wasn't expecting several hours.
Query #2:
select
*,
(select Count(*)
from [dbo].[Results] t2
where t2.RaceDate < t1.RaceDate
and t1.TrainerName = t2.TrainerName
and t2.Position = '1'
and t1.CourseName = t2.CourseName
and t2.CountryCode = 'GB') as [CourseDistanceWinners]
from
[dbo].[Results] t1
I've managed to get the query down to 15 minutes using the techniques below but I still think this is a very long time. Is there anything else I can do to improve performance of Query2 or a way to rewrite it for performance?
What I have tried so far
*
*I've changed [TrainerName] [nvarchar](255) NULL, to [TrainerName] [nvarchar](50) NULL,
*I've added a composite index and several non clustered indexes
CREATE INDEX idx_HorseName
ON [dbo].[Results] (HorseName);
CREATE INDEX idx_TrainerName
ON [dbo].[Results] (TrainerName);
CREATE INDEX idx_CourseName
ON [dbo].[Results] (CourseName);
CREATE INDEX idx_Position
ON [dbo].[Results] (Position);
CREATE INDEX idx_JockeyName
ON [dbo].[Results] (JockeyName);
CREATE INDEX idx_RaceDate
ON [dbo].[Results] (RaceDate);
CREATE INDEX idx_TrainerComposite
ON [dbo].[Results] (TrainerName, RaceDate, CourseName);
Further info:
Table structure:
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Results]
(
[CountryCode] [NVARCHAR](50) NULL,
[CourseName] [NVARCHAR](50) NULL,
[HorseName] [NVARCHAR](50) NOT NULL,
[HorseSuffix] [NVARCHAR](5) NOT NULL,
[JockeyName] [NVARCHAR](255) NULL,
[OwnerName] [NVARCHAR](255) NULL,
[Position] [NVARCHAR](255) NULL,
[PublishedTime] [NVARCHAR](6) NOT NULL,
[RaceDate] [DATETIME] NOT NULL,
[RaceTitle] [NVARCHAR](255) NULL,
[StallPosition] [NVARCHAR](255) NULL,
[TrainerName] [NVARCHAR](50) NULL,
[Rating] [INT] NULL,
CONSTRAINT [PK_Results_1]
PRIMARY KEY CLUSTERED ([HorseName] ASC,
[HorseSuffix] ASC,
[PublishedTime] ASC,
[RaceDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Query #1 execution plan:
Query #2 execution plan:
A: Use a window function!
select r.*,
sum(case when position = 1 and country_code = 'GB' then 1 else 0 end) over
(partition by horsename, coursename
order by racedate
rows between unbounded preceding and 1 preceding
) as CourseDistanceWinners
from [dbo].[Results] r
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58940763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Including file from PHP inside dialogbox of jQuery is misleading javascript I have 3 files (file1.php, file2.php and file3.php). Their contents are given below. When I load file1.php it shows two times the message of "Hello" in an alert box. But when I include file3.php before or after dialogbox (which is in file2.php) then it shows that message only one times (which is what I want).
Does anybody know where is the problem please?
Thanks.
The content of file1.php
<?php
some operations
require_once("file2.php");
?>
The content of file2.php
<script type="text/javascript">
$(document).ready(function() {
var dialogOpts={
autoOpen: true,
modal: false,
height: "auto",
resizable: false,
closeOnEscape: true,
width: 700,
position: ["center",30]
}
$('#learning_activity_wizard_dialog').dialog(dialogOpts);
});
</script>
<?php
some operations
?>
<div id="learning_activity_wizard_dialog" title="Learning Activity Wizard" class="dialogbox">
some content
<?php require_once("file3.php"); ?>
</div>
The content of file3.php
<script type="text/javascript">
$(function () {
alert('Hello');
});
</script>
sometext
A: When jQuery creates the dialog box, it copies everything in the learning_activity_wisard_dialog div to a new DOM node, including the script tag.
So, the tag runs once when the page loads, then again when the dialog is rendered. Move your script out of that div, or just use some bool to track whether it's already run or not.
A: When you do $('#learning_activity_wizard_dialog').dialog(dialogOpts); it will run the script again.
If you do not want this to happen, move that script tag out of the div that will later become a dialog.
A: http://jsfiddle.net/uRhQT/
i guess this is your problem, adding script tag inside a html that will load again using jquery.
The solution to this what you have only ... use the script outside the div.
Reason: The script tag content is executed when defined inline. So When your dialogbox is shown, the contents are copied to the dialogbox which makes it new inline script. So it gets executed and another alert box is shown.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6430818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Images not loading in macOS 12 & iOS 15 Mail app Around 3 weeks ago we realized images in our newsletter were not loading when opened in macOS 12 & iOS 15 Mail. When opened in different email apps, and in different versions of macOS/iOS Mail, the images would load with no problem. Switching from hosting the images on our usual, shared, server to hosting in Mailchimp also fixed the issue. The images are inserted in an img element's src attribute.
Unchecking "Block All Remote Content" in Mail's privacy settings did not fix the issue. We've downgraded our TLS to 1.2, as suggested in this thread, but that did not fix the issue.
Below are screenshots of the emails in Mail - not working, Gmail - working.
macOS/Mail
macOS/GMail
Image hosted on shared server - https://www.tjcresources.net/images/FINAL_Birthday_email.jpg
Image hosted on Mailchimp - https://mcusercontent.com/ef8c6666869c429f75ebf2f2b/images/1bba5438-ed06-45f9-2a4a-853facde56fe.jpg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71270176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: extract value from text file using shell script I have used curl to get the response from the restapi and below is the response which came and which i am saving in the text file in location for example c:/rest_api/response.txt.
{"@odata.context":"https://hosted.com/RestApi/v1/$metadata#Edm.String","value":"_tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ"}
As there will be new value everytime during response from the restapi, i want to use shell script or not sure if possible with curl just to extract only the value from this text file everytime and save it in new file but not sure how to do it:
_tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ
A: It looks like valid json. Use jq. Replace my echo with your curl:
$ echo '{"@odata.context":"h...","value":"_tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ"}' \
| jq -r .value
_tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ
In other words, just do curl ... | jq -r .value > /output/path
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68955188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IntelliJ Unable to find the path specified to a file in a Junit Test I have a test in IntelliJ (package: com.company.project.testClasses, path: src/test/java/tests/TestClass.java) that uses a file in a resources folder(package: testData.testDataFile.templatevalues, path: src/test/resources/testData/DataFile.file). In IntelliJ before today, this test would run successfully.
However, whenever I run the test within IntelliJ, I receive the following error:
java.io.IOException: The system cannot find the path specified.
The exception is being thrown in the File.java class (from java.io, jdk1.8.0_101) during the f.getPath()
if (!fs.createFileExclusively(f.getPath()))
throw new IOException("Unable to create temporary file");
return f;
}
I am able to run the test successfully on its own through command line as well as through eclipse.
The only thing I have noticed in IntelliJ that is different over the last year is that it has started to to notify me when I run the tests that: Command line is too long. In order to reduce its length classpath file can be used. Would you like to enable classpath file mode for all run configurations of your project and I must enable that within IntelliJ to begin running the test.
I have checked to make sure I have the most up-to-date version of IntelliJ (As of writing this post it is 2017.2.4) as well as restarting IntelliJ and my PC.
Is there any known solution to allow IntelliJ to recognize the file so I do not need to leave the IDE to run these tests?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46225041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Execute code if a PowerShell script is terminated Is it possible to force the execution of some code if a PowerShell script is forcefully terminated? I have tried try..finally and Traps, but they both don't seem to work, at least when I press Ctrl-C from PowerShell ISE.
Basically, I have a Jenkins build that executes a PowerShell script. If for any reason I want to stop the build from within Jenkins, I don't want any subprocess to lock the files, hence keeping my build project in a broken state until an admin manually kill the offending processes (nunit-agent.exe in my case). So I want to be able to force the execution of a code that terminates nunit-agent.exe if this happens.
UPDATE: As @Frode suggested below, I tried to use try..finally:
$sleep = {
try {
Write-Output "In the try block of the job."
Start-Sleep -Seconds 10
}
finally {
Write-Output "In the finally block of the job."
}
}
try {
$sleepJob = Start-Job -ScriptBlock $sleep
Start-Sleep -Seconds 5
}
finally {
Write-Output "In the finaly block of the script."
Stop-Job $sleepJob
Write-Output "Receiving the output from the job:"
$content = Receive-Job $sleepJob
Write-Output $content
}
Then when I executed this and broke the process using Ctrl-C, I got no output. I thought that what I should got is:
In the finally block of the script.
Receiving the output from the job:
In the try block of the job.
In the finally block of the job.
A: I use try {} finally {} for this. The finally-block runs when try is done or if you use ctrl+c, so you need to either run commands that are safe to run either way, ex. it doesn't matter if you kill a process that's already dead..
Or you could add a test to see if the last command was a success using $?, ex:
try {
Write-Host "Working"
Start-Sleep -Seconds 100
} finally {
if(-not $?) { Write-Host "Cleanup on aisle 5" }
Write-Host "Done"
}
Or create your own test (just in case the last command in try failed for some reason):
try {
$IsDone = $false
Write-Host "Working"
Start-Sleep -Seconds 100
#.....
$IsDone = $true
} finally {
if(-not $IsDone) { Write-Host "Cleanup on aisle 5" }
Write-Host "Done"
}
UPDATE: The finally block will not work for output as the pipeline is stopped on CTRL+C.
Note that pressing CTRL+C stops the pipeline. Objects that are sent to
the pipeline will not be displayed as output. Therefore, if you
include a statement to be displayed, such as "Finally block has run",
it will not be displayed after you press CTRL+C, even if the Finally
block ran.
Source: about_Try_Catch_Finally
However, if you save the output from Receive-Job to a global variable like $global:content = Receive-Job $sleepJob you can read it after the finally-block. The variable is normally created in a different local scope and lost after the finally-block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35414568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selectively sort vector c++ I have the following vector:
vector<unsigned> vec = {5, 6, 5, 4, 1, 3, 0, 4}
Now I want to sort this vector lexicographically by odd indices (and if odd indices are equal, then by the even indices). Such that the sorted vector "vec" is:
{0, 4, 1, 3, 5, 4, 5, 6}
I know std::sort is going to sort "vec" entirely. Is it possible to use std::sort to sort the vector selectively. Similarly for std::lower_bound. Is it possible to find the lower_bound using odd indices only.
I want the same effect as vector of pair. For efficiency reasons I am not storing vec as vector of pair.
A: With range-v3, you may do:
std::vector<unsigned> vec = {5, 6, 5, 4, 1, 3, 0, 4};
auto pair_view = ranges::view::zip(vec | ranges::view::stride(2),
vec | ranges::view::drop(1) | ranges::view::stride(2));
ranges::sort(pair_view);
Demo
A: Not so efficient but a working solution would be:
std::vector<std::pair<size_t,unsigned int>> temp_vec;
temp_vec.reserve(vec.size());
for(size_t i=0;i<vec.size();++i){
temp_vec.emplace_back(i,vec[i]);
}
std::sort(temp_vec.begin(),temp_vec.end(),[](auto l,auto r){
return /* some condition based on l.first and r.first*/;
});
std::transfrom(temp_vec.begin(),temp_vec.end(),vec.begin(),[](auto item){
return item.second;
});
A: This can be implemented by calling std::sort with a custom iterator, that skips indices and with a custom comparison fucnction, that compares the adjacent value if current comparison is equal.
The custom iterator can be built on top of the existing iterator. A construct like that is called an iterator adaptor. You don't need to write such iterator adaptor from scratch yourself, since boost has already done the hard work. You can use boost::adaptors::strided. If you cannot use boost, then you can re-implement it.
Much simpler solution would be to use pairs, though. Or better yet, a structure if there are sensible names for the members.
A: Not the fastest sorting algorithm but it works:
#include <vector>
#include <algorithm>
int main()
{
std::vector<unsigned> vec = { 5, 6, 5, 4, 1, 3, 0, 4 };
if (vec.size() > 1 && vec.size() % 2 == 0)
{
for (size_t i1 = 0, j1 = i1 + 1; i1 < vec.size() - 1 && j1 < vec.size(); i1+=2, j1 = i1+1)
{
for (size_t i2 = i1 + 2, j2 = i2 + 1; i2 < vec.size() - 1 && j2 < vec.size(); i2 += 2, j2 = i2 + 1)
{
if (vec[i1] > vec[i2] || (vec[i1] == vec[i2] && vec[j1] > vec[j2]))
{
std::swap(vec[i1], vec[i2]);
std::swap(vec[j1], vec[j2]);
}
}
}
}
return 0;
}
[On Coliru]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41829450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invalid Bot Configuration I am getting the below mentioned error while running the bot locally.
"Invalid Bot Configuration: Access denied while invoking lambda
function arn:aws:lambda:us-east-1:***********:function:dataCodeHook
from arn:aws:lex:us-east-1:***********:intent:DataProcess:4. Please
check the policy on this function."
My Edit relationship json is :
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com",
"Service": "lex.amazonaws.com",
"Service" :
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:*****-*****-*****"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "unauthenticated"
}
}
}
]
}
A: Changing the json as below has solved the issue.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com",
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": us-east-1:*****-*****-*****"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "unauthenticated"
}
}
}
]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48564265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.