text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How many years did Lord Vishnu's human incarnations live for?
As per this question lord Ram must live more then 10000 years as if he ruled his kingdom for 10000 yrs. So How many years did lord Rama live on the earth?
I also listen that lord Krishna lived for 125 yrs so how is so much difference in lord Ram and lord Krishna. anyway How many years did lord Krishna live on the earth
Is there any scripture there about How many years lord Parshurama and Kalki will live and rule?
A:
Shri RAma: 110+/- years
दशवर्षसहस्राणि दशवर्षशतानि च । रामो राज्यमुपासित्वा ब्रह्मलोकं प्रयास्यति ।। [source]
After serving the kingdom for several decades and ten years after [the age of] hundred, RAma proceeded towards Brahmaloka (highest of all planes).
Refer this answer for more anaylsis.
Shri Krishna: around 80 years
In Mahabharata's trusted edition, I could find only Drona (85) & Abhimanyu's (16) ages at war time. And based on Gandhari's curse of 36 years, we can infer all the other characters' ages.
If Bhishma was 85-90 years, then Yudhishtira would have been at least 40 years younger to him. Which makes him 45+/- years and hence Krishna & Arjuna around 43+/- years. After 36 years, Krishna died during Yadavas' civil war, hence his age would likely be less than 80.
Refer this answer for scriptural based analysis.
Additional verse: In Shrimad Bhagavatam 11.6.25, there is a following verse:
yadu-vaṁśe ’vatīrṇasya bhavataḥ puruṣottama śarac-chataṁ vyatīyāya pañca-viṁśādhikaṁ prabho
Now they have translated as "hundred and twenty five years". However it can also be interpreted as following, if done word by word:
The best among the men, who descended in Yadu dynasty; O lord you would live hundred autumns, after passing twenty five more [years].
Which means Krishna was at the age of 75 years, when this was said. Had he passed 25 autumns more, he would have finished 100 years. In Sanskrit, a sentence can often be interpreted in more than 1 ways. Also, it matches with the Mahabharata based age of Krishna of <80 years, as mentioned in the linked answer.
Lord Kalki: Unspecified
Kalki is a futuristic avatAra and there are lots of stories around him. MahabhArata mentions that, he will be born during beginning of next Satyuga. Nothing much about life span.
| {
"pile_set_name": "StackExchange"
} |
Q:
Security review checklist for a smart contract
Is there a tool, checklist of methodology to help reviewing smart contract security?
E.g. for each of function you review
Is there re-entry possibility and how it behaves on re-entry
How it behaves if loops run out of gas
How it behaves if stack limit is reaches
... and so on.
If no such tool is available is there a good source or list for all known failure modes of Ethereum smart contract security?
A:
This is the community wiki (no reputation) answer for possible attacks and how to protect against them. Feel free to update the list. If your contract functions have characteristics matching prerequisites carefully evaluate your function against given advice.
This is the list of potential attacks or mispractices enabling those attacks only. For additional resources for smart contract programming best practices see Resources link at the end of the answer.
Have unit tests
Try to ensure that your Solidity code has 100% code coverage with an automated test suite. This ensures your code is testable. The automatic test suite covers and runs every line and branch of the smart contract code at least once. Test
Solidity unit tests are usually written in TypeScript (OpenZeppelin test enviroment, Python (web3.py) or JavaScript (Truffle).
Tests will do transactions against the smart contract and check that the state of the transaction is as indented post-transaction. (Pendatically, the state is always as the letter of the contract, however in this case the letter and the indent would not match.)
Test for positive cases and negative cases - i.e. things that should not happen even though you know that it does not happen. Sometimes, when the code lives and is updated, some new issues slip through and they would be caught by the past tests - this is called regression testing.
Doing audits without tests is not very productive, as the tests should be always the first line of defence what comes to write robust code.
Set up Github continuous integration that executes all the tests for everyone commit. Reports are automatically stored for the future. This also helps other people to replicate the test environment and run it later, as often due to package upgrades the test runner tools themselves start to fail.
Example
Hegic incident
Correct use of function visibility modifiers
Internal functions are marked as such and only the proper author can call the function.
Please see The Parity Wallet Hack Explained.
Call stack attack
Synonyms: Shallow stack attack, stack attack
Prerequisites: Functions uses send() or call()
Invoking: The attacker manipulates cross-contract call stack to call() to fail by calling contract with stack of 1023.
Protection: Always check return value of a send() and call(). Prefer someAddress.send() over someAddress.call.value()
More info
http://martin.swende.se/blog/Devcon1-and-contract-security.html
Re-entrancy attack
Synonyms: Race condition
Prerequisites: Functions uses send() or call() for ethers, or transferFrom() for ERC-20 tokens or send() for ERC-777 tokens.
Invoking: The untrusted called contract calls the same function back, having it in unexpected state. This is how TheDAO was hacked.The attack can be chained over several of functions (cross function race condition).
Protection: Protect your functions with re-entrancy guards. Use Check-Effect-Interact order of actions in your functions that call anything that could be reflected back to the smartcontract.
Check-effects-interact
Use this pattern to minimize the damage of potential re-entry attack.
First Check, run things like require()
Then Effect, update counters, like balance[address] -= 10
Last, do anything that is Interact and will run code in other contracts through send(), call(), transferFrom() and others.
More info
https://github.com/ConsenSys/smart-contract-best-practices
https://twitter.com/bneiluj/status/1251448415503908864
Does reentrancy attack happens as soon as the balance in storage is modified after the withdrawal?
DoS with unexpectd throw
Prerequisites: Functions uses send() or call() with throw following on fail
Invoking: The attacker manipulates the contract state so that send() always fails (e.g. refund)
Protection: Prefer pull payment system over send()
More info
https://github.com/ConsenSys/smart-contract-best-practices
Malicious libraries
Prerequisites: Using an external contract as a library and obtaining it through the registry.
Invoking: Call another contract function through a contract registry (see library keyword in Solidity).
Protection: Ensure no dynamic parts which can be swapped out in future versions.
http://martin.swende.se/blog/Devcon1-and-contract-security.html
Integer overflow
Prerequisites: Function accepts an uint argument with is used in math
Invoking: Sending very big or very negative integer causing the sum calculation to overflow
Protection: Always check the order of values when doing math operations. E.g. https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
More info
Is it possible to overflow uints?
Integer division round down
Prerequisites: Payment logic requires division operator /
Invoking: Programmer's error
Protection: Be aware that divisions are always rounded down
Loop length and gas manipulation
Others: Allocating too small int for arrays
Prerequisites: Any loop, copy arrays or strings inside the storage. A for loop where contract users can increase the length of the loop. Consider voting scenario loops.
Invoking: The attacker increases the array length or manipulates block gas limit
Protection: Use pull style payment systems. Spread send() over multiple transactions and check msg.gas limit.
https://blog.ethereum.org/2016/06/10/smart-contract-security/
https://github.com/ConsenSys/smart-contract-best-practices
https://ethereum.stackexchange.com/a/7298/620
Fallback function consuming more than the limit of 2300 gas
Prerequisites: A Solidity contract with catch all function() { } to receive generic sends
Invoking: Programmer's error
Protection: 100% test coverage. Make sure your fallback function stays below 2300 gas. Check for all branches of the function using test suite. Don't store anything in fallback function. Don't call contracts or send ethers in fallback function.
More info:
https://blog.ethereum.org/2016/06/10/smart-contract-security/
https://github.com/ConsenSys/smart-contract-best-practices
Forced balance update
Prerequisites: Function reads contract total balance and has some logic depending on it
Invoking: selfdestruct(contractaddress) can forcible upgrade its balance
Protection: Don't trust this.balance to stay within given limits
More
https://github.com/ConsenSys/smart-contract-best-practices
Miner frontrunning
Synonym: Transaction-Ordering Dependence (TOD)
Prerequisites: A bid style market, like DAI liqudation and auctions
Invoking: The attacker sees transactions in a mempool before they are finalized in blockchain. The attacker has a priviledged connection, like a mining pool, to broadcast his transaction first and override the original benefactor.
Protection: Pre-commit schemes
More
https://www.theblockcrypto.com/post/45750/exploring-defi-trading-strategies-arbitrage-in-defi
https://github.com/ConsenSys/smart-contract-best-practices
Static analysis tools
Static analysis tools that check the code for commonly known errors, like integer oveflows. They cannot check the intent of the code, but they run try to analyse the code against well known common problems.
Myhtril
Slither
Resources
OpenZeppelin checklist for things to do before a smart contract audit
https://github.com/ConsenSys/smart-contract-best-practices
https://blog.ethereum.org/2016/06/10/smart-contract-security/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to superset effectively?
I am just starting to incorporate some dumbbell exercises in my workout. I try to reduce pauses between exercises to get more stuff done in the same time and spend less time waiting.
At the moment I am doing a routine of three different exercises:
hammer curl, shoulder press and front squats.
All 5x5, each dumbbell loaded with 2.5kg and 2.4kg bar weight.
I wonder how to order them and which (dis)advantages each order would have.
Each exercise on its own:
5x5 curl, 5x5 press, 5x5 squat.
Wait between sets.
One set of each, then repeat:
5x (5 curl, 5 press, 5 squat)
Wait only some seconds between sets
One rep of each, then repeat:
5x5 (curl, press, squat)
Wait only some seconds between sets
Last time I did this routine I did the last version and it felt OK.
I am still wondering how the order influences what effects I get from the exercises.
A:
How you organize your sets determines what you get out of them.
Each exercise on its own: 5x5 curl, 5x5 press, 5x5 squat. Wait between sets.
This is the most strength-oriented of the options. It will involve some hypertrophy and some token conditioning. Note, however, that squatting the same weight that you press and curl will not challenge your legs or back nearly as much as your shoulders and biceps.
One set of each, then repeat: 5x (5 curl, 5 press, 5 squat). Wait only some seconds between sets.
I would call this supersetting. It looks like it would primarily work hypertrophy, but there is substantial strengthiness involved too, and a fair bit of conditioning and endurance. Adding weight will eventually become difficult.
One rep of each, then repeat: 5x5 (curl, press, squat). Wait only some seconds between sets.
I would call this a dumbbell complex, which primarily stresses your conditioning, though it will definitely make you stronger. I bet it will be hard to add weight to this for very long, since you're not taking much rest, and you're putting three exercises together instead of doing them individually.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory leak from malloc through tokenise function in C
I'm encountering a memory leak when I exit my program (found using valgrind) from the tokenize function I've written. Outside of this function, after I assign the tokens to other variables, I call free(tokens) where appropriate, but this doesn't fix the problem. Any help would be hugely appreciated!
Code:
/**
* Splits user input into an array of tokens.
**/
char ** tokenize(const char * s, int * n)
{
/* Sets array of strings and allocates memory, sized appropriately. */
int i;
char * token;
char ** tokens = malloc((BUF_LEN + EXTRA_SPACES) *sizeof(*token));
char buf[BUF_LEN];
strncpy(buf, s, BUF_LEN);
/* Defines first token by a whitespace. */
token = strtok(buf, " ");
i = 0;
/* While loop defines all consequent tokens also with a whitespace. */
while (token)
{
tokens[i] = malloc((strlen(token)+EXTRA_SPACES) *sizeof(*token));
strncpy(tokens[i], token, strlen(token));
i++;
token = strtok(NULL, " ");
}
* n = i;
return tokens;
}
A:
I added a function to free your array and checked it with valgrind that there is no memory leak.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <memory.h>
size_t BUF_LEN = 32;
int EXTRA_SPACES = 16;
int length = 0;
char ** tokenize(const char * s, int * n)
{
/* Sets array of strings and allocates memory, sized appropriately. */
int i;
char * token;
char ** tokens = malloc((BUF_LEN + EXTRA_SPACES) *sizeof(*token));
char buf[BUF_LEN];
strncpy(buf, s, BUF_LEN);
/* Defines first token by a whitespace. */
token = strtok(buf, " ");
i = 0;
/* While loop defines all consequent tokens also with a whitespace. */
while (token)
{
tokens[i] = malloc((strlen(token)+EXTRA_SPACES) *sizeof(*token));
strncpy(tokens[i], token, strlen(token));
i++;
token = strtok(NULL, " ");
length++;
}
* n = i;
return tokens;
}
/* deallocates an array of arrays of char*, calling free() on each */
void free_argv(char **argv, unsigned rows) {
for (unsigned row = 0; row < rows; row++) {
free(argv[row]);
}
free(argv);
}
int main ()
{
int i = 12;
char ** ch = tokenize("abc", &i);
free_argv(ch, (unsigned) length);
}
Output
valgrind ./a.out
==28962== Memcheck, a memory error detector
==28962== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==28962== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==28962== Command: ./a.out
==28962==
==28962==
==28962== HEAP SUMMARY:
==28962== in use at exit: 0 bytes in 0 blocks
==28962== total heap usage: 2 allocs, 2 frees, 67 bytes allocated
==28962==
==28962== All heap blocks were freed -- no leaks are possible
==28962==
==28962== For counts of detected and suppressed errors, rerun with: -v
==28962== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
| {
"pile_set_name": "StackExchange"
} |
Q:
.htaccess in Symfony2-based website
I've installed Piwik on the root of my Symfony2-based website (which should accessible at mywebsite.com/piwik/index.php) and I've tried to configure my .htaccess file so I can get around the 'No route found for "GET /piwik/index.php"' exception.
The problem is I am not good enough at configuring .htaccess, as a result I still get the above exception. Of course, I have to read tutorials. This is how I have tried to configure my .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^piwik/ - [L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app.php [QSA,L]
</IfModule>
Any suggestions ? Thanks in advance.
A:
Symfony ships with this rewrite rule as a default in web/.htaccess:
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
So you should be able to drop the piwik/ directory within the web/ directory (thus, index.php will be [SymfonyAppRoot]/web/piwik/index.php) and access the page there.
By doing this, you allow Apache to serve /piwik/index.php before Symfony has a chance to get in the way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Both if and else statement called randomly
I have a method which parses HTML. In there there is an if/else statement:
if ((NSNumber1 == NSNumber2)) {
NSLog(@"dafuq1?");
} else {
NSLog(@"dafuq2?");
}
The log is sometimes like this:
...:dafuq1?
...:dafuq2?
So both parts are called. But other times just one of them gets called! Why?
Btw. iOS 7.0.4, Xcode 5.0.1
And
(NSNumber1 == NSNumber2) is true
A:
These are objects. You can't use == to compare equality. Use isEqualToNumber:.
if ([NSNumber1 isEqualToNumber:NSNumber2])
| {
"pile_set_name": "StackExchange"
} |
Q:
QTableView, select and shift+click
I have a small but quite annoying problem with Qt's QTableView
Since my view is used in a StackedLayout, I have to select a line based on a field in an other page (that part works ok).
So when I display this view, I select the line I want with a simple
QItemSelection selection = line2selection(line);
d_view->selectionModel()->select(selection, QItemSelectionModel::Select);
where line2selection creates a QItemSelection filled with all the indexes for the whole line.
As I sais, this part works ok, but introduce another problem:
When I do a shift+click to select several lines at once (which works great if I don't select a line "programatically"), it always stars the selection from the first line instead of the starting from the line currently selected.
Any idea how I could fix the problem?
btw, I tried to call the selectRow method on my view too, but doesn't seem to be much better...
A:
add the QItemSelectionModel::Current flag to QItemSelectionModel::Select so the "current" item index is updated, this index acts as the anchor for the shift+click multi-selects
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery / ajax form not passing button data
I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
A:
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ALWAYS select the last item in the list
I need to select the last item in a DYNAMIC list. The following is my script. Thanks!
WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
//select.selectByVisibleText("last item");
//select.selectByIndex(0);
//select.selectByValue("value");
Please see the page HTML below. Let me know if I can provide you with any other info. Thanks!
<div id="overview_form">
<ol>
<li>
<span>1.</span>
<label class="input_label" for="sites">Sites*</label>
<div class="select2-container select2-container-active select2-dropdown- open" id="s2id_autogen1" style="width: 500px;">
<a tabindex="-1" class="select2-choice" onclick="return false;" href="javascript:void(0)">
<span>www.roger.com_20150210075155</span>
<abbr style="display:none;" class="select2-search-choice-close"></abbr>
<div><b></b></div></a>
<input type="text" class="select2-focusser select2-offscreen" disabled="disabled">
</div>
<select style=" size="1" name="siteKey" class="select2-offscreen" tabindex="-1">
<option value="30518">www.roger.com_20150209191817</option>
<option value="30520">www.roger.com_20150209192123</option>
<option value="30522">www.roger.com_20150209192351</option>
<option value="30524">www.roger.com_20150209192910</option>
<option value="30528">www.roger.com_20150209193425</option>
<option value="30529">www.roger.com_20150209193801</option>
<option value="30531">www.roger.com_20150209194009</option>
<option value="30546">www.roger.com_20150210074133</option>
<option value="30548">www.roger.com_20150210074359</option>
<option value="30550">www.roger.com_20150210075155</option></select>
</li>
</ol>
</div>
A:
How about something like:
WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
select.selectByIndex(select.getOptions().size()-1);
| {
"pile_set_name": "StackExchange"
} |
Q:
Jhipster package.json issue in Mac
OS: 10.9.2
I am using jhipster generator, and it seems to be an issue with package.json in mac, do we have any work around?
Below is the error:
npm ERR! Error: ENOENT, utime '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/readable-stream/package.json'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR! <http://github.com/npm/npm/issues>
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/hmajumdar/Work/sandbox/jhipster
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.9
npm ERR! path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/readable-stream/package.json
npm ERR! fstream_path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/readable-stream/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call utimes
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:305:19
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: ENOENT, utime '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits/package.json'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR! <http://github.com/npm/npm/issues>
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/hmajumdar/Work/sandbox/jhipster
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.9
npm ERR! path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits/package.json
npm ERR! fstream_path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call utimes
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:305:19
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm http 304 https://registry.npmjs.org/promised-io
npm http GET https://registry.npmjs.org/win-spawn
npm ERR! Error: ENOENT, lstat '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/typedarray/package.json'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR! <http://github.com/npm/npm/issues>
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/hmajumdar/Work/sandbox/jhipster
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.9
npm ERR! path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/typedarray/package.json
npm ERR! fstream_path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/typedarray/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm http 304 https://registry.npmjs.org/uuid
npm http GET https://registry.npmjs.org/get-urls
npm http 304 https://registry.npmjs.org/astral-pass
npm http GET https://registry.npmjs.org/decompress
npm http GET https://registry.npmjs.org/get-stdin
npm ERR! Failed to parse json
npm ERR! Unexpected end of input
npm ERR! File: /Users/hmajumdar/.npm/tape/0.2.2/package/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/hmajumdar/Work/sandbox/jhipster
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.9
npm ERR! file /Users/hmajumdar/.npm/tape/0.2.2/package/package.json
npm ERR! code EJSONPARSE
npm http 304 https://registry.npmjs.org/win-spawn
npm http 304 https://registry.npmjs.org/get-urls
npm http 304 https://registry.npmjs.org/decompress
npm http 304 https://registry.npmjs.org/get-stdin
npm http GET https://registry.npmjs.org/object-keys
npm ERR! Error: ENOENT, lstat '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/uglify-js/lib/output.js'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR! <http://github.com/npm/npm/issues>
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/hmajumdar/Work/sandbox/jhipster
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.9
npm ERR! path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/uglify-js/lib/output.js
npm ERR! fstream_path /Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-uglify/node_modules/uglify-js/lib/output.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
1910 error error rolling back Error: ENOTEMPTY, rmdir '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-cssmin/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits'
1910 error error rolling back [email protected] { [Error: ENOTEMPTY, rmdir '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-cssmin/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits']
1910 error error rolling back errno: 53,
1910 error error rolling back code: 'ENOTEMPTY',
1910 error error rolling back path: '/Users/hmajumdar/Work/sandbox/jhipster/node_modules/grunt-contrib-cssmin/node_modules/maxmin/node_modules/gzip-size/node_modules/concat-stream/node_modules/inherits' }
1911 error Failed to parse json
1911 error Unexpected end of input
1912 error File: /Users/hmajumdar/.npm/tape/0.2.2/package/package.json
1913 error Failed to parse package.json data.
1913 error package.json must be actual JSON, not just JavaScript.
1913 error
1913 error This is not a bug in npm.
1913 error Tell the package author to fix their package.json file. JSON.parse
1914 error System Darwin 13.1.0
1915 error command "node" "/usr/local/bin/npm" "install"
1916 error cwd /Users/hmajumdar/Work/sandbox/jhipster
1917 error node -v v0.10.28
1918 error npm -v 1.4.9
1919 error file /Users/hmajumdar/.npm/tape/0.2.2/package/package.json
1920 error code EJSONPARSE
1921 verbose exit [ 1, true
A:
I think it was due to the way NPM was being installed in my machine, I cleared some caches and reinstalled npm. That solved it.
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript in iframe to access and modify select element of parent
I have this line of code that works fine for me:
$("#select_mod_completed_project option[value='" + projectname + "']").remove();
it basically just removes one of the options from my select box. The option to be removed is defined in the 'projectname' js var. Now this works fine for me when running in a single window but I need to to run from an iframe and the select box will be in the parent of that iframe.
A:
In the parent document, set a function that executes this code:
function removeOption(projectname) {
$("#select_mod_completed_project option[value='" + projectname + "']").remove();
}
Then just call it from the iframe using window.parent:
parent.removeOption('test');
| {
"pile_set_name": "StackExchange"
} |
Q:
Basic Open Problems in Functional Analysis
Hello I was wondering if there exists open problems in functional analysis that don't require too much machinary for studying them, I mean, problems that don't require high level prerequisites.. Does anyone know any of them:
A:
A quick Google search gave this (from 2004), which looks like what you wanted(?): You'll have to check if they have been solved since then.
http://www.eweb.unex.es/eweb/extracta/Vol-20-1/20J1Masly.pdf
Also, you can try here:
http://aimpl.org/
| {
"pile_set_name": "StackExchange"
} |
Q:
how to solve Pyqt5 create web browser when load html crash
I created a web browser by PyQt5 ,if I load url="http://www.google.com" have nothing issues,but if I load url = "http://192.168.0.106/get.html" ,run the code, the widgets crash.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
"""docstring for MainWindow"""
def __init__(self, *arg,**kwargs):
super(MainWindow, self).__init__(*arg,**kwargs)
self.setWindowTitle("Load huobi exchange bar")
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://192.168.0.106/get.html"))
self.setCentralWidget(self.browser)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
bellow is the content of get.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>huobi exchange bar</title>
</head>
<body>
<!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container">
<div class="tradingview-widget-container__widget"></div>
<div class="tradingview-widget-copyright"><a href="https://cn.tradingview.com/crypto-screener/" rel="noopener" target="_blank"><span class="blue-text">sample</span></a>TradingView</div>
<script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-screener.js" async>
{
"width": 1100,
"height": 512,
"defaultColumn": "overview",
"defaultScreen": "general",
"market": "crypto",
"showToolbar": true,
"colorTheme": "dark",
"locale": "zh_CN"
}
</script>
</div>
<!-- TradingView Widget END -->
</body>
</html>
my question is :how to solve the window crash when load about async js?
A:
I do not understand why the application is broken because even if the url did not exist this should show you the error page so if you want more details of the error you should run the code in the console/CMD.
On the other hand you do not indicate that any server executes the HTML, in addition it is not necessary to use the "http://192.168.0.106" host, just load it as a local file:
├── get.html
└── main.py
import os
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MainWindow(QMainWindow):
"""docstring for MainWindow"""
def __init__(self, *arg, **kwargs):
super(MainWindow, self).__init__(*arg, **kwargs)
self.setWindowTitle("Load huobi exchange bar")
self.browser = QWebEngineView()
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, "get.html")
url = QUrl.fromLocalFile(filename)
self.browser.setUrl(url)
self.setCentralWidget(self.browser)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
| {
"pile_set_name": "StackExchange"
} |
Q:
Doctrine 2 persist only save header object why?
I want save purchase order header with purchase order details.This my PurchaseOrder Entity Class=>
namespace AppBundle\Entity;
use AppBundle\Entity\PurchaseInvoiceDetail;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* PurchaseOrder
*
* @ORM\Table(name="purchase_order", indexes={@ORM\Index(name="fk_purchase_order_supplier1_idx", columns={"supplier_id"})})
* @ORM\Entity
*/
class PurchaseOrder
{
/**
* @var PurchaseOrderDetails
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\PurchaseOrderDetails", mappedBy="purchaseOrder",cascade={"cascade"})
* @JMS\Type("ArrayCollection<FinanceBundle\Entity\AutoAllocation>")
*/
private $purchaseOrderDetails;
public function __construct()
{
$this->purchaseOrderDetails = new ArrayCollection();
}
public function addPurchaseOrderDetail(PurchaseOrderDetails $purchaseOrderDetails)
{
$this->purchaseOrderDetails->add($purchaseOrderDetails);
}
/**
* @return PurchaseOrderDetails
*/
public function getPurchaseOrderDetails()
{
return $this->purchaseOrderDetails;
}
/**
* @param PurchaseOrderDetails $purchaseOrderDetails
*/
public function setPurchaseOrderDetails($purchaseOrderDetails)
{
$this->purchaseOrderDetails = $purchaseOrderDetails;
}
}
and PurchaseOrderDetail class as this =>
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PurchaseOrderDetails
*
* @ORM\Table(name="purchase_order_details", indexes={@ORM\Index(name="fk_purchase_order_details_purchase_order1_idx", columns={"purchase_order_id"}), @ORM\Index(name="fk_purchase_order_details_invt_item1_idx", columns={"id_item"})})
* @ORM\Entity
*/
class PurchaseOrderDetails
{
/**
* @var \AppBundle\Entity\PurchaseOrder
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\PurchaseOrder",inversedBy="purchaseOrderDetails")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="purchase_order_id", referencedColumnName="id")
* })
*/
private $purchaseOrder;
/**
* Set purchaseOrder
*
* @param \AppBundle\Entity\PurchaseOrder $purchaseOrder
*
* @return PurchaseOrderDetails
*/
public function setPurchaseOrder(\AppBundle\Entity\PurchaseOrder $purchaseOrder = null)
{
$this->purchaseOrder = $purchaseOrder;
return $this;
}
/**
* Get purchaseOrder
*
* @return \AppBundle\Entity\PurchaseOrder
*/
public function getPurchaseOrder()
{
return $this->purchaseOrder;
}
}
my php code in symfony 3.1 as follows=>
$em = $this->getDoctrine()->getManager();
$purchaseOrder = new PurchaseOrder();
$puchaseOrderDetail = new PurchaseOrderDetails();
$puchaseOrderDetail->setPrice(100);
$purchaseOrder->setPurchaseOrderDetails($puchaseOrderDetail);
$puchaseOrderDetail->setPurchaseOrder($purchaseOrder);
$em->persist($purchaseOrder);
$em->flush();
no errors occurred and just only purchase order have persisted and purchase order detail doesn't
A:
You are not persisting the detail object. Either persist it manually with
$em->persist($purchaseOrderDetail);
or fix
cascade={"persist"}
in the @ORM\OneToMany annotation of PurchaseOrder::$purchaseOrderDetails (cascade={"cascade"} is probably a typo).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is aniki more "rude" than niisan?
Older brother in Japanese is "Niisan" or "Oniisan", but in your family it is used as "Ani". I have also heard that "Aniki" can be referred as brother, but is more rude. I do not understand in what way it can be more rude, with that "ki".
In the case that aniki can be used, is it proper to also refer to your brother like, for example, Taka-ni (adding the ni at the end?)
Thank you.
A:
兄貴 is not really rude, but rough and slangy. In manga and anime, certain people such as gangs and tomboyish girls tend to use 兄貴 to refer to their own older brothers or bosses. Such people use 兄貴 to refer to someone else's brother without being offending. In real life, I occasionally hear 兄貴, but it's not common. If I'm not mistaken it's like "bro" in English. In formal settings you should avoid using this word regardless of whether it's your brother or someone else's brother.
Adding 兄【にい】 after someone's name tends to sound childish, and it's not very common outside of manga/anime worlds, either. I can imagine a fictional tomboyish female teenager who addresses her brother with ○○にい and refers to him as 兄貴 at the same time. But I doubt you can safely do the same thing in real life.
The kanji 貴 on its own means "noble" or "rare", but some words containing this kanji went through a drastic change in meaning over time. A typical example is 貴様, which was an honorific word in archaic Japanese, but is almost always derogatory in modern Japanese.
| {
"pile_set_name": "StackExchange"
} |
Q:
DLL exporting only certain templatized functions
Hey all, so this seems to be a rather strange issue to me. I have a very simple templatized container class which is part of a DLL. The entire class is defined in a header file, to allow automatic template generation. Now another part of the DLL actually requests a certain template type to be generated, so the code should exist within the DLL. However, when using the object from another executable, the constructor/destructor, plus multiple other functions work, however 2 functions are not found by the linker. Following are is the code for these two functions, as well as for a working function.
const T** getData() const
{
return m_data;
}
int getNumRows() const
{
return m_nRows;
}
int getNumCols() const
{
return m_nCols;
}
So the getNumRows() and getNumCols() functions are not found by the linker, however the getData() function is. Is this a common problem, do the functions need to have a templatized parameter in order to be generated?
@1 800 INFORMATION
I have exported this from the DLL via a standard macro:
#ifdef ACORE_EXPORTS
#define ACORE_API __declspec(dllexport)
#else
#define ACORE_API __declspec(dllimport)
#endif
And at the class definition:
template < class T >
class ACORE_API matrix
A:
The compiler will only generate member functions that are actually called.
For instance:
template <class T>
class MyClass
{public:
int function1()
{
return 0;
}
int function2()
{
T t;
t->DoSomething();
return 0;
}
};
and then later
MyClass<int> m;
m.function1();
compiles, because MyClass::function2() was never compiled.
You can force the instantiation of the entire class by doing this:
template class MyClass<int>;
In that case, every method in the class will be instantiated. In this example, you get a compiler error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Formatting Eighth Notes in LilyPond
These are the notes that LilyPond is producing
How do I make the notes look like this instead?
(I edited this image, sorry if the last eighth note looks bad)
A:
Instead of
c8\> d! c d c r8\!
try
c8[\> d!] c[ d] c r8\!
The square brackets override LilyPond's defaults in beaming quavers.
Addendum
Refer to LilyPond's documentation regarding changing the default beaming behavior for more info on how to customize how you want LilyPond to beam the quavers.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTP Error code from TransferJob under KDE (KIO)
I'm launching HTTP GET job under KDE 5 with
job = KIO::get(url, KIO::NoReload, KIO::HideProgressInfo);
in slot connected to KIO::TransferJob::result i'm getting job->error() equal to 0, but KIO::TransferJob::isErrorPage() equal to true. And data containing something like:
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
</body>
</html>
As I understand - slave http job indicates that the page is an error page but the code of this error isn't forwarded to parent job or I couldn't find a way to get it. I would like to get the code (403) without parsing the received data. Is that possible?
https://httpstat.us/403 may be used for tests
A:
Simple answer is yes you can.
The only option is TransferJob::isErrorPage() to know if any error happened. As per this line of code in transferjob.cpp
q->connect(slave, &SlaveInterface::errorPage, q, [this]() {
m_errorPage = true;
});
But if you look at http.cpp in ioslaves, you will find that meta data with key value of responsecode is added to Job::metaData so you can query that value like this:
auto httpResponseCode = job->metaData().value(QStringLiteral("responsecode"));
httpResponseCode would be a QString because KIO::MetaData is actually a QMap<QString,QString> type.
| {
"pile_set_name": "StackExchange"
} |
Q:
Element should have been "select" but was "div" getting an error in selenium
Here is the HTML code, i'm trying to select 'select customer' drop-down.
<div id="createTasksPopup_customerSelector" class="customerOrProjectSelector selectorWithPlaceholderContainer at-dropdown-list-btn-ct notSelected">
<table id="ext-comp-1057" class="x-btn-wrap x-btn at-dropdown-list-btn x-btn-over x-btn-focus" cellspacing="0" cellpadding="0" border="0" style="width: auto;">
<tbody>
<tr id="ext-gen397" class=" x-btn-with-menu">
<td class="x-btn-left">
<td class="x-btn-center">
<em unselectable="on">
<button id="ext-gen391" class="x-btn-text" type="button">- Select Customer -</button>
</em>
</td>
<td class="x-btn-right">
</tr>
</tbody>
</table>
</div>
Image -
A:
This exception generally occurs when we use Select command to select dropdowns which are not built by using "select" tag.
You can try by using sendkeys to select dropdown, just give displayed text of option in sendkeys.
If above does not work, then go for click on dropdown and again click on required option.
If it is auto complete dropdown, then click on that dropdown input box and go for senkeys char by char with small sleep, so that required option will be displayed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quick booking issue
#include <stdio.h>
#pragma pack(push)
#pragma (1)
typedef struct contact {
char firstname [40];
char lastname [40];
char address [100];
char phone[10];
}contact;
#pragma pack(pop)
int main ()
{ FILE *pFile;
contact entry = {"", "", "", ""};
char choice;
pFile = fopen("C:\\contacts.txt", "w+");
if(!pFile){
printf("File could not be open");
return 1;
}
printf("Choose a selection\n\n");
printf("1. Enter First Name\n");
printf("2. Enter Last Name\n");
printf("3. Enter Address\n");
printf("4. Enter Phone Number\n\n");
scanf( "%d", &choice);
switch (choice){
case 1:
printf("First name: \n");
fgets(entry.firstname, sizeof(entry.firstname),pFile);
break;
case 2:
printf("Last name: \n");
fgets(entry.lastname, sizeof(entry.lastname),pFile);
break;
case 3:
printf("Address: \n");
fgets(entry.address, sizeof(entry.address),pFile);
break;
case 4:
printf("Phone Number: \n");
fgets(entry.phone, sizeof(entry.phone),pFile);
break;
default:
printf(" No Choice selected, Ending Address Book Entry system");
break;
}
fwrite(&entry, sizeof(contact), 1, pFile);
printf("Enter a new contact?");
scanf("%s", &choice);
//while(choice != 'n');
fclose(pFile);
getchar();
return 0;
}
This code after I choose an entry and after I put an entry in and press enter it crashes saying Stack around the variable 'entry' was corrupted. I'm fairly confident that it is my fwrite function that I'm using. I know the first parameter fwrite looks for is a pointer to an array of elements to be written but I think I'm just confused right now. Any help would be much appreciated.
A:
You should change all your
fgets(entry.firstname, sizeof(entry.firstname),pFile);
to
fgets(entry.firstname, sizeof(entry.firstname),stdin);
Because you're reading from the console, not the file.
Also, with
scanf("%s", &choice);
and
scanf( "%d", &choice);
you're trying to read a string and a digit and store it in a char. They both should be
scanf("%c", &choice);
That said, you should think about rewriting this using ifstream, cin, getline, and std::string to make your life easier if you're not looking for maximum performance.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is 'antenna-chain permutation' and its advantages?
I am working with Wi-Fi channel state information (CSI, a sort of channel matrix with OFDM subcarriers). I am using Intel 5300 Wi-Fi card and this tool provides a way to play around with extracted CSI information via MATLAB.
Interesting thing is, there is perm, a permutation vector in a figure below:
It says a permutation vector is [2, 1, 3]. In FAQ page of the tool, it says:
perm tells us how the NIC permuted the signals from the 3 receive antennas into the 3 RF chains that process the measurements. The sample value of [3 2 1] implies that Antenna C was sent to RF Chain A, Antenna B to Chain B, and Antenna A to Chain C. This operation is performed by an antenna selection module in the NIC and generally corresponds to ordering the antennas in decreasing order of RSSI.
What I am curious about is, why does this Intel 5300 Wi-Fi card do antenna-chain permutation and what are advantages of performing it?
A:
I'll highlight terms that are worth googling in cursive below:
What you're looking at is a diversity receiver.
In this case, the idea is that by combining the signals of multiple antennas, the SNR can be maximized, minimizing the BER.
There's multiple methods of doing so – simply selecting the antenna with the highest RSSI (being probably the one with the best SNR) is called selection combining. When thinking about outage probabilities, this leads to a Bernoulli distribution, ie. the more antennas you have, the less like it is that your communication fails totally (but the gain of having more antennas quickly decreases after the second).
Another method is just adding up the signals – you can do that, and you'd get what's called equal gain combining. You'd get some sort of "oversampling" gain, supressing noise that is independent in each receiver branch, but a strong interferer might distort the result.
Then, you can add the receive signals up, but weigh them by some function that is proportional to their "quality". That way, you get maximum ratio combining, at least if the weights are basically proportional to SNR.
In a real-world receiver with a limited amount of ressources dedicated to assessing the signals, a simple ranking in three tiers of signal quality does sound like a feasible approach. For example, spending much power on synchronizing the strongest signal (i.e. estimating the phase of the channel impulse response) makes sense, since an error here has the gravest effect, whereas simpler approaches for the signals that are used to "push down" uncorrelated noise power (maybe aided by the strongest' chains info) might still make sense. Notice that modern WiFi receivers are pretty mighty beasts – not what you'd need to feel bad about if you don't understand them at once.
Another explanation might be much more in the analog than in the digital domain: For the strongest signal, you might want to use a different receive amplifier than for the weakest one – amplifiers are either a) low-noise, or b) high dynamic range or c) power-efficient (not to mention d) through z) cheap).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is wrong with my emacs/slime setup (compile-and-load/eval not working)?
I can run emacs and start slime (with M-x slime). At this point I get the REPL in the inferior-lisp buffer and can run lisp there. But when I open up lisp code in another buffer none of the slime-goodness works (C-x C-e, C-c C-k etc.) and I keep seeing this in the Messages buffer (with an increasing count-number):
slime-connection: Not connected.
Polling
"/var/folders/B9/B9B5J15dH+aNt5J5gkROEk+++TI/-Tmp-/slime.3202".. (Abort with `M-x
slime-abort-connection'.) [69 times]
Makes me think slime is not connecting to the correct lisp interpreter, but since I am very new to emacs and lisp I am stuck here. My setup is:
Mac OSX Snow Leopard
GNU Emacs 23.2
emacs-starter-kit
very few customizations: arnab.el and the files under arnab/
A:
The following is what I did to get Common Lisp and Clojure to work in the same Emacs installation, along with the excellent emacs-starter-kit. This won't let you use both at the same time (you have to restart Emacs to switch from CL to Clojure or vice versa)
I believe that the version of SLIME in ELPA is old, but works for Clojure. Newer version of SLIME won't work for Clojure. Additionally, this version of SLIME seems to be stripped down (no swank-loader.el?) and won't work with Common Lisp.
These are the steps I did to get this to work, it's just what worked for me. All of the bits are under active development, so I think breakage in this area is pretty likely.
With a fresh Emacs (no configuration at all, so move anything .emacs somewhere else for the moment) install ELPA:
http://tromey.com/elpa/install.html
From within Emacs, install the packages "slime" and "slime-repl". (M-x package-list-packages then C-s slime then i to select and x to install)
Move the files in ~/.emacs.d/elpa/slime-20100404 and ~/.emacs.d/elpa/slime-repl-20100404 to a new directory like ~/hacking/lisp/elpa-slime.
Throw out the ELPA install: $ rm -rf .emacs.d.
Now clone the emacs-starter-kit and move it to .emacs.d. I only did this with a fresh copy from technomancy's Github, so try that first if you have problems.
Get the latest SLIME with CVS:
cvs -d :pserver:anonymous:[email protected]:/project/slime/cvsroot co cvs-slime
I don't think OS X comes with CVS installed, so you'll need to install it from Macports, Homebrew or something.
I put cvs-slime in ~/hacking/lisp.
Hopefully it's obvious what the Emacs Lisp below does:
(defun slime-common-lisp ()
(interactive)
(setq inferior-lisp-program "/usr/local/bin/sbcl") ; your Common Lisp impl
(add-to-list 'load-path "~/hacking/lisp/cvs-slime/") ; your SLIME from CVS directory
(require 'slime)
(slime-setup '(slime-repl))
(slime))
(defun slime-clojure ()
(interactive)
(add-to-list 'load-path "~/hacking/lisp/elpa-slime")
(require 'slime)
(slime-setup '(slime-repl))
(slime-connect "localhost" 4005))
For Clojure you'd have to start the Clojure runtime and swank-clojure on port 4005, I think using Leiningen is the approved method:
Create a new project:
$ lein new project
$ cd project
In project.clj:
(defproject newclj "1.0.0-SNAPSHOT"
:description "FIXME: write"
:dependencies [[org.clojure/clojure "1.2.0"]
[org.clojure/clojure-contrib "1.2.0"]]
:dev-dependencies [[swank-clojure "1.2.1"]])
Then:
$ lein deps
$ lein swank
Edited to add:
If you find that Paredit in the SLIME REPL is broken while using this setup, check this out:
http://www.emacswiki.org/emacs/ParEdit#toc3
At least one other potential issue with this is that, AFAICT, if you open a Common Lisp source file and then start SLIME, you won't be able to send forms from the first buffer to the SLIME buffer. So open a SLIME buffer before opening any Common Lisp source files, and it should work. This doesn't seem to apply to Clojure.
References:
emacs setup for both clojure and common lisp with slime-fancy (slime-autodoc)
https://github.com/technomancy/swank-clojure/issues/closed#issue/31/comment/544166
| {
"pile_set_name": "StackExchange"
} |
Q:
i18n-js translations not updating with additional translations in .yml
I have been reading about this for days, and nothing seems to be working. I have seen a lot of documentation of this issue, but none of the work arounds are working for me.
I have :
Rails 5.0.1
* sprockets (3.7.1)
* sprockets-rails (3.2.0)
* i18n (0.7.0)
* i18n-js (3.0.0.rc15)
config/i18n-js.yml
translations:
- file: "app/assets/javascripts/application/i18n/translations.js"
only: '*.js*'
config/application.rb
config.middleware.use I18n::JS::Middleware
When I add new translations to the corresponding yml file, the i18n/translations.js does not update to include the new .yml translations.
For example, in en.yml:
en:
form_error:
tos_check: "You must agree to Lexody's Terms of Use to continue."
choose_city: "Please select a city from the menu."
cancel_reason: "Please provide a reason for cancelling."
$('.prompt').html('<p style="color:#e57373">' + I18n.t('form_error.cancel_reason') +'</p>');
returns: [missing "en.form_error.cancel_reason" translation]
I have tried:
Deleting translations.js and run rake i18n:js:export
rake tmp:cache:clear
rake assets:precompile
Does anyone have another solution I can try? Thanks!!
A:
Update
After looking at the additional configuration files, this config/i18n-js.yml seems suspect:
translations:
- file: "app/assets/javascripts/application/i18n/translations.js"
only: '*.js*'
According to the export configuration docs, the only key refers to the translation keys to be exported, not the filenames. So '*.js*' will match nothing, causing no translations to be exported.
Change this file to read:
translations:
- file: "app/assets/javascripts/application/i18n/translations.js"
only: '*'
(Original answer below)
Working example
Here's a minimal, working example that produces expected behavior with the i18n-js gem:
#!/bin/bash
rails _5.0.1_ new .
echo "gem 'i18n-js', '3.0.0.rc15'" >> Gemfile
echo " NEW_KEY: NEW_VALUE" >> config/locales/en.yml
bundle install
bundle exec rake i18n:js:export
grep -o '"NEW_KEY"' public/javascripts/translations.js
For me, running the above script outputs "NEW_KEY" on the last line, as expected (demonstrating that NEW_KEY is correctly added to public/javascripts/translations.js after running i18n:js:export in a fresh Rails installation), which means something else is going on in your local project.
Further investigation
In order to know what else exactly is going on, you'll have to further investigate exactly what configuration you've changed locally when compared to a fresh Rails installation.
(Note that the easiest way to do this is to provide a Minimal, Complete and Verifiable example, such as a link to a GitHub repo that produces your issue exactly.)
you say "the i18n/translations.js does not update to include the new .yml translations.", but the default path that gets updated is public/javascripts/translations.js. If you're using a non-standard path for your translations.js file, do you have additional configuration for this in config/i18n-js.yml? (If so, please share the entire contents of this file).
Have you confirmed that the new translation doesn't show up in translations.js at all (e.g., using a grep command like the one above)? Or is it possible that the issue is related to the asset pipeline configuration instead?
| {
"pile_set_name": "StackExchange"
} |
Q:
Connecting application to a google store
Now I have my application which reads magazines, books and articles. Now I want to be able to connect to the store from my app and get this items.
How do I do this?
I am pretty certain people may have already posted this but I just can't seem to write the correct phrase in google to get me to the link.
A:
You can only accomplish embeddeding using the Google Books API using the Embedded Viewer API
Say: to allow the user to download the book from Google Books in whatever format which could then be stored and read out of your app would surely go against a Policy even if you found a way to do it for free books (I'm guessing). But embedding them seems like fair game.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nullable datetime value from DatePicker
This is the case. I get the date from DatePicker control:
DateTime current = datePicker1.SelectedDate;
And I get an error: Cannot implicitly convert DateTime? to DateTime. So I guess it's up to a nullable type DateTime?.
Is it safe to cast this type to a type I need like this:
if (datePicker1.SelectedDate == null)
current= DateTime.Now;
else
current= (DateTime)datePicker1.SelectedDate; //or datePicker1.SelectedDate.Value
And in general, when is it SAFE to implicitly cast nullable values, and when it isn't?
A:
In this case you should use the null coalescing operator:
current = datePicker1.SelectedDate ?? DateTime.Now;
That will use SelectedDate if it's non-null, or DateTime.Now otherwise. The type of the expression is non-nullable, because the last operand is.
In general, you should use the Value property (or cast to the non-nullable type) if you're confident that the value is non-null at that point - so that if it is null, it will throw an exception. (If you're confidence is misplaced, an exception is appropriate.) Quite often the null coalescing operator means you don't need to worry about this though.
A:
Nullable types have a special property for this kind of thinks. It is HasValue, and moreover GetValueOrDefault. So what You really need is
DateTimePicker1.SelectedDate.GetValueOrDefault(DateTime.Now);
// or DateTime.MaxValue or whatever).
| {
"pile_set_name": "StackExchange"
} |
Q:
Error retrieving email address using facebook SDK
I want to retrieve a email address of a user by calling facebook api.
I am using
FB.api('/me?fields=email', function(response) {
var txt="Email:"+response.email;
var element=document.getElementById("email").innerHTML=txt;
});
code to retrieve a email address.
I have asked for email permission during login as follows:-
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login({scope: 'email'});
} else {
FB.login({scope: 'email'});
}
});
};
Still when I print email id it shows "undefined".
A:
Ok, I have got answer to my problem.
If you are using Facebook's Button code then You have to add extra permissions as an array. What i was doing was that calling the Login Function manually with permissions but forgot to add permissions as a scope in button code.
<div class="fb-login-button" data-max-rows="5" data-size="xlarge" data-show-faces="true" scope=['email'] data-auto-logout-link="true"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Rebranding Application Resources in .NET 2.0
I'm about to start writing a tool in .NET 2.0 (C#), and the tool needs to be re-brandable to be sold for use by other companies. We'll compile the tool in house, with other company's resources, so they don't get the source, just the generated output.
Since the re-branding will use the same default language, how do you manage multiple resources for the same language set without doing something sleazy like swapping out resx files with scripts at build time, or something even sleazier (and more error prone) like using en-US for customer A, en-CA for customer B, en-GB for customer C, etc.
A:
We found on our project that the simplest route was to have the branding in its own DLL which is then loaded dynamically through reflection. If required, there are two obvious approaches to localizing any branding:
Replace the branding DLL with another that has been localized
Use the satellite assembly technique supported by .NET
Option 1 is much easier, in my opinion but both are feasible. Of course, there are other approaches to localization.
A:
The route I've decided to go is to have an TextOverrides class. This class exposes a bunch of properties such as:
public static string ProductName
{
get
{
#if <companyNameA>
return Properties.Resources.ProductName_CompanyNameA;
#elif <companyNameB>
return Properties.Resources.ProductName_CompanyNameB;
#else
return Properties.Resources.ProductName;
#endif
}
}
This is only feasible if the number of overriden text items remains small.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can zfs/zpool be setup in an LVM formatted disk
I have Ubuntu 14.04 setup with LVM on a 500GB disk on my laptop. I want to setup/playaround with zfs/zpool. What is the best approach for this without losing my data
A:
Given that you just want to "play around" with ZFS, the easiest option is probably a file-backed pool. An alternative would be creating one or more logical volumes inside the LVM and use those.
One of the beauties of ZFS is that you can give it just about anything that can store data in a random I/O capable form, and it will "just work". In production environments, you generally want to give ZFS a whole disk (or several whole disks) and let it handle partitioning etc., but for trying things out and getting a feel for how ZFS works, a file-backed pool is almost always perfectly adequate.
In fact, I sometimes recommend having a file-backed pool resembling the full storage layout readily available, because it allows you to safely test various changes and observe the results before committing to them. Mistakes in altering ZFS pools can be costly.
To create a file-backed pool, first create a set of files of appropriate size. I'll be creating a four-device raidz1 pool where each device (file) is 2 GB, so:
sudo mkdir /.zfs
sudo dd if=/dev/zero of=/.zfs/disk1 bs=1M count=2048
sudo dd if=/dev/zero of=/.zfs/disk2 bs=1M count=2048
sudo dd if=/dev/zero of=/.zfs/disk3 bs=1M count=2048
sudo dd if=/dev/zero of=/.zfs/disk4 bs=1M count=2048
sudo chmod 0700 /.zfs
This gives us four files in /.zfs, named disk1 through disk4 respectively. Each file will be 2 GiB in size, which when accounting for raidz1 overhead gives us a usable storage capacity of a little under 6 GiB (in raidz1, one of the devices is used for parity data so not available for use).
Then create the pool (tank is the customary example name for a ZFS pool):
sudo zpool create tank raidz /.zfs/disk1 /.zfs/disk2 /.zfs/disk3 /.zfs/disk4
What this says is to create a pool named tank using defaults, and set up one vdev in that pool with the four files we just created. The pool will automatically be imported once created, and its root file system will be mounted at /tank. You can observe the result using sudo zpool status, which should print something very similar to:
pool: tank
state: ONLINE
scan: none requested
config:
NAME STATE READ WRITE CKSUM
tank ONLINE 0 0 0
raidz1-0 ONLINE 0 0 0
/.zfs/disk1 ONLINE 0 0 0
/.zfs/disk2 ONLINE 0 0 0
/.zfs/disk3 ONLINE 0 0 0
/.zfs/disk4 ONLINE 0 0 0
errors: No known data errors
We can confirm the raw size of the pool using sudo zpool list:
NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
tank 7,94G 120K 7,94G - 0% 0% 1.00x ONLINE -
and the used and available storage capacity using sudo zfs list:
NAME USED AVAIL REFER MOUNTPOINT
tank 74,8K 5,84G 25,4K /tank
Both of those commands have numerous options to control what gets printed and how; see the man page for zpool and zfs, respectively.
You can now save files into /tank and generally get your hands dirty with ZFS. To export the pool (recommended before shutdown), sudo zpool export tank (or sudo zpool export -a to export all currently imported pools). To import the pool again, sudo zpool import -d /.zfs -a (or replace the -a with the name of the pool, tank); the -d /.zfs may be needed because ZFS doesn't normally look in that directory for devices. You can add these commands to your system startup/shutdown scripts if you want to.
Have fun!
| {
"pile_set_name": "StackExchange"
} |
Q:
Login with CSRF codeigniter and ajax
i will make secure login with CSRF codeigniter and ajax. but i have a problem with my syntax. and $config['csrf_protection'] = TRUE;
this my form :
<?php echo form_open('admin/info_type_user_log/log_admin',array('id' => 'form-loginx'));?>
<div class="input-group" style="margin-bottom:10px;">
<span class="input-group-addon lab"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="username" id="username" class="form-control inp usernamex" placeholder="username" required>
</div>
<div class="input-group" style="margin-bottom:10px;">
<span class="input-group-addon lab"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="password" id="password" class="form-control inp passwordx" placeholder="password" required>
</div>
<button type="submit" name="submit" class="submit_login btn btn-md btn-primary">Login</button>
<label><input type="checkbox" class="lihat"> lihat password</label>
<?php echo form_close();?>
and this my javascript :
$('#form-loginx').submit(function(e){ // Create `click` event function for login
e.preventDefault();
var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
var me = $(this);
$('.submit_login').html('Loading ...'); //Loading button text
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
url : me.attr('action'),
type : 'POST',
data : {csrfName:csrfHash,me.serialize},
dataType : 'json',
success: function(response){ // Get the result and asign to each cases
$('.submit_login').html('Login'); //Loading button text
if(response == true){
$(".alert-sukses").html("Sedang mengarahkan..").slideToggle("fast").delay(3000).slideToggle("fast");
window.location.href = 'admin/info_type_user_log';
}else {
gagal();
}
}
});
});
and my controller :
function log_admin(){
$reponse = array('success' => true);
$user = $this->security->xss_clean($this->input->post('username'));
$pass = $this->security->xss_clean($this->input->post('password'));
$reponse = array(
'csrfName' => $this->security->get_csrf_token_name(),
'csrfHash' => $this->security->get_csrf_hash()
);
$cek = $this->model_admst->valid_log($user, md5($pass));
if($cek->num_rows() > 0){
foreach($cek->result() as $data){
$sess_data['id'] = $data->id;
$sess_data['nama_depan'] = $data->nama_depan;
$sess_data['nama_belakang'] = $data->nama_belakang;
$sess_data['email'] = $data->email;
$sess_data['username'] = $data->username;
$sess_data['gb_user'] = $data->gb_user;
$sess_data['last_login'] = $data->last_login;
$sess_data['log_access'] = "TRUE_OK_1";
$this->session->set_userdata($sess_data);
$this->model_admst->updateLastlogin($data->id);
log_helper("login", "akses login sukses");
}
$reponse['success'] = true;
}else{
$reponse['success'] = false;
}
echo json_encode($reponse);
}
and my models is :
function valid_log($user,$pass){
$this->db->where('username', $user);
$this->db->where('password', $pass);
$this->db->where('status', 'aktif');
$this->db->where('level', 'admjosslog21');
$this->db->where('akses', '1');
return $this->db->get('user');
}
A:
Try this Code
$("#state1").change(function () {
$.ajax({
url: "<?php echo base_url('admin/get_districtsfromstates'); ?>",
type: "POST",
data: {id: $(this).val(),'<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'},
success: function (data)
{
$("#district1").html(data);
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused with natural logarithms
How can we solve the following natural logarithms? I'm confused with this stuff:
$\ln(x+1) - \ln x = \ln 3$
$\ln(x+1) + \ln x = \ln 2$
A:
Here is a worked example slightly different to your question; solve the following for $q$:
$$\ln(q+2)-\ln(q)=\ln(5)\tag{1}$$
Using the laws for adding/subtracting logarithms:
$$\ln(a)-\ln(b)=\ln\left(\dfrac{a}{b}\right)$$
$$\ln(a)+\ln(b)=\ln(ab)$$
we can write $(1)$ as:
$$\ln\left(\dfrac{q+2}{q}\right)=\ln(5).$$
this is the key step because once we have a single logarithm on both sides of the equation we can "invert" it to leave what is inside the logarithm by applying exponentiation to both sides (see Appendix). So, to undo the logarithm we take the exponential of both sides of the equation:
$$e^{\ln\left(\dfrac{q+2}{q}\right)}=e^{\ln(5)}\tag{2}$$
and because $$e^{\ln(x)}=x$$
$(2)$ becomes:
$$\dfrac{q+2}{q}=5$$
which can be rearranged to solve for $q$ and we find:
$$q=\dfrac{1}{2}.$$
Appendix
The function $\ln(x)$ is the inverse of the function $e^x$. More generally the function $\log_a(x)$ is the inverse of the function $a^x$ where $\log_a$ is called the logarithm to the "base" $a$. In words, what this means is if we have:
$$z=x^y \tag{i}$$
then:
$\log_x(z)$ is the value we would have to raise $x$ to to get $z$. We can see from $(i)$ that $y$ is the value we have to raise $x$ to get $z$ so:
$$y=\log_x(z).$$ With the complicated definition out of the way, some simple examples will be more informative. If we have:
$$2^a=b$$
and we want to solve for $a$ in terms of $b$ we invert the exponentiation, i.e. we invert the "raising of the base $2$ to a power", using a logarithm with the same base; in this example the base is $2$ so we apply the logarithm to the base $2$ to both sides and get get:
$$a=\log_2(b).$$
Conversely, if as in the question at hand, we start with a logarithm, e.g:
$$\log_{10}(a)=b$$
we can express $a$ in terms of $b$ by inverting the logarithm to the base $10$ by raising the base $10$ to the power of both sides:
$$10^{\log_{10}(a)}=a=10^b.$$
The inverting of the natural (or Naperian) logarithm, $\ln$, which is log to the base $e$, was applied to both sides in the original example to "undo", and get rid of the logarithm. This was a formal step but in truth it maybe could have been skipped because it shows that if $A,B$ are positive real valued variables, i.e. they don't involve $\sqrt{-1}=i$ and are not negative because logs of negative numbers are themselves complex, then: $$\ln(A)=\ln(B)$$ implies: $$A=B.$$ Interestingly, if the variables are complex and do involve $\sqrt{-1}=i$ or are negative the "inverting" is not well defined and some further restrictions need to be specified but that is for future reading, see topics on complex logarithms.
| {
"pile_set_name": "StackExchange"
} |
Q:
DELETE FILE WITH FOLDER XP_CMDSHELL
I need to delete file with folder using sql
so i am using xp_cmdshell.
My Folder structure is
Folder-1
|
|
Folder 2 ----------------------------------------------Folder -3
| |
files.csv files.csv
I need to delete Folder-1, so that it will delete Folder 2 and folder 3 and the files containing it.
I tried using set @cmd= 'RMDIR "C:\Folder-1'
exec master..xp_cmdshell @cmd
RMDIR needs the folder to be empty. so we need to first delete the file using del command.
Then using RMDIR to delete folder 2 and folder 3, then using RMDIR to delete folder-1
Is there anyway to delete the folder with file using single command by xp_cmdshell
A:
Try RMDIR /S /Q C:\Folder-1
The /S Removes all files and directories in the specified directory/folder. the /Q is quiet mode and will not ask if its ok to delete.
HTH
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem of rank, trace, determinant and eigenvalue
Here is a problem and its solution that I translated from Korean (so it might contain some errors):
Problem:
For real n-by-n matrices $A,B$, suppose $xA+yB=I$ for non-zero real $x,y$ and $AB=0$.
Prove $$det(A+B) = \frac{1}{x^{\text{rank}(A)}y^{\text{rank}(B)}}.$$
Solution:
Let $A'=xA$ and $B'=yB$.
Then $A'+B'=I$ and $A'B'=0$.
Then it follows that $A'=A'^2$ and $B'=B'^2$.
So the minimal polynomials of $A'$ and $B'$ divides $x^2-x$.
Thus the eigenvalues are $0$ or $1$. Therefore $A'$ and $B'$ are diagonalizable.
Let $V,W$ be the eigenspace of $A'$, $B'$ respectively corresponding to the eigenvalue $1$.
Then $\text{trace}(A')=\text{dim}(V)$ and $\text{trace}(B')=\text{dim}(W)$.
(*) Also $\text{trace}(A')+\text{trace}(B')=n$.
Thus $\text{dim}(V \cap W)=0$ and $R^n=V \oplus W$ (direct sum).
(**) Thus
$$\text{det}(A+B)= \frac{1}{x}^{\text{dim}(V)} \frac{1}{y}^{\text{dim}(W)}=\frac{1}{x}^{\text{trace}(A')} \frac{1}{y}^{\text{trace}(B')}=\frac{1}{x^{\text{rank}(A)}y^{\text{rank}(B)}}$$
My question:
1) Why (*) holds?
2) Why (**) holds?
I know that the sum of eigenvalues equals $\text{trace}(A)$ and the multiple equals $\text{det}(A)$. Thank you.
A:
First, it's not true that the characteristic polynomial of $A'$ (or $B'$) must divide $x^2 - x$. What is true is that the minimal polynomial of $A'$ (or $B'$) must divide $x^2 - x$ and hence $A'$ (and $B'$) is diagonalizable with possible eigenvalues $0,1$.
Since $A' + B' = I$, we get
$$ \operatorname{trace}(A' + B') = \operatorname{trace}(A') + \operatorname{trace}(B') = \dim V + \dim W = \operatorname{trace}(I_n) = n. $$
Since $A'B' = 0$, if $v \in V \cap W$ then $0 = A' B'v = A'v = v$ which shows that $V \cap W = \{ 0 \}$. This, together with $\dim V + \dim W = n$ implies that $\mathbb{R}^n = V \oplus W$. Finally, the eigenvalues of $cB' + dI$ are $d$ with multiplicity $\dim V$ and $c + d$ with multiplicity $\dim W$. Hence,
$$ \det(A + B) = \det \left( \frac{1}{x} \left( xA + yB + (x - y)B \right) \right) = \det \left( \frac{1}{x} I + \frac{x-y}{y}B' \right) \\ = \frac{1}{x}^{\dim V} \left( \frac{1}{x} + \frac{x - y}{y} \right)^{\dim W} = \frac{1}{x}^{\dim V} \frac{1}{y}^{\dim W}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
BF3 Mortar kills
When mortaring, there is always the risk of being mortared back, so it's a good idea to keep mobile i.e. mortar, then move and redeploy. Now, when you move and kill someone with a mortar, it displays as (in my case) AlbortoTobor [KILLED] , as opposed to AlbortTobor [M224 MORTAR].
So, do these instances of [KILLED] still count towards the mortar tally...?
A:
OK. So I can confirm that if you leave the mortar, and then get a mortar kill displaying as [KILLED], that it does NOT add to your tally.
So much for deploy and move if you want that medal...
| {
"pile_set_name": "StackExchange"
} |
Q:
Thread safety in C# scripts
I'm writing a plugin for a game called Rust using a modding framework called Oxide. I'm wondering if I need to be concerned about synchronization in my plugin. Are all scripts in unity (C# or otherwise) executed on the same thread?
A:
Yes, they're all executed on the main thread, in fact unity really doesn't like it when you try to do things off the main thread. Any Unity3D specific calls you make (anything in any of the Unity namespaces) must be executed on the main thread otherwise you will get potentially very vague errors, and when errors do occur outside of the main thread unity will not report them and will not provide a stack trace.
They way most people get around mutlithreading with Unity is to create a MonoBehaviour object that starts the processing that doesn't involve unity directly in another thread, then store it in the MonoBehaviour object when its done. The MonoBehaviour object can then check each update to see if the data it needs is ready for it to make unity specific calls with, and then do so if it is ready.
| {
"pile_set_name": "StackExchange"
} |
Q:
innerHTML not writing into an svg group Firefox and IE
I am working on a project and ran into a road block. In Chrome it works as intended but not in Firefox and IE. The code below is really just a very simplified version of the real project code. Basically I'm trying to replace the circles in each group of the svg. So I start with precoded circles and then remove and set innerHTML to a new circle with new location and radius. It is necessary to remove the existing circles as in the final version I will want to completely replace the contents. I realize innerHTML will replace the contents but I am running this in a loop and so I'd ultimately need to += to the end of the circles after clearing it out.
I know probably not a good explanation...
Requirements are that it clears the children of group with id="whateverIWant" as there is more than one group, then redefines the children. There can be more than one child circle in the group, and each iteration, or refresh, there could be a different number of children circles as the last time.
A lot of trial and error got me to this point, but there are probably better methods to clear the children and re create them. Keep in mind the attributes of the new children can change and that in production I may be handling hundreds of these children. I'm also storing a collection of the children as strings in an array before adding them for purposes of other processing.
<svg viewBox="0 0 640 480" height="480" width="640" style="background-color:white" version="1.1">
<g id="redC" stroke="none" fill="red" fill-opacity="0.1">
<circle cx="100" cy="450" r="50" />
<circle cx="100" cy="50" r="50" />
</g>
<g id="greenC" stroke="none" fill="green" fill-opacity="0.1">
<circle cx="150" cy="350" r="50" />
</g>
<g id="blueC" stroke="none" fill="blue" fill-opacity="0.1">
<circle cx="100" cy="350" r="50" />
</g>
</svg>
$(document).ready(function(){
document.getElementById("redC").innerHTML = "";
for(var i=1;i<5;i++){
var num = (i*10).toString();
document.getElementById("redC").innerHTML += "<circle cx='300' cy='50' r="+num+" />";
}
});
Any advice is much appreciated.
A:
The innerHTML property on SVG elements does not yet have wide browser support. In the meantime, you can create the elements via dom manipulation methods. They have a different namespace than regular HTML elements, so to create them, you can't just use, document.createElement("circle"). Instead, you have to pass the namespace as well:
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
In my SVG projects, I extend jQuery for convenience in creating SVG elements:
var svgns = "http://www.w3.org/2000/svg";
$.svg = function $svg(tagName) {
return $(document.createElementNS(svgns, tagName));
};
You can then use jQuery methods to manipulate your SVG elements:
$(document).ready(function () {
$("#redC").empty();
for (var i = 1; i < 5; i++) {
var num = (i * 10).toString();
$.svg("circle").attr({
cx: 300,
cy: 50,
r: num
}).appendTo("#redC");
}
});
Demo: http://jsfiddle.net/FfdaL/
| {
"pile_set_name": "StackExchange"
} |
Q:
Super+D key shortcut does not show desktop
I recently installed Saucy Salamander on my computer. Previously in Ringtail, Super+D used to show the desktop. However for this release, the Super+D does not seem to work properly... Is it a bug?
A:
Super + D doesn't work starting with Ubuntu 13.10. Use Ctrl + Super + D instead, I tested it and it works.
How to change the keys:
Open the Dash and type keyboard. There should be an app called Keyboard. Click on it and then go to the Shortcuts tab. Click on the Navigation list entry and scroll down until you see Hide all normal windows, click on it and create a new shortcut, for example:
Super + D
And that's it, you're done.
A:
It is not a bug. In order to make Super+D shortcut to work you must to go to System Settings → Appearance, select Behavior tab and tick And show desktop icon to the launcher:
If you don't like to have the desktop icon on your launcher, then use Ctrl+Super+D shortcut.
Or you can use Alt+Tab to switch to desktop:
A:
With the CompizConfig Settings Manager, you can enable the Super + D shortcut to show desktop without having that annoying icon in the launcher.
Just open CompizConfig and go to Desktop >> Ubuntu Unity Plugin >> General and change the show desktop shortcut. In the Switcher tab there, you can also disable having the Desktop icon in the Alt-Tab menu.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error installing flask-mysql python module
I'm trying to install the flask-mysql module and am running into an error. It looks like a problem with vcvarsall.bat, but I'm not really sure what that hints at.
Any ideas from someone more experienced than myself?
C:\eb-virt\bucketlist>pip install flask-mysql
Collecting flask-mysql
Using cached Flask_MySQL-1.3-py2.py3-none-any.whl
Collecting MySQL-python (from flask-mysql)
Using cached MySQL-python-1.2.5.zip
Requirement already satisfied (use --upgrade to upgrade): Flask in c:\python27\lib\site-packages (from flask-mysql)
Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in c:\python27\lib\site-packages (from Flask->flask-mysql)
Requirement already satisfied (use --upgrade to upgrade): click>=2.0 in c:\python27\lib\site-packages (from Flask->flask-mysql)
Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in c:\python27\lib\site-packages (from Flask->flask-mysql)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in c:\python27\lib\site-packages (from Flask->flask-mysql)
Requirement already satisfied (use --upgrade to upgrade): MarkupSafe in c:\python27\lib\site-packages (from Jinja2>=2.4->Flask->flask-mysql)
Installing collected packages: MySQL-python, flask-mysql
Running setup.py install for MySQL-python ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\tonype~1\\appdata\\local\\temp\\pip-build-3xn7it\\MySQL-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\tonype~1\appdata\local\temp\pip-vtdlrx-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-2.7
copying _mysql_exceptions.py -> build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-2.7\MySQLdb
creating build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-2.7\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27
----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\tonype~1\\appdata\\local\\temp\\pip-build-3xn7it\\MySQL-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\tonype~1\appdata\local\temp\pip-vtdlrx-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\tonype~1\appdata\local\temp\pip-build-3xn7it\MySQL-python\
A:
You could try using these binaries for windows distributions. Flask-mysql uses mysql-python which has issues when trying to install on windows. See this.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to call a function to auto load elements in jquery mobile site
What I want to do is to have my navbar HTML markup in one place ( for easy editing).
Right now my index.html body content looks like:
<div data-role="page" id="SomePage">
<div data-role="header">
<h1>This is Page 1</h1>
</div>
<div data-role="navbar"></div>
</div>
and am calling the my files in the header as such:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" language="javascript" src="app.js"></script>
in my app.js file is where I am trying to load the nav bar. I have tried it 2 ways
The first:
var NavBar = function() {
$('div[data-role="navbar"]').html('<ul>' +
'<li><a href="#SomePage" data-transition="fade" data-icon="none">By Brand</a></li>' +
'<li><a href="#AnotherPage" data-transition="fade" data-icon="none">By Flavor</a></li>' +
'<li><a href="#LastPage" data-transition="fade" data-icon="none">Zero Nicotine</a></li>' +
'</ul>');
}
$(document).ready(function() {
NavBar();
});
This results in the page getting the app to show my links, but they are stack like a normal ul without the list-style
The second way I tried it was:
var NavBar = function() {
$('div:jqmData[role="navbar"]').html('<ul>' +
'<li><a href="#SomePage" data-transition="fade" data-icon="none">By Brand</a></li>' +
'<li><a href="#AnotherPage" data-transition="fade" data-icon="none">By Flavor</a></li>' +
'<li><a href="#LastPage" data-transition="fade" data-icon="none">Zero Nicotine</a></li>' +
'</ul>');
}
$(document).ready(function() {
NavBar();
});
This results in not seeing the links at all.
How do I create a function to load the 'navbar' in one place and use the jQuery Mobile styling?
A:
document ready should not be used with a jQuery Mobile, it will usually trigger before page is loaded into the DOM. To find more about this topic take a look at this ARTICLE or find it HERE.
Instead you should use proper jQuery Mobile page events.
I made you a working jsFiddle example.
$(document).on('pagebeforecreate', '#index', function(){
$('[data-role="navbar"]').html('<ul>' +
'<li><a href="#SomePage" data-transition="fade" data-icon="none">By Brand</a></li>' +
'<li><a href="#AnotherPage" data-transition="fade" data-icon="none">By Flavor</a></li>' +
'<li><a href="#LastPage" data-transition="fade" data-icon="none">Zero Nicotine</a></li>' +
'</ul>');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
de Rham cohomology with compact support isomorphic to $\mathbb{R}$
The $k$-dimensional de Rham cohomology with compact support is defined as $$H_c^k(M)=\frac{Z_c^k(M)}{B_c^k(M)} $$
where $Z_c^k(M)$ is the vector space of all closed $k$-forms with compact support on $M$ and $B_c^k(M)$ is the vector space of all $k$-forms $d\eta$ where $\eta$ is a $(k-1)$-form with compact support on $M$. A Comprehensive Introduction To Differential Geometry states that for a connected orientable manifold $M$ (I think $M$ is considered as with $\partial M=\emptyset $) we have $$H_c^n(M)\simeq \mathbb{R} \quad \quad \quad (*)$$
Then he says that this assertion is equivalent to two other assertion, which I list below:
Given a fixed $\omega$ such that $\int_M\omega\neq0$, then for any $\omega'$ n-form with compact support there exists a real number $\lambda$ such that $\omega' - \lambda \omega $ is exact (It is not mentioned, but I assume both $\omega$ and $\omega'$ are supposed to be closed)
An closed form $\omega$ is the differential of another form with compact support if $\int_M \omega=0$
I wanted to prove this (the equivalence of this assertions), but I cannot see how this is true.
Any help is welcome
Thanks in advance
A:
First, there is an error in your statement (1): it should say $\omega'-\lambda\omega$ is exact, not $\omega-\lambda\omega'$. (Also, $n$ should presumably be the same as the $k$ you mention elsewhere, the dimension of $M$.)
Now there is a linear map $I:H^k_c(M)\to\mathbb{R}$ which maps $[\omega]$ to $\int_M\omega$ (note that this is well-defined because the integral of an exact form is $0$). Since there exists a compactly supported $k$-form with nonzero integral, $I$ is surjective. Since $\mathbb{R}$ is a 1-dimensional vector space, the following are then equivalent:
(a) $I$ is an isomorphism.
(b) $H^k_c(M)$ is 1-dimensional, i.e. $H^k_c(M)\cong \mathbb{R}$
(c) $\ker I$ is trivial.
But (c) is exactly the same as your statement (2), since an element of $\ker I$ is $[\omega]$ such that $\int\omega=0$ and to say $[\omega]=0$ means that $\omega$ is the differential of a form with compact support. And of course (b) is the same as your statement (*).
It remains to be shown that your statement (1) is also equivalent to the others. Note first that (1) says exactly that $[\omega]$ spans $H^k_c(M)$, since it says that for any $[\omega']\in H^k_c(M)$, there is some scalar $\lambda$ such that $[\omega']=[\omega]$. So, (1) implies $H^k_c(M)$ is 1-dimensional. Conversely, assume statement (2). Fix $\omega$ such that $\int_M \omega\neq 0$ and take any other $\omega'$, and let $\lambda=\frac{\int_M\omega'}{\int_M\omega}$. Then $\int_M \omega'-\lambda\omega=0$, so $\omega'-\lambda\omega$ is exact.
| {
"pile_set_name": "StackExchange"
} |
Q:
Streaming K-means Spark Scala: Getting java.lang.NumberFormatException for input string
While I am reading CSV data from a directory which contains double values and applying streaming K-means model on it as follows,
//CSV file
40.729,-73.9422
40.7476,-73.9871
40.7424,-74.0044
40.751,-73.9869
40.7406,-73.9902
.....
//SBT dependencies:
name := "Application name"
version := "0.1"
scalaVersion := "2.11.12"
val sparkVersion ="2.3.1"
libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % sparkVersion,
"org.apache.spark" % "spark-streaming_2.11" % sparkVersion,
"org.apache.spark" %% "spark-mllib" % "2.3.1")
//import statement
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.sql.streaming.OutputMode
import org.apache.spark.sql.types._
import org.apache.spark.{SparkConf, SparkContext, rdd}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.mllib.clustering.{ KMeans,StreamingKMeans}
import org.apache.spark.mllib.linalg.Vectors
//Reading Csv data
val trainingData = ssc.textFileStream ("directory path")
.map(x=>x.toDouble)
.map(x=>Vectors.dense(x))
// applying Streaming kmeans model
val model = new StreamingKMeans()
.setK(numClusters)
.setDecayFactor(1.0)
.setRandomCenters(numDimensions, 0.0)
model.trainOn(trainingData)
I get the following error:
18/07/24 11:20:04 ERROR Executor: Exception in task 0.0 in stage 2.0
(TID
1)
java.lang.NumberFormatException: For input string: "40.7473,-73.9857" at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
scala.collection.immutable.StringLike$class.toDouble(StringLike.scala:285)
at scala.collection.immutable.StringOps.toDouble(StringOps.scala:29)
at ubu$$anonfun$1.apply(uberclass.scala:305) at
ubu$$anonfun$1.apply(uberclass.scala:305) at
scala.collection.Iterator$$anon$11.next(Iterator.scala:410) at
scala.collection.Iterator$$anon$11.next(Iterator.scala:410) at
scala.collection.Iterator$$anon$11.next(Iterator.scala:410) at
org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:193)
at
org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:63)
at
org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:96)
at
org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
at org.apache.spark.scheduler.Task.run(Task.scala:109) at
org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748) Exception in thread
"streaming-job-executor-0" java.lang.Error:
java.lang.InterruptedException at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1155)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Can anyone please help?
A:
There was a dimension issue. The dimension of the vector and numDimension passed to streaming K-means model should be the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using ADB shell, How I can disable hotspot / tethering on lollipop Nexus 5
My screen got broken and I've been using my phone with a VNC Server installed on it, but this morning i'd the stupid idea of enable hotspot just to see if I can use my mobile data plan on my laptop, but when I did this, the wi-fi got disconnected from my router and now i only have access to my phone using adb shell.
I need to disable hotspot from ADB, already searched on google but didn't find anything, i also tried disable and enabling wi-fi, doesn't works.
A:
adb shell input keyevent 3 # home
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.Settings
adb shell input keyevent 20 # down
adb shell input keyevent 20 # down
adb shell input keyevent 20 # down
adb shell input keyevent 66 # enter
adb shell input keyevent 20 # down
adb shell input keyevent 20 # down
adb shell input keyevent 66 # enter
adb shell input keyevent 20 # down
adb shell input keyevent 66 # enter
A:
A cleaner way to do it is by calling "service call" command.
For example on my phone I could call
# Start Wifi tethering
adb shell service call connectivity 24 i32 0
# Stop Wifi tethering
adb shell service call connectivity 25 i32 0
Service call will call the function number 24 in connectivity service (which happened to be the function that turn on tethering) and pass it 0 as argument (0 would be wi-fi tethering, 1 would be usb tethering and 2 would be bluetooth).
Sadly service functions code change from one android version to another. This stackoverflow reply explain how to get the right function code for your current android version.
https://stackoverflow.com/questions/20227326/where-to-find-info-on-androids-service-call-shell-command
Also this is the functions list for connectivity service for the android version I am using (Nougat)
https://android.googlesource.com/platform/frameworks/base/+/android-7.1.2_r1/core/java/android/net/IConnectivityManager.aidl
| {
"pile_set_name": "StackExchange"
} |
Q:
htaccess redirect without the first folder
So we have a system in place for dynamic content for clients.
Essentially they have their own domain. But we also store the content on our domain for deployment.
An example:
Our domain: http://domain_one.com/client_domain/home.php
Their domain: http://client_domain.com/home.php
We need to redirect to the client domain which we can place into the htaccess with php.
What we want to do is also redirect the query string. When we add the query string, it redirects the client_domain/home.php to the client_domain.com
Our rewrite url as follows:
RewriteRule !^(template_files)($!|/) http://".$domain."/ [R=301,L]
This file gets created dynamically via php for those asking about the ".$domain." bit.
A:
You can use this rule:
RewriteEngine On
RewriteCond %{REQUEST_URI} !/(template_files|web_images)/ [NC]
RewriteRule ^[^/]+/(.*)$ http://domain.com/$1 [R=301,NC,L]
| {
"pile_set_name": "StackExchange"
} |
Q:
Transfer variable to TestStep SOAPUI
I am trying to use a groovy script to create a variable and then transfer it to a SOAP request in a subsequent step.
This is my groovy Script - TestStep InputVariables:
def nextStep = testRunner.testCase.getTestStepByName("Add")
def first = 88
def second = 12
def res = nextStep.run(testRunner, context)
log.info res
Then in the SOAP step (TestStep Add) I try to use the variables this way (as suggested here):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:Add>
<tem:intA>"${#InputVariables#first}"</tem:intA>
<tem:intB>"${#InputVariables#second}"</tem:intB>
</tem:Add>
</soapenv:Body>
</soapenv:Envelope>
But it is not working. This is the response I receive:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>System.Web.Services.Protocols.SoapException: Server was unable to read request. ---> System.InvalidOperationException: There is an error in XML document (5, 33). ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Xml.XmlConvert.ToInt32(String s)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read1_Add()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()</faultstring>
<detail/>
</soap:Fault>
</soap:Body>
</soap:Envelope>
I don't know exactly what I am doing wrong. Can anyone help?
A:
The solution was a little different than in the linked question. I modified the script this way:
def nextStep = testRunner.testCase.getTestStepByName("Add")
Integer first = 88
Integer second = 12
context.first = first
context.second = second
def res = nextStep.run(testRunner, context)
log.info res
And the Add Step this way:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:Add>
<tem:intA>${first}</tem:intA>
<tem:intB>${second}</tem:intB>
</tem:Add>
</soapenv:Body>
</soapenv:Envelope>
And that was all. I received the response without errors:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AddResponse xmlns="http://tempuri.org/">
<AddResult>100</AddResult>
</AddResponse>
</soap:Body>
</soap:Envelope>
| {
"pile_set_name": "StackExchange"
} |
Q:
Initialization strings in C
I have a question about how is the correct way of manipulate the initialization of c strings
For example the next code, isn't always correct.
char *something;
something = "zzzzzzzzzzzzzzzzzz";
i test a little incrementing the number of zetas and effectively the program crash in like about two lines, so what is the real size limit in this char array? how can i be sure that it is not going to crash, is this limit implementation dependent? Is the following code the correct approach that i always must use?
char something[FIXEDSIZE];
strcpy(something, "zzzzzzzzzzzzzzzzzzz");
A:
As you say, manipulating this string leads to undefined behaviour:
char *something;
something = "zzzzzzzzzzzzzzzzzz";
If you are curious as to why, see "C String literals: Where do they go?".
If you plan to manipulate your string at all, (i.e. if you want it to be mutable) you should use this:
char something[] = "skjdghskfjhgfsj";
Otherwise, simply declare your char * as a const char * to indicate that it points to a constant.
In the second example, the compiler will be smart enough to declare this as an array on the stack of the exact size to hold the string. Thus, the size of this is limited by your stack.
Of course, you will likely want to specify the size anyway, since it is usually useful to know when manipulating the string.
A:
The second is always correct.
The first is correct only if you never change the string, since you've assigned a pointer to fixed data.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Use an If Statement with a DataFrame from Excel file?
I'm playing with some data from an Excel file. I imported the file, made it into a dataframe, and now want to iterate over a column named 'Category' for certain keywords, fine them, and retun another column ('Asin'). I'm having trouble finding the correct syntax to make this work.
the code below is my attempt at an if statement:
import pandas as pd
import numpy as np
file = r'C:/Users/bryanmccormack/Downloads/hasbro_dummy_catalog.xlsx'
xl = pd.ExcelFile(file)
print(xl.sheet_names)
df = xl.parse('asins')
df
check = df.loc[df.Category == 'Action Figures'] = 'Asin'
print(check)
A:
Alex Fish provided the correct answer, if I understand the question.
To elaborate, df.loc[df.Category == 'Action Figures'] returns a data frame with the rows that meet the bracketed condition, so ['Asin'] at the end returns the "Asin" column from that data frame.
Fyi,
check = df.loc[df.Category == 'Action Figures'] = 'Asin'
This is a multiple assignment statement - that is,
a = b = 4
is the same as
b = 4
a = b
So your code is apparently rewriting some values of your data frame df, which you probably don't want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I getting a FormatException was unhandled error?
I have created a program, and a extensive test of it, I'm getting a error that says "FormatException was unhandled, Input string was not in a correct format". The problem occurs when I leave either of the text boxes blank and press the 'Finished' button but it works fine if I enter anything below 0 or above 59 - which is the number range I want to allow. What could I do so I don't receive this error when the boxes are blank? This is my code behind 'btnFinished':
private void btnFinished_Click(object sender, EventArgs e)
{
if (lstCyclists.SelectedIndex >= 0)
{
Cyclists currentCyc = (Cyclists)lstCyclists.SelectedItem;
//Decalre the minsEntered and secsEntered variables for txtMins and textSecs
int minsEntered = int.Parse(txtMins.Text);
int secsEntered = int.Parse(txtSecs.Text);
try
{
//If the status of a cyclist is already set to Finished, show an error
if (currentCyc.Finished.ToString() == "Finished")
{
MessageBox.Show("A time has already been entered for this cyclist");
}
else
{
//if a minute lower than 0 or greater than 59 has been entered, show an error
if (minsEntered < 0 || minsEntered > 59)
{
MessageBox.Show("You can only enter a minute up to 59");
}
//if a second lower than 0 or greater than 59 has been entered, show an error
else if (secsEntered < 0 || secsEntered > 59)
{
MessageBox.Show("You can only enter a second up to 59");
}
else
{
//otherwise, set the status to finished and update the time
currentCyc.Finished = "Finished";
currentCyc.FinishedHours(Convert.ToInt32(txtHours.Text));
currentCyc.FinishedMins(Convert.ToInt32(txtMins.Text));
currentCyc.FinishedSecs(Convert.ToInt32(txtSecs.Text));
//pass the parameter to the scoreboard class to display it in lblCyclistsFinished
lblCyclistsFinished.Text += "\n" + finishLine.Scoreboard(currentCyc);
//add to the number of cyclists finished
Cyclists.NumFinished++;
lblnumFinished.Text = Cyclists.NumFinished.ToString();
//update the details box
DisplayDetails(currentCyc);
txtHours.Clear();
}
}
}
catch
//make sure all the time fields have been entered, otherwise show an error message
{
MessageBox.Show("Please ensure all time fields have been entered");
}
}
else
//make sure a cyclist has been selected when pressing "Finished", otherwise show an error message
{
MessageBox.Show("You must select a cyclist");
}
}
A:
Well, look at these lines:
int minsEntered = int.Parse(txtMins.Text);
int secsEntered = int.Parse(txtSecs.Text);
What do you expect those to return when the text boxes are blank?
Simply don't call int.Parse for empty textboxes. For example:
int minsEntered = txtMins.Text == "" ? 0 : int.Parse(txtMins.Text);
// Ditto for seconds
Of course, this will still go bang if you enter something non-numeric. You should probably be using int.TryParse instead:
int minsEntered;
int.TryParse(txtMins.Text, out minsEntered);
Here I'm ignoring the result of TryParse, and it will leave minsEntered as 0 anyway - but if you wanted a different default, you'd use something like:
int minsEntered;
if (!int.TryParse(txtMins.Text, out minsEntered))
{
minsEntered = 5; // Default on parsing failure
}
(Or you can show an error message in that case...)
A:
The problem occurs when I leave either of the text boxes blank
That's the issue. You are using int.Parse on an empty string. An empty string is not a valid integer representation and the parse fails.
You can test for the value in the textbox and default to something reasonable instead:
int minsEntered = 0;
int secsEntered = 0;
if(!string.IsNullOrWhitespace(textMins.Text))
{
minsEntered = int.Parse(txtMins.Text);
}
if(!string.IsNullOrWhitespace(txtSecs.Text))
{
secsEntered = int.Parse(txtSecs.Text);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Sponsorship opportunities for site?
So the SEO team has come out with some specifics for how they could help promote. I think the sponsorship opportunity makes the most sense for gaming.
What are the lan parties, tournaments, and gaming events that SEO could sponsor for Gaming.Stackexchange.com?
A:
I know we have a fairly strong Starcraft 2 contingent on this site. I'd be willing to take the time to organize a online Tournament and I'm even willing to put up $50 of my own money as first place prize.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this cronjob not work?
Currently trying to set up a cron job with a python script that I have git cloned from here. The hierarchy to reach my script can be described as below:
/home
|
|
/Daily-Reddit-Wallpaper
|
|
change_wallpaper_reddit.py
Now this works when I use the command, python change_wallpaper_reddit.py --time new
inside the Daily_Reddit_Wallpapers folder. However, when I try the command, * * * * * python ./change_wallpaper_reddit.py --time new, I get the error:
change_wallpaper_reddit.py: command not found
When I try to invoke * * * * * python ~/Daily-Reddit-Wallpaper/change_wallpaper_reddit.py, I get:
usage: anaconda [-h] [--show-traceback] [--hide-traceback] [-v] [-q] [--color]
[--no-color] [-V] [-t TOKEN] [-s SITE]
...
anaconda: error: argument : invalid choice: 'Daily-Reddit-Wallpaper' (choose from 'auth', u'label', u'channel', 'config', u'copy', u'download', 'groups', u'login', 'logout', u'notebook', 'package', 'remove', 'search', 'show', u'upload', u'whoami')
I do not understand why this happens.
A:
Please be aware the a cronjab executes in a shell that has a limited environment setup. By that I mean that when you open a terminal and enter env you will see a lot of environment variables; one of the most important ones is PATH. The cron job does not login so to speak, thus .profile files are not executed. So in your script you must make sure to set or complement environment variables like PATH.
Also, a cron entry should not use the ~ but put the full path.
In my system I created a small script to list the environment variables that are set when the script is started in cron. As you see a lot less than when in a terminal:
HOME=/home/willem
LANG=en_US.UTF-8
LC_ADDRESS=nl_NL.UTF-8
LC_IDENTIFICATION=nl_NL.UTF-8
LC_MEASUREMENT=nl_NL.UTF-8
LC_MONETARY=nl_NL.UTF-8
LC_NAME=nl_NL.UTF-8
LC_NUMERIC=nl_NL.UTF-8
LC_PAPER=nl_NL.UTF-8
LC_TELEPHONE=nl_NL.UTF-8
LC_TIME=nl_NL.UTF-8
LOGNAME=willem
PATH=/usr/bin:/bin
PWD=/home/willem
SHELL=/bin/sh
SHLVL=1
_=/usr/bin/env
Proper scripts start with a shebang expression, some text explaining what the script will do (you might forget after a few months) and then setting environment variables. A small example (NB willem is my user name:
#!/bin/bash # Script is created and tested for Bash.
# Example script Hello, runs outside a terminal so PATH is minimal.
# We must set env vars.
# Note I do not use "export PATH=$PATH:..." etc, because I want my progs
# directory to be found first.
export MYHOME=/home/willem
export MYLOGS=$MYHOME/logs
export MYPROGS=$MYHOME/prog
export PATH=$MYPROGS:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
#
# The main code of the script:
#
echo "Hello: started" > $MYLOGS/Hello.log
goodDay >> $MYLOGS/Hello.log # goodDay is also in $MYPROGS
...
...
#EOF
To put the script in cron, enter crontab -e:
You are in vi so go to end of file and add:
* * * * * /home/willem/prog/Hello
Close and save, and view your crontab entry/entries: crontab -l
A:
The problem is that, the script isn't designed to work with Cron. It uses few environment variables, which are not accessible from Cron and they are different, depending on the current user's desktop environment. This is the reason on its page to be described another way for running on startup. But it is possible to set values of these variables while the CronJob is running.
For example, when it is the default Ubuntu's desktop environment, the search key words should become: 'gsettings' and 'cron', then our search will lead us to wired topics as: Background not changing using gsettings from cron, where we could find additional explanations as:
If you run the script from your own environment (e.g. from a terminal
window or from Startup Applications), a number of environment
variables will be set. cron however runs your script with a limited
set of environment variables.
To edit gsettings successfully from cron, you need to set the
DBUS_SESSION_BUS_ADDRESS environment variable. You can do that by
adding two lines to your script, as described here...
Run: Daily-Reddit-Wallpaper through Cron via Startup script
Here we will create a startup script, which shall set the necessary environment variables depending of the chosen (by an argument) desktop environment.
1. First cloned Daily-Reddit-Wallpaper and also install the dependencies:
cd ~
git clone https://github.com/ssimunic/Daily-Reddit-Wallpaper.git
cd ~/Daily-Reddit-Wallpaper
sudo apt-get install python-pip
pip install -r requirements.txt
2. Create the script file - change_wallpaper_reddit.sh:
cd ~/Daily-Reddit-Wallpaper
touch change_wallpaper_reddit.sh
chmod +x change_wallpaper_reddit.sh
nano change_wallpaper_reddit.sh
The content of the script is:
#!/bin/sh
# Reference: https://askubuntu.com/a/911958/566421
# Set the script home directory:
SHOME=Daily-Reddit-Wallpaper
# Set the output folder in the home directory to save the Wallpapers to:
DIR=Pictures/Wallpapers
# Set the --time parameter value
TIME=now
# Check if the Desktop Environment is changed:
LAST=$(cat "$HOME/$SHOME/last-desktop-environment.log")
if [ "$1" != "$LAST" ]
then
# Get the name of the last saved wallpaper image:
IMG=$(ls -Art $HOME/$DIR | tail -n 1)
rm $HOME/$DIR/$IMG
fi
# Desktop Environment cases:
if [ -z ${1+x} ] || [ "$1" = "gnome" ] || [ "$1" = "unity" ]
then
# Set the necessary environment variables - PID=$(pgrep gnome-session -u $USER) - UBUNTU/UNITY/GNOME:
export GNOME_DESKTOP_SESSION_ID=true
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep gnome-session -n)/environ | cut -d= -f2-)
# Run the script:
$HOME/$SHOME/change_wallpaper_reddit.py --time $TIME --output $DIR
elif [ "$1" = "kde" ]
then
# Set the necessary environment variables - KUBUNTU/PLASMA/KDE:
export KDE_FULL_SESSION=true
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep startkde -n)/environ | cut -d= -f2-)
# Run the script:
$HOME/$SHOME/change_wallpaper_reddit.py --time $TIME --output $DIR
elif [ "$1" = "mate" ]
then
# Set the necessary environment variables - Ubuntu MATE/MATE:
export DESKTOP_SESSION=mate
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep mate-session -n)/environ | cut -d= -f2-)
# Run the script:
$HOME/$SHOME/change_wallpaper_reddit.py --time $TIME --output $DIR
elif [ "$1" = "lxde" ]
then
# Set the necessary environment variables - type 'echo $DISPLAY` to find your current display - LUBUNTU/LXDE:
export DESKTOP_SESSION=Lubuntu
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep lxsession -n)/environ | cut -d= -f2-)
export DISPLAY=$(w $(id -un) | awk 'NF > 7 && $2 ~ /tty[0-9]+/ {print $3; exit}')
# Run the script:
$HOME/$SHOME/change_wallpaper_reddit.py --time $TIME --output $DIR
elif [ "$1" = "xfce4" ]
then
# Set the necessary environment variables - XUBUNTU/XFCE4:
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep xfce4-session -n)/environ|cut -d= -f2-)
# Run the script:
$HOME/$SHOME/change_wallpaper_reddit.py --time $TIME --output $DIR
# Get the name of the last saved wallpaper image:
IMG=$(ls -Art $HOME/$DIR | tail -n 1)
# Since 'change_wallpaper_reddit.py' doesn't work properly with xfce4 we shall set the background manually:
xfconf-query --channel xfce4-desktop --property /backdrop/screen0/monitor0/workspace0/last-image --set $HOME/$DIR/$IMG
# Property list: xfconf-query --channel xfce4-desktop --list
# Current settings: xfconf-query -c xfce4-desktop -p /backdrop -lv
# Set 'zoomed' style: xfconf-query --channel xfce4-desktop --property /backdrop/screen0/monitor0/workspace0/image-style --set 5
# References: https://askubuntu.com/q/380550/566421 and https://askubuntu.com/q/414422/566421
else
echo "Wrong argument. It must be:"
echo " - empty (default) = gnome = unity"
echo " - kde"
echo " - lxde"
echo " - mate"
echo " - xfce4"
fi
# Save current value of the Desktop Environment variable:
echo "$1" > "$HOME/$SHOME/last-desktop-environment.log"
This script has one argument $1, that determine its behaviour depending of the chosen (from you) desktop environment (DE). The possible values are:
gnome or unity or empty (default) - when you use the default Ubuntu DE;
kde - when you use KUbuntu DE;
lxde - when you use LUbuntu DE;
mate - when you use Ubuntu MATE DE;
xfce4 - when you use XUbuntu DE.
Also you can customise these initial parameters:
SHOME= set the folder where Daily-Reddit-Wallpaper is located into your system.
DIR= set the output folder in the home directory to save the Wallpapers to - the default value (Pictures/Wallpapers) is used in the above script.
TIME= set the value of the --time parameter of change_wallpaper_reddit.py.
3. Create CronJob (crontab -e), that executes change_wallpaper_reddit.sh (at every hour for example):
If you use the default Ubuntu DE, this CronJob could be:
0 * * * * /home/<your user name>/Daily-Reddit-Wallpaper/change_wallpaper_reddit.sh > /home/<your user name>/Daily-Reddit-Wallpaper/cron.log 2>&1
also this syntax will bring same result:
0 * * * * /home/<your user name>/Daily-Reddit-Wallpaper/change_wallpaper_reddit.sh gnome > /home/<your user name>/Daily-Reddit-Wallpaper/cron.log 2>&1
If you use KUbuntu DE, for example, this CronJob could be:
0 * * * * /home/<your user name>/Daily-Reddit-Wallpaper/change_wallpaper_reddit.sh kde > /home/<your user name>/Daily-Reddit-Wallpaper/cron.log 2>&1
For troubleshooting check the log file: cat /home/$USER/Daily-Reddit-Wallpaper/cron.log
Voilà. It's working!
References and further reding:
How to programmatically find the current value of DISPLAY when DISPLAY is unset? (for use in crontab)
Crontab and C program that should be executed into a terminal window
Adjust brightness with xrandr and cron job
How to determine which is the current user's DE through CLI within SSH or Cron?
| {
"pile_set_name": "StackExchange"
} |
Q:
Get root domain from request
Consider the below URL as an example.
http://www.test1.example.com
Is there any method by which I can get "example.com" as an output. I know there is a method servletrequest.getServerName(). It gives me output as test1.example.com
Any help appreciated.
A:
In HttpServletRequest, you can get individual parts of the URI using the methods below. You could also use them to reconstruct the URL piece by piece (to help debugging, or other tasks), like this:
// Example: http://myhost:8080/people?lastname=Fox&age=30
String uri = request.getScheme() + "://" + // "http" + "://
request.getServerName() + // "myhost"
":" + request.getServerPort() + // ":" + "8080"
request.getRequestURI() + // "/people"
(request.getQueryString() != null ? "?" +
request.getQueryString() : ""); // "?" + "lastname=Fox&age=30"
So request.getServerName() is the closest we got to you need.
The "root domain":
For the "root domain", you'll have to work through the String returned from getServerName(). This is necessary because the Servlet would have no way of knowing ahead of time what you call "host" or what is just a domain like .com (it could be a machine called com in your network - and not just a suffix -, who knows?).
For the pattern you gave (one third+secondlevel+com/net), the following should get what you need:
String domain = request.getServerName().replaceAll(".*\\.(?=.*\\.)", "");
The above will give the following input/outputs:
www.test.com -> test.com
test1.example.com -> example.com
a.b.c.d.e.f.g.com -> g.com
www.com -> www.com
com -> com
A:
We have more reliable way of doing the same. There is google library "guava".
Add following dependency in your pom.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
Then try
InternetDomainName.from("subdomain.example.co.in").topPrivateDomain().toString()
This will give you "example.co.in"
A:
You can do this as a simple String manipulation:
String A = "http://www.test1.example.com";
String B = A.substring(A.lastIndexOf('.', A.lastIndexOf('.')-1) + 1);
There is no standard way obtain example.com from a.b.c.example.com because such a transformation is generally not useful. There are TLDs that don't allow registrations on the second level; for example all .uk domains. Given news.bbc.co.uk you'd want to end up with bbc.co.uk, right?
| {
"pile_set_name": "StackExchange"
} |
Q:
If f ≠ ω(g), does f = O(g)?
I'm stuck proving or disproving this statement:
If f ≠ ω(g), then f = O(g)
Intuitively, I think that the statement is false, however, I can't figure out a valid counterexample.
My thought is that we know that f is not bounded from below by a function of g, but that tells us nothing about an upper bound.
Any thoughts? Hints in the right direction?
A:
As a hint, this statement is false. Think about two functions that oscillate back and forth, where each function overtakes the other over and over again. That would make f ≠ ω(g), because f is repeatedly dominated by g, and would make f ≠ O(g) because f repeatedly dominates g.
You'll need to find concrete choices of f and g that make this work and formally establish that f ≠ ω(g) and f ≠ O(g) to formalize this, and I'll leave that as an exercise.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
multi language flash chart recommendation?
I need a good multi language flash chart for my company's portal, can you recommend one?
Already have tried fusion-charts, amCharts, and also OpenChart -
But they are not supporting right-to-left, and the API is not simple (they require a complex XML).
Requirements:
good looking
easy to implement (simple api)
customizable
well documented
not expensive
A:
We use "MultiChart" - for displaying arabic data, was very easy to use and it has brilliant animation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Safari HTTPS title
I see some websites have text instead of the URL, in the address bar in Safari on iPhone.
But on my website it just shows the URL.
I have HTTPS, as I'm using Blogger (Blogspot).
How can I choose the shown text?
A:
According to this question / answer on SuperUser (https://superuser.com/questions/565422/why-do-some-websites-show-the-company-name-next-to-the-url), it indicates a website that uses Extended Validation SSL encryption. The name you see in the browser address bar is the name the EV SSL certificate is issued to. It is a security feature put in place to verify that the website is actually served by the company it claims to be from. Certificates cost money, so it may or may not be worth it for your website.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the opacity of a plotly polygon or ribbon in R?
In plotly for R there is an opacity argument for lines and markers, but how do I change the opacity of fill colours in add_ribbons and add_polygons?
e.g. opacity = 0 makes the line disappear here:
plot_ly() %>% add_lines(x = 1:4, y = 1:4, color = I("red"), opacity = 0)
but has no effect on the polygon here:
plot_ly() %>% add_polygons(x = c(1, 1, 2, 2), y = c(1, 2, 2, 1),
color = I("red"), opacity = 0)
Using alpha doesn't work either. How can I change the opacity of fill colors?
A:
As an alternative you could try using fillColor and rgba color (last digit being alpha):
%>% add_polygons(fillcolor = 'rgba(7, 164, 181, 1)')
vs
%>% add_polygons(fillcolor = 'rgba(7, 164, 181, 0.2)')
Just adjust the numbers for the colour you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Samba shares from a Ubuntu 10.10 box are locked on a mac
I've got some shares on a mythbuntu machine that are set up thus:
[music]
comment = music on mythtv box
path = /media/music
read only = No
public = yes
writeable = yes
printable = yes
I can see them on my OSX laptop and if I look at the permissions it says I have read/write access, but when I try to write to the share I get an error saying that the file is locked or on a locked volume.
I have recently wiped the ubuntu OS partition and reinstalled, these shares are on a separate drive from my OS which weren't touched in the install. I had to manually edit fstab to mount them, so that could be another source of problems. However I have chown-ed them all to my ubuntu user account and on the mythtv machine they are all readable and writeable on the ubuntu machine.
As a side question, what is the difference between read only = no and writeable = yes, or indeed public in smb.conf?
A:
SAMBA is funny about things sometimes. it's a lot of hackish patchwork, but getting better. as far as using r/w vs public, r/w requires some form of authentication and public shouldn't. i would google around a bit for working confs from tutorials and examine the differences instead of trying to use the right syntax based on logic. it could have a lot to do with the order it interprets parameters. i would try not using read only and writeable. if they just flip an access bit without checking it could cause issues. haven't tested or examined source so that isn't definitive, just a thought. there's a discussion where jorge has samba working for a multimedia share over on askubuntu...he might have some pointers. i answered a question or to relating to samba over there. i'ld take a look at those discussions before i beat it up too hard.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where to store access and refresh tokens on ASP.NET client web app - calling a REST API
I've made a Web API in ASP.NET that acts as the entry point into a SQL Server database for report data. This service has a "token" endpoint that authenticates a user via ASP Identity and return a 20-minute access and 2-week refresh token.
This API should only be accessible via our own apps and products. We'll be writing an Android app, iOS app, and ASP.NET web application that will authenticate with and get data from this Web API described above. I'll be responsible for the ASP.NET client web application and the API. We are building these apps all internally for our customers to login to and use. No 3rd parties outside of my company will be calling our API through any of their own apps.
For my client ASP.NET web app, I'm writing it in ASP.NET MVC and it doesn't really have a database as of now since it communicates with the API for everything.
I've started with this as a base, and it works...but now I need to convert this HTML file to an ASP.NET web app in MVC and figure out where and how to store the access token and refresh tokens. http://blog.rfaisal.com/2014/01/14/building-your-own-api-and-securing-it-with-oauth-2-0-in-asp-net-webapi-2/
My questions are:
I understand I'll need to pass the access token in subsequent calls to the API to do CRUD operations. Where should I make my web request to authenticate the user on the web app when logging in...from the C# code behind or JavaScript as in the tutorial referenced above? I ask because I realize that I'll need the access token in my JS Ajax calls, but I've heard that the refresh token needs to be more "secure" and calling from the server code might give me more secure options of doing so??
Where do I store the access token? In a cookie created in JavaScript or the server? In JavaScript local storage? In a session variable that I can pass to the JavaScript maybe?
Where do I store the refresh token? I'll need this for renewing the access token before it's about to expire. I've Googled this to death, but cannot find a good ASP.NET solution online that tells me where or how to store this from the perspective of my consuming web application. A cookie created from the server, saved in a SQL DB that the web app uses, in a session variable?
I'm in desperate need of help, and this is driving me insane and keeping me awake at night. Hope someone can provide a full, simple example and describe fully what I need to do.
A:
1. Where to authenticate the user?
If it is a user who needs to authenticate, then you need something in your front-end. From your front-end, you can just do a POST to your back-end, with the user credentials. You verify the user credentials, and issue an accesstoken/refreshtoken pair in case the credentials are known. You will ALWAYS have to go via the back-end to authenticate a user. You mention that the tutorial does it in JS, but it does not. It POSTS to a login form. The POST is initiated in JS, but it goes to the back-end.
2. Where do I store the accesstoken?
The accesstoken can be stored the same way as normal authentication cookies are stored. You have various options (secure http-only cookie, localstorage, session storage, etc.). In the most simple scenario, you just store it in a cookie so that it is sent along with each request. However, for a mobile app, it is probably easier to store it in LocalStorage.
3. Where do I store the refreshtoken?
This highly depends on your application. I asked the same question a while ago, for mobile apps (be sure to read the comments as well). You should store the refreshtoken in a secure place. For the apps that you will develop, you can follow the suggestions from the answer I linked to, that is:
Store the refreshtoken in LocalStorage
Store the encrypted refreshtoken somewhere on the file system, using an API provided by Android/IOS. Store the encryption key in localstorage. (or the other way around).
For other kind of apps, other possibilities exist. Storing both the accesstoken and refreshtoken in LocalStorage might feel wrong from a security viewpoint, but an attacker will probably have more luck intercepting the token when it is in transit, than gaining access to the localstorage. Other, sometimes more exotic suggestions are given here (e.g. IOS secure storage).
Extra information
I personally like this series of blogposts very much. Be aware, they might start to become a little bit outdated, but they contain a wealth of information regarding a REST-OWIN set-up.
Please do not forget to implement all other security controls, which I have not mentioned as this would cloud the answer. HTTPS, http-only cookies, secure cookies, XSS preventions etc. should be implemented, or your token will be stolen much faster than the time you need to read this answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Left join and excluding non-existent rows on certain matchups
fiddle.
TABLE1
PROP1 PROP2 NUM
a a 1
a a 2
a a 3
a b 1
a b 2
a b 3
TABLE2
PROP1 PROP2 NUM
a a 1
a a 2
I want to query the missing NUM values in TABLE2 with regards to (PROP1, PROP2) tuples such as (a,b,3). However, if a tuple does not exist in TABLE2 such as (a,b). I don't want to return it in the result.
So, my expected output is
PROP1 PROP2 NUM
a a 3
Following query I wrote, returns the (a,b) tuples as well, which I don't want to.
SELECT *
FROM TABLE1 T1
LEFT JOIN TABLE2 T2 ON T1.PROP1 = T2.PROP1 AND T1.PROP2 = T2.PROP2 AND T1.NUM = T2.NUM
WHERE T2.NUM IS NULL
I want to exclude these 3 rows, so I join with TABLE2 one more time and group the results which gives me the correct result.
SELECT T1.PROP1, T1.PROP2, T1.NUM
FROM TABLE1 T1
LEFT JOIN TABLE2 T2 ON T1.PROP1 = T2.PROP1 AND T1.PROP2 = T2.PROP2 AND T1.NUM = T2.NUM
JOIN TABLE2 T22 ON T1.PROP1 = T22.PROP1 AND T1.PROP2 = T22.PROP2
WHERE T2.NUM IS NULL
GROUP BY T1.PROP1, T1.PROP2, T1.NUM
Question: Is there any way I can do it without a GROUP BY statement since it is a bit exhaustive for large tables.
I'm using Oracle 11g.
A:
This will do what you want, but I don't know if it will be more efficient:
SELECT *
FROM TABLE1 T1 JOIN
(SELECT DISTINCT PROP1, PROP2
FROM TABLE2
) TT2
ON T1.PROP1 = TT2.PROP1 AND t1.PROP2 = TT2.PROP2 LEFT JOIN
TABLE2 T2
ON T1.PROP1 = T2.PROP1 AND T1.PROP2 = T2.PROP2 AND T1.NUM = T2.NUM
WHERE T2.NUM IS NULL;
It first filters table1 on the matching rows, and then does the final comparison.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to statistically compare two algorithms across three datasets in feature selection and classification?
Problem background: As part of my research, I have written two algorithms that can select a set of features from a data set (gene expression data from cancer patients). These features are then tested to see how well they can classify an unseen sample as either cancer or non-cancer. For each run of the algorithm, a solution (a set of features) is generated and tested on Z unseen samples. Percentage accuracy of the solution is calculated like this: (correct classifications / Z) * 100.
I have two algorithms: algorithm X & algorithm Y
I have three separate (different cancers) data sets: data set A, data set B & data set C. These data sets are very different from each other. They don't have the same number of samples or same number of measurements (features) per sample.
I have run each algorithm 10 times on each data set. So, algorithm X has 10 results from data set A, 10 from data set B and 10 from data set C. Overall, algorithm X has 30 results.
My problem: I would like to see if algorithm X's combined performance across all three data sets is statistically significantly different from algorithm Y's combined performance.
Is it possible for me to combine results for algorithm X from each data set into a single set of results? This way, I would have 30 standardized results for algorithm X and 30 standardized results for algorithm Y. I can then use the t-test to see if there is a significant difference between the two methods.
Edit - These are Evolutionary Algorithms, so they return a slightly different solution each time they are run. However, if there's a feature in a sample that when present can strongly classify the sample as either being cancer or non-cancer, then that feature will be selected almost every time the algorithm is run.
I get slightly different results for each of the 10 runs due to the following reasons:
These algorithms are randomly seeded.
I use repeated random sub-sampling validation (10 repeats).
The datasets that I use (DNA microarray and Proteomics) are very difficult to work with in the sense that there are many local optima the algorithm can get stuck in.
There are lots of inter-feature and inter-subset interactions that I would like to detect.
I train 50 chromosomes and they are not restricted to any particular length. They are free to grow and shrink (although selection pressure guides them towards shorter lengths). This also introduces some variation to the final result.
Having said, the algorithm almost always selects a particular subset of features!
Here's a sample of my results (only 4 runs out of 10 for each algorithm is shown here):
Dataset/run Algorithm X Algorithm Y
A 1 90.91 90.91
A 2 90.91 95.45
A 3 90.91 90.91
A 4 90.91 90.91
B 1 100 100
B 2 100 100
B 3 95.65 100
B 4 95.65 86.96
C 1 90.32 87.10
C 2 70.97 80.65
C 3 96.77 83.87
C 4 80.65 83.87
As you can see, I've put together results for two algorithms from three datasets. I can do Kruskal-Wallis test on this data but will it be valid? I ask this because:
I'm not sure accuracies in different data sets are commensurable. If they are not, then putting them together like I've done would be meaningless and any statistical test done on them would also be meaningless.
When you put accuracies together like this, the overall result is susceptible to outliers. One algorithm's excellent performance on one dataset may mask it's average performance on another dataset.
I cannot use t-test in this case either, this is because:
Commensurability - the t-test only makes sense when the differences over the data sets are commensurate.
t-test requires that the differences between the two algorithms compared are distributed normally, there's no way (at least that I'm aware of) to guarantee this condition in my case.
t-test is affected by outliers which skew the test statistics and decrease the test’s power by increasing the estimated standard error.
What do you think? How can I do a comparison between algorithm X & Y in this case?
A:
Unless your algorithms have huge differences in performance and you have huge numbers of test cases, you won't be able to detect differences by just looking at the performance.
However, you can make use of apaired design:
run all three algorithms on exactly the same train/test split of a data set, and
do not aggregate the test results into % correct, but keep them at the single test case level as correct or wrong.
For the comparison, have a look at McNemar's test. The idea behind exploiting a paired design here is that all cases that both algorithms got right and those that both got wrong do not help you distinguishing the algorithms. But if one algorithm is better than the other, there should be many cases the better algorithm got right but not the worse, and few that were predicted correctly by the worse method but wrong by the better one.
Also, Cawley and Talbot: On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation, JMLR, 2010, 1, 2079-2107. is highly relevant.
Because of the random aspects of your algorithms, you'll also want to check the same split of the same data set multiple times. From that you can estimate the variation between different runs that are otherwise equal. It may be difficult to judge how different the selected sets of variables are. But if your ultimate goal is predictive performance,then you can also use the variation between predictions of the same test case during different runs to measure the stability of the resulting models.
You'll then also want to check (as indicated above) variation due to different splits of the data set and put this into relation with the first variance.
Fractions (like % correctly recognized samples) are usually assumed to be distributed binomially, in certain cases a normal approximation is possible, but the small-print for this hardly ever met in fields with wide data matrices. This has the consequence that confidence intervals are huge for small numbers of test cases. In R, binom::binom.confint calculates confidence intervals for the true proportion given no. of tests and no. of successes.
Finally, My experience with genetic optimization for spectroscopic data (my Diplom thesis in German) suggests that you should check also the training errors. GAs tend to overfit very fast, arriving at very low training errors. Low training errors are not only overoptimistic, but they also have the consequence that the GA cannot differentiate between lots of models that seem to be equally perfect. (You may have less of a problem with that if the GA internally also randomly subsamples train and internal test sets).
Papers in English:
Beleites, Steiner, Sowa, Baumgartner, Sobottka, Schackert and Salzer: Classification of human gliomas by infrared imaging spectroscopy and chemometric image processing, Vib Spec, 2005, 38, 143 - 149.
application oriented, shows how we interpret the selected variates and that there are known "changes" in selections that are equivalent for chemical reasons.
Beleites and Salzer: Assessing and improving the stability of chemometric models in small sample size situations, Anal Bioanal Chem, 2008, 390, 1261 - 1271.
discusses binomial confidence intervals for hit rate etc, why we could not calculate it. Instead, we use variation observed over repeated cross validation. The discussion about guesstimate for the effective sample size needs to be taken with caution, nowadays I'd say it is somewhere between misleading and wrong (I guess that is science moving on :-) ).
fig. 11 shows the independent (outer cross validation with splitting by specimen) test results from 40 different models for the same specimen. The corresponding internal estimate of the GA was 97.5% correct predictions (one model got all spectra of the specimen wrong, the remaining models were correct for all spectra - not shown in the paper). This is the problem with overfitting I mentioned above.
In this recent paper Beleites, Neugebauer, Bocklitz, Krafft and Popp: Sample Size Planning for Classification Models, Anal Chem Acta, 2013, 760, 25 - 33. we illustrate the problems with classification error estimation with too few patients/independent samples. Also illustrates how to estimate necessary patient numbers if you cannot do paired tests.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawing knots without overdrawing a grid
I would like to draw a knot with self intersections. This can be done with the TikZ library knots. However, in my situation I have a grid in the background which should not be overdrawn from the white tube at the intersection. Is it possible to prevent this automatically?
Here is a minimal example. On the left, you see how the grid is overdrawn, and on the right you see how it should look like; but this workaround is not suitable for the knots I am actually working with. To be clear: Of course, the actual knot has to overdraw the grid.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{knots}
\begin{document}
\begin{tikzpicture}[baseline]
\draw [lightgray] (0,0) grid (2,2);
\begin{knot}[consider self intersections, clip width=10]
\strand [thick] (0,0) -- (2,2) -- (2,0) -- (0,2);
\flipcrossings{2}
\end{knot}
\end{tikzpicture}
\quad
\begin{tikzpicture}[baseline]
\draw [thick] (2,0) -- (0,2);
\draw [white, line width=2ex] (0,0) -- (2,2);
\draw [lightgray] (0,0) grid (2,2);
\draw [thick] (0,0) -- (2,2) -- (2,0);
\end{tikzpicture}
\end{document}
A:
Since the grid is light gray and the knot lines are black, there is a trick with transparency. The grid is drawn on top of the knots, but with opacity=.25. Then, the black lines remain black and the grid lines on top of the white background become light gray:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{knots}
\begin{document}
\begin{tikzpicture}[baseline]
\begin{knot}[consider self intersections, clip width=10]
\strand [thick, line join=round]
(0,0) -- (2,2) -- (2,0) -- (0,2);
\flipcrossings{2}
\end{knot}
\draw [opacity=.25, line cap=rect] (0, 0) grid (2,2);
\end{tikzpicture}
\end{document}
With white background:
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does a model perform worse after reintroducing observations with missing data imputed?
My dataset contains about 12% missing data, and much of the missing data is grouped along observations (not randomly scattered or along columns). I optimized a regression method after removing the observations with large amounts of missing data (and used KNN-impute to infer the remaining missing data). I am now trying knn-impute on the entire data set, without removing any data prior, and my previous optimal regression method is now performing worse. Why might this be?
Note: optimal regression method == optimizing parameters.
So is adding in this new data worse i) as it contains lots of missing data and knn-impute is the wrong method, or ii) I just need to search for new optimal parameters.
A:
Presumably your model was optimised for one sample. If you add a large amount of new data it will generally perform worse. The performance could be even worse if the observations with missing data are systematically different in some way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disabling Google Voice Dialer
I have a Motorola Electrify M, recently factory-OTA-updated to Android 4.1.2. With the update came Google Now and the Google Voice Dialer.
Google's Voice Dialer sucks! It always get the name wrong, and then immediately places a call to the wrong person! It doesn't even ask for confirmation of the name, and to top it off the voice it uses is so irritating and LOUD it makes me want to jump out the window while driving down the freeway!
The Voice Commands app that originally came with the phone worked reasonably well, and I'd like to get it back (or even a third party app, like Dragon Assist, would be better than the current POS that's taken over the voice capabilities of my phone).
How can the Google Voice Dialer be disabled or uninstalled?
A:
Okay, I figured out how to set the good ol' Voice Commands app as the default voice commands interface. It has to be done while not connected to a hands free device via Bluetooth.
Tap into the Phone app
Tap the Phone app's microphone icon
In my case a prompt appeared asking me to select the default app to handle voice commands. Thereafter, it's used the correct Voice Commands app when connected via Bluetooth.
For those who wanted to know how to disable Google Now, here's how it's done:
Swipe up from the Home icon to activate Google Now
Scroll all the way to the bottom
Tap the Overflow menu (three vertical dot icon)
Tap Settings
Tap Google Now
Tap the OFF/ON switch in the upper-right to disable Google Now
| {
"pile_set_name": "StackExchange"
} |
Q:
C vs Haskell Collatz conjecture speed comparison
My first real programming experience was with Haskell. For my ad-hoc needs I required a tool that was easy to learn, quick to code and simple to maintain and I can say it did the job nicely.
However, at one point the scale of my tasks became much bigger and I thought that C might suit them better and it did. Maybe I was not skilled enough in terms of [any] programming, but I was not able to make Haskell as speed-efficient as C, even though I heard that proper Haskell is capable of similar performance.
Recently, I thought I would try some Haskell once more, and while it's still great for generic simple (in terms of computation) tasks, it doesn't seem to be able to match C's speed with problems like Collatz conjecture. I have read:
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell
GHC Optimization: Collatz conjecture
collatz-list implementation using haskell
But from what I see, simple optimization methods, including:
choosing "tighter" types, like Int64 instead of Integer
turning GHC optimizations on
using simple optimization techniques like avoiding unneccessary computation or simpler functions
still don't make Haskell code even close to almost identical (in terms of methodology) C code for really big numbers. The only thing that seems to make its performance comparable to C's [for big-scale problems] is using optimization methods that make the code a long, horrendous monadic hell, which goes against the principles that Haskell (and I) value so much.
Here's the C version:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int32_t col(int64_t n);
int main(int argc, char **argv)
{
int64_t n = atoi(argv[1]), i;
int32_t s, max;
for(i = 2, max = 0; i <= n; ++i)
{
s = col(i);
if(s > max) max = s;
}
printf("%d\n", max);
return 0;
}
int32_t col(int64_t n)
{
int32_t s;
for(s = 0; ; ++s)
{
if(n == 1) break;
n = n % 2 ? 3 * n + 1 : n / 2;
}
return s;
}
and the Haskell version:
module Main where
import System.Environment (getArgs)
import Data.Int (Int32, Int64)
main :: IO ()
main = do
arg <- getArgs
print $ maxCol 0 (read (head arg) :: Int64)
col :: Int64 -> Int32
col x = col' x 0
col' :: Int64 -> Int32 -> Int32
col' 1 n = n
col' x n
| rem x 2 == 0 = col' (quot x 2) (n + 1)
| otherwise = col' (3 * x + 1) (n + 1)
maxCol :: Int32 -> Int64 -> Int32
maxCol maxS 2 = maxS
maxCol maxS n
| s > maxS = maxCol s (n - 1)
| otherwise = maxCol maxS (n - 1)
where s = col n
TL;DR: Is Haskell code quick to write and simple to maintain only for computationally simple tasks and loses this characteristic when performance is crucial?
A:
The big problem with your Haskell code is that you are dividing, which you don't in the C version.
Yes, you wrote n % 2 and n / 2, but the compiler replaces that with shifts and bitwise and. GHC has unfortunately not yet been taught to do that.
If you do the substitution yourself
module Main where
import System.Environment (getArgs)
import Data.Int (Int32, Int64)
import Data.Bits
main :: IO ()
main = do
arg <- getArgs
print $ maxCol 0 (read (head arg) :: Int64)
col :: Int64 -> Int32
col x = col' x 0
col' :: Int64 -> Int32 -> Int32
col' 1 n = n
col' x n
| x .&. 1 == 0 = col' (x `shiftR` 1) (n + 1)
| otherwise = col' (3 * x + 1) (n + 1)
maxCol :: Int32 -> Int64 -> Int32
maxCol maxS 2 = maxS
maxCol maxS n
| s > maxS = maxCol s (n - 1)
| otherwise = maxCol maxS (n - 1)
where s = col n
with a 64-bit GHC you get comparable speed (0.35s vs C's 0.32s on my box for a limit of 1000000). If you compile using the LLVM backend, you don't even need to replace the % 2 and / 2 with bitwise operations, LLVM does that for you (but it produces slower code, 0.4s, for your original Haskell source, surprisingly - normally, LLVM is not worse than the native code generator at loop optimisation).
With a 32-bit GHC, you won't get comparable speed, since with those, the primitive operations on 64-bit integers are implemented through C calls - there never was enough demand for fast 64-bit operations on 32-bit systems for them to be implemented as primops; the few people working on GHC spent their time doing other, more important, things.
TL;DR: Is Haskell code quick to write and simple to maintain only for computationally simple tasks and loses this characteristic when performance is crucial?
That depends. You must have some idea of what sort of code GHC generates from what sort of input, and you must avoid some performance traps. With a bit of practice, it is quite easy to get within say 2× the speed of gcc -O3 for such tasks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple characters in a string return a false boolean when trying to find a character in the string
#Function takes a character and a string and returns a boolean reflecting if
#the character is found in the string.
def isItThereS(letter, word):
letInWord = 0
for l in word:
if l == letter:
letInWord += 1
return letInWord == True
When I put it in the operator like
isItThereS("h","hello world")
True
but when I go to find a character that repeats like "l" or "o" it returns false.
isItThereS("l","hello world")
False
How would I go about getting that to not return false, but instead return True since the character is technically in the string?
A:
you can simply use the in operator
def isItThereS(letter, word):
return letter in word
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tell if an Android app is in the "stopped" state?
I have an Android app that registers a BroadcastReceiver to handle ringer mode changes. The receiver is registered through the manifest, not dynamically. Some users report that occasionally the app doesn't respond to a ringer mode change, although manually launching the app and subsequently changing the ringer mode does trigger the app. Some time later, however, the app stops responding to ringer mode changes again.
The symptom sounds suspiciously like the app is getting into the "stopped" state; but I don't have any reason to believe that users are explicitly force closing the app, and I'm not aware of any other way that an app could get into the "stopped" state.
Is there a way for a user to determine if an app on their (non-rooted) phone is in the stopped state, so I could validate/invalidate the "stopped" state theory? I don't think it is sufficient to look at whether the "force close" button is enabled, since it would be disabled both for stopped apps as well as apps not currently running.
A:
You can query all applications on a device and see which ones are in a stopped state with this code:
private List<String> getStoppedPackages() {
ArrayList<String> stoppedPackages = new ArrayList<String>();
final PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
boolean appStopped = (packageInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0;
if (appStopped) {
String description = packageInfo.packageName;
stoppedPackages.add(description);
}
}
return stoppedPackages;
}
I made a utility app that does this for you here:
https://github.com/davidgyoung/stopped-app-detector
| {
"pile_set_name": "StackExchange"
} |
Q:
on click stopped by doubleclick
In jQuery I got a function that executes on a click, but another on a double click, the problem is that when I double click on it it clicks 2 times and do a double click so 3 executions...
here is my code :
$('.listCat li').on({
click: function() {
$(this).toggleClass("on");
refresh();
},
dblclick: function() {
$('.listCat li.on').removeClass('on');
$(this).addClass("on");
refresh();
}
});
I was thinking in the click to make a small delay and detects if there is a doubleclick, otherwise launch refresh().
Do you think of a nice clean way to do that ?
Thank you.
A:
The docs for jQuery .dblclick suggest that you don't use them together:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Workaround
If you must do this, there is a workaround on this question (as pavan mentioned in a comment on your question). I wouldn't completely trust it, though. As the jQuery docs say, the length of a double-click is often user configurable.
Also see this question: jQuery: Suppress `click` when `dblclick` is imminent?
| {
"pile_set_name": "StackExchange"
} |
Q:
Python producer/consumer with process and pool
I'm trying to write simple code for producer consumer with process. Producer is a process. For consumer I'm getting processes from Pool.
from multiprocessing import Manager, Process, Pool
from time import sleep
def writer(queue):
for i in range(10):
queue.put(i)
print 'put 1 size now ',queue.qsize()
sleep(1)
def reader(queue):
print 'in reader'
for i in range(10):
queue.get(1)
print 'got 1 size now ', queue.qsize()
if __name__ == '__main__':
q = Manager().Queue()
p = Process(target=writer, args=(q,))
p.start()
pool = Pool()
c = pool.apply_async(reader,q)
But I'm getting error,
Process Process-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "pc.py", line 5, in writer
queue.put(i)
File "<string>", line 2, in put
File "/usr/lib/python2.7/multiprocessing/managers.py", line 758, in _callmethod
conn.send((self._id, methodname, args, kwds))
IOError: [Errno 32] Broken pipe
Can anyone point me, where am I going wrong.
A:
Hi I had found this answer,
from multiprocessing import Manager, Process, Pool,Queue
from Queue import Empty
def writer(queue):
for i in range(10):
queue.put(i)
print 'put %i size now %i'%(i, queue.qsize())
def reader(id, queue):
for i in range(10):
try:
cnt = queue.get(1,1)
print '%i got %i size now %i'%(id, cnt, queue.qsize())
except Empty:
pass
class Managerss:
def __init__(self):
self.queue= Queue()
self.NUMBER_OF_PROCESSES = 3
def start(self):
self.p = Process(target=writer, args=(self.queue,))
self.p.start()
self.workers = [Process(target=reader, args=(i, self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
def join(self):
self.p.join()
for w in self.workers:
w.join()
if __name__ == '__main__':
m= Managerss()
m.start()
m.join()
Hope it helps
| {
"pile_set_name": "StackExchange"
} |
Q:
D3 Multi Series Line chart not working with correct xAxis values
I have a D3 multi-series line chart in my application and it shows vehicle brands in x-axis and sales in y-axis. I have used ordinal scale for x-axis since it is strings that I'm dealing with in the x-axis. But the chart doesn't render correctly with the given values. Even though I have 4 car brands for x-axis values, it shows only two of them.
Can someone tell me what has happened here? Sample code is given below.
Fiddle : https://jsfiddle.net/yasirunilan/zn01cjbo/3/
var data = [{
name: "USA",
values: [{
date: "BMW",
price: "100"
},
{
date: "Nissan",
price: "110"
},
{
date: "Toyota",
price: "145"
},
{
date: "Bentley",
price: "241"
},
{
date: "Ford",
price: "101"
}
]
},
{
name: "UK",
values: [{
date: "BMW",
price: "130"
},
{
date: "Nissan",
price: "120"
},
{
date: "Toyota",
price: "115"
},
{
date: "Bentley",
price: "220"
},
{
date: "Ford",
price: "100"
}
]
}
];
const margin = 80;
const width = 1000 - 2 * margin;
const height = 550 - 2 * margin;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.time.format("%B");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = d.date;
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scale.ordinal()
.range([0, width], 0.4)
.domain(d3.extent(data[0].values, function(d) {
return d.date;
}));
var yScale = d3.scale.linear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height - margin, 0]);
// var color = d3.scale.ordinal(d3.schemeCategory10);
var color = d3.scale.category10();
/* Add SVG */
var svg = d3.select("svg")
.attr("width", (width + margin) + "px")
.attr("height", (height + margin) + "px")
.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.svg.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width - margin) / 2)
.attr("y", 5);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', (d, i) => color(i))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.style("fill", (d, i) => color(i))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom").tickSize(1);
var yAxis = d3.svg.axis().scale(yScale)
.orient("left").tickSize(1);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.attr('text-anchor', 'middle')
.text("No. of Employees");
A:
You need to use Array.map in the domain and the rangePoints() to set the range
var xScale = d3.scale.ordinal()
.rangePoints([0, width], 0.1)
.domain(data[0].values.map(function(d) { return d.date; }));
| {
"pile_set_name": "StackExchange"
} |
Q:
This code emulates command ls|cat -n, but i need to transmit the needed directory through stdin instead of ".", how can i do it?
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *de;
DIR *dr;
int i = 1;
dr = opendir("."); // need to get directory through stdin insted of this
if (dr == NULL) printf("Could not open directory");
while (((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}
A:
You read it from stdin and use in place of ".". Here is the full example
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int main(){
struct dirent *de;
char dirbuf[BUFSIZ] = {0};
DIR *dr;
int i = 1;
puts("Chose the directory: ");
if (fgets(dirbuf, BUFSIZ, stdin) == NULL) {
perror("fgets");
exit(-1);
}
dirbuf[strlen(dirbuf)-1] = '\0'; // remove \n
dr = opendir(dirbuf); // need to get directory through stdin insted of this
if (dr == NULL) {
perror("opendir");
exit(-1);
}
while(((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery para adicionar elemento na div função.append
Boa tarde, Estou tentando adicionar um elemento direto em uma div. Só que aparentemente a função .append, precisa de uma div e outro elemento. O problema é que o elemento que vem antes, é variavel e o meu icone não deve ser.
Mesmo assim testando isso, meu codigo não funcionou.
<script>
$(".card VI").ready(function(){
$("#creditcardZone").append("<h1>Teste</h1>");
});
</script>
HTML:
<div id="creditcardZone" class="card_list"> <label class="card EL"><input type="radio" checked="" value="EL" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="ELO"><span><small>ELO</small></span></label><label class="card MC"><input type="radio" value="MC" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="MasterCard"><span><small>MasterCard</small></span></label><label class="card DC"><input type="radio" value="DC" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="Diners"><span><small>Diners</small></span></label><label class="card AX"><input type="radio" value="AX" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="American Express"><span><small>American Express</small></span></label><label class="card VI"><input type="radio" value="VI" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="Visa"><span><small>Visa</small></span></label></div>
Se esta função não serve para este caso, tem alguma alternativa de função parecida com essa, porém que eu consiga colocar um elemento dentro de uma div, e não ao lado de outro elemento?
PS: Não tenho acesso ao HTML, por isso preciso fazer assim.
Coloquei uma imagem pra exemplificar. Basicamente preciso adicionar uma bandeira ali "transferencia bancaria", depois de adiciona-la, vou transformar em pop-up para que ela de uma mensagem de dados bancarios, só isso.
A:
É isto o que você precisa, incluí um alert pra você ver que é possível incluir um evento no click, você pode chamar uma função, etc...
(function(){
var lbl, input, span, small;
//Cria o label
lbl = document.createElement("label");
lbl.setAttribute("class", "card VII");
//cria o input
input = document.createElement("input");
input.setAttribute("type", "radio");
input.setAttribute("value", "VII");
input.setAttribute("class", "rdoCreditCards");
input.setAttribute("name", "CreditCardProvider");
input.setAttribute("id", "outros");
input.setAttribute("displayname", "outros");
input.setAttribute("onClick", "alert('hello')");
//cria o span
span = document.createElement("span");
//cria o small
small = document.createElement("small");
//junta tudo
span.appendChild(small);
input.appendChild(span);
lbl.appendChild(input);
document.getElementById("creditcardZone").appendChild(lbl);
})();
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container"> <br />
<div id="creditcardZone" class="card_list"> <label class="card EL"><input type="radio" checked="" value="EL" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="ELO"><span><small>ELO</small></span></label><label class="card MC"><input type="radio" value="MC" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="MasterCard"><span><small>MasterCard</small></span></label><label class="card DC"><input type="radio" value="DC" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="Diners"><span><small>Diners</small></span></label><label class="card AX"><input type="radio" value="AX" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="American Express"><span><small>American Express</small></span></label><label class="card VI"><input type="radio" value="VI" class="rdoCreditCards" name="CreditCardProvider" id="CreditCardProvider" displayname="Visa"><span><small>Visa</small></span></label></div>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any in-game meeting places for players?
Are there any well-established locations where players will meet up in the E:D galaxy?
Are there player-based groups (like the Fuel Rats, but more social) that regularly gather in-game? If so, where?
I listen to the very awesome Radio Sidewinder and they sometimes mention bars for pilots to visit and get some R&R, or markets that sell exotic goods (there are no locations other than stations in the game yet, so maybe the markets are real, but I'm pretty sure there's no bars yet). I assume these are fake commercials intended to give the station a more realistic feel, but it made me wonder, if I'm lonely and want some guaranteed humanoid interaction, where can I go?
I realise there are traffic hot spots, such as the Sol system, stations that sell discounted ships, expansion systems, etc. There are also areas where players gather to race, which I have no desire to try and I'm not sure how you could spectate really, but it's pretty cool.
I'm looking for a "player-designated" hot spot, if that makes more sense.
A:
I actually found a great answer to a related question on SE, How can I find other players in Elite: Dangerous? that includes some relevant details. That question focuses on finding players anywhere, in any number. While I've come across my fair share of wandering players and 2-3 man wings, I was looking more for specific locations that groups of people tend to congregate around habitually.
The best and most relevant tips from that answer are as follows:
This list of subreddits leads to pages for many E:D groups, which sometimes give you an idea of where they gather, what they do, who they are, etc.
There is also a suggestion to visit the "Old Worlds" that are mentioned in the original Elite fiction and games:
Go to the "Old Worlds" cluster (Leesti, Lave, Zaonce, etc). This is the area that people started the original 1984 game in. There's a number of rare commodities available in the area, and multiple active player groups active in the area.
Without turning this into a continually-evolving list question, I think this is the best advice on finding player congregations at specific locations. These links will most likely continue to be accurate for at least the near future, if not longer.
| {
"pile_set_name": "StackExchange"
} |
Q:
send response to a client from a server
I want to send a response to a client after he is connected
Here is the snippet of the code
try {
while (true)
{
in = socket.getInputStream();
out = socket.getOutputStream();
byte[] reception = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = in.read(reception);
String bufferServer = "Buffer Server ";
baos.write(reception, 0, read);
reception = baos.toByteArray();
String chaine = new String(reception, "Cp1252");
System.out.println("Reception from client : " + chaine);
byte[] bufferServeurToClient = bufferServer.getBytes();
out.write(bufferServeurToClient); // send to client
out.flush();
}
}
The clients can send multiple request , that ' s why i use a while(true) in order to listen requests until client disconnect.
The problem is that i receive nothing from the server in the client side.
If i remove the while(true) it works and i receive the variable "bufferServeurToClient" at client side
edit: Client side which work now , but when i print the response , i have a lot of weird character(square) after my string , why?
String ip = InetAddress.getLocalHost ().getHostAddress ();
Socket socket = new Socket(ip, port);
System.out.println("SOCKET = " + socket);
InputStream in = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
OutputStream out = socket.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(out);
String bufferClient="Buffer Client ";
byte[] bufferClientToServer= bufferClient.getBytes();
out.write(bufferClientToServer);
byte[] reception = new byte[1024] ;
int read;
while ((read = bis.read(reception)) != -1){
String chaine = new String( reception , "Cp1252" );
System.out.println("Reception from server: " + chaine);
}
bis.close();
bos.close();
}
Thank you for your help
A:
The clients can send multiple request, that's why I use a while(true) in order to listen requests until client disconnect.
If the client can send multiple requests, you'll need a way of differentiating between them - and between the responses. Currently, you're just assuming that a single call to read will do the job:
int read =in.read(reception);
That could read part of a request, or potentially multiple requests. Common options to fix this are to use some sort of delimiter (e.g. one request per text line) or to use length-prefixing, where (say) the first four bytes of each request or response say how much more data there is.
Now you haven't shown what your client side looks like at all - but my guess is that you're actually waiting for the server to close the connection, which of course you'll never do while the while(true) loop is there. So that's another piece of code you'll need to modify.
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically move the pin in digdog MapKitDragAndDrop framework
I have the digdog MapKitDragAndDrop in one my projects to achieve drag and drop pins. Im also allowing the user to search for location based on the address.
When the user searched and found his location coordinates, i want the pin to move to that location. Animation etc is not mandatory
I not able to figure out how to move the pin manually.
A:
Just provide a new set of coordinates for your annotation, remove it and put it back in the map view's annotations. Some code from you would help be precise.
But basically the idea is that you remove the annotation from the map view and then put it back again, with the good coordinates. As a DDAnnotation is a MKPlacemark, that shouldn't be too hard.
It would look like:
- (void)annotation:(DDAnnotation*)annotation hasNewCoordinates:(CLLocation)location{
[_mapView removeAnnotation:annotation];
annotation._coordinate = location;
[_mapView addAnnotation: annotation];
}
Of course untested.
| {
"pile_set_name": "StackExchange"
} |
Q:
Escaping Quotes does not work in JavaScript innerHTML
I have got a quite bad "quoting situation" at the moment.
I am working inside an innerHTML and inside this i want to call a function on the onClick-Event, which leaves me with the following:
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="sendUpdatedGroup(id, document.getElementById("groupName").value, document.getElementById("groupDesc").value)">Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="deactivateOverlay()">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
I already tried escaping the quotes and using HTML-Quotes, but neither worked.
A:
Instead of HTML encoding the single quotes, just JavaString escape your single quotes.
'<button type="button" class="mui-btn mui-btn--raised"
onclick="sendUpdatedGroup(id, document.getElementById(\'groupName\').value,
document.getElementById(\'groupDesc\').value)">Speichern</button>'+
If you don't want to get into escaping hell , don't use event handlers as HTML attributes (which we stopped doing about 10 years ago).
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" >Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
var buttons = modalEl.querySelectorAll('.formbuttons button');
buttons[0].addEventListener('click', function() {
sendUpdatedGroup(id,
document.getElementById('groupName').value,
document.getElementById('groupDesc').value))
});
buttons[i].addEventListener('click', deactivateOverlay);
| {
"pile_set_name": "StackExchange"
} |
Q:
get parameter of array in twig loop
When I dump an array in twig, it gives the following result:
array(1) {
[0]=>
object(TEST\Bundle\BlogBundle\Entity\Follow)#364 (3) {
["id":"TEST\Bundle\BlogBundle\Entity\Follow":private]=>
int(1)
["follower"]=>
int(2)
["followed"]=>
int(1)
}
}
int(1)
int(1)
How can I access the follower parameter inside my loop which is:
{% for fol in followers %}
<pre> {{ dump(fol) }} </pre>
{% endfor %}
Thank you for your help.
A:
Use TWIG attribute docs. Example:
{% for fol in followers %}
<pre> {{ dump(attribute(fol[0], follower)) }} </pre>
{% endfor %}
Please make you sure that you have getters for follower in TEST\Bundle\BlogBundle\Entity\Follow or follower attribute is public.
Or simillarly print value:
{% for fol in followers %}
<pre> {{ fol[0].follower }} </pre>
{% endfor %}
| {
"pile_set_name": "StackExchange"
} |
Q:
Crystal Report add leading zeros but do not show for sorting calculated field in group
I have a calculated field in Crystal Report which starts with numbers and is already sorted as text. I want to sort it like numbers. The calculated field consists of two numberfields and a textfield. Like this:
{numberfield1} & "." & {numberfield2} & " " & {textfield}
The Report shows the data like this (already sorted):
1.2 sometext
10.3 sometext
2.30 sometext
2.4 sometext
What I want to achive is to sort first for {numberfield1} and then {numberfield2} with following result:
1.2 sometext
2.4 sometext
2.30 sometext
10.3 sometext
I already tried this:
http://www.crystalreportsbook.com/Forum/forum_posts.asp?TID=19668
so my code looks like this:
totext({numberfield1},"00", 0) & "." &
totext({numberfield2},"00",0) & " " &
{textfield}
As far as I understand, this code should hide the leading zeros. But it does not. The leading zeros are still displayed in the report. At least, the sorting is working. The result:
01.02 sometext
02.04 sometext
02.30 sometext
10.30 sometext
I also tried:
cstr(val({numberfield}))
totext(tonumber({numberfield}))
These remove the leading zeros, but the sorting does not work.
Thank you very much for your time!
A:
Create a first formula. Let's call it "TheOneThatYouSee":
{numberfield1} & "." & {numberfield2} & " " & {textfield}
//i just copied your formula
Create a second formula. Let's call it "TheOneThatYouDoNotSee":
totext({numberfield1},"00", 0) & "." &
totext({numberfield2},"00",0) & " " &
{textfield}
//i just copied your formula
Then you sort by TheOneThatYouDoNotSee (group by).
Then you put the TheOneThatYouSee in the details section.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use spring transaction in multithread
I have a method as below:
ClassA.java
@Transactional
public void methodA(){
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.execute(new Runnable() {
public void run() {
classB.methodB();
}
});
}
ClassB.java
@Transactional
public void methodB(){
updateDB();
}
Can the methodB work well? Per my understanding, methodB will attach the transaction of methodA, what if methodA exits before methodB? I guess only methodA can be commited by the transaction. But methodB will not commit because the transaction commited before.
Can I use @Transactional(propagation = Propagation.REQUIRES_NEW) for methodB. This can let methodB have a new transaction. But according to spring doc, the transcation of methodA will suspend when it invoke methodB. I feel very confuse here.
Can anyone help me on this issue? Thanks in advance.
A:
No, methodB() will not be executed in the same transaction as methodA(). Spring's @Transactional only works on a single thread - it creates a session when a thread first enteres a method with @Transactional (or a method in a class with @Transactional), and then commits it when it leaves that method.
In your example, the transaction will end after you schedule the job in the thread pool. methodB() will have it's own transaction.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git pull error: Your local changes to the following files would be overwritten by merge:
I am trying to pull changes from remote branch but getting an error which doesn't make sense
when I do
git pull
I get back
error: Your local changes to the following files would be overwritten by merge:
file/name/path
some/more/filenamepath
Please, commit your changes or stash them before you can merge.
Aborting
Problem is I have no changes that need to be committed
When I do
git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 7 different commits each, respectively.
#
nothing to commit (working directory clean)
there are no working changes
I've tried git reset --hard HEAD but that didn't help
any ideas?
Files are on the NFS file system, maybe that has something to do with.
This is on OSX
Thanks
UPDATE:
This issue has to do something with NFS, because when I went to the original source and did git pull from there everything worked fine, which fixed it for this instance, but still not sure exactly why it causes issues with NFS.
A:
I had this same issue, and the fetch/rebase answer didn't work for me. Here's how I solved it:
I deleted the file that was causing the issue, checked it out, and then pulled successfully.
rm file/name/path/some/more/filenamepath
git checkout file/name/path/some/more/filenamepath
git pull
A:
Delete the problematic files.
Run git reset --hard.
That should fix it.
A:
You should:
fetch (updating all remote tracking branches, like origin/master)
rebase your current branch on top of origin/master in order to replay your 2 commits on top of the 7 updated commits that you just fetched.
That would be:
git checkout master
git fetch
git rebase origin/master
A shorter version of the above set of commands would be the following single command:
git pull --rebase
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP-EWS move email to folder
I am using php-ews to get attachment and save them to specific directory and now i need to move the mail into another folder. Im stuck in here :
$client = new Client($host, $username, $password, $version);
$request = new FindItemType();
$request->ParentFolderIds = new NonEmptyArrayOfBaseFolderIdsType();
// Return all message properties.
$request->ItemShape = new ItemResponseShapeType();
$request->ItemShape->BaseShape = DefaultShapeNamesType::ALL_PROPERTIES;
// Search in the user's inbox.
$folder_id = new DistinguishedFolderIdType();
$folder_id->Id = DistinguishedFolderIdNameType::INBOX;
$request->ParentFolderIds->DistinguishedFolderId[] = $folder_id;
$response = $client->FindItem($request);
// Iterate over the results, printing any error messages or message subjects.
$response_messages = $response->ResponseMessages->FindItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
$code = $response_message->ResponseCode;
$message = $response_message->MessageText;
continue;
}
$items = $response_message->RootFolder->Items->Message;
foreach ($items as $item) {
$subject = $item->Subject;
$sender = $item->From->Mailbox->EmailAddress;
//move mail item from folder "INBOX" to folder "DONE"
}
}
A:
Here is a working solution, using php-ews 1.0
You can use the existing class MoveItemType
$request = new MoveItemType();
$request->ItemIds = new NonEmptyArrayOfBaseItemIdsType();
$item_id = new ItemIdType();
$item_id->Id = 'foobarfoobar';
$request->ItemIds->ItemId[] = $item_id;
$request->ToFolderId = new TargetFolderIdType();
$folder_id = new FolderIdType();
$folder_id->Id = $this->treatedFolderId;
$request->ToFolderId->FolderId = 'barbar';
$response = $this->client->MoveItem($request);
$response_messages = $response->ResponseMessages->MoveItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
// Error treatment .....
continue;
}
$items = $response_message->Items->Message;
foreach ($items as $item) {
// ...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Where should I place Recaptcha.dll in my asp.net mvc application?
So, I've implemented ReCaptcha in my ASP.NET MVC application via these instructions:
http://devlicio.us/blogs/derik_whittaker/archive/2008/12/02/using-recaptcha-with-asp-net-mvc.aspx
My question is, after I've created my reference to my dll, where should I place the DLL in my solution? Should I just make a references folder or ... ?
What is best practice on where I should place the recaptcha.dll in my project so the reference will work for others who pull down my solution.
A:
I created the CaptchaValidatorAttribute in the business logic layer and referenced the dllin that library.
As to physical location, in the project I placed the library in a ThirdPartLibrarys directory and referenced it there.
When the project comes down from source control, it will be in the right place for the reference. (Assuming your source control solution allows you to check in files from the file system.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Tkinter Scrollbar and Menu crashing for no reason
I'm trying to make a simple GUI with tkinter in Python 2.7. Yesterday it was working perfectly, but today it crashes for a very odd error:
sbar.pack(side=RIGHT, fill=Y)
NameError: name 'RIGHT' is not defined
When I remove the arguments, there still is another error quite similar:
menubar=Menu(mgui)
NameError: name 'Menu' is not defined
I have no idea why this happens, why it stopped working. I'm not sure if it's because the code is wrong or maybe the tools I'm working with are.
Here's the code:
import Tkinter as tk
import tkMessageBox
from ScrolledText import *
mgui=tk.Tk()
mgui.geometry('700x450')
mgui.title('Adminstrador de ntoas')
mtitle=tk.StringVar()
mtext=tk.StringVar()
sbar = tk.Scrollbar(mgui)
sbar.pack()
menubar=Menu(mgui)
def donothing():
filewin = Toplevel(mgui)
button = Button(filewin, text="Do nothing button")
button.pack()
def llama_crea_notebook():
cng_gui=tk.Toplevel(width=700,height=200)
cng_gui.title("Generado de Notebooks")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Create Notebook", command=donothing)
filemenu.add_command(label="Change Notebook", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Close", command=quit)
menubar.add_cascade(label="File", menu=filemenu)
notemenu = Menu(menubar, tearoff=0)
notemenu.add_command(label="Read Note", command=donothing)
notemenu.add_command(label="Delete Note", command=donothing)
menubar.add_cascade(label="Note", menu=notemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Manual", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
A:
You import the tkinter module as import Tkinter as tk, that means that for everything you want to access from tkinter must be done as
tk.<something>
Button, Menu, RIGHT... all belong to tkinter. Solution: replace import Tkinter as tk with from Tkinter import *.
However, using tk.<something> is more readable so I would advise that option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ask user to continue viewing the next 5 lines of data
I am trying to get the next 5 data rows without writing a loop every time ([:5], [5:10], [10:15],etc...). I have some idea but I been stuck on this one for awhile, what are some ways to go about this to get the user to show the next 5?
def raw_data(df):
ask_user = input('Would you like to view more raw data for the city selected? \nPrint yes or no: ')
while True:
if ask_user == 'yes':
return df.iloc[:5]
else:
break
A:
Add a variable that accumulates each time the function runs. (Let's call it runs) Initialize it outside of the function and add one to it inside of the function. From here, multiply it by 5 to get your range.
runs = 0
def raw_data(df):
while True:
ask_user = input('Would you like to view more raw data for the city selected? \nPrint yes or no: ')
if ask_user == 'yes':
runs += 1 #Adds 1 to current value, same as runs = runs + 1
return df.iloc[(x-1)*5:x*5]
elif ask_user == 'no':
return
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP mssql count rows in a statement
I would like to count the number of rows in a statement returned by a query. The only solutions I found were:
sqlsrv_num_rows() This one seems a bit too complicated for such a simple task like this and I read that using this slows down the execution quite a bit
Executing a query with SELECT COUNT This method seems unnecessary, also it slows down the execution and if you already have a statement why bother with another query.
Counting the rows while generating a table As I have to generate a html table from the statemnt I could put a variable in the table generating loop and increment it by one, but this one only works when you already have to loop through the entire statement.
Am I missing some fundamental function and/or knowledge or is there no simpler way?
Any help or guidance is appreciated.
EDIT: The statement returned is only a small portion of the original table so it wouldn't be practical to execute another query for this purpose.
A:
In sql server table rows information is stored in the catalog views and Dynamic Management Views you can use it to find the count
This method will only work for the physical tables. So you can store the records in one temp table and drop it later
SELECT Sum(p.rows)
FROM sys.partitions AS p
INNER JOIN sys.tables AS t
ON p.[object_id] = t.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE p.index_id IN ( 0, 1 ) -- heap or clustered index
AND t.NAME = N'tablename'
AND s.NAME = N'dbo';
For more info check this article
If you don't want to execute another query then use select @@rowcount after the query. It will get the count of rows returned by previous select query
select * from query_you_want_to_find_count
select @@rowcount
| {
"pile_set_name": "StackExchange"
} |
Q:
Zsh customized prompt and updating variable's value
I would like to use the value of a variable set in my zsh shell to display in my prompt line.
For example, let's say export TOKEN='hello' is set in my session. At that time, I load my prompt which contains a "$TOKEN".
This works fine, and the prompt is correctly displayed. However, if I change the value of TOKEN, my prompt do not get updated.
How do I make zsh to update my prompt every time I have executed a command?
A:
There's a couple of ways you could do this. You should look into the precmd and preexec functions. They're in the hook functions section of zshmisc (which you can read online or using man zshmisc.
A simple solution would be to read this unix.stackexchange.com question, which says to put this in your ~/.zshrc file:
setopt prompt_subst
PROMPT='$TOKEN'
This will do what you want:
┌─(simont@charmander:s000)─────────────────────────────────────▸▸▸▸▸▸▸▸▸▸─(~ )─┐
└─(12:44)── export GREETING="foo" ──(Wed,Dec12)─┘
foo ┌─(simont@charmander:s000)─────────────────────────────────▸▸▸▸▸▸▸▸▸▸─(~ )─┐
└─(12:44)── export GREETING="bar" ──(Wed,Dec12)─┘
bar ┌─(simont@charmander:s000)─────────────────────────────────▸▸▸▸▸▸▸▸▸▸─(~ )─┐
└─(12:44)──
(This messes up my prompt a little, but you can see the foo and bar displaying nicely as they should, updating when $GREETING is changed. In your case, use $TOKEN).
My prompt heavily borrows from Phil!'s ZSH Prompt, which I found very useful when learning to customise mine.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the general solution of a differential equation with only one root?
So to get the general solution I know there are three cases, if there are 2 real and distinct roots, if there are 2 repeated roots, and 2 complex roots. But I have ran into a undetermined coefficient question that is $y'-y=1$, where the highest degree is only the first derivative. What I have done so far there is pretty much always a second derivative in the question, so I have never ran into this before. From $r-1=0$ I got that there is only one root which is 1, but since this goes into none of the three cases I'm used to I'm not sure what happens now. What would the general solution look like when there is only one root? My only guess has been $y=c_1e^{x}$
A:
In a linear ODE with constant coefficients, a root $r$ of the characteristic polynomial with multiplicity $k$ contributes homogeneous solutions $e^{rt},t e^{rt},\dots,t^{k-1}e^{rt}$ (a total of $k$ of them). When the coefficients are real and $r=a+bi$ is complex, $\overline{r}$ is also a root. Accordingly, to get real solutions, we combine the two together, obtaining $e^{at} \cos(bt),e^{at} \sin(bt),t e^{at} \cos(bt),t e^{at} \sin(bt),\dots,t^{k-1} e^{at} \cos(bt),t^{k-1} e^{at} \sin(bt)$ (a total of $2k$ solutions).
In your case, $1$ is a root with multiplicity $1$ so the homogeneous solution is $C e^t$.
| {
"pile_set_name": "StackExchange"
} |
Q:
SSL errors when using Npgsql and SSL certificate authentication
I'm having trouble establishing a connection to a PostgreSQL database that is configured only to accept a valid SSL certificate. I can connect using pgAdmin III with the appropriate certificate and key, but I cannot get it working with Npgsql. When I try to open a connection to the database, I get System.IO.IOException: The authentication or decryption has failed. Here is my code:
NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder();
csb.Database = "database";
csb.Host = "psql-server";
csb.UserName = "dreamlax"; // must match Common Name of client certificate
csb.SSL = true;
csb.SslMode = SslMode.Require;
NpgsqlConnection conn = new NpgsqlConnection(csb.ConnectionString);
conn.ProvideClientCertificatesCallback += new ProvideClientCertificatesCallback(Database_ProvideClientCertificatesCallback);
conn.CertificateSelectionCallback += new CertificateSelectionCallback(Database_CertificateSelectionCallback);
conn.CertificateValidationCallback += new CertificateValidationCallback(Database_CertificateValidationCallback);
conn.PrivateKeySelectionCallback += new PrivateKeySelectionCallback(Database_PrivateKeySelectionCallback);
conn.Open(); //System.IO.IOException: The authentication or decryption has failed
The callbacks are defined like this:
static void Database_ProvideClientCertificates(X509CertificateCollection clienteCertis)
{
X509Certificate2 cert = new X509Certificate2("mycert.pfx", "passphrase");
clienteCertis.Add(cert);
}
static X509Certificate Database_CertificateSelectionCallback(X509CertificateCollection clientCerts, X509Certificate serverCert, string host, X509CertificateCollection serverRequestedCerts)
{
return clienteCertis[0];
}
static AsymmetricAlgorithm Database_PrivateKeySelectionCallback(X509Certificate cert, string host)
{
X509Cerficate2 thisCert = cert as X509Certificate2;
if (cert != null)
return cert.PrivateKey;
else
return null;
}
static bool MyCertificateValidationCallback(X509Certificate certificate, int[] certificateErrors)
{
// forego server validation for now
return true;
}
I set breakpoints confirming that each callback was returning something valid, but still the IOException is thrown.
A:
I fixed this problem by modifying the Npgsql source. Rather than using Mono's Mono.Security.Protocol.Tls.SslClientStream, I changed it to use System.Net.Security.SslStream instead. These were the steps I took:
Modify NpgsqlClosedState.cs:
Remove the using Mono.Security.Protocol.Tls; directive and the one below it.
Add a using System.Net.Security; directive.
In the NpgsqlClosedState.Open() method, where it says if (response == 'S'), changed it to:
if (response == 'S')
{
//create empty collection
X509CertificateCollection clientCertificates = new X509CertificateCollection();
//trigger the callback to fetch some certificates
context.DefaultProvideClientCertificatesCallback(clientCertificates);
// Create SslStream, wrapping around NpgsqlStream
SslStream sstream = new SslStream(stream, true, delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
// Create callback to validate server cert here
return true;
});
sstream.AuthenticateAsClient(context.Host, clientCertificates, System.Security.Authentication.SslProtocols.Default, false);
stream = sstream;
}
Modify NpgsqlConnection.cs, remove the using Mono... directives. This will cause a number of errors regarding missing types, in particular, these will be regarding 3 sets of delegate/event combos that use Mono types. The errors will always appear in groups of three because these callbacks all tie in with Mono's SslClientStream class. Remove each group of three and replace it with a single ValidateServerCertificate delegate/event. This single event should be used in the constructor for the SslStream class that was used in step 1.3 above.
The changes to NpgsqlConnection.cs will trigger more errors in other files NpgsqlConnector.cs, NpgsqlConnectorPool.cs etc. but the fix is the same, replace the 3 Mono-based callbacks with the new ValidateServerCertificate.
Once all that is done, Npgsql can be used without Mono components and with (for me) working SSL certificate authentication.
My pull request on github can be found here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modify existing yaml file and add new data and comments
I recently saw that the go yaml lib has new version (V3)
with the nodes capabilities (which in my opinion is a killer feature :) ) which can helps a lots with modifying yamls without changing the structure of the file
But since it is fairly new (from last week ) I didn't find some helpful docs and example for the context which I need (add new object/node and to keep the file structure the same without removing the comments etc)
what I need is to manipulate yaml file
for example
lets say I’ve this yaml file
version: 1
type: verbose
kind : bfr
# my list of applications
applications:
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
Now I got an json object (e.g. with app2) which I need to insert to the existing file
[
{
"comment: "Second app",
"name": "app2",
"kind": "golang",
"path": "app2",
"exec": {
"platforms": "dockerh",
"builder": "test"
}
}
]
and I need to add it to the yml file after the first application, (applications is array of application)
version: 1
type: verbose
kind : bfr
# my list of applications
applications:
# First app
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
# Second app
- name: app2
kind: golang
path: app2
exec:
platforms: dockerh
builder: test
is it possible to add from the yaml file the new json object ? also remove existing
I also found this blog
https://blog.ubuntu.com/2019/04/05/api-v3-of-the-yaml-package-for-go-is-available
This is the types which represent the object
type VTS struct {
version string `yaml:"version"`
types string `yaml:"type"`
kind string `yaml:"kind,omitempty"`
apps Applications `yaml:"applications,omitempty"`
}
type Applications []struct {
Name string `yaml:"name,omitempty"`
Kind string `yaml:"kind,omitempty"`
Path string `yaml:"path,omitempty"`
Exec struct {
Platforms string `yaml:"platforms,omitempty"`
Builder string `yaml:"builder,omitempty"`
} `yaml:"exec,omitempty"`
}
update
after testing the solution which is provided by wiil7200 I found 2 issues
I use at the end write it to file
err = ioutil.WriteFile("output.yaml", b, 0644)
And the yaml output have 2 issue.
The array of the application is starting from the comments, it should
start from the name
After the name entry the kind property and all others after are
not aligned to the name
any idea how to solve those issue ? regard the comments issue, lets say I got it from other property
and not from the json (if it make it more simpler)
version: 1
type: verbose
kind: bfr
# my list of applications
applications:
- # First app
name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
- # test 1
name: app2
kind: golang
path: app2
exec:
platform: dockerh
builder: test
A:
First, let Me Start off by saying using yaml.Node does not produce valid yaml when marshalled from a valid yaml, given by the following example. Probably should file an issue.
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v3"
)
var (
sourceYaml = `version: 1
type: verbose
kind : bfr
# my list of applications
applications:
# First app
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
`
)
func main() {
t := yaml.Node{}
err := yaml.Unmarshal([]byte(sourceYaml), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
b, err := yaml.Marshal(&t)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
Produces the following invalid yaml in go version go1.12.3 windows/amd64
version: 1
type: verbose
kind: bfr
# my list of applications
applications:
- # First app
name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
Secondly, using a struct such as
type VTS struct {
Version string `yaml:"version" json:"version"`
Types string `yaml:"type" json:"type"`
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"`
Apps yaml.Node `yaml:"applications,omitempty" json:"applications,omitempty"`
}
From ubuntu's blog and the source documentation it made it seem that it would correctly identify fields within the struct that are nodes and build that tree separately, but that is not the case.
When unmarshalled, it will give a correct node tree, but when remarshalled it will produce the following yaml with all of the fields that yaml.Node exposes. Sadly we cannot go this route, must find another way.
version: "1"
type: verbose
kind: bfr
applications:
kind: 2
style: 0
tag: '!!seq'
value: ""
anchor: ""
alias: null
content:
- # First app
name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
headcomment: ""
linecomment: ""
footcomment: ""
line: 9
column: 3
Overlooking the first issue and the marshal bug for yaml.Nodes in a struct (on gopkg.in/yaml.v3 v3.0.0-20190409140830-cdc409dda467) we can now go about manipulating the Nodes that the package exposes. Unfortunately, there is no abstraction that will add Nodes with ease, so uses might vary and identifying nodes can be a pain. Reflection might help here a bit, so I leave that as an exercise for you.
You will find comment spew.Dumps that dump the entire node Tree in a nice format, this helped with debugging when adding Nodes to the source tree.
You can certainly remove nodes as well, you will just need to identify which particular nodes that need to be removed. You just have to ensure that you remove the parent nodes if it were a map or sequence.
package main
import (
"encoding/json"
"fmt"
"log"
"gopkg.in/yaml.v3"
)
var (
sourceYaml = `version: 1
type: verbose
kind : bfr
# my list of applications
applications:
# First app
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
`
modifyJsonSource = `
[
{
"comment": "Second app",
"name": "app2",
"kind": "golang",
"path": "app2",
"exec": {
"platforms": "dockerh",
"builder": "test"
}
}
]
`
)
// VTS Need to Make Fields Public otherwise unmarshalling will not fill in the unexported fields.
type VTS struct {
Version string `yaml:"version" json:"version"`
Types string `yaml:"type" json:"type"`
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"`
Apps Applications `yaml:"applications,omitempty" json:"applications,omitempty"`
}
type Applications []struct {
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"`
Path string `yaml:"path,omitempty" json:"path,omitempty"`
Exec struct {
Platforms string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
Builder string `yaml:"builder,omitempty" json:"builder,omitempty"`
} `yaml:"exec,omitempty" json:"exec,omitempty"`
Comment string `yaml:"comment,omitempty" json:"comment,omitempty"`
}
func main() {
t := yaml.Node{}
err := yaml.Unmarshal([]byte(sourceYaml), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
// Look for the Map Node with the seq array of items
applicationNode := iterateNode(&t, "applications")
// spew.Dump(iterateNode(&t, "applications"))
var addFromJson Applications
err = json.Unmarshal([]byte(modifyJsonSource), &addFromJson)
if err != nil {
log.Fatalf("error: %v", err)
}
// Delete the Original Applications the following options:
// applicationNode.Content = []*yaml.Node{}
// deleteAllContents(applicationNode)
deleteApplication(applicationNode, "name", "app1")
for _, app := range addFromJson {
// Build New Map Node for new sequences coming in from json
mapNode := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
// Build Name, Kind, and Path Nodes
mapNode.Content = append(mapNode.Content, buildStringNodes("name", app.Name, app.Comment)...)
mapNode.Content = append(mapNode.Content, buildStringNodes("kind", app.Kind, "")...)
mapNode.Content = append(mapNode.Content, buildStringNodes("path", app.Path, "")...)
// Build the Exec Nodes and the Platform and Builder Nodes within it
keyMapNode, keyMapValuesNode := buildMapNodes("exec")
keyMapValuesNode.Content = append(keyMapValuesNode.Content, buildStringNodes("platform", app.Exec.Platforms, "")...)
keyMapValuesNode.Content = append(keyMapValuesNode.Content, buildStringNodes("builder", app.Exec.Builder, "")...)
// Add to parent map Node
mapNode.Content = append(mapNode.Content, keyMapNode, keyMapValuesNode)
// Add to applications Node
applicationNode.Content = append(applicationNode.Content, mapNode)
}
// spew.Dump(t)
b, err := yaml.Marshal(&t)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
// iterateNode will recursive look for the node following the identifier Node,
// as go-yaml has a node for the key and the value itself
// we want to manipulate the value Node
func iterateNode(node *yaml.Node, identifier string) *yaml.Node {
returnNode := false
for _, n := range node.Content {
if n.Value == identifier {
returnNode = true
continue
}
if returnNode {
return n
}
if len(n.Content) > 0 {
ac_node := iterateNode(n, identifier)
if ac_node != nil {
return ac_node
}
}
}
return nil
}
// deleteAllContents will remove all the contents of a node
// Mark sure to pass the correct node in otherwise bad things will happen
func deleteAllContents(node *yaml.Node) {
node.Content = []*yaml.Node{}
}
// deleteApplication expects that a sequence Node with all the applications are present
// if the key value are not found it will not log any errors, and return silently
// this is expecting a map like structure for the applications
func deleteApplication(node *yaml.Node, key, value string) {
state := -1
indexRemove := -1
for index, parentNode := range node.Content {
for _, childNode := range parentNode.Content {
if key == childNode.Value && state == -1 {
state += 1
continue // found expected move onto next
}
if value == childNode.Value && state == 0 {
state += 1
indexRemove = index
break // found the target exit out of the loop
} else if state == 0 {
state = -1
}
}
}
if state == 1 {
// Remove node from contents
// node.Content = append(node.Content[:indexRemove], node.Content[indexRemove+1:]...)
// Don't Do this you might have a potential memory leak source: https://github.com/golang/go/wiki/SliceTricks
// Since the underlying nodes are pointers
length := len(node.Content)
copy(node.Content[indexRemove:], node.Content[indexRemove+1:])
node.Content[length-1] = nil
node.Content = node.Content[:length-1]
}
}
// buildStringNodes builds Nodes for a single key: value instance
func buildStringNodes(key, value, comment string) []*yaml.Node {
keyNode := &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: key,
HeadComment: comment,
}
valueNode := &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: value,
}
return []*yaml.Node{keyNode, valueNode}
}
// buildMapNodes builds Nodes for a key: map instance
func buildMapNodes(key string) (*yaml.Node, *yaml.Node) {
n1, n2 := &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: key,
}, &yaml.Node{Kind: yaml.MappingNode,
Tag: "!!map",
}
return n1, n2
}
Produces yaml
version: 1
type: verbose
kind: bfr
# my list of applications
applications:
- # First app
name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
- # Second app
name: app2
kind: golang
path: app2
exec:
platform: dockerh
builder: test
| {
"pile_set_name": "StackExchange"
} |
Q:
Linuxで自宅にサーバーを立てたい
私はいくつかのプログラミング言語が使えて、ソフトウエア開発の経験はまだわずかばかりの新米エンジニアです。
最近、Linuxサーバー構築に関心があり、ノートパソコンを利用して趣味用にサーバーを立ててみたいと思うようになりました。
そこで疑問なのですが、
サーバーコンピュータにしようとしているノートパソコンはWindows7 32bit 4GBの、とても高スペックとは言えないマシンですが、そこにLinuxを入れてサーバー用に構築することは可能でしょうか?
よくサーバーは24時間365日稼働させるもの…そしてそれによる高稼働の負荷が原因で火災などの発生事例が後を立たず危険とありますが、趣味で使う以上、例えば自分の作ったWebアプリケーションをちょっと動かしてみたら、毎回サーバーの電源を切って、「ただちゃんとサーバーとして機能しているか」の確認程度にたまに使うという使い方はできないのでしょうか?
また、Webサーバー、メールサーバー、DBサーバー以外に、プログラムを動かすためのAPサーバーも立てることができますか?
自宅に回線は引いていないので、スマホのテザリングではダメですか?(毎月50GBくらいは使えます)
サーバーが動いているかの確認だけをしたいので、アクセスするのは私一人だけです。
例えばJavaなどのWebアプリをローカルで動かすだけなら既存のTomcatでいいじゃんというのは正論だと思うのですが、純粋にサーバーに関する知識を深めたく、練習だけしたいという思いから質問させて頂きました。
インフラの知識はど素人レベルなのですが、何か私自身の認識に誤りがあればそこの指摘も含めてご教授頂きたく思います。宜しくお願い致します。
A:
とても失礼なことを申し上げると、その質問が出てくる時点で、外部公開サーバを作るための知識と経験が足りていません。
ご自身で「あまりに素人すぎる」と自覚されているので、今はまだ知識や経験が無いことは恥ではありません。察するに「固定IPアドレス」とか「ファイアーウォール」といった用語についても、よくご存じないかもしれません。それらを理解してから、外部公開サーバを立てることを考えましょう。よく理解しないまま外部公開して不正アクセスされたとき、自分だけ被害に遭うならまだしも、他人に迷惑をかける恐れがあります。もしそうなってしまうと無知は罪です。
今のところは、「サーバを構築すること」と「外部からアクセスできるようにすること」は分けて考えましょう。自宅のLANでサーバとクライアントを作るだけなら、PCが2台あれば済みます。サーバーは余りのPCでもRaspberry Piでもなんでも構いません。サーバー構築を学習することが目的ですから、使う前に電源を入れて、使い終わったら電源を切れば大丈夫です。外からアクセスすることはできませんが、サーバの構築を習得するだけなら充分です。
構築方法とセキュリティの経験を積んだら、簡単なサービスから外部公開することができるでしょう。まずはWebサーバです。外からアクセスできるようにするには、固定IPアドレスが利用できるプロバイダと契約する必要がありそうです(ダイナミックDNSサービス等を利用するなら必須ではありません)。ですが、ご心配の通り、火災のリスクなどを考えると、自宅サーバーではなくて、VPSを借りるのも良いと思います。月額$3.5で20GBみたいなサーバーが借りられますから、最近は自宅サーバーを運用するメリットは少なくなってきています。VPSでも特権ユーザー(rootアカウント)が利用できますから、知識さえあればどんなサービスでも実行できます。
メールサーバはかなり難易度が高いので覚悟してください。せっかくメールサーバを運用するなら、自分で取得したドメイン名のメールアドレスを使いたくなると思いますので、DNSサーバも立てることになります。DNSサーバを提供しているVPSサービスやドメイン名レジストラもあると思いますので、そういうのを利用するのも手です。
アクセスするのは自分一人だけのつもりでも、公開サーバにすれば、確実に攻撃されます。そんな攻撃に耐えるのも、サーバー運用の腕の見せ所ですので、経験を積んでください。
ところで、ノートPCにはバッテリーが搭載されているので、「初めから無停電電源装置が付属している」なんて言われることがありますが、これはあまり信用しない方がいいので、ノートPCが自宅サーバに向いているかはちょっと疑問です。いずれにしても、自宅に回線を引いていないことを考えると、まず外部公開しない自宅LANで修行を積んでから、VPSを借りるのが、現実的なコースではないかと思います。
A:
とりあえずサーバといってもピンキリで、あなた一人しかユーザーが居ないならそれこそ Raspberry PI でも立派にサーバーになりますし、一般公開してアクセス数が増えれば増強しないといけなくなるでしょうし、状況次第。
サーバ立てるって言っても、要するにインバウントパケットを待ち受けしているマシンを1台用意するだけの話なので特別なことではないです。独立 LAN 上でやればセキュリティとか気構えも心の準備もいらないっす。
A1. オイラもインターネットに物理的接続されていない LAN でサーバ立てたことあります。当時の商用 UNIX 機よりあなたの予定しているノートのほうがよっぽど高性能です。今ならむしろ、ちょっと強力なマシンに仮想マシンを作っちゃうほうが安上がりかも。
A2. あなたしかユーザが居ないのなら、都度、電源断・再投入する運用で十分。一度一般公開してしまうとなかなかそうはいかなくなります。
A3. AP サーバって Redmine とか TestLink とか WordPress とかですよね。ユーザがあなた1人なら、(仮想)マシン1台で上にすべて同時に立てて問題ないです。スケールアップが必要になったときどうするかはその時考えればよい話。
A4. 最初はセキュリティ的に、インターネットと物理的接続のない完全独立 LAN でやりましょう。それならネット接続は不要。一般公開したくなったら TLS も必要になりそうですし、固定 global-IP アドレスサービスを強く検討。
外部に接続されていない完全孤立 LAN 上でも DHCP / DNS / MTA / HTTP 等、いわゆる「インフラ」技術の基礎は十分学べます(スケーリングや対攻撃保護機構は別)。で、そのためのマシンを用意して云々が面倒な人は AWS っす。無料プランで問題ないでしょう(ってオイラは AWS の回し者ちゃいますよ)
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql replication of certain columns
I've got two rails applications. One is internal and second is external client version.
In client version I have got cutted version of database. So, now I need to replicate my master MySQL db but not all data: only certain columns and certain tables.
How can I implement this job?
If there are some ruby stuff (gem for working with replication in this way), it'll be great.
A:
Replication is typically something you do at the database layer, here is the documentation for Mysql replication:
http://dev.mysql.com/doc/refman/5.0/en/replication.html
That would typically replicate the entire database.
Another solution would be to have a job (perhaps written in ruby), that runs a couple of times a day and copies the desired data.
Perhaps you want to push data from the master to the slaves with as little delay as possible? Then you could make a hook on the save() method in ActiveRecord, that pushes the changes to the slave db.
Haven't looked in to it, but perhaps this is something: http://www.rubyrep.org/
| {
"pile_set_name": "StackExchange"
} |
Q:
Complex cross domain scripting
I have the following scenario, a user on domain1.com opens a new window on domain2.com. Domain2 contains a pretty complex web app where the user can browse and select documents. When the user is done searching for the right document he want's to send the select document back do domain1 and close the window. Is this possible in any way? I guess JSONP is not good enough because the response is not immediate?
A:
Use message API to communicate between the windows
There is a library for cross-browser implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it considered good practise to have jQuery scripts in a PHP conditional?
I have several jQuery scripts that are used on my website, but not on every page. I place these scripts in a PHP conditional so that it only outputs them on the required pages.
Now what I'm wondering is: is this considered good practice? Does this speed up the website? Are there even any positive aspects to using this method?
<?php if ( is_home() ) { ?>
<script>
//jQuery code
//jQuery code
//jQuery code
</script>
<?php } ?>
A:
Even though there is nothing wrong with doing this you are giving up browser-side caching for a minor temporary convenience. I say temporary because this is definitely not something I would deploy on a larger scale system.
The reason browser-side caching is being given up is because a PHP file is always requested fresh by the browser because it is assumed to have dynamic data.
I would recommend a /assets/js/pages/home.js layout for your JS files which get conditionally included as an external file because this will be much more scalable in the future:
<?php if ( is_home() ) { ?>
<script src="/assets/js/pages/home.js"></script>
<?php } ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i show a pair forms a semigroup?
An operation . is defined on the set $Z×Z$, ie. the set containing all pairs of integers by:
$(u,v).(x,y)=(u+v,v.y)$
How can i show that the pair ($Z×Z$, . ) forms a semigroup?
A:
A semigroup is defined as a set with a closed associative binary operation. Since the operation is well defined and close, it is only left to check that it is associative as well.
But that is immediate since both sum and multiplication in $\mathbb{Z}$ are associative, and an operation defined in two coordinates is associative iff each coordinate is associative.
| {
"pile_set_name": "StackExchange"
} |
Q:
$\tan2x$ in terms of $\cos x$ alone
This is not exactly a homework question but something I was trying to do to get my basics back on track.
I wanted to find $\tan2x$ in terms of $\cos x$ alone. I was able to do it in terms of $\sin x$ alone.
$\tan2x = \sin2x/\cos2x$
Since, $\cos2x = 1-2\sin^2x$
Therefore, $\tan2x = (\sin2x / 1-2\sin^2x)$
Is it possible to do it in terms of $\cos x$ alone ?
A:
$$\tan2x = \frac{\sin2x}{\cos2x}=\pm\frac{2\sin x\cos x}{\cos^2x-\sin^2x}=\pm\frac{2\cos x\sqrt{1-\cos^2x}}{2\cos^2x-1}$$
A:
You can, but only using care. It's not restrictive to assume $x\in[0,2\pi]$, because $\tan2x$ has $2\pi$ as period. Then you have
$$
\tan2x=
\begin{cases}
\dfrac{2\cos x\sqrt{1-\cos^2x}}{2\cos^2-1} &
x\in[0,\pi]\\[2ex]
-\dfrac{2\cos x\sqrt{1-\cos^2x}}{2\cos^2-1} &
x\in[\pi,2\pi]
\end{cases}
$$
(the values $\pi/4$, $3\pi/4$, $5\pi/4$ and $7\pi/4$ are excluded, of course).
In other words, you can only express $|\tan2x|$ in terms of $\cos x$ alone.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hide a field when editing that is visible when adding an item?
I have a problem with trying to hide a field when editing an entry that must be visible when adding an entry.
My table structure is as follows:
equip_items
--------------
id (pk)
equip_type_id (fk to equip_types)
site_id (fk to sites)
equip_status_id (fk to equip_status)
name
(equip_type_id, site_id, name) is a composite unique key constraint in the db. I have implemented a callback on the name field that deals with grocery_CRUD validation of the unique constraint - taking into account either editing existing or adding new equip_items.
function unique_equip_item_check($str, $edited_equip_item_id){
$var = $this->Equip_Item_model->is_unique_except($edited_equip_item_id,$this->input->post('site_id'),$this->input->post('equip_type_id'),$this->input->post('name'));
if ($var == FALSE) {
$s = 'You already have an equipment item of this type with this name.';
$this->form_validation->set_message('unique_equip_item_check', $s);
return FALSE;
} else {
return TRUE;
}
}
I have the site_id and equip_type_id set as hidden fields as I do not want the user to change these - no problem.
$crud->field_type('site_id', 'hidden', $site_id);
$crud->field_type('equip_status_id', 'hidden', iQS_EqStatus_InUse);
When users add an equip_item I want them to be able to select the equip_type from a list of types - No problem, this is default grocery_CRUD behaviour.
$crud->add_fields('equip_status_id', 'site_id', 'equip_type_id', 'name');
When users edit an equip_item I don't want the user to be able to edit the equip_type. I figured no problem I can just set the edit_fields to exclude equip_type_id:
$crud->edit_fields('equip_status_id', 'site_id', 'name', 'barcode_no');
BUT this plays havoc with my validation callback because the value of the equip_type_id field is nowhere on the edit form and it is obviously needed by my validation routine.
So I need to have the equip_type_id field visible and acting normal when adding a new record but hidden when editing a record.
I've tried this hack of all hacks :
if ($this->uri->segment(4)!= FALSE){$crud->field_type('equip_type_id', 'hidden');}
My theory was that "$this->uri->segment(4)" only give a false result if adding a new record, but it does not work.
I have also tried:
$crud->callback_edit_field('equip_type_id', array($this,'edit_equip_type_field_callback'));
with
function edit_equip_type_field_callback($value = '', $primary_key = null){
return '<input type="hidden" value="'.$value.'" name="equip_type_id"';
}
But that doesn't work it just screws up the layout of the form fields - the 'Type' label etc is still visible.
Any suggestions?
A:
I think the problem is that you have to add the field equip_status_id to the edit fields.
So in your case this will simply solve your problem:
$crud->edit_fields('equip_status_id', 'site_id',
'name', 'barcode_no','equip_status_id');
or
$crud->fields('equip_status_id', 'site_id', 'name',
'barcode_no','equip_status_id'); //for both add and edit form
of course you have to also use your hack:
if ($this->uri->segment(4)!= FALSE) {
$crud->field_type('equip_type_id', 'hidden');
}
or you can do it with a more proper way:
$crud = new grocery_CRUD();
if ($crud->getState() == 'edit') {
$crud->field_type('equip_type_id', 'hidden');
}
...
With this way you will also remember why you did this hacking to the code.
| {
"pile_set_name": "StackExchange"
} |
Q:
AS3 .addEventListener in a loop?
I am creating a line of Sprite elements. Every sprite element has different job, when it is clicked. How can I make the function inside the addEventListener to know which button was clicked?
In this case, the traced value of i when it is cliicked is always 6. Which is wrong, because 6 is only the last element of the array. What about the rest of them, the beginning?
for (var i:int = 0; i < 6; i++) {
var barPart:Sprite = new Sprite();
barPart.x = i * (30);
barPart.y = 0;
barPart.graphics.beginFill(0x000000, 0.2);
barPart.graphics.drawRect(0, 0, 10, 10);
barPart.graphics.endFill();
barPart.addEventListener(MouseEvent.CLICK, function(_event:MouseEvent):void {
trace(i);
});
}
A:
When the application is build and the listeners are added, the loop has already executed, so the index "i" will always be six by the time the user ends up clicking the button.
To distinguish between the different items, use their "name" property (prop of DisplayObject) like shown ...
Try not to have listener function as a method closure in a loop, instead do this:
for (...)
{
... code
barPart.name = "barPart-" +i;
barPart.addEventListener(MouseEvent.CLICK, barPart_clickHandler);
}
and implement the function (event handler separately) like:
private function barPart_clickHandler(e:MouseEvent):void
{
// the event's target will let you know who dispatched the function
var name:String = Sprite(e.currentTarget).name;
name = name.replace("barpart-", "");
switch(name)
{
case '0':
// your code
break;
.
.
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Basic Jasmine test setup with Webstorm
I've tried following the documentation on this. It helped me setup a JsTestDriver environment using something like-but-not-quite JUnit as the test language.
https://code.google.com/p/js-test-driver/wiki/GettingStarted
I would like to replicate this setup in Webstorm - creating the remote server, capture browsers as "slaves," output results in Webstorm, etc - but use Jasmine in lieu of the JsTestDriver language.
Can this be done? If so, can someone point me in the right direction?
Thanks in advance.
A:
I found what I was looking for.
http://devnet.jetbrains.com/thread/435906
This link provides details on how to set up Jasmine in Webstorm via JsTestDriver. It also includes a sample Jasmine/Webstorm project for download. I was missing lines in my .jstd file that load Jasmine.js and JasmineAdapter.js (must be referenced first). With those files included, the .jstd file runs the unit test environment. Very nice.
Here is the entire config (jstd) file contents.
load:
- jasmine-lib/jasmine.js
- jasmine-lib/JasmineAdapter.js
- src/Greeter.js
test:
- test/GreeterTest.js
| {
"pile_set_name": "StackExchange"
} |
Q:
android.view.InflateException:Binary XML file line #17: Error inflating class fragment
i have checked all similar questions(This and others ) but still couldn't figure out the cause of the error, it keeps shutting down at some point during run time...
CategoryDetailFragment.java
/**
* A simple {@link Fragment} subclass.
*/
public class CategoryDetailFragment extends Fragment implements View.OnClickListener{
@BindView(R.id.categoryNameTextView) TextView mCategoryNameTextView;
@BindView(R.id.addPostButton) Button mAddPostButton;
private Category mCategory;
public static CategoryDetailFragment newInstance(Category category) {
CategoryDetailFragment categoryDetailFragment = new CategoryDetailFragment();
Bundle args = new Bundle();
args.putParcelable("category", Parcels.wrap(category));
categoryDetailFragment.setArguments(args);
return categoryDetailFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategory = Parcels.unwrap(getArguments().getParcelable("category"));
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_detail, container, false);
ButterKnife.bind(this, view);
mAddPostButton.setOnClickListener(this);
mCategoryNameTextView.setText(mCategory.getName());
return view;
}
fragment_category_detail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.epicodus.talkaboutit.ui.CategoryDetailFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Category Name"
android:id="@+id/categoryNameTextView"
android:layout_gravity="center"
android:textAlignment="center"
android:paddingTop="10dp"
android:textSize="20sp"/>
<fragment
android:name = "com.epicodus.talkaboutit.ui.PostListFragment"
android:id="@+id/postListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout="@layout/fragment_post_list"
android:layout_below="@+id/categoryNameTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="69dp"
android:layout_above="@+id/addPostButton" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Post"
android:id="@+id/addPostButton"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.epicodus.talkaboutit, PID: 27394
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
at com.epicodus.talkaboutit.ui.CategoryDetailFragment.onCreateView(CategoryDetailFragment.java:57)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:20151)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
at android.view.View.measure(View.java:20151)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6330)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:20151)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6330)
at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:401)
at android.view.View.measure(View.java:20151)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6330)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:20151)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6330)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:747)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:629)
at android.view.View.measure(View.java:20151)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6330)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3158)
at android.view.View.measure(View.java:20151)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2594)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1549)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1841)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1437)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7397)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:920)
at android.view.Choreographer.doCallbacks(Choreographer.java:695)
at android.view.Choreographer.doFrame(Choreographer.java:631)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:906)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.interna
I/Process: Sending signal. PID: 27394 SIG: 9
Application terminated.
the error seems to come from this line
View view = inflater.inflate(R.layout.fragment_category_detail, container, false);
I've tried all i could, any help is appreciated...
A:
Check whether you are saved the layout file of the fragment as V-24. This may cause the problem in inflating the view if your minimum SDK version less than 24. As of I Know, View inflation error in android is happening mostly due to version-specific layout or drawable.
| {
"pile_set_name": "StackExchange"
} |
Q:
let Path.register() register a ArrayList
I want to choose, which File-System-Event I want to get(ENTRY_CREATE, ENTRY_MODIFY and/or ENTRY_DELETE). Is it possible to save the events in an ArrayList<WatchEvent.Kind> and to register all the events in this ArrayList with the path?
My idea was like:
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
...
ArrayList<WatchEvent.Kind> eventList;
...
addEvent(ENTRY_MODIFY);
addEvent(ENTRY_CREATE);
...
for (WatchEvent.Kind<?> event : eventList) {
key = dir.register(watcher, event);
}
...
public void addEvent(WatchEvent.Kind event) {
eventList.add(event);
}
This seems to register only the last one, in my example the ENTRY_DELETE to the File-System. How can I register all of them, so that I can add the events I want to register with the addEvent() method?
A:
I found it by my myself, it is pretty simple.
Just create an ArrayList, add all the Events you want to add and make an Array out of the list. It can be done like this:
ArrayList<WatchEvent.Kind> eventList = new ArrayList<>();
eventList.add(StandardWatchEventKinds.ENTRY_CREATE);
WatchEvent.Kind[] eventArray = eventList.toArray(new WatchEvent.Kind[eventList.size()]);
key = dir.register(watcher, eventArray);
It is important, that no element is null in the Array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Building a nested array based on value
I have a nested array that I want to process into another nested array based on a value in the original.
Here's my original array, it's nested because I'll introduce other values later.
$dataArray = array (
0 => array(
"adgroupid" => "5426058726"
),
1 => array(
"adgroupid" => "5426058086"
),
2 => array(
"adgroupid" => "5426058086"
),
3 => array(
"adgroupid" => "5426058087"
),
4 => array(
"adgroupid" => "5426058087"
),
5 => array(
"adgroupid" => "5426058088"
),
6 => array(
"adgroupid" => "5426058089"
),
7 => array(
"adgroupid" => "5426058089"
),
8 => array(
"adgroupid" => "5426058090"
Here's the result I'm currently getting, note the strings in Array numbers 1 & 2 should be nested in the same array, like in 3 & 5.
array (size=10)
0 =>
array (size=1)
0 => string '5426058726' (length=10)
1 =>
array (size=1)
0 => string '5426058086' (length=10)
2 =>
array (size=1)
0 => string '5426058086' (length=10)
3 =>
array (size=2)
0 => string '5426058087' (length=10)
1 => string '5426058087' (length=10)
4 =>
array (size=1)
0 => string '5426058088' (length=10)
5 =>
array (size=2)
0 => string '5426058089' (length=10)
1 => string '5426058089' (length=10)
6 =>
array (size=4)
0 => string '5426058090' (length=10)
Here's my code, I need to use the if statement because at a later stage I want to introduce another argument:
$newdataArray = array();
$j = 0; // Set value of working variables
$adgroupidcheck = 0;
foreach ($dataArray as $value) { // Loop through the array
if( $adgroupidcheck != $value['adgroupid'] ) { // Check $adgroupidcheck
$newdataArray[][] = $value['adgroupid']; // Create a new nested array
$j ++; // increment $j
} else {
$newdataArray[$j][] = $value['adgroupid']; // Add to the current array
}
$adgroupidcheck = $value['adgroupid']; // Set $adgroupidcheck
}
So my problem is that my code only works after the first instance of the array check loop hasn't worked.
Any help would be appreciated.
Thank you.
A:
You should just pre-increment your $j value so it get added as the correct array. Otherwise it's sent to the next one, just make a quick trace.
if( $adgroupidcheck != $value['adgroupid'] ) {
$newdataArray[++$j][] = $value['adgroupid'];
} else {
$newdataArray[$j][] = $value['adgroupid'];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Building Python 2.6 as shared library broke (after previously working), any reason why?
I'm on a VPS running CentOS, with has Python 2.4 installed - which unfortunately means that I have to avoid breaking it. So I'm installing Python 2.6 as a separate install, then using virtualenv. Yesterday, I installed Python 2.6 with --enable-shared, so I could compile mod_wsgi - and it worked fine. Today, I had to start from scratch, and re-installed Python 2.6 as a shared library - and it broke, for reasons unknown. I'm hoping someone can tell me why it broke.
Note that I'm not just asking how to fix it, but why it broke. I'm pretty sure one of the answers to fixing it, will be to "set the LD_LIBRARY_PATH variable". I don't want to do that for two reasons. One, I didn't do it yesterday, and everything worked. Two, I have to avoid breaking the Python 2.4 part of CentOS, and if I add that variable to my environment via .bashrc, I'm not sure what, if anything else, might break.
Installing Python 2.6
deleted/created all relevant directories, not just *make clean*
tar -xzvf Python-2.6.6.tgz
./configure --prefix=/foo/python26 --enable-shared
make
make altinstall
Everything seemed to work, there were no obvious errors in the make outputs. Just that Python wouldn't run.
Hiding a library in plain sight
bin/python2.6: error while loading shared libraries: libpython2.6.so.1.0:
cannot open shared object file: No such file or directory
[/foo/python26/lib]# ls -l
lrwxrwxrwx 1 root root 19 May 27 15:09 libpython2.6.so -> libpython2.6.so.1.0*
-r-xr-xr-x 1 root root 5624403 May 27 15:09 libpython2.6.so.1.0*
drwxr-xr-x 25 root root 20480 May 27 15:09 python2.6/
[/foo/python26/bin]# ls -l
-rwxr-xr-x 1 root root 10142 May 27 15:09 python2.6*
-rwxr-xr-x 1 root root 1433 May 27 15:09 python2.6-config*
missing file! yesterday there was a 'python' linked to python2.6
[/foo/python26/bin]# ldd python2.6
libpython2.6.so.1.0 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00002ababe46c000)
A third reason I don't want to set LD_LIBRARY_PATH is, it doesn't make any sense. The make process created the shared library, and copied it into the right directory. Python knows where it is, the file is under its own lib directory.
So what changed from yesterday, when it worked, to today when it's broken? I installed a few other packages, like django (which I removed) and nginx - I didn't remove nginx, but I don't see how it could have affected anything.
A:
Thanks to Vensky's post on installing Python 2.6, I have what seems like a fix - although I still don't understand why things broke, and this fix seems kludgy. But at least it's working.
Create a file with this line:
#/etc/ld.so.conf.d/python2.6.conf
/foo/python2.6/lib
Then run the ldconfig command, with no arguments.
Checking that it works:
[~]# ldconfig -p | grep python
libpython2.6.so.1.0 (libc6,x86-64) => /foo/python26/lib/libpython2.6.so.1.0
libpython2.6.so (libc6,x86-64) => /foo/python26/lib/libpython2.6.so
libpython2.4.so.1.0 (libc6,x86-64) => /usr/lib64/libpython2.4.so.1.0
libpython2.4.so (libc6,x86-64) => /usr/lib64/libpython2.4.so
[/foo/python26/bin]# ldd python2.6
libpython2.6.so.1.0 => /foo/python26/lib/libpython2.6.so.1.0 (0x00002b351dc1a000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00002b351dfca000)
Python 2.6 is definitely working, and appears to be linked to the shared library now. And it doesn't look like it should interfere with the system's Python 2.4.
| {
"pile_set_name": "StackExchange"
} |
Q:
Capitalize the first letter of each string
I've been trying to capitalize the first letter of each word in a string, but it says TypeError: Cannot assign to read only property '0' of string 'i' . My logic looks fine but surely the way I'm doing this is not right. Any suggestions.
function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
// console.log(word[0][0]);
for (var i = 0; i < word.length - 1; i++) {
word[i][0] = word[i][0].toUpperCase();
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");
A:
Try like so: (see comments in code)
function titleCase(str) {
str=str.toLowerCase();
var word = str.split(" ");
for (var i=0; i < word.length; i++) { // you don't need -1 here as you had
word[i] = word[i].charAt(0).toUpperCase() + word[i].slice(1); // see changes in this line
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");
| {
"pile_set_name": "StackExchange"
} |
Q:
Order history in dashboard
In my store,When a customer places an order, it appears in the “My Orders” section of their account. However, once the order status is changed to Transfer WMS, the order history no longer appears.
Any help on this?
Thank you
A:
Transfer WMS is not a default status in Magento. This is not a problem, except for the fact that statuses are married to states, and only states that have the option visible_on_front property set to a truthy value will display to a customer.
Here's the block that is responsible for display of recent orders in the dashboard to the customer:
#file: app/code/core/Mage/Sales/Block/Order/History.php
class Mage_Sales_Block_Order_History extends Mage_Core_Block_Template
{
public function __construct()
{
parent::__construct();
$this->setTemplate('sales/order/history.phtml');
$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
->setOrder('created_at', 'desc')
;
$this->setOrders($orders);
Mage::app()->getFrontController()->getAction()->getLayout()->getBlock('root')->setHeaderTitle(Mage::helper('sales')->__('My Orders'));
}
//....snip
}
The reason this is important is because it's filtering the state out of the view if it is not marked visible. If you are using a custom state you'll have to modify this in the xml definition. Custom states can be added via config xml, and may have been added via a module. You'll have to search for it, and it usually looks like this:
<order>
<states>
<new translate="label">
<label>New</label>
<statuses>
<pending default="1"/>
</statuses>
<visible_on_front>1</visible_on_front>
</new>
</states>
</order>
This particular snippet comes from /app/code/core/Mage/Sales/etc/config.xml. Notice the visible_on_front property - that's your way of controlling whether the customer will see this or not.
Best of luck.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.