source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0020148777.txt"
] | Q:
Getting rails error
I previously installed rails with the preinstalled ruby that comes with mac. I have recently installed ruby through rvm.
I then did
rails -v
and got the following error
kingsosina$ rails -v
/Library/Ruby/Site/2.0.0/rubygems/dependency.rb:298:in `to_specs': Could not find 'railties' (>= 0) among 5 total gem(s) (Gem::LoadError)
from /Library/Ruby/Site/2.0.0/rubygems/dependency.rb:309:in `to_spec'
from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in `gem'
from /usr/bin/rails:22:in `<main>'
What has gone wrong here? Do I need to gem install rails again?
my lastest output
kingsosina$ which ruby
/Users/kingsosina/.rvm/rubies/ruby-2.0.0-p353/bin/ruby
kingsosina$ which rails
/Users/kingsosina/.rvm/gems/ruby-2.0.0-p353/bin/rails
kingsosina$ which gem
/Users/kingsosina/.rvm/rubies/ruby-2.0.0-p353/bin/gem
kingsosina$
Does everything seem ok? and how does terminal know to reference this version of ruby instead of the pre-installed version on the mac, when i do ruby -v?
A:
For what it's worth, the paths shown in your error output indicate that you're still referencing the OSX version of ruby. You'll want to enter the directory and type
rvm use X.X.X-pXXX
where X.X.X-pXXX is the ruby version that you want rvm to use. You can also add a file called .ruby-version with X.X.X-pXXX in it and rvm and other ruby version managers will switch to the appropriate version for you. Adding a .ruby-gemset file will also switch to the appropriate set of gems.
Finally, you'll need to make sure that the gems are installed in the rvm ruby/gemset combination. Putting that all together, to get started with the latest ruby and latest rails gem you would...
rvm install 2.0.0
rvm use 2.0.0
rvm gemset use --create my-project-gems
gem install rails
|
[
"stackoverflow",
"0055179142.txt"
] | Q:
Why does Generator.prototype.return take a value?
I'm trying to figure out why Generator.prototype.return takes a value.
I get that it stops the generator from processing and renders each next call with:
{
done: true,
value: undefined,
}
But when you pass it a value such as generator.return(4), all it does is give you back an object as if you called Generator.prototype.next and your value prop was 4.
My only guess is this could be useful when composing generators together or when you're doing some sort of two-way communication; although, since it kills off the generator, two-way communication doesn't make much sense.
A:
The .return() method takes a value because it provides two-way communication in the same way as .next() and .throw() do.
A yield expression can have 3 different outcomes:
It can evaluate like a plain expression, to the result value of that
It can evaluate like a throw statement, causing an exception
It can evaluate like a return statement, causing only finally statements to be evaluated before ending the function
(a 4th possible outcome is that the generator never gets resumed)
which are achieved by calling the respective method on the suspended generator with the respective value. This includes the exception value and the return value.
But when you pass it a value such as generator.return(4), all it does is give you back an object as if you called Generator.prototype.next and your value prop was 4.
Not necessarily. You might think that when a return statement is evaluated it always comes back with that return value, and unlike an exception from a throw statement it could not be intercepted. It's true that the return value cannot be accessed within the generator function, but it can be suppressed or changed through a finally clause.
[ function* exampleA() {
try { yield; } finally {}
},
function* exampleB() {
try { yield; } finally { yield 'Y'; }
},
function* exampleC() {
try { yield; } finally { return 'Z'; }
},
function* exampleD() {
try { yield; } finally { throw 'E' }
}
].forEach(genFn => {
try {
const gen = genFn();
gen.next();
console.log(gen.return('X'));
} catch(e) {
console.log(e);
}
});
(Of course, doing such things in a finally clause is a bad practice, but it's possible)
|
[
"stackoverflow",
"0017331199.txt"
] | Q:
adding xml innertext with foreach loop
I am trying to add values to the saml:AttributeValue elements of this xml document:
<saml:AttributeStatement xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Attribute Name="FNAME">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="LNAME">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="Gender">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="UniqueID">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="DateOfBirth">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="ClientID">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
Using this c# code:
//get the AttributeStatement node
XmlNode attrs = assertion.SelectSingleNode("//saml:AttributeStatement", ns1);
//get the Attribute nodes within the AttributeStatement node
XmlNodeList attr = attrs.SelectNodes("//saml:Attribute", ns1);
//foreach node in the Attribute node list get the AttributeValue node and add an innerText value
foreach (XmlNode xn in attr)
{
XmlNode attrValue = xn.SelectSingleNode("//saml:AttributeValue", ns1);
switch (xn.Attributes["Name"].Value)
{
case "FNAME":
attrValue.InnerText = UserInfo.FirstName;
break;
case "LNAME":
attrValue.InnerText = UserInfo.LastName;
break;
case "Gender":
attrValue.InnerText = UserInfo.Email;
break;
case "UniqueID":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
case "DateOfBirth":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
case "ClientID":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
default:
attrValue.InnerText = "No attribute listed";
break;
}
//output each AttributeValue innerText.
lblTest.Text += attrValue.InnerText + " ";
}
The lblTest is displaying how I would expect - with the correct values for all 6 elements, but the document is not displaying any values at all. Is this the correct way to loop through and add these values to nodes?
A:
You are doing the right thing up to a point: the trouble is, you're only updating the in-memory copy of your XML document.
See http://support.microsoft.com/kb/301233 for instructions on how to use XmlDocument.Save() to save your in-memory changes down to your XML file.
|
[
"stackoverflow",
"0060218836.txt"
] | Q:
Node.JS + Express parse CSV file on server
Essentially, what I have is a form where a user will upload a CSV file.
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" name="file" required>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<input type="submit" class="btn btn-primary btn-block">
</form>
FYI: I'm using getbootstrap.com as my style sheet.
Now, the form sends a POST request to /upload which is where my node.js code is. What I need is for the server to parse this CSV file and extract the data. I've got no idea what to do as all the different NPM packages such as Multer are using a system where the save the file locally and then parse it.
Edit: Forgot to mention this, but temporary local CSV hosting is not an option.
I need the client to upload server to process it and push to a DB, can't save the file locally anywhere.
Edit 2: I've used multer and the memory processing option and have gotten the following.
const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", function(req, res) {
response.sendFile(__dirname + "/views/index.html");
});
app.post("/upload", upload.single('file'), async (req, res) => {
res.send(req.file)
});
const listener = app.listen(process.env.PORT, function() {
console.log("Your app is listening on port " + listener.address().port);
});
Now once I upload the file, I'm getting the following response (this is what req.file is).
{"fieldname":"file","originalname":"tech.csv","encoding":"7bit","mimetype":"application/octet-stream","buffer":{"type":"Buffer","data":[67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101]},"size":56}
So It's pretty clear that our data happens to be
67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101
but how do I process that? The csv file data was
CLASS ID,TECH #,FIRST NAME,LAST NAME
6O,6O01,Anish,Anne
So how do I go from the information provided in the buffer data attribute to the actual data?
A:
All you have to use is Multer. Multer will return a buffer object which you can then make a string with the .toString() attribute.
Code:
const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer = require('multer');
var buffer = require('buffer/').Buffer
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", function(request, response) {
response.sendFile(__dirname + "/views/index.html");
});
app.post("/upload", upload.single('file'), async (req, res) => {
var b = req.file["buffer"]
console.log(b.toString())
res.send(b.toString())
});
const listener = app.listen(process.env.PORT, function() {
console.log("Your app is listening on port " + listener.address().port);
});
|
[
"stackoverflow",
"0009584476.txt"
] | Q:
Android Ice Cream Sandwich tablets that support Face Detection
I'm trying to build an application for android tablets that uses androids new face detection which is only compatible with ICS and up. I upgraded my Asus transformer to ICS but I don't believe it supports Face Detection. Does anyone know of any tablets that have or can be upgraded to ICS that do support Face Detection?
A:
If your camera (front facing) works, it is built into ICS http://www.gottabemobile.com/2011/12/15/how-to-setup-face-unlock-on-android-4-0/
As far as coding for it:
https://developer.android.com/reference/android/media/FaceDetector.html
and
http://arstechnica.com/gadgets/news/2011/10/first-look-android-40-sdk-opens-up-face-recognition-apis.ars
So hardware restriction should be minimal. Code away and test!
Also: some examples pre ICS Face recognition API for java android
EDIT After reading through all your similar posts:
Android face detection MaxNumDetectedFaces
Android face detector using android camera
I assume you are running a ROM and there is probably a driver or kernel issue preventing yours from working, but the device does support it as most would:
http://www.androidauthority.com/install-android-4-0-on-asus-transformer-with-face-unlock-working-revolver-rom-57840/
Try a different ROM and use one that is known to work. Then that problem is solved and you can start coding and finding more problems ;-)
If you are not running a ROM and you upgraded to Stock ICS for the Asus Transformer...it looks like they broke it: http://www.mobileinquirer.com/2012/asus-transformer-missing-face-unlock-feature-unlocked-but-risks-associated/ and you'd be better off rooting the device if you want to use it for testing and debugging.
|
[
"electronics.stackexchange",
"0000416455.txt"
] | Q:
Regarding pinout of PCF8574 I2C 8-bit expander
I need some help understanding the pins of I2C 8-bit expander (PCF8574AT) that looks like this,
https://mbrobotics.es/blog/arduino-lcd-1602-i2c/
In the datasheet for this part, there is a pinout diagram for the 16 pin header but nothing is mentioned about the four pins on the top of the module which is SDA, SCL, VSS, and VDD but these already exist in the 16 pin header.
Datasheet for the expander,
https://www.nxp.com/docs/en/data-sheet/PCF8574_PCF8574A.pdf
Please help me understand why there are two sets of these pins. Basically, I want to understand how the on-chip IC of the module is wired to the header on its side plus the header on top.
Edit: Added datasheet.
Edit: Clarification.
A:
The 4-pin header J1 is what you connect to your Arduino (or other micro-controller). It has ground, power, and the two I2C lines.
The 16-pin header J2 is what you connect to the HD44780 LCD. 4 pins are not used because the unit is intended to use 4-pbit mode. The header has the same ground and power pins as the 4-pin header, because these must be passed through to the LCD. The I2C lines (scl, sda) are not on this 16-pin header.
|
[
"stackoverflow",
"0000265185.txt"
] | Q:
Randomizing RegEx In PHP
Basically I want to use RegEx to grab stuff in between paragraphs in a document. I think the expression would be:
<p>.+?</p>
Say it grabs 10 items using this RegEx, I then want PHP to randomly choose one of those and then save it to a variable. Any ideas?
A:
// Test data
$str = '<p>a1</p><p>b2</p><p>c3</p><p>d4</p>';
// Pull out all the paragraph contents into $matches
preg_match_all('_<p>(.+?)</p>_is', $str, $matches);
// $matches[0] contains all the <p>....</p>
// $matches[1] contains the first group, i.e. our (.+?)
// Echo a random one
echo $matches[1][array_rand($matches[1])];
|
[
"stackoverflow",
"0049457927.txt"
] | Q:
bind() throws an error EINVAL, UDP server on Linux
I have a problem with a simple UDP server realization. I have the following code that works great in a little standalone application. But if I just copy-paste that into another, more complicated application, it fails - bind() function returns -1 and sets errno to 22 (EINVAL). This another application also has a TCP server that works good and it starts on start of the application. Please guys, your ideas, why have I the problem. Thanks in advance!
UPD: By the way, getsockname() function sometimes fails too in that application (It says that the handle is invalid).
UPD 2: thanks to fbynite I fixed a typo in the code. Now bind() returns no errors, but recvfrom() is freezing. Of course a datagram was sent from a client
int handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (handle < 0)
{
std::cout << "socket(): " << std::strerror(errno)) << std::endl;
return;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(6660);
if (bind(handle, (sockaddr*)&addr, sizeof(addr)) < 0)
{
std::cout << "bind(): " << std::strerror(errno)) << std::endl;
close(handle);
return;
}
else
{
sockaddr cl;
socklen_t clLen;
char buffer[100];
int bytes = recvfrom(handle, buffer, 100, 0, &cl, &clLen);
buffer[bytes] = '\0';
std::cout << buffer << std::endl;
}
A:
It was a little out of sync. Actually the server was starting after the client has sent a datagram. The problem is solved.
|
[
"stackoverflow",
"0038280929.txt"
] | Q:
Why isn't my directive rendering any bound elements?
This follows from my question Recursion with ng-repeat in Angular, but is no way a duplicate. Now I know how to do that, but am asking why my current solution to the problem isn't working.
I'm busy adapting the huge Metronic Angular theme, and my first task is to dynamically load side menu items from a REST api. The container for the side meny, in the main index.html page (only page used: doing spa) looks like this:
<div data-ng-include="'tpl/sidebar.html'" data-ng-controller="SidebarController" class="page-sidebar-wrapper"></div>
Then sidebar.html looks like this:
<div class="page-sidebar navbar-collapse collapse">
<ul class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"
ng-class="{'page-sidebar-menu-closed': settings.layout.pageSidebarClosed}"
rsng-menuItem="menuItems">
</ul>
</div>
You'll notice my custom directive, rsng-menuItem, used for recursing a menu tree:
angular.module("ReflexPortalApp").directive("rsngMenuItem", ["$parse", function ($parse) {
return {
restrict: "A",
scope: true,
templateUrl: "/tpl/sidebar/menu-item.html",
link: function (scope, element, attrs) {
scope.List = $parse(attrs.rsngMenuItem)(scope);
}
}
}]);
and it's template looks like this:
<li ng-repeat="item in List" ng-class="{\'nav-item\': !item.IsHeading, \'start\': item.IsStart}">
<a href="{{item.Href}}" ng-class="{\'nav-link nav-toggle\': item.subItems && item.subItems.length > 0}">
<i ng-if="{{item.Icon && item.Icon.length > 0}}" class="icon-{{item.Icon}}"></i>
<span class="title">{{item.Text}}</span>
<span ng-if="{{item.DecorClass || item.DecorText}}" class="{{item.DecorClass}}">{{item.DecorText}}</span>
</a>
<ul rsng-menuItem="item.subItems" class="sub-menu"></ul>
</li>
In SideBarController1, the menu items do load successfully from the REST API, and are assigned to themenuItems` scope property, so they should be available for binding.
Lastly, a menu item looks like this in JSON:
{
"IsDisabled": "0",
"seq": 2,
"Href": "javascript:;",
"Id": "2",
"IsStart": "0",
"IsNavItem": "1",
"DecorText": null,
"ApiCall": null,
"Index": 3,
"Text": "Accounting",
"Icon": "settings",
"ParentId": null,
"DecorClass": "arrow",
"subItems": [
{
"DecorClass": "arrow",
"ParentId": "2",
"Icon": "wrench",
"Text": "Statement",
"Index": 1,
"ApiCall": "statement&CustID=4446&statementdate=2016-05-01",
"DecorText": null,
"IsNavItem": "0",
"IsStart": "0",
"Id": "3",
"Href": "list",
"seq": 1,
"IsDisabled": "0"
}
]
}
When I started, and didn't have a clue how to do recursion in templates, I simply used a recursive code loop and jQuery to 'manually' construct and populate all the elements for each menu item, and that worked fine, but writing HTML with code literals stinks.
Now I simply get an empty side menu, with no errors in the console (gotta love that part of Angular), and was wondering if I'm doing anything obviously wrong.
A:
The problem lies in your directive-name, angular simply doesn't recognize your directive because it doesn't deal well with uppercase letters in attribute-names. Rename rsng-menuItem to rsng-menu-item.
However, this won't work because you can't just recursively nest directives in angular, it will end in an infinite loop.
There are multiple solutions for this, take a look at Recursion in Angular directives and
https://github.com/marklagendijk/angular-recursion
|
[
"french.stackexchange",
"0000008456.txt"
] | Q:
Responsable « du/de la », « de » ou « pour » quelque chose ?
Je suis en train d'écrire mon CV et je voudrais connaitre quelques petits détails sur le mot « responsable ».
Comment on peut l'utiliser ? Je veux décrire les responsabilités que j'avais pendant mon stage. Alors dois-je écrire du (ou au féminin de la) :
Responsable du développement du logiciel
Responsable de la maintenance
ou bien de :
Responsable de développement du logiciel
ou avec pour ?
Responsable pour le développement du logiciel
A:
Responsable du développement et Responsable de la maintenance sont couramment utilisés.
|
[
"graphicdesign.stackexchange",
"0000031683.txt"
] | Q:
Learning a new program! (A designers nightmare)
Does it have to be so difficult?
I open up gimp. Wait, what does what?
I open up inkscape. The controls are so different. Cntrl+D does not work. Ar.AR.ar.
Photoshop, illustrator and more.
Why does it take ages to learn? Is graphics design so hard?
Help before i pass away(give me some advice please)
A:
This question is way too broad, but in short:
Some things are complex; you cannot have lots of options and possibilities without complexity. Dumbing down results in poor scope.
As for keyboard shortcuts etc, this xkcd might explain some:
|
[
"stackoverflow",
"0006135117.txt"
] | Q:
Regular expression problem
Expression should start with a alphanumeric and should have alphabets, @, $, %, _, - and a single space in the middle and should ends with alphanumeric.
E.g.
1a1 -- valid
1111 -- invalid
2222$2211 -- valid
%11a25 -- invalid
A:
This will match one or more alphanumeric characters, followed by any alphabetic characters plus the extra characters, followed by one or more alphanumeric characters.
/^[a-z\d]+[a-z @$%_-][a-z\d]+$/i
jsFiddle.
The fiddle validates the same as your test data.
You should learn about regular expressions.
|
[
"stackoverflow",
"0038695392.txt"
] | Q:
error: no resource identifier for attribute 'srcCompat'
I've added 2 images using Copy+Paste in the @drawable folder, but I get the error
Error:(25) No resource identifier found for attribute 'srcCompat' in package 'com.example.francydarkcool.maps'
I've added:
defaultConfig {
vectorDrawables.useSupportLibrary = true;
...
}
in build.gradle
and also:
ImageView img1 = new ImageView(this);
img1.setImageResource(R.drawable.cascada3);
setContentView(img1);
ImageView img2 = new ImageView(this);
img2.setImageResource(R.drawable.cascada1);
setContentView(img2);
in my .java file.
This is my activity_cascada_urlatoarea.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#479fc7"
android:orientation="vertical"
android:weightSum="480">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="227dp"
app:srcCompat="@drawable/cascada3"
android:id="@+id/imageView5"
android:layout_weight="0.50"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
app:srcCompat="@drawable/cascada1"
android:id="@+id/imageView7"
android:layout_weight="0.33"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:orientation="horizontal"
android:weightSum="1">
<Button
android:text="Back"
android:layout_width="118dp"
android:layout_height="29dp"
android:id="@+id/button2"
android:background="@color/cast_mini_controller_main_background"
android:textSize="14sp"
android:textStyle="normal|bold"
android:textAlignment="center"
android:layout_marginTop="30dp"
android:onClick="backbttn"
android:layout_marginLeft="20dp"/>
<Button
android:text="Next"
android:layout_width="118dp"
android:layout_height="29dp"
android:id="@+id/button8"
android:background="@color/cast_mini_controller_main_background"
android:textAlignment="center"
android:textStyle="normal|bold"
android:layout_weight="0.16"
android:layout_marginTop="30dp"
android:layout_marginLeft="110dp"
android:onClick="nextbttn"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
If i try to change
xmlns:app="http://schemas.android.com/apk/res-auto"
with
xmlns:app="http://schemas.android.com/apk/lib/com.app.chasebank"
I get no errors, but no images are shown...
Please help.
A:
make sure in your app's build.gradle file that under dependency .. you are using the latest version of support library(any version 23.3+ will work).
compile 'com.android.support:appcompat-v7:24.1.1'
Then clean and rebuild project.
|
[
"stackoverflow",
"0041870582.txt"
] | Q:
React Redux router saga material-ui and tabs corresponding to current route
I'm pretty new to react and I'm using react-boilerplate + material-ui
I have tabs like so:
And I want to be able to change the current tab so it would change the current route and vice-versa.
Also when refreshing the page with a route it should go to the right tab.
So I have my tabpagechooser container component like so:
index.js:
/*
*
* TabsPageChooser
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { changeTab } from './actions';
import makeSelectTab from './selectors';
import messages from './messages';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
export class TabsPageChooser extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props)
this.handleHome = this.props.onChangeTab.bind(null, 0);
this.handleSettings = this.props.onChangeTab.bind(null, 1);
this.handleAbout = this.props.onChangeTab.bind(null, 2);
}
render() {
console.log(this.props);
return (
<Tabs initialSelectedIndex={this.props.tab.tabIdx} >
<Tab
icon={<FontIcon className="material-icons">home</FontIcon>}
label={<FormattedMessage {...messages.home} />}
onActive={this.handleHome} />
<Tab
icon={<FontIcon className="material-icons">settings</FontIcon>}
label={<FormattedMessage {...messages.settings} />}
onActive={this.handleSettings} />
<Tab
icon={<FontIcon className="material-icons">favorite</FontIcon>}
label={<FormattedMessage {...messages.about} />}
onActive={this.handleAbout} />
</Tabs>
);
}
}
TabsPageChooser.propTypes = {
onChangeTab: React.PropTypes.func,
};
const mapStateToProps = createStructuredSelector({
tab: makeSelectTab(),
});
function mapDispatchToProps(dispatch) {
return {
onChangeTab: (tabId) => {
dispatch(changeTab(tabId));
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TabsPageChooser);
actions.js:
/*
*
* TabsPageChooser actions
*
*/
import {
ROUTES_ID,
CHANGE_TAB,
} from './constants';
export function changeTab(tabId) {
return {
type: CHANGE_TAB,
tab: tabId,
};
}
export function urlFromId(tabId) {
if (!(tabId > 0 && tabId < ROUTES_ID)) {
return '/';
}
return ROUTES_ID[tabId];
}
export function changeTabFromUrl(url) {
console.log(url);
return changeTab(ROUTES_ID.indexOf(url));
}
constants.js:
/*
*
* TabsPageChooser constants
*
*/
export const CHANGE_TAB = 'app/TabsPageChooser/CHANGE_TAB';
export const ROUTES_ID = [
'/',
'/settings',
'/about',
];
reducer.js:
/*
*
* TabsPageChooser reducer
*
*/
import { fromJS } from 'immutable';
import {
CHANGE_TAB,
} from './constants';
const initialState = fromJS({
tabIdx: 0,
});
function tabsPageChooserReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_TAB:
return state.set('tabIdx', action.tab);
default:
return state;
}
}
export default tabsPageChooserReducer;
sagas.js:
import { take, call, put, select, takeLatest, takeEvery } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { changeTabFromUrl, urlFromId } from 'containers/TabsPageChooser/actions';
import { makeSelectTab } from 'containers/TabsPageChooser/selectors';
import { CHANGE_TAB } from 'containers/TabsPageChooser/constants';
import { LOCATION_CHANGE } from 'react-router-redux';
function* doChangeTab(action) {
//Act as dispatch()
yield put(changeTabFromUrl(action.payload.pathname));
}
function* doChangeUrl(action) {
//Act as dispatch()
yield put(push(urlFromId(action.tab.tabId)));
}
// Individual exports for testing
export function* defaultSagas() {
yield takeEvery(LOCATION_CHANGE, doChangeTab);
yield takeEvery(CHANGE_TAB, doChangeUrl);
}
// All sagas to be loaded
export default [
defaultSagas,
];
My problem is especially that last file, the LOCATION_CHANGE event, trigger the changeTab action which in turn trigger the CHANGE_TAB event, which trigger a location change etc...,
What am I doing wrong, how should I do ?
A:
I finally succeeded,
What I have changed:
/*
*
* TabsChooser
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { changeTab } from 'containers/App/actions';
import { makeSelectLocationState, makeSelectTabsChooser } from 'containers/App/selectors';
import messages from './messages';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
const locationId = [
'/',
'/settings',
'/about',
];
export class TabsChooser extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
this.contentsTab = [
{ route: this.props.onChangeTab.bind(null, locationId[0]), icon: <FontIcon className='material-icons'>home</FontIcon>, label: <FormattedMessage {...messages.home} />, },
{ route: this.props.onChangeTab.bind(null, locationId[1]), icon: <FontIcon className='material-icons'>settings</FontIcon>, label: <FormattedMessage {...messages.settings} />, },
{ route: this.props.onChangeTab.bind(null, locationId[2]), icon: <FontIcon className='material-icons'>favorite</FontIcon>, label: <FormattedMessage {...messages.about} />, },
];
let tabId = locationId.indexOf(this.props.tabLocation);
return (
<div>
<Tabs value={tabId} >
{this.contentsTab.map((tab, i) =>
<Tab key={i} value={i} icon={tab.icon} label={tab.label} onActive={tab.route} />
)}
</Tabs>
</div>
);
}
}
TabsChooser.propTypes = {
onChangeTab: React.PropTypes.func,
tabLocation: React.PropTypes.string,
};
function mapDispatchToProps(dispatch) {
return {
onChangeTab: (location) => dispatch(changeTab(location)),
};
}
const mapStateToProps = createStructuredSelector({
tabLocation: makeSelectTabsChooser(),
});
export default connect(mapStateToProps, mapDispatchToProps)(TabsChooser);
I now send the location instead of the the tab id in changeTab(),
I move action.js, reducer.js, selector.js and sagas.js into containers/App
action.js:
/*
* App Actions
*
*/
import { CHANGE_TAB, TABCHANGE_LOCATION } from './constants'
export function changeTab(tabLocation) {
return {
type: CHANGE_TAB,
tabLocation,
};
}
export function changeLocation(tabLocation) {
return {
type: TABCHANGE_LOCATION,
tabLocation,
};
}
constants.js:
/*
* AppConstants
*/
export const CHANGE_TAB = 'app/App/CHANGE_TAB';
export const TABCHANGE_LOCATION = 'app/App/TABCHANGE_LOCATION';
reducer.js:
/*
* AppReducer
*
*/
import { fromJS } from 'immutable';
import {
CHANGE_TAB,
TABCHANGE_LOCATION,
} from './constants';
// The initial state of the App
const initialState = fromJS({
tabLocation: window.location.pathname // Initial location from uri
});
function appReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_TAB:
return state.set('tabLocation', action.tabLocation);
case TABCHANGE_LOCATION:
return state.set('tabLocation', action.tabLocation);
default:
return state;
}
}
export default appReducer;
The initialState tabLocation is set with the window.location.pathname, so the right tab is selected at app bootup.
selector.js:
/**
* The global state selectors
*/
import { createSelector } from 'reselect';
const selectGlobal = (state) => state.get('global');
const makeSelectLocationState = () => {
let prevRoutingState;
let prevRoutingStateJS;
return (state) => {
const routingState = state.get('route'); // or state.route
if (!routingState.equals(prevRoutingState)) {
prevRoutingState = routingState;
prevRoutingStateJS = routingState.toJS();
}
return prevRoutingStateJS;
};
};
const makeSelectTabsChooser = () => createSelector(
selectGlobal,
(globalState) => globalState.getIn(['tabLocation'])
);
export {
selectGlobal,
makeSelectLocationState,
makeSelectTabsChooser,
};
sagas.js:
import { take, call, put, select, takeLatest, takeEvery, cancel } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { changeLocation } from './actions';
import { makeSelectTabsChooser } from './selectors';
import { CHANGE_TAB } from './constants';
import { LOCATION_CHANGE } from 'react-router-redux';
function* updateLocation(action) {
//put() act as dispatch()
const url = yield put(push(action.tabLocation));
}
function* updateTab(action) {
const loc = yield put(changeLocation(action.payload.pathname));
}
// Individual exports for testing
export function* defaultSagas() {
const watcher = yield takeLatest(CHANGE_TAB, updateLocation);
const watcher2 = yield takeLatest(LOCATION_CHANGE, updateTab);
}
// All sagas to be loaded
export default [
defaultSagas,
];
So finally the sagas wrap it up.
|
[
"stackoverflow",
"0028814291.txt"
] | Q:
make this sql query faster or use pl sql?
So the below query on an oracle server takes around an hour to execute.
Is it a way to make it faster?
SELECT *
FROM ACCOUNT_CYCLE_ACTIVITY aca1
WHERE aca1.ACTIVITY_TYPE_CODE='021'
AND aca1.ACTIVITY_GROUP_CODE='R12'
AND aca1.CYCLE_ACTIVITY_COUNT='999'
AND
EXISTS
(
SELECT 'a'
FROM ACCOUNT_CYCLE_ACTIVITY aca2
WHERE aca1.account_id = aca2.account_id
AND aca2.ACTIVITY_TYPE_CODE='021'
AND aca2.ACTIVITY_GROUP_CODE='R12'
AND aca2.CYCLE_ACTIVITY_COUNT ='1'
AND aca2.cycle_activity_amount > 25
AND (aca2.cycle_ctr > aca1.cycle_ctr)
AND aca2.cycle_ctr =
(
SELECT MIN(cycle_ctr)
FROM ACCOUNT_CYCLE_ACTIVITY aca3
WHERE aca3.account_id = aca1.account_id
AND aca3.ACTIVITY_TYPE_CODE='021'
AND aca3.ACTIVITY_GROUP_CODE='R12'
AND aca3.CYCLE_ACTIVITY_COUNT ='1'
)
);
So basically this is what it is trying to do.
Find a row with a R12, 021 and 999 value,
for all those rows we have to make sure another row exist with the same account id, but with R12, 021 and count = 1.
If it does we have to make sure that the amount of that row is > 25 and the cycle_ctr counter of that row is the smallest.
As you can see we are doing repetition while doing a select on MIN(CYCLE_CTR).
EDIT: There is one index define on ACCOUNT_CYCLE_ACTIVITY table's column ACCOUNT_ID.
Our table is ACCOUNT_CYCLE_ACTIVITY. If there is a row with ACTIVITY_TYPE_CODE = '021' and ACTIVITY_GROUP_CODE = 'R12' and CYCLE_ACTIVITY_COUNT = '999', that represents the identity row.
If an account with an identity row like that has other 021 R12 rows, query for the row with the lowest CYCLE_CTR value that is greater than the CYCLE_CTR from the identity row. If a row is found, and the CYCLE_ACTIVITY_AMOUNT of the row found is > 25 and CYCLE_ACTIVITY_COUNT = 1, report the account.
Note that identity row is just for identification and will not be reported.
For example, this a SELECT on a account_id which should be reported.
Account_ID Group_Code Type_code Cycle_ctr Activity_Amount Activity_count
53116267 R12 021 14 0 999
53116267 R12 021 25 35 1
53116267 R12 021 22 35 1
53116267 R12 021 20 35 1
There are several other Activity_count apart from 999 and 1, so a WHERE clause for that is necessary.
Similarly if the above example was like following
Account_ID Group_Code Type_code Cycle_ctr Activity_Amount Activity_count
53116267 R12 021 14 0 999
53116267 R12 021 25 35 1
53116267 R12 021 22 35 1
53116267 R12 021 20 **20** 1
It wouldnt be reported because the activity_amount of the row with the lowest cycle_ctr greater than the cycle_ctr of the identity row is 20, which is less than 25.
Explain plan after
explain plan for select * from account_activity;
select * from table(dbms_xplan.display);
Plan hash value: 1692077632
---------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop |
---------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 470M| 12G| 798K (1)| 02:39:38 | | |
| 1 | PARTITION HASH ALL | | 470M| 12G| 798K (1)| 02:39:38 | 1 | 64 |
| 2 | TABLE ACCESS STORAGE FULL| ACCOUNT_ACTIVITY | 470M| 12G| 798K (1)| 02:39:38 | 1 | 64 |
---------------------------------------------------------------------------------------------------------------
A:
Rewrite the query using explicit joins, and not with EXISTS.
Basically these two lines
WHERE aca1.account_id = aca2.account_id
AND (aca2.cycle_ctr > aca1.cycle_ctr)
are the join condition for joining the first and second select, and this one joins the first and the third.
WHERE aca3.account_id = aca1.account_id
The query should look like this
select distinct aca1.*
FROM ACCOUNT_CYCLE_ACTIVITY aca1, ACCOUNT_CYCLE_ACTIVITY aca2, ACCOUNT_CYCLE_ACTIVITY aca3
WHERE
join conditions and other selection conditions
|
[
"stackoverflow",
"0058345417.txt"
] | Q:
How to get the function pointer of a class member in a function of the same class?
I'm stumped on this.
I have a class Foo with a function DoTheThing1 that takes a pointer to a void function with 0 parameters and calls the function.
class Foo {
public:
Foo () {}
void DoTheThing1 (void (*theThing)()) {
theThing();
}
};
I have another class Bar that has an instance of Foo.
Class Bar also has its own function DoTheThing2 where it tries in it's construct to pass a pointer of DoTheThing2 to Foo's DoTheThing1.
class Bar {
public:
Foo* foo = new Foo();
Bar () {
foo->DoTheThing1(&Bar::DoTheThing2);
}
void DoTheThing2 () {
// Something happens.
}
};
I get this error error C2664: 'void Foo::DoTheThing1(void (__cdecl *)(void))': cannot convert argument 1 from 'void (__cdecl Bar::* )(void)' to 'void (__cdecl *)(void) at the line where the function pointer get's passed in.
Bar () {
foo->DoTheThing1(&Bar::DoTheThing2); /// Does not like.
}
I'm unsure of how to work around this. It seems some weird cast is required.
EDIT
Actually, my situation is a little more complicated than just calling a function pointer from a class member within itself. What my code actually does is set the pointer to a variable, then it gets called later.
class Foo {
public:
void (*m_onEvent) ();
Foo () {}
void SetTheThing (void (*theThing)()) {
m_onEvent = theThing;
}
template <typename T>
void SetTheThing (T&& theThing) {
m_onEvent = theThing;
}
void DoTheThing1 () {
m_onEvent();
}
};
class Bar {
public:
Foo* foo = new Foo();
Bar () {
foo->SetTheThing([this](){ DoTheThing2(); }); // error C2440: '=': cannot convert from 'T' to 'void (__cdecl *)(void)'
foo->SetTheThing(&DoTheThing2); // '&' illegal operation on bound member function expression.
}
void DoTheThing2 () {
std::cout << "I did the thing." << std::endl;
}
};
int main () {
Bar* bar = new Bar();
bar->foo->DoTheThing1();
}
EDIT
So now I'm trying to hack it using a class template, but I keep getting stopped by this error: Term does not evaluate to a function taking 0 arguments.
I'm trying to figureout how my function pointer doesn't evaluate to anything.
template <typename U>
class Foo {
public:
void (U::*m_theThing) ();
Foo () {}
void SetTheThing (void (U::*theThing)()) {
m_theThing = theThing;
}
void DoTheThing1 () {
m_theThing(); // Term does not evaluate to a function taking 0 arguments.
}
};
class Bar {
public:
Foo<Bar>* foo = new Foo<Bar>();
Bar () {
foo->SetTheThing(&Bar::DoTheThing2);
}
void DoTheThing2 () {
std::cout << "I did the thing." << std::endl;
}
};
int main () {
Bar* bar = new Bar();
bar->foo->DoTheThing1();
}
A:
Old way: You need a template to get the class and a specialization for functions.
Working example:
#include <iostream>
//For member function of class C
template <typename C = void>
struct TheCaller
{
TheCaller() : theClass(nullptr), mf(nullptr) {}
C* theClass;
void (C::*mf)();
void SetTheThing(C* aClass, void (C::*memberFunction)())
{
theClass = aClass;
mf = memberFunction;
}
void CallTheThing()
{
if ( theClass )
(theClass->*mf)();
}
};
//Specialization for any function
template <>
struct TheCaller<void>
{
TheCaller() : mf(nullptr) {}
void (*mf)();
void SetTheThing(void (*memberFunction)())
{
mf = memberFunction;
}
void CallTheThing()
{
if ( mf )
mf();
}
};
struct Bar
{
void DoTheBarThing()
{ std::cout << "DoTheBarThing called" << std::endl; }
};
void AFunction()
{ std::cout << "AFunction called" << std::endl; }
int main()
{
TheCaller<Bar> foo;
Bar bar;
foo.SetTheThing(&bar, &Bar::DoTheBarThing);
foo.CallTheThing();
TheCaller<> foo2;
foo2.SetTheThing(&AFunction);
foo2.CallTheThing();
}
|
[
"stackoverflow",
"0017433873.txt"
] | Q:
Pattern for treating zero as truthy
I often do stuff like this:
delay = delay || 24; // default delay of 24 hours
But I actually want to permit 0, and 0 || 24 === 24, instead of 0.
I'm wondering what the best pattern is to take user input from command line, or input from wherever, and do the same logic, only treat zero as truthy. I think the best pattern I've found is to do exactly that:
delay = (delay === 0 ? delay : (delay || 24));
Firstly, it permits things like 'abc', which is really wrong. But if I put in an early + it lets null slide through, which is also wrong. Secondly, very ugly, because it's clearly working around a language deficiency rather than doing something elegant with the language tools available. And not terribly readable. I'm doing something that is one line of thought and I'd like to do it in one actual line of code (not one line on technicality, like this is). But most other ideas I have had get even uglier:
delay = typeof delay === 'number' ? delay : 24; // but typeof NaN === 'number', so
delay = (!isNaN(delay) && typeof delay === 'number') ? delay : 24;
Note that this actually would work with string - if i were interested in accepting "", then
str = typeof str === 'string' ? str : 'default';
Since there is no NaN hole, and this is intelligently readable: if we have a string use that, otherwise use defaut.
Or this route:
delay = !isNaN(+delay) ? delay : 24; // fails on null
delay = !Number.isNaN(+delay) ? delay : 24; // still fails on null
// same thing with null check, now way uglier than we started
So I still like my hacky ternary and boolean logic better. Yes, I am looking for a condensed, one-line solution, since JS is rife with patterns and what would be clever in many other languages is well-recognized and readable and clear in JS. But I'm novice and trying to learn good patterns, hence, this question.
To be more explicit on the requirements:
0 needs to go to 0.
undefined needs to go to 24.
All actual numbers under typeof need to go to themselves, except NaN.
I strongly feel null should go to 24 because I very rarely use JS code that treats null and undefined differently on purpose. I feel it's better to keep it that way.
I slightly feel NaN should go to 24 because this more closely follows the || pattern. Falsy things should go to default.
'abc' should go to 24 - in my real application this is user input, and the user should not mistakenly type, say an email.
'123abc' should ideally go to 24, which conversion to Number catches but parseInt does not. I believe emails can start with numbers, so this drives the point home that this is something that ought to be caught.
Underscore or lodash answers are acceptable, in particular, to those of you who have lectured me on trying to be "clever" instead of writing a 2-3 line function. Those libraries exist precisely because there are many simple 2-3 line functions accomplishing the same thing in many places in many code bases all over the world, and it's far more readable and maintainable and robust to have those isolated as something like, say, _.readNumber. If no such method exists and I am able to come up with general enough requirements, I will submit a poll request myself and post that as answer to this question. This is something I like about JS - it has good ecosystem in that it's very possible to not have to write these utility methods. Since I'm particularly dealing with user input it may be better for me to write a slightly more specialized function and submit to commander.js, which is where I keep needing this.
A:
Nowhere is int a requirement mentioned, so assuming you want any number, otherwise defaulting to 24, you could use this:
delay = isFinite(delay) ? delay : 24;
Or the safer:
delay = isFinite(parseFloat(delay)) ? delay : 24;
Or the Robert Lemon special:
delay = isFinite(parseFloat(delay))|0||24;
Of course having someone else understand the statement at a glance is more important than syntactic sugar. You're writing code to be understood by man and machine, not to ward off industrial spies.
A:
The cleanest solution, by far:
delay = numberOrDefault(delay, 24);
// i = i || 24 doesn't work with i = 0, so this small func takes care of this.
function numberOrDefault(input, default) {
// a few lines handling your case
}
Don't try to abuse the language. Don't try to be clever. Don't try to obfuscate your code. It will serve noone but your ego, and will hurt the maintainability and readability of your code.
Functions are there and can have names. They're done exactly for the purpose you're looking for: give names to some bunch of instructions. Use them.
A:
Assuming user input as some comments are saying, then it begins as any possible string so may as well test it.
delay = /^(\d+)$/.exec( delay ) ? Number( RegExp.$1 ) : 24;
Note this also protects against negative integers, which although not given as a requirement is nonsensical as a delay of time.
|
[
"stackoverflow",
"0036037074.txt"
] | Q:
How can I render country flags as a ribbon, using CSS only?
I need to present some data. Each block of data needs a country flag. I would like to display the country flag, using a nice little hanging banner, like this:
This image is edited in paint, and the example I've used, comes from this page
This link right here, shows how to display flags of Europe++ in pure CSS. In my system, I only need Nordic flags, which are all represented by a cross.
From the codepen example:
@function cross($back, $main, $detail: $back){
@return linear-gradient(90deg, transparent 28%, $main 28%, $main 34%, transparent 34%),
linear-gradient(transparent 42%, $detail 42%, $detail 46%, $main 46%, $main 58%, $detail 58%, $detail 62%, transparent 62%),
linear-gradient(90deg, $back 25%, $detail 25%, $detail 28%, $main 28%, $main 34%, $detail 34%, $detail 37%, $back 37%);
}
If I derive this (and rotate it 90deg to fit my preferred orientation, I can get something like this:
HTML:
<div class="norway"></div>
CSS:
.norway{
background: linear-gradient(180deg, transparent 28%, blue 28%, blue 34%, transparent 34%),
linear-gradient(90deg, transparent 42%, white 42%, white 46%, blue 46%,
blue 58%, white 58%, white 62%, transparent 62%),
linear-gradient(180deg, red 25%, white 25%, white 28%, blue 28%, blue 34%,
white 34%, white 37%, red 37%);
height: 600px;
width: 400px;
}
The hanging banner example however, is not really displaying the element itself, merely its border. I like the split in the bottom, So I would like to be able to set the linear gradients on the different border sides individually, or somehow otherwise solve the problem. I have tried a few approaches, but I can't seem to make the gradients work on individual border sides.
Does anyone know how I can display my flags as split end ribbons, using only CSS?
By the way, the Czech Republic is easy...
UPDATE:
I was able to render a Norwegian version, but I had to make two elements. One displaying the flag in the background of an element, and another element over it, displaying only the bottom border, in the same color as the block background. It seems like a pretty fragile solution, though...
https://jsfiddle.net/azjctc1y/
A:
You have a great base to go on. It just needs a few tweaks here and there. (Making individual styles for flags is going to be a colossal pain though). There's just a few places you could improve it. In most cases when using absolute positioning, you may want to have whatever you are positioning align with some edge of the parent element. For that you can use negative values like left: -1em or whatever, but a lot of times, it's more robust to leave left auto and set the right attribute to 100%. You also set the bottom border to right:0. In throwing it in this answer I discovered that the font size difference caused it to be aligned incorrectly. One way you can fix that is to give it a left:50% with a negative margin equal to the left border. In this case it's 1.5em. A few changes, but it's all about understanding and leveraging top, right, bottom, and left to their fullest potential, which includes percent based values.
Hope it helps!
body {
padding: 2em;
}
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
.test-container{
background-color: lightgrey;
border: 1px solid black;
position: relative;
padding: 10px;
margin: 10px;
min-height: 100px;
}
.ribbon {
position: absolute;
top: 0;
right: 1em;
z-index: 1;
color: #eee;
font-size: 2em;
}
.norway {
position: absolute;
top: -0.5em;
right: 1em;
z-index: 1;
font-size: 2em;
height: 70px;
width: 42px;
background: linear-gradient(180deg, transparent 28%, blue 28%, blue 34%, transparent 34%),
linear-gradient(90deg, transparent 40%, white 40%, white 46%, blue 46%, blue 54%, white 54%, white 60%, transparent 60%),
linear-gradient(180deg, red 25%, white 25%, white 28%, blue 28%, blue 34%, white 34%, white 37%, red 37%);
}
.ribbon:before {
content: "";
font-size: 0.5em;
position: absolute;
border-style: solid;
border-color: transparent transparent #B71C1C transparent;
top: 0;
right: 100%;
border-width: 0 0 1em 0.7em;
z-index: -1;
}
.ribbon:after {
content: "";
font-size: 0.5em;
position: absolute;
height: 5em;
border: 1.5em solid #F44336;
z-index: -1;
bottom: 0;
border-top-width: 1.5em;
border-bottom-color: lightgrey;
border-right-color: transparent;
border-left-color: transparent;
border-top-color: transparent;
left: 50%;
margin-left: -1.5em;
-webkit-transition: height 0.5s;
transition: height 0.5s;
}
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
<div class="test-container">
<a class="norway ribbon"></a>
Norway
</div>
</div>
</div>
</div>
|
[
"stackoverflow",
"0005488864.txt"
] | Q:
Is it possible for a website project to reference a signed assembly in visual studio?
I'm aware of the following two different types of web projects in Visual Studio 2008:
Website project
Web application project
A web application project can reference a signed assembly as long as the web application's assembly is also signed with the same key. However, this doesn't work with the website project because there is no place to sign an assembly. I think this is because the assembly is compiled dynamically on the server?
Anyway, is it possible to get the website project working with this signed assembly? Or will I have to convert this website project into a web application project?
Edit:
The following situation has required me to ask for clarification in this matter:
I have a class library that is being referenced by several other projects in my solution in Visual Studio. One of the projects is a windows application that will be deployed to specific external users. In order to make sure that the application is using the correct assembly and to also prevent others from using the assembly (I am aware of the limitations with respect to its effectiveness), all assemblies have been signed and all the classes in the library are declared as Friend (internal).
The website project doesn't seem to have a way for me to sign its assembly and I get the following message when attempting to use anything from the library: "CLASS is not assessable in this context because it is 'Friend'", which is to be expected.
The following attributes are inside the AssemblyInfo.vb file in my class library project:
<Assembly: InternalsVisibleTo("OtherProject1, PublicKey=AAA...")>
<Assembly: InternalsVisibleTo("OtherProject2, PublicKey=AAA...")>
...
My Conclusion:
Looks like the cleanest way to do this would be to convert the website into a web application but this would require a bit of time to do since our site is pretty fleshed out already and as pointed out in other discussions, can be quite a pain to do. Going forward, I think creating a web application in the first place may have been a better idea and much more flexible for future development.
A:
There's no requirement for the two projects to be signed with the same key - after all the framework assemblies are all signed with MS's key, which you don't have access to yet you can happily reference them from both Web Site and Web Application projects.
There's nothing at all stopping you referencing a signed assembly from a Website project - what errors are you seeing?
Edit to add
In light of your updated information, yes, I think you'll have to either:
Convert the web site to a web application - as you rightly point out, there's no way to sign the site, and indeed, there's no real control over the libraries that ASP.NET will generate for the site.
Compile two versions of the class library, one signed, the other not. You could probably use conditional compilation to achieve this.
Edit to add
I think the conditional compilation will probably end up getting messy quickly, but in brief it would work like this:
Open the Project Properties for the class library, and go to the Build tab.
Switch the "Configuration" dropdown to "All Configurations"
In the "Conditional compilation symbols" box, add a new symbol, such as "INTERNAL".
Go to the class libraries that you want to make public, and modify them to something like:
#if INTERNAL
internal class MyClass
#else
public class MyClass
#endif
{
[...]
}
Then, when you need to produce the Public version of the library, remove the "INTERNAL" symbol from the properties and rebuild - you could make this easier by creating a new set of Debug and Release configurations that have this symbol defined, and switch between them using the Solution Configuration dropdown.
Potential issues:
It might not be easy to tell whether you've got the symbol defined or not - I don't know what the behaviour is in vanilla VS, however with ReSharper installed it will grey out the parts of the code that won't be compiled under the current set of symbols, and flags the class as inaccessible as you type.
You'll want to leave your properties and methods as public so that when you don't build it as "INTERNAL" you can access the them, but this will look a bit odd (although doesn't produce any warnings so clearly is legal).
|
[
"serverfault",
"0000706694.txt"
] | Q:
Use Nginx as Reverse Proxy for multiple servers
I am trying to configure nginx as a reverse proxy for multiple servers on my LAN. They should go out on my WAN with different subdomains. My configuration looks like this:
@ReverseProxy:/etc/nginx/sites-enabled$ cat reverseproxy
server {
server_name DOMAIN.eu;
# app1 reverse proxy follow
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://10.0.2.5:80;
}
server {
server_name Subdomain.domain.eu;
# app2 reverse proxy settings follow
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://10.0.2.33:80;
}
But I am getting this error and can't get any further....
@ReverseProxy:/etc/nginx/sites-enabled$ nginx -t
nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
2009/01/04 12:22:13 [warn] 1302#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1
2009/01/04 12:22:13 [emerg] 1302#0: "proxy_pass" directive is not allowed here in /etc/nginx/sites-enabled/reverseproxy:8
nginx: configuration file /etc/nginx/nginx.conf test failed
A:
Your problem is that you are using proxy_pass inside server block, which is not allowed. Try using:
server {
server_name Subdomain.domain.eu;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://10.0.2.33:80;
}
}
inside your server block. Proxy options cannot be set on server level, as nginx documentation tells.
The other problems in your log happen because you have somehow your nginx starting up as a regular user, although it is supposed to start up as root.
A:
This thread solved my problem, but I thought it would be useful for others to have a completed configuration to see. The following configuration will reverse proxy for hostnames app1.local and app2.local, where app1 gets forwarded to another application listening on port 3300 and app2 is forwarded to a different application listening on port 3000. It is in a file here /etc/nginx/sites-available/two-applications.conf
server {
server_name app1.local;
location ~ {
proxy_pass_header Authorization;
proxy_pass http://localhost:3300;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
client_max_body_size 0;
proxy_read_timeout 36000s;
proxy_redirect off;
}
}
server {
server_name app2.local;
location ~ {
proxy_pass_header Authorization;
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
client_max_body_size 0;
proxy_read_timeout 36000s;
proxy_redirect off;
}
}
Also, those hostnames are made up and need to be in /etc/hosts as follows to have them work:
127.0.0.1 app1.local
127.0.0.1 app2.local
For the sake of completeness (as setup on Ubuntu Linux), this file lives in /etc/nginx/sites-available/two-applications.conf and is symlinked into /etc/nginx/sites-enabled/two-applications.conf The filename and symlink name can be anything of course. After updating that running sudo service nginx reload will pick up the change.
|
[
"stackoverflow",
"0043259850.txt"
] | Q:
A function that recieves three numbers and a list, gets an average of those three numbers and subtracts the average from each number on the list
I've got a question regarding how to improve something small I wrote. I'm fairly new to Python and I tried to make this with a for loop but failed, I was wondering if there was a more efficient way to write this function(I wanted to do it with a for loop but if u guys have a better idea I'd appreciate if you posted it). Thanks!
Btw, the list recieved is only numbers, there aren't any strings, chars, etc.
def newList(n1,n2,n3,List):
avg = (n1+n2+n3)/3
i=0
while i<len(List):
List[i] -= avg
i += 1
print D
A:
Python’s list comprehensions are useful when you want to perform the same operation on every item in a list. For example, suppose you had a list of numbers defined as follows:
list_of_numbers = [1, 2, 3, 4, 5]
To add 5 to every number in this list and put it into a variable called new_list, you’d use a list comprehension:
new_list = [number + 5 for number in list_of_numbers]
If you check the value of new_list, you’ll see it is:
[6, 7, 8, 9, 10]
You can use a list comprehension in your newList() method:
def newList(n1, n2, n3, list):
average = (n1 + n2 + n3) / 3
result_list = [item - average for item in list]
return result_list
When you call it like so:
newList(1, 2, 3, [4, 5, 6])
you’ll get this result:
[2, 3, 4]
|
[
"stackoverflow",
"0027650157.txt"
] | Q:
Scala initialize a constructor called more than once
I have a simple class in Scala. I want to init some data when class is created. This is my code:
class SomeClass(someSeq: Seq[Int]) {
val someMap = scala.collection.mutable.Map.empty[Int, Set[String]]
init()
def init(): Unit = {
println("init")
}
override def getData(aValue: Int): Set[String] = {
println("I was called")
}
}
And the code that runs it:
def someClass = new SomeClass(a)
for (i <- 1 to 3) {
someClass.getData(i)
}
This is the output:
init
init
I was called
init
I was called
init
I was called
The code in "Init" initializes "someMap".
For some reason, the Init method get called every time I call the method "getData". What am I doing wrong?
A:
def someClass = new SomeClass(a)
your def defines a method. Invoking the method calls new SomeCLass(a).
for (i <- 1 to 3) {
someClass.getData(i)
}
Your for loop calls the someClass method three times. Each of those invocations calls new SomeClass(a). The constructor calls init each time. someClass then returns the new instance, and getData is called on that.
So it's not calling getData that causes init to be called. It's calling new SomeClass(a)
Try
val someClass = new SomeClass(a)
instead. That will call new SomeClass(a) once and assign the result to someClass.
Also, your posted code doesn't even compile (because getData's body doesn't return the correct type)
|
[
"stackoverflow",
"0016511321.txt"
] | Q:
Python global object variable
I want to make use on an object that has been instantinated inside of a class from a standalone module. I am trying to do this by makeing the object reference global. I think I want to make use of the current object and not create a new one.
Assume I have this code in a module file
import moduleFile
class A():
def checkAdmin(self):
global adminMenu
adminMenu = SRMadminMenu()
class SRMadminMenu()
def createAdminMenu(self):
pass
####Put code to create menu here####
def createSubMenu(self,MenuText):
pass
####Create a submenu with MenuText####
In moduleFile.py I have this code
def moduleFile_Admin_Menu():
global adminMenu
adminMenu.createSubMenu("Module Administration")
the code in moduleFile.py gives me the following error.
NameError: global name 'adminMenu' is not defined
A:
You must declare global variable outside from class.
## Code file something.py
import moduleFile
adminMenu = None
class A():
def checkAdmin(self):
global adminMenu
adminMenu = SRMadminMenu()
then moduleFile.py,
from something import adminMenu
def moduleFile_Admin_Menu():
global adminMenu
adminMenu.createSubMenu("Module Administration")
Note: If you will not change adminMenu variable, you don't have to write global adminMenu
|
[
"stackoverflow",
"0004342271.txt"
] | Q:
ASP .NET MVC Forms authorization with Active Directory groups
I'm attempting to authenticate using users and groups in ASP.NET MVC against Active Directory.
I have put the following attribute on all my classes (except the account class):
[Authorize (Roles="SubcontractDB Users")]
This group is found under OU=Area->OU=Groups->OU=Company->CN=SubcontractDB in active directory. I'm assuming I also need to setup a RoleManager in web.config which I've attempted to do as follows:
<roleManager defaultProvider="ADRoleProvider">
<providers>
<clear />
<add name="ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</roleManager>
My connection string is:
<add name="ADConnectionString"
connectionString="LDAP://blah.com:389/DC=blah,DC=wateva,DC=com"/>
Obviously I'm doing it wrong as this doesn't work. All I want to do is allow access to users that are a member of a certain group in AD.
A:
So I ended up implementing my own authorize attribute and using that:
namespace Application.Filters
{
public class AuthorizeADAttribute : AuthorizeAttribute
{
public string Groups { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (base.AuthorizeCore(httpContext))
{
/* Return true immediately if the authorization is not
locked down to any particular AD group */
if (String.IsNullOrEmpty(Groups))
return true;
// Get the AD groups
var groups = Groups.Split(',').ToList<string>();
// Verify that the user is in the given AD group (if any)
var context = new PrincipalContext(ContextType.Domain, "server");
var userPrincipal = UserPrincipal.FindByIdentity(context,
IdentityType.SamAccountName,
httpContext.User.Identity.Name);
foreach (var group in groups)
if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
return true;
}
return false;
}
}
}
And then I can simply use the following above controllers or functions
Using Application.Filters;
...
[AuthorizeAD(Groups = "groupname")]
NB: You could simply use new PrincipalContext(ContextType.Domain); however there is a bug in .NET 4.0 that throws a (0x80005000) error at userPrincpal.IsMemberOf(...). See here for details.
If you would like to know how to redirect to another page based on failed authorization, check my answer here: Adding an error message to the view model based on controller attribute in ASP.NET MVC
A:
It's no longer necessary to implement your own attribute for this functionality in ASP.NET MVC 3. The AspNetWindowsTokenRoleProvider works with Active Directory users and groups. To use this with AuthorizeAttribute you need to add the following to your web.config:
<authentication mode="Windows" />
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider"
applicationName="/" />
</providers>
</roleManager>
Then, on your controllers or action methods, you can refer to Active Directory Groups like so:
[Authorize(Roles = "YOURDOMAIN\\Group1, YOURDOMAIN\\Group2")]
|
[
"stackoverflow",
"0021316379.txt"
] | Q:
Android delete button
So I have an activity which has Table View inside a Scroll View.
I dynamically add rows to the table view. Each row has 2 stings and 2 integers queried from a database. I need to add a button on the row that deletes the entire row , and also delete the data from the database containing that row.
I Have set up the button , but I failed to write onClickListner to it. I do not know how to detect which of the buttons is to be pressed, and how to associate it with the corresponding row.
Any help greatly appreciated. Thanks !
This is the method which adds a row. Location object just holds the data fetched from the DB.
public void insertRow(Location l,int index){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = inflater.inflate(R.layout.row, null);
TextView textview = (TextView) newRow.findViewById(R.id.textViewLocation);
TextView textview2= (TextView) newRow.findViewById(R.id.coordinates);
textview2.setText(l.getLatitude() +" | "+ l.getLongitude());
textview.setText(l.getName());
//Button remove = (Button) newRow.findViewById(R.id.removeButtonLocation);
// remove.setOnClickListener(removeLocationListener);
// Add the new components for the location to the TableLayout
a.addView(newRow, index);
}
And the layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/locations_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/row0"
android:layout_gravity="center" />
<ScrollView
android:id="@+id/Locations_scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableLayout
android:id="@+id/stockTableScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/egg_shell" >
</TableLayout>
</ScrollView>
</LinearLayout>
A:
Okay, so let's start with your issues one at a time. You actually have the code there already, but it is commented out, let's look at it:
Button remove = (Button) newRow.findViewById(R.id.removeButtonLocation);
remove.setOnClickListener(removeLocationListener);
This says there is an object called removeLocationListener you haven't included that does the work. An OnClickListener defines just one function, onClick (View v). The View passed is the view in reference. So, you want to get the row associated with that view, and delete it. Let's first get the row:
public void onClick(View v) {
TableRow row=(TableRow) v.getParent();
}
Okay, so how do you remove the row now that you have it? It turns out you have to remove it from the layout above it. So let's do the same thing done before to get the view it's in:
public void onClick(View v) {
TableRow row=(TableRow) v.getParent();
TableLayout tl=(TableLayout) v.getParent();
tl.removeView(row);
}
Let's just define removeLocationListener somewhere:
OnClickListener removeLocationListener= new OnClickListener() {
@Override
public void onClick(View v) {
TableRow row=(TableRow) v.getParent();
TableLayout tl=(TableLayout) v.getParent();
tl.removeView(row);
}
};
BTW, you might want to look at a ListView, which is better suited for such things. You can even pass in a Cursor directly to it, which will make the whole thing a lot easier to manage.
|
[
"stackoverflow",
"0027297647.txt"
] | Q:
rspec capybara selector rails 4
I am trying to write an rspec test that will;
visit the store page
select a value in the Countries select box
and test that the value exists (initially in the Countries box but I would also be testing for cities which is dependent on Country in the second test)
HTML page
<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails Tutorial Sample App</title>
<link data-turbolinks-track="true" href="/assets/application.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/custom.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/password_resets.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/people.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/products.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/scaffolds.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/sessions.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/static_pages.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/store.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/users.css?body=1" media="all" rel="stylesheet" />
<script data-turbolinks-track="true" src="/assets/jquery.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/jquery_ujs.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/bootstrap.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/turbolinks.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/password_resets.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/people.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/products.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/sessions.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/static_pages.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/store.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/users.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/application.js?body=1"></script>
<meta content="authenticity_token" name="csrf-param" />
<meta content="NcsV3Ve7QqLTjeLNz5MLuCxzvG8urc63NiDk7RZTGtM=" name="csrf-token" />
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a href="/" id="logo">sample app</a>
<nav>
<ul class="nav btn-group navbar-nav navbar-right list-inline">
<li><a href="/">Home</a></li>
<li><a href="/help">Help</a></li>
<li><a href="/signin">Sign in</a></li>
</ul>
</div>
</ul>
</nav>
</div>
</div>
</header>
<div class="container">
<h2>some text</h2>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<form accept-charset="UTF-8" action="/store/show" method="get"><div style="display:none"><input name="utf8" type="hidden" value="✓" /></div>
<label for="catalogue_country">Country</label>
<select id="countries_select" name="catalogue[country_id]"><option selected="selected" value="1">France</option>
<option value="2">Italy</option>
<option value="3">United Kingdom</option></select>
<div class="pull-right">
<input class="btn brn-large btn-primary" name="commit" type="submit" value="Add to Cart" />
</form> </div>
</div>
</div>
</div>
</div>
<footer class="footer">
<small>
<a href="http://railstutorial.org/">Rails Tutorial</a>
by Michael Hartl
</small>
<nav>
<ul>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
<li><a href="http://news.railstutorial.org/">News</a></li>
</ul>
</nav>
</footer>
<pre class="debug_dump">--- !ruby/hash:ActionController::Parameters
controller: store
action: index
</pre>
</div>
</body>
</html>
My test
require 'spec_helper'
describe "index" do
subject { page }
before do
visit store_path
select "United Kingdom", :from => "catalogue[country_id]"
end
it { should have_select('country_id', :selected => 'United Kingdom') }
end
The failures
Failures:
1) index
Failure/Error: visit store_path
NoMethodError:
undefined method `id' for nil:NilClass
The rails console [app.store_path] verifies that store_path is '/store'
The select boxes are dynamically populated according to the directions in this blog posting
Any help is appreciated, thanks in advance
There are the routes
match '/store', to: 'store#index', as: :store, via: 'get'
get 'store/show'
match 'store/update_cities', to: 'store#update_cities', as: :update_cities, via: 'get'
match 'store/update_currencies', to: 'store#update_currencies', as: :update_currencies, via: 'get'
Its one index page (store_path) which has a countries select box.
This is the store controller
def index
@countries = Country.all
@cities = City.where("country_id = ?", Country.first.id)
@currencies = Currency.where("country_id = ?", Country.first.id)
@locations = Location.where("city_id = ?", Location.first.id)
@products = Product.where("Location_id = ?", Product.first.id)
@plugs = Plug.where("Location_id = ?", Plug.first.id)
end
def show
end
def update_cities
@cities = City.where("country_id = ?", params[:country_id])
respond_to do |format|
format.js
end
end
A:
Are you trying to visit a specific store, or listing all the stores ?
in your case you are trying to visit a specific store which you need to pass a parameter for it in this case the store id
To know the exact path write in the console:
rake routes
you will find each path to its url, if you want to list all the stores you need to write:
stores_path
instead of:
store_path
store_path is /store/:id
|
[
"stackoverflow",
"0037233740.txt"
] | Q:
How do I use padding if my string has odd number of characters in C?
I am using C as my programming language (not C++) and I am required to encrypt whatever the user types in using a 2-rail fence cipher method of coding in C, AND then pad whatever empty space there is left in the encrypted name with an 'x'. Because it's 2-rail fence the empty space happens if the output string has ODD number of characters!
Here is an example.
Let's say someone write this name: andredimera (all lowercase, no space). The name is 11 characters long. If padding with the x is done correctly, the encrypted name should give me this output WITH the padding -->
adeiea
nrdmrx
adeieanrdmrx
But I keep getting this output without the padding-->
adeiea
nrdmr
adeieanrdmr
This is FRUSTRATING! This has been a class quiz for almost a week now, I have not done well, and nobody has been able to help me out no thanks to my short-term memory. I would really appreciate this if someone can help me solve this, with an explanation on how you came up with the solution, so I can get it right in future endeavors. I don't want just the hint or explanation for me to go fish it out myself. I've had my share of it already this week. Thank you. I appreciate your help. :)
Oh, and here is my code:
UPDATED: Code was reposted because I was stupidly compiling it in a completely different solution. That code should work now.
Which now brings me to my latest question based on my updated code: how can I make my char pad = 'x' be added into my char str if the user input has odd number of characters?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char row, col;
char str[100][100];
char pad = 'x';
printf("****Welcome to The Caesar's Palace for Encrypted Names****");
printf("\n Please enter your name: ");
scanf("%s", str);
printf("You entered: %s\n", str);
printf("2-RAIL CIPHER ENCRYPTION:\n");
for (row = 0; row < 1; ++row)
{
for (col = 0; col < 12; col += 2)
{
printf("%c", str[row][col]);
}
printf("\n");
for (col = 0; col < 12; col += 2)
{
printf("%c", str[row][col + 1]);
}
}
printf("%c", pad);
printf("\n");
for (row = 0; row < 1; ++row)
{
for (col = 0; col < 12; col += 2)
{
printf("%c", str[row][col]);
}
for (col = 0; col < 12; col += 2)
{
printf("%c", str[row][col + 1]);
}
}
printf("\n");
printf("\n");
return 0;
}
A:
Here are what you need to do to fix your codes:
Step 1 Add a define hashtag and the include string library to the top of your code...
#include <string.h>
#define BUFFER_SIZE 100
Step 2 Replace these following members that you have...
char row, col;
char str[100][100];
char pad = 'x';
...to these ones
int col, size;
char str[BUFFER_SIZE];
Step 3: Right below your scanf, define your size with a strlen. Strlen calculates and returns to you the length of a string. Any string that you input. This is my strlen for your problem. Use it. ;)
size = strlen(str);
Step 4:
From 2-Rail cipher encryption till the last printf function, replace your code to the ones below.
for (col = 0; col < size; col += 2)
{
printf("%c", user[col]);
}
printf("\n");
for (col = 0; col < size; col += 2)
{
//printf("%c", user[col + 1]);
if (col + 1 != size)
printf("%c", user[col + 1]);
else
printf("x");
}
printf("\n");
for (col = 0; col < size; col += 2)
{
printf("%c", user[col]);
}
for (col = 0; col < size; col += 2)
{
if (col + 1 != size)
printf("%c", user[col + 1]);
else
printf("x");
}
In case you need explanation, your issue was simple, you had an extra row in your C-string that the program was not using. Additionally, you needed the strlen and an if function that basically says "if you've reached the end of the character string in an array of more than 100 characters, then print an x. If you did not have that code in the program would either print nothing (as stated in your issue) or print a zero.
But, keep in mind that if you type in a super long C-string name that is more than 100+ characters and you have the x padding at the end, it will cause some memory issue. Just food for thoughts.
But from now, do these steps and your codes should work with the output you wanted. (hopefully it should). This was my ouput.
adeiea
nrdmrx
adeieanrdmrx
|
[
"stackoverflow",
"0017114676.txt"
] | Q:
Checking if an item is contained in a ManyToManyField (django)
So I have a ManyToManyField relationship between Item1 and Item2. On a webpage, I want to display one of two messages based on whether the two items are connected or not. I'm just not sure how to query my exact item using the {% if %} template tag.
Roughly what I'm looking for is
{% if Item1 is connected to Item2 %} Display Message1
{% else %} Display Message2 {% endif %}
Any tips on how I'd get this done?
class Profile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=50)
eventList = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='event_set+')
def __unicode__(self):
return self.name
A:
It still not clear to me what object you want to see if connected to other but if you want to know if a user is in an specific event you can do it like this:
{% if event in user.eventList.all %}
Display Message1
{% else %}
Display Message2
{% endif %}
You can use operator in in if conditions in modern django versions.
Hope this helps!
|
[
"apple.stackexchange",
"0000302124.txt"
] | Q:
Setting static IP address
How do I set a static IP address on a iPhone 5s running iOS 11.0.3?
Have looked in Wi-Fi but could see nothing about setting static IP address.
Thanks
Elaine
A:
Settings → Wi-Fi, tap the i on the currently-connected network, choose Configure IP and set to Manual, then set the IP Address, Subnet Mask and Router.
|
[
"stackoverflow",
"0029860937.txt"
] | Q:
VS2013 MVC Debug: Chrome Doesn't Reflect Updated File
I was busily debugging an MVC4 app, written in C# under VS2013, using the Chrome debugger. Everything was working fine... until suddenly Chrome stopped reflecting updates to the view I was editing.
In other words, I'd change code in the view in VS2013 (while the server was running), flip over to Chrome, hit reload (or event Ctrl-F5)...and my changes were ignored.
I tried clearing the Chrome cache. No joy.
I tried rebooting the machine. No joy.
What the heck is going on? Feels like there's a cached version of the file someplace which didn't get deleted.
A:
You might want to read the post below:
http://www.asp.net/visual-studio/overview/2013/using-browser-link
The Browser Link controls are located in the dropdown with the circular arrow icon. The arrow icon is the Refresh button.
I have not tried this but according to the post, the Refresh button would reload your changes.
Hope it helps.
|
[
"stackoverflow",
"0024794344.txt"
] | Q:
2D area search and destroy algorithm
I am trying to write an algorithm for an AI bot to search a 2D rectangular grid for a stationary object to destroy. The bot is constrained by a set number of moves that will not allow it to reach every corner of the space. The bot is only able to sense walls and objects in the squares directly adjacent to it (N/S/E/W), though not diagonally. The size of the space is constant and known, but the starting point of the bot and object is unknown.
I want to search the room in the most effective manner to increase the likelihood of finding the object over a number of tests.
So far I figure if the bot moves in a straight line until it hits the nearest wall takes a step back and turns left and continues until it hits another wall. From there the bot should be able to take a step back and turn left again. Then follow the wall along and move back through the remainder of the room in a zig-zag fashion. (Let me know if that description of movement need clarification.)
Is there a more efficient way of moving through this space to find the object?
A:
You said the bot is constrained by a set number of moves that will not allow it to reach every corner of the space. In that case I would maybe suggest a "G" pattern.
I think the zig zag will "eventually" cover every tile, but it is also much more likely for it to re-scan the first few tile you begin with. Since you don't have unlimited moves, every extra tile you scan counts. What I meant by a "G" pattern, is that the robot starts in the middle of "G", hits a wall, and go around the room following the walls. I think that would minimize the chance of revisting the tiles you've already scan. After the "G" scan if you have extra moves then maybe you can zig-zag the remaining space in the inner-rectangle which you have full knnowledge of how big it is.
Also, keep the length/width of the room in your program after it hits the third wall so it knows when to turn early before hitting the 4th wall, saving a few moves to take 1 step back.
lastly, you shouldrecord where in the room you started and the initial path you've scan(you can calculate that once the first "G" is scanned). With that info, if you can determine if your initial path is on your side of the room or closer to the other side. If it is closer to your side where you first "G" scan ends, maybe take another "C" scan around it to reach the other side of the room before starting the zig-zag to minimize the chance of re-scanning the initial path before the moves end. The moves required for "C" and zig-zag should be the same.
|
[
"stackoverflow",
"0036442444.txt"
] | Q:
"gulp-sass": 2.1.1 - how to log errors at compile time
I'm using "gulp-sass": 2.1.1 to compile my project. I'm having some issues identifying where the missing files are from. Whats the best way to logout this error information. Is there a flag or something I can set whilst compiling?
Jimi
A:
Make sure you are using .on('error', ...) in your task:
gulp.task('sass', function () {
return gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
|
[
"stackoverflow",
"0005895128.txt"
] | Q:
Attempted to access an unloaded appdomain when using System.DirectoryServices
We've implemented a Membership Provider that authenticates to Active Directory and it's using System.DirectoryServices.
While using this Membership Provider in an ASP.Net MVC 3 application on Visual Studio 2010 with webdev server we sometimes (1 out of 6 times) get an exception when logging in the application.
System.IO.FileNotFoundException: Could not load file or assembly 'System.Web' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Web'
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(Int32 lnFormatType)
at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo()
at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName()
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p)
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper()
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups()
=== Pre-bind state information ===
LOG: DisplayName = System.Web (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: System.Web | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
Calling assembly : HibernatingRhinos.Profiler.Appender, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0774796e73ebf640.
The calling assembly was HibernatingRhinos.Profiler.Appender so after disabling the profiler in log4net config we got to the real exception:
System.AppDomainUnloadedException: Attempted to access an unloaded appdomain. (Except at System.StubHelpers.StubHelpers.InternalGetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis)
at System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis)
at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(Int32 lnFormatType)
at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo()
at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName()
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p)
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper()
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups()
The exception is always thrown at the same method, but for now we are not able to reproduce it as it happens randomly, but approximately 1 out of 6 times.
We do however not get the exception when using IIs instead of the built-in Visual Studio 2010 web server.
It probably has something to do with racing conditions when using multiple appdomains in the context of Visual Studio webdev, but that's just guessing.
We would really like to know what's the cause of the problem as we don't want to have these exceptions in a production environment.
We found 2 similar cases but no one has found a real solution:
http://our.umbraco.org/forum/developers/extending-umbraco/19581-Problem-with-custom-membership-and-role-provider
http://forums.asp.net/t/1556949.aspx/1
Update 18-05-2011
The smallest amount of code (in asp.net mvc) to reproduce the exception, where userName is your Active Directory loginname.
using System.DirectoryServices.AccountManagement;
using System.Web.Mvc;
namespace ADBug.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string userName = "nickvane";
var principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(
principalContext,
IdentityType.SamAccountName,
userName);
if (userPrincipal != null)
{
PrincipalSearchResult<Principal> list = userPrincipal.GetAuthorizationGroups();
}
return View();
}
}
}
Alas, the exception still happens at random, so no fully reproducable bug.
A:
Here is what works for me (.Net 4):
Instead of this:
principalContext = new PrincipalContext(ContextType.Domain)
create the principal context with the domain string as well:
E.g.
principalContext = new PrincipalContext(ContextType.Domain,"MYDOMAIN")
It should be fixed in 4.5. See comment, hasn't been fixed yet, but adding the second argument still works as workaround.
|
[
"stackoverflow",
"0022842215.txt"
] | Q:
Regular expressions working differently
Im testing on this website: Regex Tester
And I came up with this expression /[\w ]/ that does exactly what I want on that website, which is to select special characters.
BUT when I use it in my PHP file it isnt working.
In my PHP i have this function:
function removeSpecialChar($str) {
return str_replace("/[^\w ]/", "", $str);
}
For example lets say that $str="asdf1234 !"#¤asd"
It should return "asdf1234 asd" but it isnt, any ideas?
A:
Use preg_replace when you need the regex-based replacement. str_replace will treat the given string as is - without any special meaning given to metacharacters.
$str = 'asdf1234 !\"#¤asd';
function removeSpecialChar($str) {
return preg_replace('/[^\w ]/', '', $str);
}
echo removeSpecialChar($str); // asdf1234 asd
|
[
"stackoverflow",
"0024388528.txt"
] | Q:
Abaqus Python script to open several odb files by variable name
I have a txt-file called "odbList.txt" which contains the names of several odb-files.
plate_2mm.odb
plate_4mm.odb
plate_6mm.odb
Now I wrote a Python Script, where I want to open each of these files in a loop.
# list of ODB-Files
odbList = [ ]
f = file( 'W:/someDirectory/odbList.txt' , 'r')
count = 0
for line in f.readlines() :
odbList.append (line)
count = count + 1
def getSIF(case, i):
odb = openOdb(path = 'W:/someDirectory/' + case)
# start analyses for each case
for i in xrange(0,count):
getSIF(odbList[i], i)
I get the following error message:
OdbError: Cannot open file W:/someDirectory/plate_2mm.odb
. *** ERROR: No such file: W:/someDirectory/plate_2mm.odb
The weird thing however is that it works perfectly fine when I hardcode the complete path.
Another weird thing. If I use this line instead:
odb = openOdb(path = case)
I get following error message:
OdbError: Cannot open file C:/Temp/plate_2mm.odb
. *** ERROR: No such file: C:/Temp/plate_2mm.odb
And if I transfer all my files into C:/Temp everything works fine. But why doesn't it work if I use the first version / a different folder? Especially since it is working when hardcoded.
A:
Most of the times when I open a file I use the following:
f=open(file_name,'r')
s=f.read().splitlines()
f.close()
while '' in s:
s.remove('')
You will now have a list in s without enters.
Alternatively you can use something like
import os
odbList=[]
for fileN in os.listdir("."):
if '.odb' in fileN:
odbList.append(fileN)
This will find all files containing .odb in the name in the script's directory/working directory
|
[
"stackoverflow",
"0016061736.txt"
] | Q:
Recursive iteration over dynamically nested object array
I am using angular JS and one of their examples:http://jsfiddle.net/furf/EJGHX/
I need to take the data when the update function occurs and add some values to it before I send to the server. (If doing this with angular instead of js would be better let me know)
I'm trying to get the 'parentid' and the 'index' and update the children.
Here is the data I'm looping through
{
"children": [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "1",
"children": [{
"id": "10",
"index": "0",
"text": "Grandstream GXP-21XX"
}, {
"id": "11",
"index": "1",
"text": "Polycom Soundstation/Soundpoint"
}, {
"id": "23",
"index": "2",
"text": "New Polycom"
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0",
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2",
"children": [{
"id": "9",
"index": "0",
"text": "Sonicwall"
}, {
"id": "12",
"index": "1",
"text": "Cisco"
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0",
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0",
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": "1",
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1",
"children": []
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7",
"children": [{
"id": "16",
"index": "0",
"text": "Porting and New Number Details"
}, {
"id": "18",
"index": "1",
"text": "Partner Setup"
}, {
"id": "19",
"index": "2",
"text": "test"
}, {
"id": "21",
"index": "3",
"text": "test"
}]
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0",
"children": []
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1",
"children": []
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2",
"children": []
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11",
"children": []
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3",
"children": []
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "2",
"children": []
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14",
"children": []
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15",
"children": []
}]
}
This is how I'm currently looping through it, but it only gets the first dimension
for (i = 0, l = data.length; i < l; i++) {
parentid = data[i].id == null ? '0' : data[i].id;
data[i].index = i;
if (data[i].children) {
if (data[i].children.length > 0) {
for (q = 0, r = data[i].children.length; q < r; q++) {
data[i].children[q].parentid = parentid;
data[i].children[q].index = q;
}
}
}
}
I found this one on another fiddle, but I don't know how I would grab the parentid or the index
$.each(target.children, function(key, val) { recursiveFunction(key, val) });
function recursiveFunction(key, val) {
actualFunction(key, val);
var value = val['children'];
if (value instanceof Object) {
$.each(value, function(key, val) {
recursiveFunction(key, val)
});
}
}
function actualFunction(key, val) {}
A:
If I'm understanding you correctly, you want each 'child' to have a parentID (defined by its parent; 0 otherwise) and an index (based on its position within it sibling set).
function normalize(parent) {
if (parent && parent.children) {
for (var i = 0, l = parent.children.length; i < l; ++i) {
var child = parent.children[i];
child.index = i;
if (!child.parentId) child.parentId = parent.id || '0';
normalize(child);
}
}
}
normalize(data);
A:
Recursion is calling function inside the same function. Your sample is not a recursion at all;
function runRecursive(input) {
for (var i = 0, l = input.length; i < l; i++) {
var current = input[i];
parentid = current.id == null ? '0' : current.id;
current.index = i;
if (current.children && current.children.length > 0) {
runRecursive(current.children);
};
};
};
runRecursive(data.children);
Also you should define i and l with var keyword, otherwise it will be located in window context and recursion logic will broken.
Though I don't get what is parentid variable for and why it defined outside visible code.
|
[
"stackoverflow",
"0016459570.txt"
] | Q:
How to read a file into Vector of Doubles?
I have a name of a file (as a string), and that file contains certain amount (1000000, for example) double-precision floating-point values (stored as binary, 8 bytes for each, obviously).
What would be the best way to read those doubles into a vector?
A:
Here's how I did it in the end:
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.ByteString.Lazy as BS
import Data.Binary
import Data.Binary.Get
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce
readDoubles :: Int -> FilePath -> IO (V.Vector Double)
readDoubles n f = BS.readFile f >>= return . runGet (getVector n)
getVector :: Int -> Get (V.Vector Double)
{-# INLINE getVector #-}
getVector n = do
mv <- liftGet $ VM.new n
let fill i
| i < n = do
x <- fmap unsafeCoerce getWord64be
(unsafePerformIO $ VM.unsafeWrite mv i x) `seq` return ()
fill (i+1)
| otherwise = return ()
fill 0
liftGet $ V.unsafeFreeze mv
liftGet :: IO b -> Get b
liftGet = return . unsafePerformIO
|
[
"stackoverflow",
"0054897108.txt"
] | Q:
Git commit messages from pull request
How to get git commit message from a pull request, may be the request has more than one commits, how can I get these messages.
I know the command git log to get commit message, but I just want to show the relevant commit record for this pull request.
A:
Most code hosting platforms provide pull requests as a specially named ref. For example, on GitHub, pull requests are named pull/ID/head, where ID is the pull request number.
So if the main repository is named origin, you can check out the branch for pull request 123 by running git fetch origin pull/123/head:pr-123, which would create the branch pr-123. You can then run git log on it as normal.
If you're using GitLab or Bitbucket, they have similar configurations, but the names of the refs differ. You can consult the documentation for the platform you're using to see which refs they use.
Of course, these platforms also provide web interfaces you can use if you like.
|
[
"stackoverflow",
"0002638587.txt"
] | Q:
Accessible way to add form elements dynamically (jQuery)
I'm setting up a form in which multiple entries can potentially be made (via an Add more button) for one of the qestions. I'm trying to figure out the best way to make this accessible without javascript and also to allow the input fields to be shown dynamically each time the Add button is clicked. There are 3 pieces of data i need to collect for each entry, below is the basics of what the HTML will look like:
Type: <input name = "type[]" id = "type" />
Sub type: <input name = "subtype[]" id = "type" />
Number: <input name = "num[]" id = "type" />
I don't have a problem with the JS code required to create this content dynamically on each click of the Add button, but I am thinking that as it is reasonable to set a limit on the amount of rows a person could add (for this type of data, 10 entries would be the very maximum i would expect), I could just add ten empty fields to the HTML form. Then, my jQuery code would hide them on domready, then each time the Add button is clicked, it simply shows the next available empty field on the form (until it gets to the 10th, at which point the Add button is disabled).
Does this approach make any sense?
A:
Yes, you've described the usual progressive-enhancement way of handling dynamic rows.
You can always compromise as well: put n spare rows on the page as you describe so that a non-JS user can only add n rows at a time, but use JS to clone/add new rows as necessary so that JS users can add as many as they like.
(If the user can come back and add more rows afterwards, and it's not likely a non-JS user will want to add many rows at once, you can just make n=1 for the simple version: an empty row which is removed from the document by script and cloned back into the document as needed.)
|
[
"physics.stackexchange",
"0000281301.txt"
] | Q:
Is there a known isotope that generates anti-matter?
I heard that even a banana generates a minute quantity of antimatter. Does any know radioactive nuclear reaction produce antimatter along with alpha, beta and gamma radiation?
A:
Bananas are notorious for having high levels of potassium, though a quick Google will find plenty of other potassium rich foods. Anyhow, one of the common radioactive isotopes of potassium is potassium-40. This mostly decays by emission of an electron and anti-neutrino but rarely it can decay by emission of a positron i.e. anti-matter. So it is true that bananas emit minute quantities of anti-matter.
But ...
Bananas don't emit a net amount of antimatter because the electron is always paired with an anti-neutrino and the positron is always paired with a (not anti) neutrino. The number of particles emitted is always equal to the number of anti-particles emitted. This always true and is the result of conservation of lepton number.
A:
This is the chart of nuclides, i.e. the isotopes of all atoms.
The green color shows that most nuclei have isotopes decaying with beta+ decay, i.e. positrons. If you go to the link there is interactive information.
From this it is seen that everyday items which will always have a tiny percentage of the long lived isotopes will be decaying into positrons, the antiparticle of an electron.
Nuclides that have too many protons will decay with beta+
alpha, beta and gamma radiation
The "beta" in your question is both a beta+ and beta- , and yes the statement is correct.
The beta+ decay frees a positron into the environment of the nuclide.
$^\mathtt{A}_\mathtt{Z}X \rightarrow ^\mathtt{\hphantom{Z-}A}_\mathtt{Z-1}X' + e^+ + ν_e$
This decay is used in positron emission tomography, because the positron meeting an electron in the environment will annihilate into two photons and give medical information:
Positron emission tomography (PET)1 is a nuclear medicine, functional imaging technique that is used to observe metabolic processes in the body. The system detects pairs of gamma rays emitted indirectly by a positron-emitting radionuclide (tracer), which is introduced into the body on a biologically active molecule.
|
[
"stackoverflow",
"0008216410.txt"
] | Q:
Minimum javascript string value for use in backbone comparator
I want a minimum string value to use in my comparator. Assume that my validation prevents name from being the empty string.
This appears to be working correctly. Are there any values of "name" for which it will fail?
S.FileList = Backbone.Collection.extend
model: S.File
comparator: (file) ->
# We add display files alphabetically, but with meta.file at the top.
if file.get("name") == "meta.file"
return ""
return file.get("name")
A:
Assuming your validation prevents name from being the empty string, and enforces it being a string: Yes, this will work. "" < str where str is any string other than "".
Again, you've got to make sure that typeof name is 'string', because while
"" < "0"
is true,
"" < 0
is false.
|
[
"stackoverflow",
"0005996571.txt"
] | Q:
Android how do I set a percentage padding/margin so EditText has 10% margin on either side?
Does android support % or is there a way to approximate. I have two very different screen sizes and I but percentage-wise I want the EditBox in the activity to have same margin for both screen size as a proportion of screen size. How can this be done.
A:
It doesn't really support setting values by percent(except for some of the xml Animation files seem to) If you are dead set on using a percentage the best way I can think of is from java call getWidth and getHeight then multiply those by your decimal and set the result with setMargin(), or setPadding().
A:
This is possible in XML by wrapping your EditText inside of a LinearLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="10"
android:gravity="center"
>
<EditText
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="8"
/>
</LinearLayout>
A:
Edit: The Layouts from this answer are now deprecated. Use the solution that Eugene Brusov proposed. Also, thank you chancyWu for the comment.
There is now a better way that came out with support library version 23.0.0 (about time, right?). You can now use PercentFrameLayout or PercentRelativeLayout.
If you wanted the EditText to be 80% of the screen's width with a 10% margin on either side, the code would look like this:
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_height="wrap_content"
app:layout_widthPercent="80%"
app:layout_marginStartPercent="10%"
app:layout_marginEndPercent="10%"/>
</android.support.percent.PercentRelativeLayout>
You can also take a look at PercentLayoutHelper.PercentLayoutParams
|
[
"stackoverflow",
"0039868617.txt"
] | Q:
Is this a bad c++ object construction?
I've seen in a few places objects constructed as such:
Foo foo;
foo = *(new Foo());
In my opinion this is horribly wrong. The new operator allocates memory for Foo, then the pointer is dereferenced and used to copy the contents to the original and already constructed foo object. The memory allocated is leaked, as the pointer is lost.
Is this evil and should never ever be done or am I missing something?
A:
It's very very horrible, yes, but there's not a guaranteed memory leak.
That depends on the type Foo.
In practice there will never be a type where it's not a memory leak, but in principle one can define e.g.
struct Foo
{
std::unique_ptr<Foo> p;
void operator=( Foo& o ){ p.reset( &o ); }
};
I added the horrible incompatible-with-standard-containers void result type, just for good measure. :)
So, regarding
” the memory allocated is leaked, as the pointer is lost. Is this true or am I missing something?
… you're ¹only missing the case of the trainee who copies the above code directly from this SO answer and inserts it in the company's Big Application™, for some inexplicable reason.
Notes:
¹ Martin Matilla writes in a comment on the question: “I suppose this kind of initialization comes from Java/C# programmers trying to create new objects, noticing the compiler does not allow them to do so as foo is an object not a pointer, and adding the * so the compiler is happy.”, which is another possibility.
|
[
"electronics.stackexchange",
"0000461043.txt"
] | Q:
Does a robotic lawn mower sense that it is outside the perimeter wire? If so, how?
I have a robotic lawn mower. Sometimes if the grass is really slippery, the lawn mower can slide outside of the perimeter wire. When that happens, the lawn mower shuts down and I get a notification on my phone. The notification says that the mower is outside of its wire.
Does the lawn mower really have sensors that can distinguish whether the movwer is inside or outside the perimeter? Or does it only assume that it is outside, since it has crossed the perimeter wire once (and only once)?
How does the lawn mower know that it is outside of the perimeter wire?
A:
Expanding my comment into a tentative answer.
There is a low power radio transmission system called the "inductive loop" which uses a large loop of wire as an antenna. It provides good signal strength within the loop, and virtually none outside.
This allows induction loops to provide radio coverage e.g. within a building such as a concert hall or theatre or hospital with virtually no interference to other spectrum users outside the building. One common use is to help hearing aid users at the theatre.
But its characteristics are just about ideal for confining a robot within a space defined by a perimeter wire. Transmit a simple code at low power. If the robot loses the signal, it must stop. Simple as that.
Now I don't know if any specific lawnmower uses this system, but it's the most obvious candidate.
|
[
"stackoverflow",
"0008703738.txt"
] | Q:
Restoring an old manuscript with image processing
Say i have this old manuscript ..What am trying to do is making the manuscript such that all the characters present in it can be perfectly recognized what are the things i should keep in mind ?
While approaching such a problem any methods for the same?
Please help thank you
A:
Some graphics applications have macro recorders (e.g. Paint Shop Pro). They can record a sequence of operations applied to an image and store them as macro script. You can then run the macro in a batch process, in order to process all the images contained in a folder automatically. This might be a better option, than re-inventing the wheel.
I would start by playing around with the different functions manually, in order to see what they do to your image. There are an awful number of things you can try: Sharpening, smoothing and remove noise with a lot of different methods and options. You can work on the contrast in many different ways (stretch, gamma correction, expand, and so on).
In addition, if your image has a yellowish background, then working on the red or green channel alone would probably lead to better results, because then the blue channel has a bad contrast.
|
[
"stackoverflow",
"0038269248.txt"
] | Q:
Init custom UITableViewCell from nib without dequeueReusableCellWithIdentifier
SWIFT
I need to make an array of cells. I have few custom cell classes (inheritated from UITableViewCell) with nib files.
How to init cell without registering nib in tableview and doing dequeueReusableCellWithIdentifier?
I did it like this, but don't think, that it will work:
var labelCell = CustomCellClass.initialize()
A:
I'm inferring from the discussion in comments elsewhere that the reason you want to not allow cells to be dequeued and reused is that you're having trouble keeping track of user input captured in the cells.
The bottom line is that you really should allow the cells to be dequeued and reused and just handle that appropriately. If you're having problems with cells being reused, this can be resolved by separating the “model” (i.e. your data) from the “view” (i.e., the UIKit controls). This is the spirit of the model-view-controller pattern, but is true in any of those patterns that have separation of concerns (e.g., MVVP, MVP, etc.).
The key is that as values change in the cell, your cell should immediately tell the view controller so that the view controller can update the model immediately. Then, when the view controller needs to later do something with the value associated with a particular row, it doesn't retrieve it from the cell, but rather from its own model.
So, I might define a protocol for the cell to inform the table view that its text field changed:
protocol CustomCellDelegate: class {
func cell(_ cell: CustomCell, didUpdateTextField textField: UITextField)
}
And I'd then define a cell class that called that delegate:
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate?
@IBOutlet weak var customTextField: UITextField! // hook up outlet to this property in IB
@IBAction func didChangeValue(_ sender: UITextField) { // hook up "editing changed" action for the text field to this method in IB
delegate?.cell(self, didUpdateTextField: sender)
}
}
Now, the view controller will:
register the reuse identifier with the NIB in question;
in cellForRowAt, populate the text field and specify itself as the delegate for that cell; and
handle the didUpdateTextField method to update model if user changes anything.
Thus, something like:
class ViewController: UITableViewController {
var values = ["One", "Two", "Three"] // some initial values
private let cellIdentifier = "CustomCell"
override func viewDidLoad() {
super.viewDidLoad()
// if you’re using NIBs, you register them.
// obviously if using prototype cells in your storyboard, this isn’t necessary.
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) // or use cell prototype with storyboard identifer specified
}
}
// MARK: - UITableViewDataSource
extension ViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomCell
// populate cell and specify delegate
cell.delegate = self
cell.customTextField.text = values[indexPath.row]
return cell
}
}
// MARK: - CustomCellDelegate
extension ViewController: CustomCellDelegate {
func cell(_ cell: CustomCell, didUpdateTextField textField: UITextField) {
// when the cell tells us that its text field's value changed, update our own model
if let indexPath = tableView.indexPath(for: cell), let string = textField.text {
values[indexPath.row] = string
}
}
}
Many people might be inclined to simplify this further, by hooking the IBAction for the text field directly to a view controller method. That works, and eliminates the need for this protocol, but the problem is that you need to figure out with which row this particular UIKit control is associated. The common trick is to navigate up the view hierarchy to identify the appropriate cell (e.g. often the text field will be in a content view within the cell, so you grab textField.superview.superview as! UITableViewCell), but that feels a little fragile to me.
But regardless of this little detail, hopefully this illustrates the broader pattern. Rather than trying to have cells keep track of user input, you should have the cell (the “view”) update the controller of any data changes immediately, and the view controller then updates the model immediately, and you no longer need to worry about the cell reuse optimizations that iOS employs.
For Swift 2 renditions, see previous revision of this answer.
|
[
"stackoverflow",
"0011238471.txt"
] | Q:
A Simple pthread_create causing 100% CPU usage in Qt
When a simple Thread is run with just an infinite loop in it causing 100% CPU, how come is this possible?
My thread call is as follows on a QEvent in Qt dialog class, Say on a button click.
pthread_t thread_id;
pthread_create( &thread_id, NULL, DataCollectionThread, (void*) this );
And my thread procedure is,
void* DataCollectionThread( void* pParam )
{
((m_DataCollection*)pParam)->m_ReadDatafromport();
return NULL;
}
And this ReadData() contains...
while(1)
{
}
My requirement is collecting data from serial port and plot a graph continuously. But as the CPU usage is 100%, any hardware interrupt in between plotting cause the plotting to stall, as the CPU switches the task to handle interrupt.
I am calling this thread in a Qt::Dialog based class. I am pretty sure that nothing other than this is triggered. What's wrong with this? Does a simple infinite loop causes 100% CPU consumption eh? Or Is there any problem with using pthread_create in Qt?
EDIT:For Jonathon Reinhart
This is the actual while loop
while( 1 )
{
while(( Dataisavailable))
{
//push the read data to stack
}
if(!m_DataReadable)
break;
}
A:
One simple hack to get around this: Go to sleep for (short) periods to let the CPU do other stuff. #include <ctime> and add somewhere in your loop:
struct timespec ts;
ts.tv_sec=0;
ts.tv_nsec=10000000; // 10 milliseconds
nanosleep(&ts, NULL);
Of course, it would be better if you could explicitly sleep until you have actual work to do (more input to read, a full queue to trim). But adding in short sleeps will probably be sufficient.
It might make sense to look into your m_pDataProvider object's implementation. Check for or add a method allowing you to sleep until there's more data. If you're just reading from a character device (e.g. ttyS0), poll or select might be useful here.
|
[
"math.stackexchange",
"0000446164.txt"
] | Q:
Let $\sim $ be equivalence relation on $\mathbb N$ so there 4 different integers
Let $\sim $ be equivalence relation on $\mathbb N$ so there are $4$ different integers: $i,j,k,m$ that for all $n\in \mathbb N$ there's $t\in \{i,j,k,m\}$ such that $n \sim t$ then:
A. $1\leq \left | \left \{ \left [ n \right ]:n\in \mathbb{N} \right \} \right |\leq 4$
B. $\left | \left \{ \left [ n \right ]:n\in \mathbb{N} \right \} \right |=4$
C. $\left | \left \{ \left [ n \right ]:n\in \mathbb{N} \right \} \right |>5$
D. $0\leq \left | \left \{ \left [ n \right ]:n\in \mathbb{N} \right \} \right |\leq 4$
Can someone explain what to do here and how to get to the answer.
thank you!
A:
You are given an equivalence relation on $\Bbb N$, and you are told that there are four integers that any other integer is equivalent to at least one of those.
How many equivalence classes are there? I assume that you are supposed to mark the true statements. But for a correct answer on that you will have to ask your teachers.
HINT: Remember that if $a\sim b$ then $[a]=[b]$. This should get you a long way in the answers.
|
[
"serverfault",
"0000642954.txt"
] | Q:
How to make a domain receiving email behind cloudflare?
I have a web server hosting multiple domains (centos + postfix + dovcot), one of my domain its dns is hosted on cloudflare (ie. abcd.com), but when I use gmail to send email to a [email protected], [email protected] will not be able to receive the email. Here is the MX record I set in cloudflare:
Type Name Value TTL Active
mx mail handled by mail.abcd.com with priority10 Automatic
cname mail is an alias of abcd.com Automatic grey cloud
Any knows how can I make the domain receive the emails?
A:
You have two distinct errors in your configuration:
The MX record should be for your domain, not for a subdomain.
An MX record should not point to a CNAME. Point it to a record with an IP address.
An example of a working domain:
|
[
"stackoverflow",
"0042652941.txt"
] | Q:
How to save one plot for each variable contained in a matrix as a R element and with the variable name as element name? (With a loop)
I've tried this
fdist <- function(X) {
for(i in 1:ncol(X)){
print(i)
gg <- ggplot(X, aes(x=X[,i])) + stat_ecdf(geom = "step")
gg <- gg + labs(x=paste(names(X[,i])))
assign(paste(names(X[,i]), i, sep = ''), gg + labs(x = names(X[,i])))
end}
}
but at first I got all plots saved with the numeration as names, and now isn't even getting to save the plots as R elements.
Thanks for help.
A:
First, use a data frame. ggplot2 works much better with data frames.
df = as.data.frame(X)
Better to create your plots in a named list than as many separate objects. The creation can be simple using lapply like this:
plot_list = lapply(names(df), function(x) {
ggplot(df[x], aes_string(x = x)) +
stat_ecdf(geom = "step")
})
Looping/lapplying over the names means the default label will be correct. And use aes_string() instead of aes() when using a column name stored in a variable.
If you arent comfortable with lapply you can still use a for loop for the same result:
plot_list = list()
for (x in names(df)) {
plot_list[[x]] = ggplot(df[x], aes_string(x = x)) +
stat_ecdf(geom = "step")
}
|
[
"stackoverflow",
"0020092985.txt"
] | Q:
Extract response from facebook graphi api using ajax
I am trying to get the like count from facebook API. I am using the following ajax code to send the url with page name.
$("#get_like_count").click(function() {
$.ajax({
url:"https://graph.facebook.com/cocacola?fields=likes",
success: function(data) {
alert(data["likes"]);
}
});
});
I get the following response
{
"likes": 75968460,
"id": "40796308305"
}
Now, my question is how do I extract like and id values into a javascript variable? I tried to alert the data but nothing pops!
A:
You can use the JSON keys as object members, or through an array.
For example,
data {
"key1": "value1",
"key2": "value2"
}
You can access key1 and key2 as
data.key1
or
data['key1']
As an extension, you can assign them to JS variables
var value1 = data.key1;
var value2 = data['key2'];
Edit:
In context to your question,
var likes;
$.ajax({
//rest of the code remains the same
success: function(data) {
likes = data.likes;
console.log(likes);
}
});
|
[
"stackoverflow",
"0016621206.txt"
] | Q:
Utilising Python dictionaries
I have a program which writes a text file containing names and some queries. The first four lines start by defining a parental figure on left and their children after the colon; think of it as a family tree if you will. The exercise asks us to use dictionaries to help solve this problem.
This is how the file starts off..
test_file = open('relationships.txt', 'w')
test_file.write('''Sue: Chad, Brenda, Harris
Charlotte: Tim
Brenda: Freddy, Alice
Alice: John, Dick, Harry
mother Sue
mother Charlotte
mother Brenda
mother Dick
''')
test_file.close()
The output should be ..
Mother not known
Mother not known
Sue
Alice
I'm unsure on how to create this mother query that checks to see which mother the child belongs to. I've tried a few things such as..
parents = {}
for line in lines[0:4]:
parent, child = line.strip().split(':')
if parent in parents:
parents[parent] += str(child)
else:
parents[parent] = str(child)
print(parents)
I'm stuck at this point on how to then access and figure out whose mother is who. The only other way I can think of which is far less elegant would be to switch the key and value around to have a huge list of lines individually labelling every child's mother.
A:
You should keep a list of children, not a single string:
for line in lines[0:4]:
parent, child = line.strip().split(':')
if parent in parents:
parents[parent].append(child)
else:
parents[parent] = [child]
Now, you can iterate over the parents and just check for a particular child:
child = 'Peter'
for parent, children in parents.items():
if child in children:
print('Mother is', parent)
break
else:
print('Mother not known')
Building a dictionary that maps children to their parents would make the lookup faster.
A:
To actually address your question of using dictionaries:
parentchild_map = {}
for line in lines:
if ':' not in line:
continue
mother, multichildren = line.split(':')
children = multichildren.strip().split(', ')
parentchild_map[mother] = children
Then you can check for a match like this:
for parent, children in parentchild_map.items():
if child in children:
print ("Mother is ", parent)
break
else:
print ('Mother not known.')
(EDIT: added missing "break" in above code)
To make the lookup faster, you could generate a reverse dictionary ahead of time
reversemap = {}
for parent, children in parentchild_map.items():
for child in children:
reversemap[child] = parent
then you would be able to just go:
mother = reversemap.get(child)
if mother:
print ('Mother is ', mother)
else:
print ('Mother unknown.')
Whichever query algorithm you chose, the first or second one, I expect you would put it in a function accepting a 'child' parameter, so you could easily do as many queries as you want.
|
[
"stackoverflow",
"0031391591.txt"
] | Q:
Best way to divide elements in a dictionary by the sum of columns C#
I have a dictionary of ints:
Dictionary<string, int[]> ret = new Dictionary<string, int[]>();
int[] a = {1,2,3,4,5};
int[] b = { 3, 6, 9, 10, 12 };
int[] c = {2,3,3,5,6};
ret.Add("abc", a);
ret.Add("def", b);
ret.Add("ghi", c);
What is the best way to sum the values in each of the columns and then divide by the total? For example the first value would be 1/{1+3+2}
Here is what I tried but I think it sums by rows instead and it does not work because a type conversion error
public static Dictionary<string, double[]> freq(Dictionary<string, int[]> rawct)
{
Dictionary<string, double[]> scores = new Dictionary<string, double[]>();
foreach (KeyValuePair<string, int[]> kvp in rawct)
{
double[] percent = Array.ConvertAll(kvp.Value, x => (double)x);
var total = (double)kvp.Value.Sum();
var result = percent.Select(d => d / total);
scores.Add(kvp.Key, kvp.value);
}
return scores;
}
A:
If you want to divide by the columns, i think you can do this (assumming all arrays are of the same size, in this example, 5 itens):
Dictionary<string, double[]> scores = ret.ToDictionary(r=> r.Key,
r => r.Value.Select((v, index)=>
(double)v / ret.Values.Sum(values=> values[index]) // this is sum the columns
).ToArray());
Output:
abc
0,166666666666667
0,181818181818182
0,2
0,210526315789474
0,217391304347826
def
0,5
0,545454545454545
0,6
0,526315789473684
0,521739130434783
ghi
0,333333333333333
0,272727272727273
0,2
0,263157894736842
0,260869565217391
|
[
"stackoverflow",
"0001580534.txt"
] | Q:
how to know if between 2 date's it past 5 days - Oracle 10g?
I have two date's:
1) 01/05/2009
2) 06/05/2009
How can I know if there's 5 days between them?
A:
You can subtract two dates to get the difference in days between them (the unit for date columns in Oracle is 1 day).
In your example, I assume date is spelled in DD/MM/YYYY format. So you could do this:
select case when
abs(to_date('01/05/2009','DD/MM/YYYY') - to_date('06/05/2009','DD/MM/YYYY')) = 5
then 'YES'
else 'NO'
end as ARE_DATES_5_DAYS_APART
from
dual;
If the two dates are two columns in a table, then use table name instead of "dual" in query above.
|
[
"stackoverflow",
"0010481585.txt"
] | Q:
Closing WPF dialog box from contained UserControl
Hi I have a WPF application with various UserControls that contain key functionality. I want to be able to show say a FileManager UserControl in a tab on the main application, or have a dialog pop up when required, that contains the same UserControl.
It seemed like a good idea to create a modal Window and set its Content to the FileManager Usercontrol. But when I am finished with it, I am not sure how to close the containing Window, using a button on the UserControl. Is there an elegant way of doing this without having to store a reference to the Window in the UserControl?
Thanks for any advice!
A:
Create an Event which is called when the respective button on the user control is clicked. That way, the containing control can react to the event in the appropriate manner. For example, a dialog could just close itself.
A:
Is closing a window something that is integral to the functionality of the control in all the contexts where the control is hosted? E.g Does closing a window apply to the case where the control is hosted in a tab of the main app?
If not then you might be better off separating window closing code out of the UserControl in into the window/dialog that is hosting it - using events or whatever to tie the two together.
|
[
"stackoverflow",
"0006024279.txt"
] | Q:
django model serialization
I want to serialize models so:
class Schedule(models.Model):
Title = models.CharField(max_length=512)
class ScheduleEvent1(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
Description = models.TextField()
class ScheduleEvent2(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
AnotherField = models.TextField()
ShortDescription = models.TextField()
make smth like serializers.serialize('json', Schedule.objects.all())
The result likes
[
{
"pk": 2,
"model": "Schedule",
"fields": {
"Title": "Some Title",
"ScheduleEvent1": [
{
"pk": 19,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr",
}
},
{
"pk": 20,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr2222",
}
}
],
"ScheduleEvent2": [
{
"pk": 15,
"model": "ScheduleEvent2",
"fields": {
"AnotherField": "Some text",
"ShortDescription" : "Some text ...",
}
}
]
}
}
]
In general. I have entity tree. And I need serialize this tree from root.
tnx for help.
A:
http://docs.djangoproject.com/en/1.3/topics/serialization/#dependencies-during-serialization
Covers the essence of this. The resulting file is not precisely what's required, since the objects won't be nested. However it is what Django produces by default and it's what Django will use for deserialization.
If you use Piston you can easily define a Handler which will produce nested JSON, but it won't be precisely as shown because Piston's JSON emitter isn't precisely in the Django format.
Getting to precisely what's hoped-for leads to extending the Django serializer to produce a nested JSON object as the natural key. See http://code.djangoproject.com/browser/django/trunk/django/core/serializers/python.py. Lines 47-59
Or, you can define a natural_key method which uses Django's 'django.core.serializers.json .Serializer` to emit the JSON serialization of the object instead of some other natural key value. This is a little weird semantically, but it may do what you want.
|
[
"stackoverflow",
"0008160556.txt"
] | Q:
Looking for a technical overview of jQuery Mobile
I am implementing a mobile presentation of a website using jQuery Mobile. The JQM site provides a nice intro which includes features, accessibility concerns, and supported devices.
From the technical standpoint, I understand all of the events and when they fire, however, I'm a little fuzzy on what is actually happening under the hood. I believe there is more to it than meets the eye. I have found that it integrates well with RESTful oriented frameworks such as Rails and ASP.NET MVC, but does not do well with ASP.NET Web Forms.
Can anyone provide a brief overview of how it works including how, when, and why these additional events occur? The life-cycle of a page loading and a page transition, for example, would be very helpful.
A:
A really good overview http://www.ibm.com/developerworks/web/library/wa-jqmobile/
|
[
"stackoverflow",
"0043866744.txt"
] | Q:
Call toString() when convert String to Object
Here is my example code:
String str = "hello";
Object obj = (Object)str;
System.out.println(obj.toString());
I found the source code of Object, and the toString() method is:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
I thought the result of the example shound be the address of this Object, like [B@15db9742 , after I convert str to Object , but it still print hello. Why? Shoundn't obj use the method of Object? Can Anyone explain the principle of it to me?
A:
This is polymorphism (specifically, runtime polymorphism). It doesn't matter what the type of your reference to the object is (Object or String), as long as that type has toString (so your code compiles), the toString that will be used is the one the object itself actually has, not necessarily the one provided by the type of your reference. In this case, the object is a String no matter what the type of your reference to it is, so String#toString is used.
|
[
"stackoverflow",
"0006986553.txt"
] | Q:
How to reuse commonjs modules in the browser and server using modulr?
I'm using modulr for using commonjs modules in the browser.
The goal is to be able to reuse some of those modules also in a server environment.
These "shared" modules need to do something like this:
var _ = _ || require("underscore");
meaning:
if _ exists as a global var (browser environment), use it
else load the "underscore" module (server), and use it instead
Now, since modulr does static analysis in all the code, looking for the require calls in order to generate the final js file, it will fail the build.
Is there a way to work around this problem?
(For example, if modulr supported something like --ignore=<module_list> parameter, everything would run fine.)
A:
Apparently there's no way to fix this in modulr, so I had to create a workaround module named Env which looks like this:
// Env.js
var my = {
modules: undefined,
require: require
};
exports.override = function(modules) {
my.modules = modules;
};
exports.require = function(path) {
if (my.modules && my.modules[path]) {
return my.modules[path];
} else {
// my.require(...) is needed instead of simply require(...)
// because simply require(...) will cause a modulr parsing failure
return my.require(path);
}
};
And at the client side, have a specific initializer that does:
// ClientInitializer.js
Env = require('shared/Env');
Env.override({ underscore: _ });
So, the "shared" modules can do:
// SharedModule.js
var _ = require('shared/Env').require('underscore');
If the "shared" module is running in the server, the normal require function is called.
If it is running in the browser, the Env module will answer with the global _ variable.
|
[
"stackoverflow",
"0031114776.txt"
] | Q:
Button vs. Clickable Div in HTML
In HTML is it better to use a button or a clickable div?
Either way I'm going to use jQuery to handle the event of the click, but I'm wondering if there are advantages/disadvantages to using one over the other. Such as execution speed, loading speed, etc.
<button id="temp">Click</button>
vs.
<div id="temp">Click</div>
The code I'm using to handle the click event looks like this,
$("#temp").click(function(){
//Event details here
};
I understand that the button element is already pre-styled to look like a button and that (on windows) if you you press the enter key after a button has been selected (via click) the button will reactivate as if it were clicked again, but that is both of those factors aren't very important to me.
A:
<button> has some inbuild things that you may like, but also has some styling restrictions that not apply to <div>.
<button> can be focused, where <div> has to have tabindex attribute to make focus work.
Pressing it can submit a form if configurated for ex. has built in onclick handler: <button onclick="submit()">
Usage of <button> applies to HTML5 document specyfication which puts divs in place of containers elevating role of contextual elements like <footer>, <section> and <button>.
In short I always use <div>s as can style it how I need and program them how I like, am not fancying predefined behaviours as they can vary on different browsers :)
|
[
"stackoverflow",
"0046429149.txt"
] | Q:
Pass rails variable to ajax in javascript
I am new to rails. I am trying to use ajax and call a controller method. The controller method creates an instance variable which I presume is available to success callback in ajax.
However, whenever I run the code, JS console gives "test_array is null" error. Please suggest a solution and an insight into what is happening. The code is as follows.
I have thoroughly researched this issue on internet (including SO) but none of the answers seem to be fitting my problem.
sentiscores_controller.rb
def render_phrase
@tag_cloud_temp = [{text: 'Hello', weight: 1000},{text: 'World!', weight: 1100}]
end
index.html.erb
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = <%= raw @tag_cloud_temp.to_json%>;
console.log(test_array[0]['text']);
},
error: function(exception){
console.log("Error! : "+exception);
}
})
The actual html source code looks like the following
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = null;
console.log(test_array[0]['text']);
},
error: function(exception){console.log("Error! : "+exception);}
})
A:
In your controller, you'll want to render the JSON back to the AJAX call, like this:
# controller method
@tag_cloud_temp = [{text: 'Hello', weight: 1000},{text: 'World!', weight: 1100}]
render json: {
tag_cloud_temp: @tag_cloud_temp
}
Then, in your AJAX call, you'll want to recieve the data from that render, like this:
// in ajax call
success: function(data) {
console.log(data);
}
If you look at the data object, you should see the information from your controller.
|
[
"stackoverflow",
"0058734667.txt"
] | Q:
How do I make icon and text go beside each-other in an Ionic ion-segment-button using CSS?
I am trying the get an icon and text to go beside eachother in the ion segment button. I am trying to float the text left, but this is not working.
I am currently using the float one div method, are there any other methods that I can try?
this image is what I am currently getting in the view.
But I want to achieve something along the lines of this , where the text is beside the image.
HTML
<ion-toolbar style="width: 100% !important" color="medium">
<ion-segment (ionChange)= "segmentChanged()" [(ngModel)]="segment" color="dark">
<ion-segment-button value = "0">
<ion-icon id ="heart" name="heart"></ion-icon><p id="Wipped">Wipped</p>
</ion-segment-button>
<ion-segment-button value="1">
<ion-icon name="heart-half"></ion-icon><p id="Wipping">Wipping</p>
</ion-segment-button>
</ion-segment>
</ion-toolbar>
SCSS
ion-segment-button {
border: 1px solid black;
overflow: hidden !important;
}
#Wipped {
width: 300px !important;
float:left !important;
border: 1px solid red !important;
}
#heart {
border: 1px solid green !important;
overflow: hidden !important;
}
A:
try this :-
<ion-toolbar style="width: 100% !important" color="medium">
<ion-segment (ionChange)= "segmentChanged()" [(ngModel)]="segment" color="dark">
<ion-segment-button value = "0" layout="icon-start">
<ion-icon id ="heart" name="heart"></ion-icon><p id="Wipped">Wipped</p>
</ion-segment-button>
<ion-segment-button value="1" layout="icon-start">
<ion-icon name="heart-half"></ion-icon><p id="Wipping">Wipping</p>
</ion-segment-button>
</ion-segment>
</ion-toolbar>
add only ion-segment-button with layout="icon-start"
|
[
"stackoverflow",
"0005347614.txt"
] | Q:
C++ Copy Constructor invocation
Quick question. If I have an array and have properly overloaded the assignment operator, then when I do something like this:
A = B
When A and B are both objects of type array, am I calling the copy constructor, or just the overloaded assignment operator(=)?
I know that a copy constructor is called when
Pass By value
return a value of class type
when an object is being declared and initialized by another object of the same type given in parenthesis.
3 above makes me confused and thinking that A = B is also calling the copy constructor.
Is it just calling the overloaded assignment operator?
Thanks!
A:
None of the above: you cannot assign arrays.
If you have your own array class, and it has something like this:
struct arr
{
arr& operator=(const arr& other)
{
// ...
}
};
arr a, b;
Then these are equivalent:
a = b;
a.operator=(b);
It's just like calling a function.
A:
Since you've said the array is your own class with an overloaded assignment operator then you've already answered your own question.
The copy constructor is literally only called when you are constructing the object from another:
Obj a;
Obj b(a);
It might wind up being called by some sort of compiler magic if you do:
Obj a;
Obj b = a;
But I never bothered to actually look that up.
If you just do a = b you are not constructing a, therefore you'd not call the copy constructor.
Make sense?
|
[
"stackoverflow",
"0002214727.txt"
] | Q:
Why am I getting Debug assertion failed after strcpy_s?
im just starting to learn about sockets and i have been given this code, and i have to make the port lookup logic work. But the problem is i keep getting this run time error and I dont know why?
// portlookup.cpp
// Given a service name, this program displays the corresponding port number.
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>
using namespace std;
int main (int argc, char **argv)
{
char service[80]; // This string contains name of desired service
struct servent *pse; // pointer to service information entry
short port; // Port # (in Network Byte Order) of desired service
if (argc < 2)
{
cout << "Please specify a service." << endl;
}
strcpy_s(service, sizeof(service), argv[1]);
WORD wVersion = 0x0202;
WSADATA wsaData;
int iResult = WSAStartup(wVersion, &wsaData); // Returns zero if successful
if (iResult != 0) {
cout << "Insufficient resources to startup WINSOCK." << endl;
return 0;
}
port = htons( (u_short) atoi(service)); // 1st try to convert string to integer
if (port == 0) { // if that doesn't work, call service function
pse = getservbyname(service,NULL);
if (pse) {
port = pse->s_port;
}
else
{
cout << "Invalid service request." << endl;
return INVALID_SOCKET;
}
}
cout << "Service: " << service << endl;
cout << "Port: " << htons(port) << endl;
}
A:
Your problem appears to be that you aren't passing a command line, you check argc < 2, but when it is < 2 you execute the strcpy_s anyway.
In Visual Studio, Got to the Project Properties dialog, from there go to the Debugging page
and add the service name to Command Arguments
And fix your argument checking code
if (argc < 2)
{
//cout << "Please specify a service." << endl;
cerr << "error: no service specified." << endl;
return EXIT_FAILURE; // return some non-zero value to indicate failure.
}
|
[
"stackoverflow",
"0044840441.txt"
] | Q:
react-select-plus + search not working with comma
I am using react-select-plus control in react for drop down. I am refer this demo click here. and package is npm package. When I search any data using space that's work fine. example are below screen shot :
Now, My Issue is In data there are specific comma in that word then Isn't work.
example are below screen shot.
Now, my desire result is ignore comma in my search criteria and give me that data.
How, should I solve this.
A:
It's solved using filter option function in react-select-plus. The syntax is in ES 6/7 :
filterOptions = options => options;
|
[
"math.stackexchange",
"0000099986.txt"
] | Q:
Evaluating $\int y'(x) \cdot (y(x) +1)^2 \cdot dx$
I evaluate the following integral with pen and paper:
$$\int y'(x) \cdot (y(x) +1)^2 \cdot dx$$
And I get to the following result:
$$\frac{(y(x) + 1)^3}{3}+C$$
However, after that I went to WolframAlpha to check if my answer was right, I got the following result:
Which is pretty much what I got, but where does $\dots +y(x)^2+y(x)$ come from?
I do not understand that. I would appreciate it if somebody explains that to me.
A:
$(y(x)+1)^3=(y(x))^3+3(y(x))^2+3y(x)+1$
A:
It comes from expanding the cube $(y(x)+1)^3$ with the binomial formula: $(y(x)+1)^3=y(x)^3+3y(x)^2+3y(x)+1$; multiplying that by 1/3 gives the other answer, and the +1/3 added on at the end is swallowed up in the constant.
|
[
"stackoverflow",
"0037757148.txt"
] | Q:
Angular select doesn't work in .net webbrowser-control
Struggling trying to get Angular select working on a page inside a .net webbrowser control. I have set the registry value discussed here, Web browser control emulation issue (FEATURE_BROWSER_EMULATION), to no avail.
I have boiled my problem down to the below snippet, when the user chooses a option from the dropdown fakevalue does not change when the page is in the webcontrol, it works in regular IE and friends.
<select ng-model="fakeValue">
<option ng-value="166">166</option>
<option ng-value="167">167</option>
</select>
{{fakeValue}}
Any ideas, am I setting up the html incorrectly. Do I need another directive?
A:
Perhaps you are capturing & dissallowing the event in Excel somewhere?
|
[
"superuser",
"0001133040.txt"
] | Q:
Unable to boot into windows 10 with rEFInd (solved)
Edit: Solved, see below.
I just installed arch linux on my previously only windows 10 laptop. I have one ssd for arch linux and one for windows. I want to use rEFInd as my bootloader, which works perfectly for arch linux. I tried to set up a menu entry for windows following this tutorial. The problem is, I don't have \EFI\tools\shell.efi or fs0:\EFI\tools\launch_windows.nsh. My hunch is that because I have two ssds and I was previously only using the windows one, I have two ESPs so my windows .efi files don't exist on my arch linux ESP. Is this accurate? I tried digging through the partitions on my windows drive but I don't see any .efi files there either. Is it possible that windows was booting using BIOS and didn't create those files?
Edit: I had to reinstall windows in UEFI mode. I had it in legacy mode.
A:
rEFInd should automatically detect the Windows EFI boot loader and create a menu entry for it. If this isn't happening, then my hunch is that Windows is installed to an MBR disk in BIOS/CSM/legacy mode, not to a GPT disk in EFI/UEFI mode. You can check the partition table types of your disks like this (as root):
parted /dev/sda print | grep Table
Change /dev/sda for each of your disks (they're probably /dev/sda and /dev/sdb, but might be something more exotic). parted reports GPT disks as gpt, but uses msdos for MBR disks. If my hunch is correct, then the Linux disk will probably show up as GPT and the Windows disk as MBR.
If I'm right, you can try editing refind.conf (usually in /boot/efi/EFI/refind or /boot/EFI/refind): Uncomment the scanfor line and add hdbios to the options. This will tell rEFInd to activate its support for booting BIOS-mode OSes. You'll probably get one or two gray diamond-shaped icons when you boot, one of which should boot Windows. (If you get just one icon and it doesn't boot Windows, also try uncommenting the uefi_deep_legacy_scan option in refind.conf.) If you want to hide the non-functional Windows boot entry, you can do so with dont_scan_volumes, assuming you can find a unique part of the boot option's description to hide it.
As an alternative to all of this, or if rEFInd's BIOS-mode support doesn't work on your computer, you could convert Windows to boot in EFI mode rather than BIOS mode. This is riskier than adding BIOS-mode support to rEFInd's configuration, but it may boot a little faster and it will let Windows access EFI features. See this page for instructions on how to make this change.
If I'm wrong in my assumption that Windows is booting in BIOS mode, then something else is wrong -- perhaps a damaged filesystem on the ESP that holds the Windows boot loader or even a destroyed Windows boot loader. The necessary repair will depend on the exact nature of the problem. In this case, please run the Boot Info Script. This will generate a file called RESULTS.txt. Post that file to a pastebin site and post the URL to your document here.
|
[
"stackoverflow",
"0039063376.txt"
] | Q:
WPF opening a new window from an event
I'm trying to open a new window inside an event once it is triggered and im receiving: The calling thread must be STA, because many UI components require this.
Can anyone help me out ?
A:
Try to invoke your code from the dispatcher:
Application.Current.Dispatcher.Invoke((Action)delegate{
//your code
});
|
[
"android.stackexchange",
"0000033993.txt"
] | Q:
Using a fully charged Galaxy Note
Is it safe to use a Galaxy Note that is fully charged and at the same time it is plugged in to the wall socket? I'm worried that the battery might be charging and discharging at the same time and it will tremendously produce severe stress in the battery. Thus it will shorten the lifespan of the battery.
A:
Yup, It is perfectly fine. I do it regularly while playing games.
|
[
"ru.stackoverflow",
"0000869129.txt"
] | Q:
Python, мутация, неверный результат
Функция modify_list(l), которая должна принимать на вход список целых чисел, удалять из него все нечётные значения, а чётные нацело делить на два. Где ошибка?
l = [1, 2, 3, 4, 5, 6, 8, 20]
def modify_list(l):
count = 0
for i in l:
if i%2 == 0:
x = i//2
l.pop(count)
l.insert(count,x)
count+=1
else:
l.pop(count)
modify_list(l)
print(l)
Мой неверный результат работы программы:
[4, 10, 6, 8, 20]
A:
Ваша ошибка в том, что вы, изменяя длину списка, пытаетесь "на лету" вставлять элементы по старым (до удаления) индексам.
Чуть более идиоматичный вариант решения:
l[:] = [x//2 for x in l if x % 2 == 0]
результат:
[1, 2, 3, 4, 10]
|
[
"stackoverflow",
"0014119280.txt"
] | Q:
mysql where 10 < id < 20
i am going to select some certain ids from db. my logic is this: depending on hour, i am selecting some certain items like this, because the job is running in cronjob, and it runs every *:31 minutes, so every hour, this is my logic:
pseudo code:
get hour // 08:30
take 08 and mult(08,10); // 80
get items from db whose ids lie between 80 < id < 90
how can i do this query in mysql? this 80 < id < 90 condition i need in mysql in php
A:
You can use the keyword between
select * from tableName where id between 80 AND 90
|
[
"stackoverflow",
"0048166577.txt"
] | Q:
NavigationIcon click not working in ActionBar
In my actvity, I created a ActionBar, used a back icon, its showing in the app, but on clicking back icon nothing is happening, didn't got the function onnavigationiconclick event working also, below is my code, kindly assist so that on clicking the back icon user can be send to MainActivity --
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab1gridlatestvideos);
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Latest Videos");
}
A:
Inside your activity
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
|
[
"serverfault",
"0000182983.txt"
] | Q:
Massive CPU usage spike, How do I find out what causes it?
I have a server running CentOS Linux, and very rarely (maybe once every 3 months) something happens that causes it to have an exceptionally high CPU load (400%) that causes the server to basically freeze up.
The problem I have is that when I reboot the server, I can't figure out what caused the spike. I tried setting up a cron job to occasionally dump to a log file the top 10 CPU processes, but when the CPU load is high the cron job apparently won't run either.
I'm sort of new to running a server, so I'm hoping you guys might have some advice on how I could better log the processes and figure out what's causing the sudden spike the next time it happens. I'm sure it's just a script or process that goes out of control, but until I can figure out which one it is I'm sort of at a loss...
Thanks for any help you can provide!
A:
Not strictly speaking an answer to your question, but check out monit. You can configure it to monitor all kinds of stuff, including global system stats. For example, if cpu usage is over 97% for 3 minutes, my servers will reboot. If apache uses >80% cpu for 5 minutes, it gets restarted, and so on. It's an incredibly useful piece of software and has me sleeping much, much easier at nights. :-)
A:
How often did you run that logging cronjob? Maybe you should run it more often, because CPU usage doesn't peak instantly, you have to see an increase somewhere. Alternatively, you could use atop to monitor resource load (including CPU load) overtime.
|
[
"stackoverflow",
"0047486928.txt"
] | Q:
How does one control if allocated memory is stored in L1,L2, L3 cache or other in JavaScript?
Speeds of L1 cache are faster than L2 and so on and so forth. How does one control where the memory is allocated to In JavaScript? How does one see where the memory is being allocated to?
I understand is most likely not possible. I'm asking the question in this manner to avoid a boolean question.
A:
One does not control memory allocation in JavaScript.
Also, caches are supposed to be transparent, they are automatically managed by the hardware. You just allocate RAM, not specific cache memory, and when you use it it will get cached. You'd have a very hard time to manually control this, even in lower-level languages.
|
[
"stackoverflow",
"0018491560.txt"
] | Q:
PrimeFaces FileUpload Filter ClassNotFound Exception
I am getting an error while running a JSF project. Here is the error log;
org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter PrimeFaces FileUpload Filter
java.lang.ClassNotFoundException: org.primefaces.webapp.filter.FileUploadFilter
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:527)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:509)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:137)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
org.apache.catalina.core.StandardContext startInternal
SEVERE: Error filterStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Project] startup failed due to previous errors
I've already created a user library added commons-fileupload-1.3.jar and commons-io-2.4.jar files but I'm still gettin the error. Any ideas?
A:
I gather that you mean the Eclipse-specific user library management when you said "user library" there. I also gather that you've PrimeFaces already installed, otherwise this is food for Mr. Obvious. Its FileUploadFilter will indeed fail to initialize like that if Commons FileUpload and/or Commons IO are absent. You should see a NoClassDefFoundError further in the stack trace.
Just creating a new "user library" and adding to Build Path of project's properties is not exactly the right way. They also need to end up in /WEB-INF/lib of the built WAR. Usually, you'd need to add the user library in Deployment Assembly section of project's properties as well. However, this whole process is unnecessarily clumsy. Just drop those two JAR files in /WEB-INF/lib folder of dynamic web project. Eclipse will then automatically do all the necessary magic. You don't need to fiddle in project's properties. To avoid conflicts, undo all those changes which you ever made in Build Path.
|
[
"stackoverflow",
"0042875601.txt"
] | Q:
PhpStorm shows button which jumps to function
Does anyone knows how to remove this button?
When I hover it shows "Function". Clicking right selects the method the cursor is located at.
I already disabled all plugins but still showing.
A:
Settings/Preferences
Editor | General | Appearance
Uncheck Show breadcrumbs option
NOTE: It will remove it for all supported languages (e.g. HTML/XML/CSS/etc) and not just PHP.
|
[
"stackoverflow",
"0013899295.txt"
] | Q:
Passing a string and use it in cursor query
My main activity passes a string to another activity (let's just call it sub activity). In this sub activity, I need to use that string in a cursor raw query to select data from the database that matches the string.
public class RestaurantsInfo extends ListActivity {
static final String restaurantListTable = "RestaurantList";
static final String colRestaurantID = "RestaurantID";
static final String colRestaurantName = "RestaurantName";
static final String colRestaurantStore = "StoreNo";
static final String colRestaurantAddress = "StoreAddress";
public String strRestaurantName;
RestaurantDB db = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
db=new RestaurantDB(RestaurantsInfo.this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String strRestaurantName = extras.getString("RestaurantName");
setTitle(strRestaurantName);
getData();
}
private Cursor doQuery(String strRestaurantName) {
return(db.getReadableDatabase().rawQuery("SELECT "+colRestaurantID+" AS _id, "+colRestaurantName+", "+colRestaurantStore+", "+colRestaurantAddress+
" FROM "+restaurantListTable+" WHERE "+colRestaurantName+" = strRestaurantName ORDER BY "+colRestaurantStore+"", null));
}
public void getData() {
SimpleCursorAdapter adapter;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
adapter=new SimpleCursorAdapter(this, R.layout.activity_address,
doQuery(strRestaurantName), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore,
RestaurantDB.colRestaurantAddress },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3 },
0);
}
else {
adapter=new SimpleCursorAdapter(this, R.layout.activity_address,
doQuery(strRestaurantName), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore,
RestaurantDB.colRestaurantAddress },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
}
setListAdapter(adapter);
}
}
As you can see from the codes, I try to pass the string strRestaurantName and use it in WHERE in the query, but it just doesn't work! The log file says "no such column as strRestaurantName" but I don't mean it as a column. I tried doQuery() instead of doQuery(strRestaurantName), but it gave the same error too. What should I do?
A:
You must wrap SQL Strings in quotes:
"WHERE "+colRestaurantName+" = '" + strRestaurantName + "'"
(I had this backwards at one point, sorry).
Though really you should use parametrization to prevent SQL injection attacks. As in:
return(db.getReadableDatabase().rawQuery(
"SELECT "+colRestaurantID+" AS _id, "+colRestaurantName+", "+colRestaurantStore+", "+colRestaurantAddress+
" FROM "+restaurantListTable+
" WHERE "+colRestaurantStore+" = ?" +
" ORDER BY "+colRestaurantStore,
new String[] {strRestaurantName}));
It seems that my private doQuery() can't retrieve the value of strRestaurantName when the intent and bundles are placed inside onCreate().
You have accidentally created two variables named strRestaurantName... You have the field variable and a local variable in onCreate(). Change this line:
String strRestaurantName = extras.getString("RestaurantName");
To this:
strRestaurantName = extras.getString("RestaurantName");
Now you will only have one strRestaurantName and it will have the appropriate value in doQuery().
|
[
"stackoverflow",
"0017853819.txt"
] | Q:
NoReverseMatch Reverse for '' with arguments '()' and keyword arguments '' not found
I have this in a django view:
edit_url = reverse('ventas:clientes_edit',kwargs={'id':str(self.object.id)})
And this in urls.py:
url(r'^clientes/edit/(?P<pk>\d+)$',forms.ClienteUpdateView.as_view(), name="clientes_edit"),
When I create a new customer via ajax I need to return a reverse url with the id in a JSON data to put in a series of actions buttons for edit, delete... but always I get this error and I don't know how to accomplish it, this the complete error:
NoReverseMatch at /ventas/clientes/add/
Reverse for 'clientes_edit' with arguments '()' and keyword arguments '{'id': '38'}' not found.
Any ideas?
Edit:
The Django version is 1.5
A:
The kwargs should pass the pk not id to match the url
edit_url = reverse('ventas:clientes_edit',kwargs={'pk':self.object.id})
also your url expects an int pk not string.
|
[
"stackoverflow",
"0031928678.txt"
] | Q:
XPages Links: can we compute wether to add parameter or not?
I have a form where users can create "links" in a side box. These links can refer to a document Inside the database or to an external site.
For "internal" links, I am adding a parameter so I can track the click from the side box (needed for stats), but I don't want to add that parameter for external URLs.
I tried computing the param in the properties, but the link is still built adding "/?=" at the end of the URL. Not a big deal, but I'd rather make it clean and just don't add the param part for external URLs.
I can't use the "loaded" property as this param is computed for each link in a repeat control, and I am using a view column in that computation.
Thanks :D
A:
If you don't have a pager, you can set repeatControler="true" on the repeat and then use the loaded property.
Otherwise you should be able to compute the link, as I do in this Data View, using "Custom language" - combining literal strings and SSJS.
|
[
"japanese.stackexchange",
"0000072067.txt"
] | Q:
What does こんな mean in the following sentence?
Please allow to establish the context.
There is 1990 roleplaying video game titled “Illumina!” (Japanese title: イルミナ!), which is one of Cocktail Soft's products.
In the game, there is an evil necromancer named Rasuneti (Japanese name: ラスネティ). As the game goes on, she becomes a threat to the protagonist. Their confrontation finally ends with the protagonist running his sword through her heart. At that point, she says the following:
ば…ばかな…私が…こんな…
I think the translation goes something like this:
Ab...absurd...I am...like this...
I know that こんな usually means “such” or “like this”, but when I see the word being used like this in Japanese media, I keep getting the feeling that it is being used to mean something else.
Am I on the right track? What does it mean in that context?
Thanks in advance.
A:
I think when used like that there is usually something not said, like in this case it could be こんなことあり得ない, "It's not possible something like this [to be defeated by the hero]", or 私がこんなふうに殺された, "Ab... absurd... me being killed like this...".
|
[
"serverfault",
"0000562843.txt"
] | Q:
DNSSEC and IPSec DNS Server and DNS Client Configuration
I'm about to deploy DNSSEC for some of my domains and as I was getting ready I did some reading on the subject. I came across some Microsoft Technet articles talking about Name Resolution Policy Table which allows one to configure Windows DNS clients to use IPSec when communicating with the DNS server to provide integrity and (optionally) authentication.
This seems like a pretty good idea from where I am sitting but alas the NRPT is a Windows only thing. Is there an equivalent in the Linux / OpenBSD world? Having both DNSSEC and IPSec in combination would seem to be the perfect solution for security concious server admins.
A:
This whole NRPT thing sounds like a way to bring DNSSEC somewhat in line with DNSCurve, except that instead of having a single standard and spec like it is the case with DNSCurve itself, they're simply throwing up a bunch of unrelated ones together into a big administration and configuration mess.
Deploying DNSSEC for recursive and authoritative servers are two completely different tasks.
What exactly are you trying to accomplish? In the Linux and BSD world, if you simply want to ensure that DNSSEC verification/validation is taking place, best way to go about it is to run your own local recursive or caching resolver. For some details of how it's done, take a look at the recent changes that were made to the upcoming FreeBSD 10, where they've introduced unbound to base tree, which, when used correctly (e.g. if it's set as the only available resolver), is not supposed to resolve any domain names which have DNSSEC enabled, but have records that are not signed correctly, but which were supposed to have been signed.
As far as authoritative servers go, if you want some extra security and privacy, your best bet is to run DNSCurve as a front-end, and possibly still have DNSSEC in the backend, if needed.
I guess for recursive DNS, you'd be doing exactly the same thing, but the other way around: maybe configure a local unbound to be a caching/verification resolver, which would issue all of its queries through a local DNSCurve-aware recursive resolver, but never otherwise.
However, in both of the above examples, I think you're pretty much stepping into an uncharted territory.
|
[
"stackoverflow",
"0003625920.txt"
] | Q:
Making a web page as a default page for the server name where the application is hosted
Suppose I have a server wid some virtual name as ABC. And also I have a .Net web application XYZ with some .aspx pages like Home.aspx etc.
Now if I want to make Home.aspx page as the default page when I type the server name in brower the Home.aspx opens automatically. what I need to do in this case.
Currently Iam accessing the application with this URL
https://ABC/XYZ/Home.aspx
But I want to access the application in this way:
http://ABC
A:
I'm not sure in which version of iis you are working, but in the iis 7 manager:
Select the site that responds to the url / which could be "default web site" depending on your set up
Open the "Default Document" option
Select the Add action and enter Home.aspx. If you already see it in the list, you might need to move it up if something else is taking preference (select Home.aspx, and on the right hit the move up action)
In previous IIS versions just do the same but from the properties of the site.
A:
There is not a way in IIS to get:
https://ABC/XYZ/Home.aspx
to point to:
https://ABC
because XYZ/Home.aspx is not a valid "default document". Default documents must be in the same folder.
If you are trying to get:
https://ABC/XYZ/Home.aspx
to point to:
https://ABC/XYZ
then see eglasius's answer.
Otherwise, you will need to set Default.aspx as the default document.
Then create a file Default.aspx in your website root folder containing:
<%@ page language="C#" %>
<%
Server.Transfer("/XYZ/Home.aspx");
%>
|
[
"stackoverflow",
"0034887297.txt"
] | Q:
Javascript: converting binary data in Uint8Array to string corrupting file
I'm trying to upload a video file in chunks to a server via a standard jQuery $.ajax call. The process is simple:
Use the slice() method on the file object to read a chunk
Use FileReader.readAsArrayBuffer to read the resulting blob
Create a Uint8Array of that result in the FileReader.onload callback
Use String.fromCharCode.apply(null, intArrayName) to convert it into a binary string
Upload that binary string as a chunk in the AJAX call's data property
When I finish uploading all the chunks, the server's API complains that the file upload is incomplete. To test this method, I converted the concatenated binary strings into a Blob and had Chrome save it to my downloads folder, only to find out my media player said the file was unplayable.
I've read posts on this site and other articles suggesting that directly converting binary data represented by integers to strings results in a loss of data, and that the suggestion is convert it to a base64-encoded string, since Javascript doesn't have a StreamContent object like C# does.
The problem is that even if I set Content-Transfer-Encoding to base64 I don't think the API (which wasn't written by us) picks up on it and can tell that a base64 decoding is needed.
My question is: is this the only sure-fire way of sending video data over an AJAX call safely? If not, how else can I send it in the data field of my AJAX request? There are probably thousands of uploaders like this on the Internet but nowhere can I find solid documentation on how to do this. If it turns out that the server needs to expect base64 encoding, we might have to write a middle-man API to do this decoding for us.
A:
Thanks to Patrick Evans, it turns out all I needed to do was upload the blob itself:
function upload(file) {
var offset = 0; // what's been sent already
var fileSize = file.size;
var chunkSize = 64 * 1024; // bytes
while (offset < fileSize) {
var blob = file.slice(offset, chunkSize + offset);
var urlToUse = ((offset + blob.size) >= fileSize) ? videoFinishBaseUrl : videoContinueBaseUrl;
$.ajax({
url: urlToUse,
method: 'POST',
data: blob,
headers: requestHeaders,
contentType: false,
processData: false,
cache: false,
async: false,
success: function(data) {
jQuery('#uploadmsg').text('Finished offset ' + offset);
offset += blob.size;
},
error: function(err) {
jQuery('#uploadmsg').text(err);
}
});
}
};
|
[
"stackoverflow",
"0045425754.txt"
] | Q:
Regex find text between tags in files
I am trying to find in alley files using a regex search in WebStorm. I have 2 scenarios.
Scenario 1: text inside html tag
<p>testing</p>
Scenario 2: dynamic text inside {{ and }} inside html text
<p>{{testing}}<p>
I was able to find text between html tags using below regex for Scenario 1
>(.*?)</
I am trying to find only places with scenario 1 and not with scenario 2. I mean I want to see all the hard coded text between html tags and not any text between {{ and }}. Any suggestion or pointer?
A:
Have you tried using regexr.com?
Edit
How is this:
>(\w+)</
|
[
"stackoverflow",
"0039141163.txt"
] | Q:
Null Validation for list?
I am attempting to add validation for my ArrayList if it is null, below is my current implementation:
List<Person> personList = new ArrayList<>():
if(personList!=null){
//do something
}
However, this still throws an exception If the list is deemed to be null, how can I fix this?
A:
check (personList!= null) && !personList.isEmpty() in your code.
if((personList!= null) && !personList.isEmpty())
//do something
}
now it will never throw null pointer exception.
|
[
"stackoverflow",
"0058572641.txt"
] | Q:
running LinearRegression model using scikit-learn with different pandas dataframe (loop question)
I have a dataframe with cost, wind, solar and hour of day and like to use the linear regression model from scikit-learn to find the how wind and solar impact the cost. I have labelled each hour with P1-P24 (24 hour a day) i.e. each row depending on the hour of the day will be assigned with a P(1-24)
Therefore i have defined each corresponding row of wind/solar/cost to different dataframe according to the hour of the day
The code runs okay with everything i wanted to do. However I struggle to build a for loop code run repeatedly for every hour to find the linreg.intercept, linreg.coef and np.sqrt(metrics.mean_squared_error(y_test, y_pred) function from scikit-learn on various panda dataframe (P1 to P24).
So at the moment i have to manually change the P number 24 times to find the corresponding intercept/coefficient/mean squared error for each hour
I have some code below for the work but i always struggle to build for loop
I tried to build the for loop using for i in [P1,P2...] but the dataframe became a list and i also struggle to incorporate it to the scikit-learn part
b is the original dataframe with columns: cost, Period (half hourly, therefore i have period 1 to 48), wind, solar
import dataframe
b = pd.read_csv('/Users/Downloads/cost_latest.csv')
To put it into hourly therefore:
P1 = b[b['Period'].isin(['01','02'])]
P2 = b[b['Period'].isin(['03','04'])]...
the scikit-learn part:
feature_cols = ['wind','Solar']
X = P1[feature_cols]
y = P1['Price']
and here is my issue, i need to change the P1 to P2...P24 before running the following codes to get my parameters
the following are the scikit-learn part:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
fit the model to the training data (learn the coefficients)
linreg.fit(X_train, y_train)
print(linreg.intercept_)
print(linreg.coef_)
list(zip(feature_cols, linreg.coef_))
y_pred = linreg.predict(X_test)
from sklearn import metrics
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
I think there is a smarter way to avoid me manually editing the following (P value) and running everything in one go, i welcome your advice, suggestions
thanks
X = P1[feature_cols]
y = P1['Price']
A:
Just use this:
for P in [P1,P2, P3,P4,P5,P6,P7]:
X = P[feature_cols]
y = P['Price']
All together:
from sklearn import metrics
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
all_intercepts = []
all_coefs = []
for P in [P1,P2, P3,P4,P5,P6,P7]:
X = P[feature_cols]
y = P['Price']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
linreg = LinearRegression()
linreg.fit(X_train, y_train)
print(linreg.intercept_)
print(linreg.coef_)
list(zip(feature_cols, linreg.coef_))
y_pred = linreg.predict(X_test)
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
all_intercepts.append(linreg.intercept_)
all_coefs.append(linreg.coef_)
print(all_intercepts)
print(all_coefs)
P will be your dataframes P1,P2,... according to each iteration
|
[
"stackoverflow",
"0023569073.txt"
] | Q:
Button OnClick Fires When Enter Key Is Pressed In Input Text Field In IE
I have a couple of input textboxes on my webpage for searching:
<input type="text" id="mfrText" name="MfrSearchText" value='@ViewBag.SearchAndSort.MfrSearchText' />
<input type="text" id="partText" name="PartNoSearchText" value="@ViewBag.SearchAndSort.PartNoSearchText" /> </
<input type="text" id="descText" name="DescriptionSearchText" value="@ViewBag.SearchAndSort.DescriptionSearchText" />
I have a button that has a click event to show a dialog box.
<button class="btnAdd btn-xs">Add</button>
The issue I have is when the enter key is hit and one of the input fields has the focus, the button onclick event is fired and the dialog box is displayed. I have tried e.preventDefault() and I have also tried checking if the enter key was pressed instead of a mouse click with no luck. This happens in IE but not in Chrome. How do I prevent this behavior ?
My click event:
$(".btnAdd").click(function (e) {
alert($(".btnAdd").is(":focus"));
var partID = $(this).closest('tr').attr('id');
$("#divAdd").dialog({
modal: true,
title: 'Increase Qty',
buttons: {
"Save": function () {
var qty = $("#addQtyAdd").val();
var clockNo = $("#addClockNo").val();
var asset = $("#addAssetNo").val();
AddPart(partID, qty, clockNo, asset);
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$(".ui-dialog-title").css("color", "lightgreen");
});
A:
That is desired/intended behaviour.
Try:
<button type="button" class="btnAdd btn-xs">Add</button>
This will stop the button from being seen as a submit control, and will be ignored by Enter keypresses.
|
[
"ja.stackoverflow",
"0000004487.txt"
] | Q:
Primefaces の DataExporter による PDF 出力で日本語を出力する
PrimeFaces の DataExporterで PDF を出力すると日本語が表示されません。
以下のような対応を実施してみましたが、解決できていません。
iTextAsian.jar をプロジェクトに組み込み
primefaces-extensions の exporter を利用し、
fontName=HeiseiKakuGo-W5,encording=UniJIS-UCS2-H を指定
対処方法をご存知の方がいれば教えてください。
A:
ドキュメントが見当たらないので Primefaces Extensions のソース見てみました。
https://github.com/primefaces-extensions/core/blob/master/src/main/java/org/primefaces/extensions/component/exporter/PDFExporter.java
createCustomFonts の 917行目 の箇所が問題のようです。
if (fontName != null && FontFactory.getFont(fontName).getBaseFont() != null) {
this.cellFont = FontFactory.getFont(fontName, encoding);
this.facetFont = FontFactory.getFont(fontName, encoding, Font.DEFAULTSIZE, Font.BOLD);
} else {
this.cellFont = FontFactory.getFont(FontFactory.TIMES, encoding);
this.facetFont = FontFactory.getFont(FontFactory.TIMES, encoding, Font.DEFAULTSIZE, Font.BOLD);
}
FontFactory.getFont が fontName しか渡していないので "HeiseiKakuGo-W5" Font が取れず else の方に流れているようです。
ここを以下のように書き換えると動きそうですが、PrimeFaces Extensions をビルドしないとダメなので大変な感じですね。
if (fontName != null && FontFactory.getFont(fontName, encoding).getBaseFont() != null) {
一応、iText の field をいじる方法で日本語出ました。
ダウンロードをする前のどこかのタイミングで
FontFactory.defaultEncoding = "UniJIS-UCS2-H";
をしておけば日本語出力されました。
iText 詳しくないのでどんな影響が出るかは分かりませんが、解決の糸口になればと思います。
|
[
"stackoverflow",
"0003163611.txt"
] | Q:
Mercurial project overlapping?
I have a site/backoffice solution that works with this structure:
/bo // mercurial repo
/site // site files
/www/admin // mercurial repo
/var // site specific vars
The backoffice works seamless across several sites and therefore all projects have a mercurial repo and code contributions done to project A always get replicated on projects B and C. This has worked well so far but now I feel I should also be doing a repo to the root /.
Is it possible? Can I have a repo on / excluding both the /bo and the /www/admin and have it all work nicely together or should I anticipate problems?
A:
You could setup a repo at the root, and:
declare /site and /var as SubRepos,
while ignoring /bo and /www/admin
That way, all your current repos still go on unchanged, but you also have one global repo with only what you need.
|
[
"meta.stackexchange",
"0000107247.txt"
] | Q:
Closing one "your bounty expires in the next 24 hours" banner closes them all
A moment ago, I had two "The bounty on your question expires in the next 24 hours" notification banners active here on MSO. I closed one, and it disappeared as expected. When I moved on to another question, both banners were gone.
I can see how this logic made sense back in the one-bounty-at-a-time days, but now that users can have three simultaneous open bounties each, the dismissal button should only dismiss the selected notification.
EDIT :
Although this is marked completed, it happened again today.
A:
Our code responsible for "message dismissal" used the message type as opposed to message id as the key for ridding the user of messages.
I just changed it so, in general, we dismiss on message id now. If we need any notifications to dismiss based on "family", let me know so I can special case it.
Keep in mind that many messages get dismissed by simply visiting the profile page.
|
[
"ru.stackoverflow",
"0000840378.txt"
] | Q:
Зачем массивы вообще нужны?
Я думаю, что массивы и особенно листы (динамические массивы) бесполезны, но раз они используются, то значит нет?
Вот я думаю типа так: если массив отсортированный, то отсортированный он для бинарного поиска, но для бинарного поиска есть двоичное дерево поиска (сбалансированное), вставка/удаление в котором будет О(лог н), когда в массиве О(н), то есть отсортированный масив < сбалансированное двоичное дерево поиска, а если массив неотсортированный, то зачем он нам нужен, если мы можем в таком случае использовать связной список?
Ибо тогда поиск одинаков, а вставка/удаление О(1). А динамический массив плох, ибо каждый раз при вставке служба, которая участвует в распределении памяти, будет искать новые места в памяти, где будет n + 1 (+ 1 это новый элемент) свободных ячеек подряд. То есть динамический массив тратит много усилий на поиски ячеек, когда связной список просто укажет ссылку на след. элемент. Ну а если динамический массив отсортирован, то юзаем сбалансированное двоичное дерево поиска, где тоже при вставке/удалении не будет возни с ячейками, просто поменять ссылки и сбалансировать.
Так в чем же профит массивов? Почему в каждом первом коде я вижу массивы и листы (динамические массивы или списки)?
A:
Массив это самая быстрая модель связи ( число <-> число ) . Скорость будет O(1). В языке C эта модель используется для реализации switch например. В ассемблере или в любом языке число может представлять себя как буква, адрес памяти, разница адресов памяти и т.д. Списки и деревья например используют память в куче, так как размер списка не фиксированный, а динамический. Скорость операционки не бесконечная, она должна отслеживать динамическую память. Если использовать фиксированный массив по длине int m[10]; , он будет хранится в стеке, что не нагружает операционку, и скорость даёт максимальную. У каждой реализации данных свои фишки и нужно знать , что вам надо.
|
[
"stackoverflow",
"0060120820.txt"
] | Q:
Creating a df of dates to pass onto a purrr function
I am trying to create a tbl_df that has 2 columns start_date and end_date. Every row would have 6 days between the start_date and end_date. I want to use the start_date and end_date values from each row to feed into a scrape function using purrr::map.
# example tbl_df
df <- tibble::tribble(
~start_date, ~end_date,
"6/1/2019", "6/7/2019",
"6/8/2019", "6/14/2019"
)
df
#> # A tibble: 2 x 2
#> start_date end_date
#> <chr> <chr>
#> 1 6/1/2019 6/7/2019
#> 2 6/8/2019 6/14/2019
I tried to bind 2 vectors, but they are usually uneven length. Is there a better way to solve this problem? I'm also not sure if purrr would accept dates as an argument value.
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
start_date <- lubridate::ymd("2019-06-01")
end_date <- lubridate::ymd("2019-08-01")
start_dates <- seq(start_date, end_date, by = "1 week" )
end_dates <- seq (lubridate::ymd("2019-06-07"), end_date, by = "1 week")
Created on 2020-02-07 by the reprex package (v0.3.0)
Example function would be:
scrape_function <- function(start_date, end_date) {
url <- glue::glue("http://www.example.com/start_date={start_date}&end_date={end_date}")
# scrape data and return df
df
}
Also, how would I use the start_date and end_date values to pass along to purrr::map2dfr using safely?
A:
I think the web scraping code has just confused the issue. Is it just that you want to split a time period into 7 day chunks? Perhaps this
start_date <- lubridate::ymd("2019-06-01")
end_date <- lubridate::ymd("2019-08-01")
split_weeks <- function(start_date, end_date){
df <- tibble::tribble(
~start_date, ~end_date,
start_date, start_date + 6)
interim_end_date <- start_date + 6
while(interim_end_date < end_date){
df <- df %>% tibble::add_row(start_date=interim_end_date + 1,
end_date=interim_end_date + 7)
interim_end_date <- interim_end_date + 7
}
return(df)
}
split_weeks(start_date, end_date)
#> # A tibble: 9 x 2
#> start_date end_date
#> <date> <date>
#> 1 2019-06-01 2019-06-07
#> 2 2019-06-08 2019-06-14
#> 3 2019-06-15 2019-06-21
#> 4 2019-06-22 2019-06-28
#> 5 2019-06-29 2019-07-05
#> 6 2019-07-06 2019-07-12
#> 7 2019-07-13 2019-07-19
#> 8 2019-07-20 2019-07-26
#> 9 2019-07-27 2019-08-02
Or to fix your code to give vectors of equal length
start_dates <- seq(start_date, end_date, by = "1 week" )
end_dates <- seq(lubridate::ymd("2019-06-07"), by = "1 week",
length.out=length(start_dates))
|
[
"physics.stackexchange",
"0000093007.txt"
] | Q:
Is a Betelgeuse supernova able to neutralise earth's nuclear arsenal?
According to an article on newscientist.com, a neutrino beam could neutralise nuclear bombs by inducing a slow meltdown of the nuclear fuel. The neutrino generator
would need to be more than a hundred times more powerful than any existing particle accelerator
Seems not much to me, compared to the "$10^{46}$ joules, approximately 10% of the star's rest mass," which, wikipedia says, "is converted into a ten-second burst of neutrinos, which is the main output of a supernova"
So, is a supernova able to neutralise earth's nuclear arsenal?
A:
No. Ordinary supernovas do not produce neutrinos of large enough energy to cause such a nuclear weapon meltdown, even if the inverse square law diminution of flux is not an issue.
The original paper on which the NewScientist based its article is the preprint
Sugawara, H., Hagura, H., Sanami, T. Destruction of Nuclear Bombs Using Ultra-High Energy Neutrino Beam. arXiv:hep-ph/0305062.
There we could see the principles on which this hypothetical weapon is based upon. To melt a nuclear weapon ultra-high energy neutrino beam (about 1000 TeV, well higher than energy achievable in modern accelerators) is produced. At such energies the mean free path of the neutrino is comparable with radius of the Earth. At the same time the beam would be narrow enough, so its spread at the distance in question is negligible. The high energy neutrinos interacting with matter would produce hadron showers. If such an event happens near the fissionable material, nuclear fission could be initiated by hadrons, and if the power of the beam is large enough, the energy released by such process would be large enough to meltdown a nuclear weapon (cause a fizzle).
However, neutrinos released by an 'ordinary' supernova are of much smaller energies (from several MeV to several dozen MeV). The neutrinos of such an energies do not cause hadron showers (at all), the cross-section of interaction with matter is much smaller, so the induced fission events would be negligible even at a distances where neutrino radiation from supernovae would cause lethal dose (Thanks, Ross Millikan for the reminder). (Incidentally, the ultra-high energy neutrino beam weapon from the paper would also be able to produce lethal dose within seconds).
So even if supernova event occurs near enough to threaten the life on Earth, neutrinos from it wont damage nuclear weapons. And Betelgeuse is far away enough that had it exploded it wont cause noticeable damage to Earth ecosystem.
One could also note, that ultra-high energy neutrinos detected recently by the IceCube detector, have the energy in that same energy range (>1 PeV), so there probably are astrophysical sources of such neutrinos.
|
[
"stackoverflow",
"0056012204.txt"
] | Q:
Read Only Operations in SQL Server in a External Subnetwork PC
To put everyone in context: we have a deployed Windows Forms App, coded in C#, and querying data from/to a SQL Server 14 DB. Everything works fine, till the day we needed to push the app outside the main subnetwork 192.168.0.X, to 192.168.1.X.
Here with my partner, we believed that doing a little rework in the connection string could solve the first problem we had ahead (no connection to the DB; no login, no simple queries, no nothing), along this one, that doesn't allow us to write any data into the DB, using Stored Procedures or not. We already thinked that this could be one of the sources of this problem, but it wasn't, because we can do some SELECT queries without any drama. This, on the affected PC, of course.
Previously, it was:
user id=myUser; password=myPass; server=myIP; Trusted_Connection=no; database=myDBName; connection timeout=30;
Now, it is:
Data Source=myServerName; Initial Catalog=myDatabaseName; User ID=myUsername;Password=myPassword; Server=IP, Port (if necessary);
Simple Select Query
Some Screenshots of the Exceptions, printed in MessageBox'es:
1st (and 3rd) Exception: Possible Truncated Data (this repeats itself again after the 2nd one)
2nd Exception: Couldn't Open a Connection
We've already checked the TCP/IP, port configs from SSMS, physical firewall port forwarding, more variations on the conn. string, different IPv4 configs, and nothing seems to work (even with a new super user, with all DB and Server Privilegies). So here we are, so close, and so far from solving this thing.
2nd day Edit: Doing double checks in the affected code (where the Exceptions occur), even with the suggestions that @iakobski made, it's still the same. Same exceptions, in the same place. The only difference is the speed of the app to throw them, because it can close the pending transaction faster, and the exceptions are handled, thanks to the 'finally' clause.
Also, as I noticed while doing a deeper debugging, INSERT's or UPDATE's by themselves aren't the problem, but the Stored Procedures ones. Because it failed to Update/Select data in SP modules that uses the SQLSERVERPROCEDURE.SQLSERVER.Exec form, but not while inserting a Log Entry (which I believe is the classic way to execute SQL Commands):
SqlCommand cmd = new SqlCommand();
con.ConnectionString = CadenaConexion;
cmd.Connection = con;
cmd.CommandText = "INSERT INTO LOG(LOG_ID_USUARIO,LOG_FECHA,LOG_PROCESO,LOG_CANTIDAD,LOG_PEDIDO,LOG_ITEM)" +
"VALUES(@log_id_usuario, @log_fecha, @log_proceso, @log_cantidad, @log_pedido, @log_item)";
try
{
cmd.Parameters.Add("@log_id_usuario", SqlDbType.Int).Value = Log_id_usuario;
cmd.Parameters.Add("@log_fecha", SqlDbType.DateTime).Value = Log_fecha;
cmd.Parameters.Add("@log_proceso", SqlDbType.Text).Value = Log_proceso;
cmd.Parameters.Add("@log_cantidad", SqlDbType.Int).Value = Log_cantidad;
cmd.Parameters.Add("@log_pedido", SqlDbType.Int).Value = Log_pedido;
cmd.Parameters.Add("@log_item", SqlDbType.Int).Value = Log_item;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
}
catch (Exception ex)
{
exSrc = "log";
exMsg = ex.Message;
exNota = "ERR_LogUsu01: No se ha podido Insertar el Registro a la Tabla Log";
exStTr = ex.StackTrace;
registrarEnLogErr();
MessageBox.Show(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally { con.Close(); }
So, if yesterday I was pretty sure that this little file called SQLSERVERPROCEDURE.dll that has direct relations with the Stored Procedures that are processed by it has a lot to do here, I'm sure-r now. Somehow, it may be using the old Connection String, but I don't know how I can change it, because every call that's done to this file, refers to the Conn. String as "DBSQL" (tried to change it when calling, putting the SharedData.Instance().StringConexion, and also a 'cn' variable [with ToString()], with no luck. Said that the Conn. String is not defined). Take a look at the definition in a SP with .dll calling, and the .dll file itself:
Update Module:
SqlConnection cn = new SqlConnection(SharedData.Instance().StringConexion);
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@nta_venta", nta_venta);
param.Add("@item", item);
param.Add("@cantidad", cantidad);
cn.Open();
SQLSERVERPROCEDURE.SQLSERVER.Exec("DBSQL", SP, param);
cn.Close();
}
catch (Exception ex)
{
exSrc = this.Name;
exMsg = ex.Message;
exNota = "ERR_Corte02: Pedido: " + nta_venta + "-" + item + " con Falta de Parámetros válidos en Actualiza";
exStTr = ex.StackTrace;
registrarEnLogErr();
MessageBox.Show(ex.Message);
}
finally { cn.Close(); }
DLL File: Title on VS: SQLSERVER (from metadata)
#region Ensamblado SQLSERVERPROCEDURE, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
// C:\Users\User\source\repos\MY-APP\packages\EXECSQLSERVERPROCEDURE.2.0.0\lib\net40\SQLSERVERPROCEDURE.dll
#endregion
using System.Collections.Generic;
using System.Data;
namespace SQLSERVERPROCEDURE
{
public static class SQLSERVER
{
public static DataTable Exec(string NombreConexion, string Procedimiento, Dictionary<string, object> VariableYValores, DataTable dt = null);
public static DataSet Exec(string NombreConexion, string Procedimiento, Dictionary<string, object> VariableYValores, DataSet ds = null);
public static void Exec(string NombreConexion, string Procedimiento, Dictionary<string, object> VariableYValores);
}
}
1st StackTrace (not valid anymore because it's resolved with re-done Open and Close statements):
Excepción producida: 'System.Data.SqlClient.SqlException' en System.Data.dll
El subproceso 0x3f5c terminó con código 0 (0x0).
Excepción producida: 'System.Data.SqlClient.SqlException' en SQLSERVERPROCEDURE.dll
Excepción producida: 'System.InvalidOperationException' en System.Data.dll
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Transactions.resources\v4.0_4.0.0.0_es_b77a5c561934e089\System.Transactions.resources.dll' cargado. El módulo se compiló sin símbolos.
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Excepción no controlada</Description><AppDomain>myApp.exe</AppDomain><Exception><ExceptionType>System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>No está autorizado a cambiar la propiedad 'ConnectionString'. El estado actual de la conexión es abierta.</Message><StackTrace> en System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
en System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
en MY_APP.Class.log_errores.INSERT_log_err() en C:\Users\User\Source\Repos\MY-APP\MY APP\Class\log_errores.cs:línea 34
en MY_APP.PrcsCorte.registrarEnLogErr() en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 378
en MY_APP.PrcsCorte.cargarPedido(Int32 nv, Int32 it) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 267
en MY_APP.PrcsCorte.PrcsCorte_Activated(Object sender, EventArgs e) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 39
en System.Windows.Forms.Form.OnActivated(EventArgs e)
en System.Windows.Forms.Form.set_Active(Boolean value)
en System.Windows.Forms.Form.WmActivate(Message&amp; m)
en System.Windows.Forms.Form.WndProc(Message&amp; m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</StackTrace><ExceptionString>System.InvalidOperationException: No está autorizado a cambiar la propiedad 'ConnectionString'. El estado actual de la conexión es abierta.
en System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
en System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
en MY_APP.Class.log_errores.INSERT_log_err() en C:\Users\User\Source\Repos\MY-APP\MY APP\Class\log_errores.cs:línea 34
en MY_APP.PrcsCorte.registrarEnLogErr() en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 378
en MY_APP.PrcsCorte.cargarPedido(Int32 nv, Int32 it) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 267
en MY_APP.PrcsCorte.PrcsCorte_Activated(Object sender, EventArgs e) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 39
en System.Windows.Forms.Form.OnActivated(EventArgs e)
en System.Windows.Forms.Form.set_Active(Boolean value)
en System.Windows.Forms.Form.WmActivate(Message&amp; m)
en System.Windows.Forms.Form.WndProc(Message&amp; m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</ExceptionString></Exception></TraceRecord>
Excepción no controlada del tipo 'System.InvalidOperationException' en System.Data.dll
No está autorizado a cambiar la propiedad 'ConnectionString'. El estado actual de la conexión es abierta.
El subproceso 0x2e54 terminó con código 0 (0x0).
El subproceso 0x42cc terminó con código 0 (0x0).
El subproceso 0x3d84 terminó con código 0 (0x0).
Excepción no controlada: System.InvalidOperationException: No está autorizado a cambiar la propiedad 'ConnectionString'. El estado actual de la conexión es abierta.
en System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
en System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
en MY_APP.Class.log_errores.INSERT_log_err() en C:\Users\User\Source\Repos\MY-APP\MY APP\Class\log_errores.cs:línea 34
en MY_APP.PrcsCorte.registrarEnLogErr() en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 378
en MY_APP.PrcsCorte.cargarPedido(Int32 nv, Int32 it) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 267
en MY_APP.PrcsCorte.PrcsCorte_Activated(Object sender, EventArgs e) en C:\Users\User\Source\Repos\MY-APP\MY APP\PrcsCorte.cs:línea 39
en System.Windows.Forms.Form.OnActivated(EventArgs e)
en System.Windows.Forms.Form.set_Active(Boolean value)
en System.Windows.Forms.Form.WmActivate(Message& m)
en System.Windows.Forms.Form.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
El programa '[17180] myApp.exe' terminó con código 0 (0x0).
2nd StackTrace:
'myApp.exe' (CLR v4.0.30319: DefaultDomain): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: DefaultDomain): 'C:\Users\User\Source\Repos\MY-APP\MY APP\bin\Debug\myApp.exe' cargado. Símbolos cargados.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Data.resources\v4.0_4.0.0.0_es_b77a5c561934e089\System.Data.resources.dll' cargado. El módulo se compiló sin símbolos.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.Wrapper.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Caching\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.Caching.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Numerics\v4.0_4.0.0.0__b77a5c561934e089\System.Numerics.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms.resources\v4.0_4.0.0.0_es_b77a5c561934e089\System.Windows.Forms.resources.dll' cargado. El módulo se compiló sin símbolos.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_es_b77a5c561934e089\mscorlib.resources.dll' cargado. El módulo se compiló sin símbolos.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\Users\User\Source\Repos\MY-APP\MY APP\bin\Debug\SQLSERVERPROCEDURE.dll' cargado. No se encuentra el archivo PDB o no se puede abrir.
'myApp.exe' (CLR v4.0.30319: myApp.exe): 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\PrivateAssemblies\Runtime\Microsoft.VisualStudio.Debugger.Runtime.dll' cargado. Se omitió la carga de símbolos. El módulo está optimizado y la opción del depurador 'Sólo mi código' está habilitada.
Excepción producida: 'System.Data.SqlClient.SqlException' en System.Data.dll
Excepción producida: 'System.Data.SqlClient.SqlException' en System.Data.dll
El subproceso 0x1184 terminó con código 0 (0x0).
El subproceso 0xfe0 terminó con código 0 (0x0).
El subproceso 0xc70 terminó con código 0 (0x0).
El subproceso 0x4b64 terminó con código 0 (0x0).
El subproceso 0x5e04 terminó con código 0 (0x0).
El subproceso 0x3ef4 terminó con código 0 (0x0).
El subproceso 0x3b58 terminó con código 0 (0x0).
El subproceso 0x480c terminó con código 0 (0x0).
Excepción producida: 'System.Data.SqlClient.SqlException' en SQLSERVERPROCEDURE.dll
El subproceso 0x48f0 terminó con código 0 (0x0).
El subproceso 0x4238 terminó con código 0 (0x0).
Excepción producida: 'System.Data.SqlClient.SqlException' en System.Data.dll
El subproceso 0x5ddc terminó con código 0 (0x0).
El subproceso 0x5184 terminó con código 0 (0x0).
El subproceso 0x3074 terminó con código 0 (0x0).
El subproceso 0x3bdc terminó con código 0 (0x0).
El subproceso 0x55f4 terminó con código 0 (0x0).
El subproceso 0x44b4 terminó con código 0 (0x0).
El programa '[18484] myApp.exe' terminó con código 0 (0x0).
SSMS Screenshots:
Server Roles
Database Roles
Permissions
Settings and Status
A:
First, sorry about posting this so late. Second, among all the answers, I can say I did the following (and worked):
Added using blocks to all DB performing operations
Added a IsServerConnected Method, using this as reference:
What's the best way to test SQL Server connection programmatically? in my Error Log Method
(This is the real answer) Went to App.config file and checked the special Connection String that EXECSQLSERVERPROCEDURE plugin uses, and updated the DB Connection Credentials
Sometimes, the most headbreaking problems have incredible easy answers, don't you think?
Thanks guys!
|
[
"stackoverflow",
"0014382725.txt"
] | Q:
How to get the correct IP address of a client into a Node socket.io app hosted on Heroku?
I recently hosted my first Node app using Express and socket.io on Heroku and need to find the client's IP address. So far I've tried socket.manager.handshaken[socket.id].address, socket.handshake.address and socket.connection.address , neither of which give the correct address.
App: http://nes-chat.herokuapp.com/ (also contains a link to GitHub repo)
To view IPs of connected users: http://nes-chat.herokuapp.com/users
Anyone know what the problem is?
A:
The client IP address is passed in the X-Forwarded-For HTTP header. I haven't tested, but it looks like socket.io already takes this into account when determining the client IP.
You should also be able to just grab it yourself, here's a guide:
function getClientIp(req) {
var ipAddress;
// Amazon EC2 / Heroku workaround to get real client IP
var forwardedIpsStr = req.header('x-forwarded-for');
if (forwardedIpsStr) {
// 'x-forwarded-for' header may return multiple IP addresses in
// the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
// the first one
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {
// Ensure getting client IP address still works in
// development environment
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
A:
You can do it in one line.
function getClientIp(req) {
// The X-Forwarded-For request header helps you identify the IP address of a client when you use HTTP/HTTPS load balancer.
// http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-for
// If the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"]
// http://expressjs.com/4x/api.html#req.ips
var ip = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0] : req.connection.remoteAddress;
console.log('IP: ', ip);
}
I like to add this to middleware and attach the IP to the request as my own custom object.
|
[
"cs.stackexchange",
"0000030688.txt"
] | Q:
are the activations of hidden nodes in an ANN binary or real valued?
this may seem to be a pretty basic question, but it is something i have been puzzling over for some time.
when calculating the activations of nodes in a hidden layer in an ANN using sigmoid neurons for use with the backpropagation algorithm - should the output of the neuron be thresholded or not?
say the activation vector for layer $i$ is calculated by:
$\mathbf{a}_i = \sigma(\mathbf{w}_i\mathbf{a}_{i-1} + \mathbf{b}_i)$
where $\sigma$ is the sigmoid activation function
should it actually be:
$\mathbf{a}_i = (\sigma(\mathbf{w}_i\mathbf{a}_{i-1} + \mathbf{b}_i) > 0.5$)
to ensure that $\mathbf{a}_i$ is binary vector? or should the real value from $\sigma$ be passed on to the next layer?
my main reason for asking this is that biological neurons don't transmit real valued data, but i haven't really been able to find any definitive answer anywhere to this question or anyone who explicitly says to threshold the value; it seems like a pretty fundamental question to the functioning of ANNs, so either i am missing something in my reading, or it is considered so common-sense that it doesn't need to be mentioned much.
any help would be greatly appreciated
A:
When you do thresholding your activation function becomes a step function. The problem with that is that step functions are not differentiable, so you would not be able to do basic gradient descent to learn the parameters. You can see the sigmoid as a continuous approximation of a step function.
|
[
"stackoverflow",
"0063232528.txt"
] | Q:
Spring jpa disable merge
i want disable merge in jpa repository. It should only be possible to create new records and prohibit updating old ones.
So, how to disable the update of records for the repository if i extends from JpaRepository?
A:
Making your entity immutable can stop changes happening to managed entities and as a result no changes will be propagated within the transaction.
However it does not stop hibernate updating the database record, if you passed immutable record with id assigned and it already exists in db.
So I think you can look into @PreUpdate entity listener and throw exception. So if someone tries to update, it will throw exception and update will not happen.
But the best way is to create service which hides the repository and
Service does a find before save to avoid second point
Make the entity immutable to make sure first point.
|
[
"stackoverflow",
"0034455520.txt"
] | Q:
Java logging framework - with printf() support
In c, printf() is really easy to use, and in Java System.out.printf() is also amazing, but in log4j, seems only can use "First name: "+ firstName +", Age: " + age, which is very uncomfortable.
The questions are:
What is the difficulty that prevents log4j from implement such a feature?
What logging framework support such feature, can u give a short example that include the maven dependencies & Java code.
A:
You can use org.slf4j.Logger which provides a way to format log in such manner.
For example,
LOGGER.info("Roll number of Student {} is {}.", studentName, rollNumber);
A:
You could use String's format method like:
logger.info(String.format("Student %s with roll number %d found!", studentName, rollNumber));
|
[
"workplace.stackexchange",
"0000003590.txt"
] | Q:
Resigned before accepting a conditional offer
I made a very rash decision now I am regretting it to the bone. I accepted a conditional letter from a company for a full time job while working in a per-week job. I was asked when I would like to resume and I filled in two weeks in order for my Criminal check and Background information to be received.
Then after I gave my notice within the company. I know its a rash thing to do but I told my boss because I knew they will call him up for references. He then countered the offer with something quite close to the offer given to me. I rejected it after taking a week to consider with the hope that my references will have been back due to the living condition of the environment.
Now the other company came back to me after about a week and three days saying they have not even started the background checks yet asking me to shift my resumption by one week to enable them finish the screening. I have resigned already and I have two days to go.
What are my options? Do I even have any left?
A:
It sounds like it is already a bit too late. Take it as a lesson learned that it is harder to build a relationship than to break one. You said "No" to your current employer twice, so staying with them now only damages your credibility in their eyes.
If the offer is solid, just ride the week out as unexpected vacation time. If you have any doubt that the offer won't materialize then use the time off to redouble your efforts in landing a job. Realistically, you can't hurry the new employer, and presenting your particular dilemma to them might damage their opinion of your judgement.
Sometimes you can ask to start contingent on a successful screening; however, in today's environment that is very unlikely to occur.
In the future, let your prospective employer know that they are absolutely not permitted to call your current employer for references until after a job offer is made. Make it a point of professionalism, indicating that you would hope nobody would upset their business by performing such a disruptive task.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.