qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
1,481,124 | I setup catching hotkey on alt+printscreen. It catches perfectly but there is nothing in the buffer - no image. How can I get the image from Clipboard.GetImage() after catching hotkey?
Here is the the code.
```
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Magic_Screenshot
{
public enum ModifierKey : uint
{
MOD_NULL = 0x0000,
MOD_ALT = 0x0001,
MOD_CONTROL = 0x0002,
MOD_SHIFT = 0x0004,
MOD_WIN = 0x0008,
}
public enum HotKey
{
PrintScreen,
ALT_PrintScreen,
CONTROL_PrintScreen
}
public class HotKeyHelper : IMessageFilter
{
const string MSG_REGISTERED = "Горячие клавиши уже зарегистрированы, вызовите UnRegister для отмены регистрации.";
const string MSG_UNREGISTERED = "Горячие клавиши не зарегистрированы, вызовите Register для регистрации.";
//Делаем из нашего класса singleton
public HotKeyHelper()
{
}
//public static readonly HotKeyHelper Instance = new HotKeyHelper();
public bool isRegistered;
ushort atom;
//ushort atom1;
ModifierKey modifiers;
Keys keyCode;
public void Register(ModifierKey modifiers, Keys keyCode)
{
//Эти значения нам будут нужны в PreFilterMessage
this.modifiers = modifiers;
this.keyCode = keyCode;
//Не выполнена ли уже регистрация?
//if (isRegistered)
// throw new InvalidOperationException(MSG_REGISTERED);
//Сохраняем atom, для последующей отмены регистрации
atom = GlobalAddAtom(Guid.NewGuid().ToString());
//atom1 = GlobalAddAtom(Guid.NewGuid().ToString());
if (atom == 0)
ThrowWin32Exception();
if (!RegisterHotKey(IntPtr.Zero, atom, modifiers, keyCode))
ThrowWin32Exception();
//if (!RegisterHotKey(IntPtr.Zero, atom1, ModifierKey.MOD_CONTROL, Keys.PrintScreen))
// ThrowWin32Exception();
//Добавляем себя в цепочку фильтров сообщений
Application.AddMessageFilter(this);
isRegistered = true;
}
public void UnRegister()
{
//Не отменена ли уже регистрация?
if (!isRegistered)
throw new InvalidOperationException(MSG_UNREGISTERED);
if (!UnregisterHotKey(IntPtr.Zero, atom))
ThrowWin32Exception();
GlobalDeleteAtom(atom);
//Удаляем себя из цепочки фильтров сообщений
Application.RemoveMessageFilter(this);
isRegistered = false;
}
//Генерирует Win32Exception в ответ на неудачный вызов импортируемой Win32 функции
void ThrowWin32Exception()
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
//Событие, инициируемое при обнаружении нажатия HotKeys
public event HotKeyHelperDelegate HotKeyPressed;
public bool PreFilterMessage(ref Message m)
{
//Проверка на сообщение WM_HOTKEY
if (m.Msg == WM_HOTKEY &&
//Проверка на окно
m.HWnd == IntPtr.Zero &&
//Проверка virtual key code
m.LParam.ToInt32() >> 16 == (int)keyCode &&
//Проверка кнопок модификаторов
(m.LParam.ToInt32() & 0x0000FFFF) == (int)modifiers &&
//Проверка на наличие подписчиков сообщения
HotKeyPressed != null)
{
if ((m.LParam.ToInt32() & 0x0000FFFF) == (int)ModifierKey.MOD_CONTROL && (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen))
{
HotKeyPressed(this, EventArgs.Empty, HotKey.CONTROL_PrintScreen);
}
else if ((m.LParam.ToInt32() & 0x0000FFFF) == (int)ModifierKey.MOD_ALT && (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen))
{
HotKeyPressed(this, EventArgs.Empty, HotKey.ALT_PrintScreen);
}
else if (m.LParam.ToInt32() >> 16 == (int)Keys.PrintScreen)
{
HotKeyPressed(this, EventArgs.Empty, HotKey.PrintScreen);
}
}
return false;
}
//Необходимые Win32 константы и функции
const string USER32_DLL = "User32.dll";
const string KERNEL32_DLL = "Kernel32.dll";
const int WM_HOTKEY = 0x0312;
[DllImport(USER32_DLL, SetLastError = true)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, ModifierKey fsModifiers, Keys vk);
[DllImport(USER32_DLL, SetLastError = true)]
static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport(KERNEL32_DLL, SetLastError = true)]
static extern ushort GlobalAddAtom(string lpString);
[DllImport(KERNEL32_DLL)]
static extern ushort GlobalDeleteAtom(ushort nAtom);
}
}
```
Where is the bug? | 2009/09/26 | [
"https://Stackoverflow.com/questions/1481124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276640/"
] | Make sure the XML that you download from last.fm is gzipped. You'd probably have to include the correct HTTP header to tell the server you support gzip. It would speed up the download but eat more server resources with the ungzipping part.
Also consider using asynchronous downloads to free server resources. It won't necessarily speed the process up, but it should make the server administrators happy.
If the XML itself is big, use a SAX parser, instead of a DOM parser. | I think there's a limit of 1 API call per second. I'm not sure this policy is being enforced through code, but it might have something to do with it. You can ask the Last.fm staff on IRC at [irc.last.fm](http://irc://irc.last.fm) #audioscrobbler if you believe this to be the case. |
42,730,632 | I tried to update ng-model value as result of $http.get call but it's not updated.
Here is my code.
**main.js**
```
angular.module('app', [])
.controller('mainCtrl', ['$http', function($http) {
var main = this;
main.show = true;
$http({
method: 'GET',
url: 'api url'
})
.then(function(res) {
main.show = true;
console.log('succeed call, main.show: ' + main.show);
}, function(res) {
main.show = false;
console.log('failed call, main.show: ' + main.show);
});
console.log('out of call, main.show: ' + main.show);
}]);
```
**index.html**
```
...
<body ng-app='app' ng-controller='mainCtrl as main'>
<a ng-show='main.show' href='/'>Succeed</a>
<a ng-hide='main.show' href='/'>Failed</a>
</body>
...
```
**console log when api succeed**
```
out of call, main.show: true
succeed call, main.show: true
```
**console log when api failed**
```
out of call, main.show: true
failed call, main.show: false
```
My problem is the html always show me 'Succeed' link.
I tried many things even use `$timeout`, `$apply`, but it's also not working.
There are some answers for similar problems, but it was not working for me.
What should I do to solve the problem? | 2017/03/11 | [
"https://Stackoverflow.com/questions/42730632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7129790/"
] | The way you are making your http calls are wrong.
First in the controller:
```
.controller('mainCtrl', ['$http', function($http) ...
```
In the controller first http should be passed as string: `'$http'`.
Asynchronous calls are made in the following way:
```
var promise = $http({
method : 'POST',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
promise.then(function (response) {
yourData = response.data;
console.log(response.data);
return yourData;
})
.catch(function (error) {
console.log("Something went terribly wrong.");
});
``` | Set main.show initial value to false
```
main.show =false;
```
Also define the ng-app value in HTML tag |
26,154,497 | I am making a comma separated "tag" type system, and I want the tags to scroll left to right, then go to the next line if the next tag would cause that line to be wider than the max width of the container.
I get different results if I use `<span>` or `<div>`
```
<span class="tag"><span class="tagspan" ></span></span>
<div class="tag"><span class="tagspan" ></span></div>
```
but neither one correctly wraps to the next line. ( If I use span it WILL wrap to next line, but it will break the tag in half and place the rest of it on the next line ).
Surely there must be an easy fix for this. I am trying to avoid having to calculate the width of each line and compare its current width to the width it would be if the next tag were added, then deciding if there needs to be a line break or not.
Any suggestions would be greatly appreciated.
[JS Bin Here](http://jsbin.com/wasiv/9/edit)
jQuery:
```
$('document').ready( function() {
var value;
var tag;
var cloned;
$('#tag').on( 'change keyup', function(){
value = $('#tag').val();
tag = value.split(',');
if (tag[1] != null && tag[0] !== ''){
cloned = $('.tag').first().clone().appendTo('#container');
$(cloned).find('span').html(tag[0]);
$(cloned).css({'opacity' : '1', 'width' : $(cloned).find('span').width() + 'px'});
$('#tag').val('');
}
if (tag[1] != null && tag[0] === ''){
$('#tag').val('');
}
console.log($('.tagspan').width() + 'px');
});
});
``` | 2014/10/02 | [
"https://Stackoverflow.com/questions/26154497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615776/"
] | You can use float:left to your tag elements instead of the container and drop the display:inline-flex attribute which results in a line break if your tags reach the end of the line. Edit: change the outer span elements to divs for that effect.
// thanks Gary ;) | This is more related to `CSS` styling than `JavaScript` code, I think I got it working just tweaking two classes in your `CSS` code:
```
span {
vertical-align:middle;
display: inline-flex;
word-break: keep-all;
}
#container {
text-align: left;
display: block;
min-width:400px;
max-width:400px;
height:100px;
border:1px solid;
}
```
This is how it looks like:

The thing is, span elements must fit into its parent element, that's why you should make children display inline and not its parent.
Working example: [Wrap span tags into DIV](http://jsbin.com/wihagozifixi/1/edit?html,css,js,output) |
5,684,811 | in a div, have elements (not necessarily 2nd generation) with attribute `move_id`.
First, would like most direct way of fetching first and last elements of set
tried getting first and last via:
```
var first = div.querySelector('[move_id]:first');
var last = div.querySelector('[move_id]:last');
```
this bombs because :first and :last were wishful thinking on my part (?)
cannot use the Array methods of `querySelectorAll` since `NodeList` is not an Array:
```
var first = (div.querySelectorAll('[move_id]'))[0];
var last = (div.querySelectorAll('[move_id'])).pop();
```
this bombs because `NodeList` does not have method `pop()`
(yes, one could could use Array methods on top of the NodeList:
```
var first = div.querySelector('[move_id]');
var last = Array.prototype.pop.call(div.querySelectorAll('[move_id']));
```
this works, and is what I'm using now, but thinking there has to be something more direct that I'm simply missing)
Second, need to verify that the elements are listed by pre-oder depth-first traversal as per <http://en.wikipedia.org/wiki/Tree_traversal> | 2011/04/16 | [
"https://Stackoverflow.com/questions/5684811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/662063/"
] | `:last` is not part of the css spec, this is jQuery specific.
you should be looking for [`last-child`](https://www.w3.org/TR/selectors-3/#last-child-pseudo)
```
var first = div.querySelector('[move_id]:first-child');
var last = div.querySelector('[move_id]:last-child');
``` | You can get the first and last element directly.
```js
//-- first element
console.log( document.querySelector("#my-div").querySelectorAll( "p" )[0] );
//-- last element
console.log( document.querySelector("#my-div").querySelectorAll( "p" )[document.querySelector("#my-div").querySelectorAll( "p" ).length-1] );
```
```html
<div id="my-div">
<p>My first paragraph!</p>
<p>Here is an intermediate paragraph!</p>
<p>Here is another intermediate paragraph!</p>
<p>Here is yen another intermediate paragraph!</p>
<p>My last paragraph!</p>
</div>
``` |
35,129,038 | For syntax highlighting of Python in Python, I'm using the "keywords" module to get a list of the keywords (for, in, raise etc.).
But how can I get a list of essential built-in functions? I.E. the ones listed here: <https://docs.python.org/2/library/functions.html>
(I want to do it programmatically of course, in case the list ever changes) | 2016/02/01 | [
"https://Stackoverflow.com/questions/35129038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423420/"
] | `dir(builtins)` is not enough, simply because [`builtins`](https://docs.python.org/3/library/builtins.html) module also exposes exceptions and warnings, as well as `False`, `True`, `None` and lots of other constants and "internal" functions.
You could test the type of the object
```
import builtins # __builtin__ in Python 2
from inspect import isbuiltin
for name, val in vars(builtins).items():
if isbuiltin(val):
print(name)
```
but even then, in Python 3 the output would include `__build_class__` which isn't in the list of [Built-in Functions](https://docs.python.org/3/library/functions.html).
Really, it's fine to hardcode names of built-in functions. | You can get a list of the builtins functions in python typing the following:
```
print dir(__builtins__)
``` |
7,531,172 | I'm starting a project and i've decided to use Django.
My question is regarding to the creation of the database. I've read the tutorial and some books and those always start creating the models, and then synchronizing the DataBase. I've to say, that's a little weird for me. I've always started with the DB, defining the schema, and after that creating my DB Abstractions (models, entities, etc).
I've check some external-pluggable apps and those use that "model first" practice too.
I can see some advantages for the "model-first" approach, like portability, re-deployment, etc.
But i also see some disadvantages: how to create indexes, the kind of index, triggers, views, SPs, etc.
So, How do you start a real life project? | 2011/09/23 | [
"https://Stackoverflow.com/questions/7531172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | Triggers, views, and stored procedures aren't really a part of the Django world. It can be made to use them, but it's painful and unnecessary. Django's developers take the view that business logic belongs in Python, not in your database.
As for indexes, you can create them along with your models (with things like `db_index` and `unique_together`, or you can add them later via database migrations using something like South. | Mostly we don't write SQL (e.g. create index, create tables, etc...) for our models, and instead rely on Django to generate it for us.
It is absolutely okay to start with designing your app from the model layer, as you can rely on Django to generate the correct database sql needed for you.
However, Django does provide various functions for you to replicate these database functions:
* triggers: [Django code or MySQL triggers](https://stackoverflow.com/questions/4061304/django-code-or-mysql-triggers)
* indexes: can be specified with `db_index=True`
* unique constraints: `unique = True` or `unique_togther = (('field1', field2'),)` for composite unique constraint.
The advantage with using Django instead of writing sql is that you abstract yourself away from the particular database you are using. In other words, you could be on `SQLite` one day and switch to `PostgresQL` or `MySQL` the next and the change would be relatively painless.
**Example:**
When you run this:
```
python manage.py syncdb
```
Django automatically creates the tables, indexes, triggers, etc, it needs to support the models you've created. If you are not comfortable with django creating your database for you, you can always use:
```
python manage.py sqlall
```
This will print out the SQL statements that Django would need to have in order for its models to function properly. There are other `sql` commands for you to use:
see: <https://docs.djangoproject.com/en/1.3/ref/django-admin/#sql-appname-appname> |
48,269,248 | I want to use XGBoost for online production purposes (Python 2.7 XGBoost API).
In order to be able to do that I want to control and **limit the number of threads used by XGBoost** at the *predict* operation.
I'm using the *sklearn* compatible regressor offered by XGBoost (xgboost.XGBRegressor), and been trying to use the param ***nthread*** in the constructor of the regressor to limit the max threads used to 1.
Unfortunately, XGBoost keeps using multiple threads regardless of the value set in *nthread*.
Is there another way to limit XGBoost and force it to perform the *predict* operation using n=1 threads? | 2018/01/15 | [
"https://Stackoverflow.com/questions/48269248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5524815/"
] | Answer:
Standard set\_params with nthread fails, but when using `regr._Booster.set_param('nthread', 1)` I was able to limit XGBoost to using a single thread.
As mentioned above the env variable `OMP_NUM_THREADS=1` works as well. | Currently `n_jobs` can be used to limit threads at predict time:
`model._Booster.set_param('n_jobs', 2)`
*More info*
Formerly (but now deprecated):
`model._Booster.set_param('nthread', 2)` |
1,548,446 | How can I know if a TIFF image is in the format CCITT T.6(Group 4)? | 2009/10/10 | [
"https://Stackoverflow.com/questions/1548446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use this (C#) code example.
It returns a value indicating the compression type:
1: no compression
2: CCITT Group 3
3: Facsimile-compatible CCITT Group 3
4: CCITT Group 4 (T.6)
5: LZW
```
public static int GetCompressionType(Image image)
{
int compressionTagIndex = Array.IndexOf(image.PropertyIdList, 0x103);
PropertyItem compressionTag = image.PropertyItems[compressionTagIndex];
return BitConverter.ToInt16(compressionTag.Value, 0);
}
``` | You can run `identify -verbose` from the [ImageMagick](http://en.wikipedia.org/wiki/ImageMagick) suite on the image. Look for "Compression: Group4" in the output. |
5,369,632 | Right now in my game I'm drawing true type fonts like this:
```
for(int i = linesSkipped; i <= maxitems + linesSkipped; ++i)
{
if(i >= (int)textRows.size())
{
break;
}
paintargs.graphics()->drawText(AguiPoint(textX - 2,
textY - 2 + (i * getFont().getLineHeight())),
textRows[i].c_str(),AguiColor(0,0,0),getFont());
paintargs.graphics()->drawText(AguiPoint(textX + 2,
textY + 2 + (i * getFont().getLineHeight())),
textRows[i].c_str(),AguiColor(0,0,0),getFont());
paintargs.graphics()->drawText(AguiPoint(textX,
textY + (i * getFont().getLineHeight())),
textRows[i].c_str(),AguiColor(255,128,0),getFont());
}
```
So I draw it with an offset of 2, then with an offset of -1 .
It almost does what I want, but the top right and bottom left edges are still unstroked:

Is there a way to draw it such that it would look like stroking in Photoshop?
Thanks | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146780/"
] | Which API are you using? Is that GDI+?
You can draw the outlines at more locations before drawing the inside:
```
(x-2, y-2) (x, y-2) (x+2,y-2)
(x-2, y ) (x+2,y )
(x-2, y+2) (x, y+2) (x+2,y+2)
```
Or you can see if your graphics API has something like paths. With paths, you tell the graphics library you want to start a path, then draw the text once, then end the path. Once that's done, you tell the graphics library to "stroke and fill" the path. This is the cleanest solution. | You need to draw the text in all corners! What you're doing is drawing in the top-left corner and in the bottom-right corner, which is respectively `X=-2, Y=-2` and `X=2, Y=2`.
What you need to do, is to draw them in the bottom-left and the top-right corner too, which would be respectively `X=-2, Y=2` and `X=2, Y=-2`. |
42,925,288 | I have this **real code** to show and hide two divs depending on device type:
**Problem**: in Android the #div-desktop is shown.
* I need to show only div#div-mobile on mobile devices
* I need to show only div#div-desktop on desktop devices
CSS
```
@media screen and (min-width: 0px) and (max-width: 700px) {
#div-mobile { display: block; }
#div-desktop { display: none; }
}
@media screen and (min-width: 701px) and (max-width: 3000px) {
#div-mobile { display: none; }
#div-desktop { display: block; }
}
```
HTML
```
<div id="div-mobile">m<img width="100%" height="auto" src="http://uggafood.com/wp-content/uploads/2017/03/ugga-food_mobile.jpg" alt="" width="600" height="1067" /></div>
<div id="div-desktop">d<img width="100%" height="auto" src="http://uggafood.com/wp-content/uploads/2017/03/ugga-food_desktop.jpg" alt="" width="1920" height="1280" /></div>
``` | 2017/03/21 | [
"https://Stackoverflow.com/questions/42925288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1121218/"
] | **EDIT**
After seeing your site, you need to add:
```
<meta name="viewport" content="width=device-width, initial-scale=1">
```
---
You can just use `min-width`
Also, don't use `width/height` html tags in `img` use CSS instead
---
```css
img {
max-width: 100%
}
#div-desktop {
display: none;
}
@media screen and (min-width: 701px) {
#div-mobile {
display: none;
}
#div-desktop {
display: block;
}
}
```
```html
<div id="div-mobile">m<img src="http://uggafood.com/wp-content/uploads/2017/03/ugga-food_mobile.jpg" alt="" /></div>
<div id="div-desktop">d<img src="http://uggafood.com/wp-content/uploads/2017/03/ugga-food_desktop.jpg" alt="" /></div>
``` | this line only find the size resolution of the user system and gives to your css code
`<meta name="viewport" content="width=device-width, initial-scale=1.0">` |
11,687,038 | I want to add a static function to a class in EcmaScript 5 JavaScript. My class definition looks as follows:
```
var Account = {};
Object.defineProperty(Account, 'id', {
value : null
});
```
And I would create a new instance like this:
```
var theAccount = Object.create(Account);
theAccount.id = 123456;
```
Now I want to add a static function to the `Account` class. If I had created the `Account` class using a constructor function and the `prototype` property like this:
```
var Account = function () {
this.id = null;
};
```
...I could just do:
```
Account.instances = {};
Account.createInstance = function () {
var account = new Account();
account.id = uuid.v4();
Account.instances[account.id] = account;
return account;
};
```
But since I am using `Object.defineProperty` and not the `prototype` property to add members, `Account.instances` and `Account.createInstance` would also be instantiated when calling `Object.create` and therefore be properties of the instance.
How do i add a static member to a class when using EcmaScript 5 style object creation? | 2012/07/27 | [
"https://Stackoverflow.com/questions/11687038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1557495/"
] | For ES 5 if you want static methods:
```
// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
alert("I am a Person object ;)");
};
// An instance method;
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
this.name = nameIn;
}
```
see @<https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/> | You seem to have some different things mixed up. The prototype is going to be shared fallback properties. If you want to define a static (I assume by what you're doing you mean non-writable property?) you can use defineProperty in the constructor.
```
function Account(){
Object.defineProperty(this, 'id', {
value: uuid.v4()
});
Account.instances[this.id] = this;
}
Account.instances = {};
Account.prototype.id = null;
var account = new Account;
``` |
17,848 | Is there any way I, as a **viewer**, can change the aspect ratio of a video where the uploader got it wrong? It's driving me mad! Can't believe YouTube doesn't have anything for me to fix this... Does it?
---
**Edit:** is there perhaps a program for viewing YouTube videos outside of the browser that has the feature? For instance, [Miro](http://www.getmiro.com/) can show youtube videos, although unfortunately it doesn't seem to have a feature to adjust the aspect ratio either.
---
**Bounty:** looking for new options, since iDesktop can no longer do this. | 2010/01/14 | [
"https://webapps.stackexchange.com/questions/17848",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/12388/"
] | At long last, [YouTube Center](https://addons.mozilla.org/en-us/firefox/addon/youtube-center/), a Firefox addon, enables me to do this!
 | this issue is SOLVED. Just add a code to your video youtube tags in order to choose the ratio aspect. Please check out [this video](http://www.youtube.com/watch?v=MFPcAIM8fB0) to find some examples: |
5,124,441 | I have a `div` (`div1`) that has its position, width, height, everything all set, and it is set externally, so I can't know ahead of time what those values are.
Inside and at the top of `div1` is another `div` (`div2`). I want `div2` to float on the right of `div1` without affecting the following information in `div1`.
I can add the attribute `position:absolute` and get `div2` to float and not affect the contents, however, I cannot get it to float on the right, even when applying `float:right`. | 2011/02/26 | [
"https://Stackoverflow.com/questions/5124441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/562697/"
] | If I understand correctly:
First, apply `position: relative` to your `div1`.
As it "won't work" when you have both `float: right` and `position: absolute` on your `div2`, you should replace the `float: right` rule with `right: 0`. | with just relative positioning?
```
<div style="height:300px;width:300px;position:relative;background-color:red">
<div style="height:100px;width:100px;position:relative;float:right;background-color:yellow">
</div>
``` |
27,920,669 | I am surprised that the following code when input into the Chrome js console:
```
{} instanceof Object
```
results in this error message:
>
> Uncaught SyntaxError: Unexpected token instanceof
>
>
>
Can anyone please tell me why that is and how to fix it? | 2015/01/13 | [
"https://Stackoverflow.com/questions/27920669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536299/"
] | `{}`, in that context, is a *block*, not an object literal.
You need change the context (e.g. by wrapping it in `(` and `)`) to make it an object literal.
```
({}) instanceof Object;
``` | If you try this:
```
var a = {}
a instanceof Object
```
outputs `true`, which is the expected output.
However, in your case
```
{} instanceof Object
```
The above doesn't outputs true.
The latter **isn't** the same as the first one. In the first case, we create an object literal, while in the second case we don't. Hence you get this error. |
201,743 | I am currently learning about TDD and trying to put it into practice in my personal projects. I have also used version control extensively on many of these projects. I am interested in the interplay of these two tools in a typical work flow, especially when it comes to the maxim to keep commits small. Here are some examples that come to mind:
1. I start a new project and write a simple test to create an as-yet-nonexistent class. Should I commit the test before writing the class even though the test doesn't even compile? Or should I stub out the minimum amount of code that is needed to get the test to compile before committing?
2. I find a bug and write a test to recreate it. Should I commit the failing test or implement the bug fix and then commit?
These are the two examples that come immediately to mind. Feel free to provide additional examples in your answer.
**Edit:**
I made an assumption in both examples that immediately after writing the test I will write code to make the test pass. Another situation might also arise: I work on a project using TDD for several hours without committing. When I finally make commits, I want to break up my work into small chunks. (Git makes this relatively easy even if you want to want to commit only some of the changes in a single file.)
This means that my question is as much about as *what* to commit as it is about *when* to commit. | 2013/06/16 | [
"https://softwareengineering.stackexchange.com/questions/201743",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/61509/"
] | It is my understanding of the world that one commits to mark a point that it may be desirable to return to. The point a which a test fails (but compiles) is definitely one such point. If I were to wander off in the wrong direction trying to make a test pass, I would want to be able to revert the code back to the starting point and try again; I can't do this if I haven't committed. | For *code reviews*, especially regarding bug fixes, I like to see that a test failed before the fix was implemented. So I'd actually encourage to commit and push **your** branch so that I can be assured that:
1. the test actually failed
2. the problem is actually fixed with the next commit
If both happens in only one commit I won't really be able to see if either test or code just do nothing.
Of course, for that to work you should have automatic multi branch continuous integration.
After code review though, I agree with the other answers and it might be sensible to squash commits together. |
9,484,571 | I have this code so far:
```
private class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
String myEmail = theParams[1];
String myPassword = theParams[2];
HttpPost post = new HttpPost(myUrl);
post.addHeader("Authorization","Basic "+ Base64.encodeToString((myEmail+":"+myPassword).getBytes(), 0 ));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = null;
try
{
response = client.execute(post, responseHandler);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null)
{
response += s;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result)
{
}
}
```
This code does not compile because I am running into confusion at the point of:
```
response = client.execute(post, responseHandler);
InputStream content = execute.getEntity().getContent();
```
I got that code from tinkering with various examples, and not sure what Object the client is supposed to be, and whether the first line will just get me the server response, or I have to go the route of getting the InputStream and reading the server response in?
Please help me understand how to do this correctly.
Thank you! | 2012/02/28 | [
"https://Stackoverflow.com/questions/9484571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731255/"
] | You might want to switch to [`HttpURLConnection`](http://developer.android.com/reference/java/net/HttpURLConnection.html). According to [this article](http://android-developers.blogspot.com/2011/09/androids-http-clients.html) its API is simpler than `HttpClient`'s and it's better supported on Android. If you do choose to go with `HttpURLConnection`, authenticating is pretty simple:
```
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
});
```
After that, continue using `HttpURLConnection` as usual. A simple example:
```
final URL url = new URL("http://example.com/");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
builder.append(new String(buffer, 0, readCount));
}
final String response = builder.toString();
``` | The version of Apache's `HttpClient` shipped with Android is [based on an old, pre-BETA version of `HttpClient`](https://hc.apache.org/httpcomponents-client-4.3.x/android-port.html). Google has [long recommended against using it](http://android-developers.blogspot.se/2011/09/androids-http-clients.html) and [removed it in Android 6.0](https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html). Google's replacement `HttpURLConnection` [does not support HTTP digest authentication](https://developer.android.com/reference/java/net/HttpURLConnection.html), only basic.
This leaves you with a few options, including:
* Migrate to `HttpURLConnection` (as Google recommends) and use a library, [bare-bones-digest](https://github.com/al-broco/bare-bones-digest), for digest authentication. Example below.
* Use the [OkHttp](https://square.github.io/okhttp/) library instead of `HttpURLConnection` or `HttpClient`. OkHttp does not support digest out of the box, but there's a library [okhttp-digest](https://github.com/rburgst/okhttp-digest) that implements a digest authenticator. Example below.
* Continue using the (deprecated) `HttpClient` by explicitly adding the `'org.apache.http.legacy'` library to your build, as mentioned in the [changelist for Android 6.0](https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html).
* There is an Apache project for porting newer versions of `HttpClient` to Android, but the project has been discontinued. Read more on [Apache's page on HttpClient for Android](https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html).
* Implement HTTP digest yourself.
Here is a verbose example of how to authenticate a request using [bare-bones-digest](https://github.com/al-broco/bare-bones-digest) and `HttpURLConnection` (copied from the project's github page):
```
// Step 1. Create the connection
URL url = new URL("http://httpbin.org/digest-auth/auth/user/passwd");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Step 2. Make the request and check to see if the response contains
// an authorization challenge
if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Step 3. Create a authentication object from the challenge...
DigestAuthentication auth = DigestAuthentication.fromResponse(connection);
// ...with correct credentials
auth.username("user").password("passwd");
// Step 4 (Optional). Check if the challenge was a digest
// challenge of a supported type
if (!auth.canRespond()) {
// No digest challenge or a challenge of an unsupported
// type - do something else or fail
return;
}
// Step 5. Create a new connection, identical to the original
// one..
connection = (HttpURLConnection) url.openConnection();
// ...and set the Authorization header on the request, with the
// challenge response
connection.setRequestProperty(
DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
auth.getAuthorizationForRequest("GET", connection.getURL().getPath()));
}
```
Here is an example using [OkHttp](https://square.github.io/okhttp/) and [okhttp-digest](https://github.com/rburgst/okhttp-digest) (copied from the okhttp-digest page):
```
client = new OkHttpClient();
final DigestAuthenticator authenticator = new DigestAuthenticator(new Credentials("username", "pass"));
final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
client.interceptors().add(new AuthenticationCacheInterceptor(authCache));
client.setAuthenticator(new CachingAuthenticatorDecorator(authenticator, authCache));
Request request = new Request.Builder()
.url(url);
.get()
.build();
Response response = client.newCall(request).execute();
``` |
23,757,820 | ```
function changeBGG1() {
var a = $('#vbox').css("backgroundColor");
if (a == "#800000") {
$('#vbox').css("webkitAnimation", 'Red2Green 2s');
$('#vbox').css("backgroundColor", '#004C00');
}
}
```
i know that there is an error in the condition check, but i dnt know how to avoid it as there is no method to parse a color. | 2014/05/20 | [
"https://Stackoverflow.com/questions/23757820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648908/"
] | In CSS, background colours are generally returned in `rgb(...)` format, *but not always*. If there's transparency involved, it'll be `rgba(...)` format. Some browsers (especially older ones) will use `#RRGGBB` format.
Long story short, you *cannot* rely on the value of `backgroundColor` for any kind of comparison.
Use a `.data()` property instead. | Try this :)
```
$.fn.getHexBackgroundColor = function() {
var rgb = $(this).css('background-color');
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function changeBGG1() {
var a = $('#vbox').getHexBackgroundColor();
if (a == "#800000") {
$('#vbox').css("webkitAnimation", 'Red2Green 2s');
$('#vbox').css("backgroundColor", '#004C00');
}
}
``` |
38,104,600 | I was wondering if it is possible to change the position of a column in a dataframe, actually to change the schema?
Precisely if I have got a dataframe like `[field1, field2, field3]`, and I would like to get `[field1, field3, field2]`.
I can't put any piece of code.
Let us imagine we're working with a dataframe with one hundred columns, after some joins and transformations, some of these columns are misplaced regarding the schema of the destination table.
How to move one or several columns, i.e: how to change the schema? | 2016/06/29 | [
"https://Stackoverflow.com/questions/38104600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6529357/"
] | The [spark-daria](https://github.com/mrpowers/spark-daria) library has a `reorderColumns` method that makes it easy to reorder the columns in a DataFrame.
```
import com.github.mrpowers.spark.daria.sql.DataFrameExt._
val actualDF = sourceDF.reorderColumns(
Seq("field1", "field3", "field2")
)
```
The `reorderColumns` method uses @Rockie Yang's solution under the hood.
If you want to get the column ordering of `df1` to equal the column ordering of `df2`, something like this should work better than hardcoding all the columns:
```
df1.reorderColumns(df2.columns)
```
The [spark-daria](https://github.com/MrPowers/spark-daria) library also defines a `sortColumns` transformation to sort columns in ascending or descending order (if you don't want to specify all the column in a sequence).
```
import com.github.mrpowers.spark.daria.sql.transformations._
df.transform(sortColumns("asc"))
``` | **Spark Scala Example:**
Let's assume a you have a dataframe `demo_df` and it has following column set:
`id, salary, country, city, firstname, lastname`
and you want to rearrange its sequence.
**demo\_df**
[](https://i.stack.imgur.com/YMgHh.png)
Select all the column(s) and drop those column(s) you want to rearrange.
I have removed 'salary, country, city' columns from the list of columns.
`val restcols = demo_df.columns.diff(Seq("salary", "country", "city"))`
Now rearrange the column name(s) according to your requirement and append or prepend to the remaining column(s)
**Example to prepend the column(s)**
`val all_cols = Seq($"salary", $"city", $"country") ++: restcols.map(col(_))`
Now select the dataframe and provide the newly defined column list
`demo_df.select(all_cols: _*).show()`
[](https://i.stack.imgur.com/1jY9W.png)
**Example to append the column(s)**
`val all_cols = restcols.map(col(_)) ++ Seq($"salary", $"city", $"country")`
`demo_df.select(all_cols: _*).show()`
[](https://i.stack.imgur.com/EHWUr.png)
Hope it helps. Happy Coding !! |
47,049,524 | I was told to use proxy pattern in my program which is not that clear to me.
I have some issues with `Proxy &operator*()` , I don't know what should I return there to get a value of current index in file.
I had this before and it worked:
```
int &operator*()
{
return ptr->getValue(index);
}
```
But I was told to change it to `Proxy`.
If I compile with `Proxy &operator*()` then I'm getting
>
> error: invalid initialization of reference of type 'IntFile::Proxy&'
> from expression of type 'int'|
>
>
>
Full code:
```
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
class IntFile
{
public:
int value;
FILE* file;
IntFile()
{
file = fopen("text.txt", "r+b");
}
~IntFile()
{
fclose(file);
}
virtual int& getValue(int index)
{
fseek(file, 4*index, SEEK_SET);
fread(&value, 4, 1, file);
return value;
}
virtual int setValue(int value)
{
fseek(file, 0, SEEK_CUR);
fwrite(&value, 4, sizeof(value),file);
return 0;
}
class Proxy
{
private:
IntFile *ptr;
long index;
public:
Proxy(IntFile* ptr3)
{
ptr = ptr3;
}
Proxy& operator=(int value)
{
ptr->setValue(value);
}
operator int() const
{
return ptr->getValue(index);
}
};
friend struct iterator;
struct iterator
{
int index;
int value2;
IntFile* ptr;
iterator(IntFile* ptr2, int idx, FILE* ptrfile)
{
ptr = ptr2;
index = idx;
fseek(ptrfile, 4*index, SEEK_SET);
}
bool operator==(const iterator&other) const
{
return index == other.index;
}
bool operator!=(const iterator&other) const
{
return index!=other.index;
}
Proxy &operator*()
{
// How to do that?
}
int &operator=(int value)
{
this->value2 = value;
}
iterator&operator++()
{
this->index = index+1;
}
iterator&operator--()
{
this->index = index -1;
}
};
iterator begin()
{
return iterator(this, 0, file);
}
iterator end(int number)
{
return iterator(this, number, file);
}
iterator rbegin(int number)
{
return iterator(this, number-1, file);
}
iterator rend()
{
return iterator(this, -1, file);
}
};
int main()
{
IntFile myfile;
int number;
cout << "Enter number of elements: " << endl;
cin >> number;
vector <int> myVector;
cout << "Enter your numbers: ";
for ( int i = 0; i < number; i++)
{
cin >> myfile.value;
myVector.push_back(myfile.value);
}
fwrite(&myVector[0], sizeof(vector<int>::value_type), myVector.size(),myfile.file);
cout << endl << "FORWARD 1 by 1: " << endl;
for (IntFile::iterator i = myfile.begin(); i != myfile.end(number); ++i)
{
cout << *i << " ";
}
cout << endl << "BACKWARD 1 by 1: " << endl;
for (IntFile::iterator i = myfile.rbegin(number); i != myfile.rend(); --i)
{
cout << *i << " ";
}
cout << endl;
return 0;
}
``` | 2017/11/01 | [
"https://Stackoverflow.com/questions/47049524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8866446/"
] | Returning a proxy requires of you to return a proxy **object**. You attempt to return a reference to such an object, but it doesn't exit. And we cannot bind a proxy reference to an integer.
The fix is simple, just return a new object by value:
```
Proxy operator*()
{
return Proxy(ptr);
}
``` | Try this
```
Proxy &operator*()
{
// How to do that?
return *this;
}
```
It avoid you to create another new Proxy |
7,715,760 | I've bound a command to a button on a Ribbon control. The CanExecute method on the button gets called as expected but clicking on the button doesn't cause the Execute method to be called. The `CanExecute` sets the `CanExecute` property to `true` - the button in question is enabled and clickable.
Has anyone else seen this behaviour before? If so how do I fix it!
EDIT:
```
CommandBinding commandBinding = new CommandBinding(StaticCommands.ThisCommand, ThisCommandExecutedHandler, ThisCommandCanExecuteHandler);
CommandManager.RegisterClassCommandBinding(this.GetType(), commandBinding);
CommandBindingList.Add(commandBinding);
```
`StaticCommands.ThisCommand` is a `RoutedCommand` with an input gesture of `F5`.
Unfortunately I can't post any xaml because everything is wrapped up in another team's libraries. I am assuming that is correct for now. Also, using the keyboard gesture associated with the command (pressing `F5`) causes the execute method to be called.
There are no exceptions thrown, no messages in the output window, and snoop shows everything bound correctly. I'm really stumped. | 2011/10/10 | [
"https://Stackoverflow.com/questions/7715760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/280780/"
] | This usually happens if the parameters dont match in type correctly... are you binding `CommandParameter` of one type and accepting a different type parameter in the Command.Execute() call? | Fixed this by wrapping the `RoutedCommands` in a [`RelayCommand`](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090051). I have no idea why that worked, but assuming there's a problem in the other team's assembly. |
24,573,548 | i need to run new-installed program from command prompt on windows 7 like it is posibble for notepad calc or some other windows-basic program... How i can do that? I tryed to use enviroment variables but i fell in stuck with it. Is there a way for something like this ? | 2014/07/04 | [
"https://Stackoverflow.com/questions/24573548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097635/"
] | try like this command
start c:\"Program Files"\VideoLAN\VLC\vlc.exe
or you can use
"c:\Program Files\VideoLAN\VLC\vlc.exe"
quote must need for the the file/folder name which is having space | So according to the comments to your question, you now managed to start your program from whereever you are by including it's path to the %path% variable.
Your new error "Unable to run package setup. Failed to load module. ImportErorr: No module named Package setup" comes from your program, which fails to load some of it's modules.
That's because it looks for them in the current working directory. (where you are, not where the program and it's modules are stored)
Create a short batchfile in the program's folder:
```
cd /d "%~dp0"
start program.exe
```
Save it as "program.bat" (if you just enter "program", it will look first, if there is a .bat and starts that instead of an .exe with the same name).
The first line changes the current working directory to the file, where that .bat (and the program and it's modules) resides, the second line just starts the program itself. |
2,010,895 | I am trying to get the jquery getJSON function to work. The following seems very simple yet it doesn't work.
```
$("#edit-item-btn").live('click', function() {
var name = this.id;
$.getJSON("InfoRetrieve",
{ theName : name },
function(data) {
alert(name);
});
});
``` | 2010/01/06 | [
"https://Stackoverflow.com/questions/2010895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
] | Shouldn't you be doing alert(data)? | Have you tried using Firebug or Chrome Developer Tools to see what requests are being made?
Does a file called `InfoRetrieve` exist in the current path of your site? What does it return? |
6,601,042 | I have 3 text inputs for a phone number - phone\_ac, phone\_ex, phone\_nm - i.e. 999 555 1212
I can use jquery to validate each individually and give 3 error messages:
```
"Phone number (area code) is required."
"Phone number (exchange) is required."
"Phone number (last 4 digits) is required."
```
Is there a way to have one error message only if ANY of the 3 fields are blank? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6601042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618157/"
] | This should do the job. You didn't really link to cURL before.
```
build: $(SOURCES)
$(CXX) -o $(OUT) $(INCLUDE) $(CFLAGS) $(LDFLAGS) $(LDLIBS) $(SOURCES)
```
Notice the *added* `$(LDLIBS)`.
Oh, I should add that basically what happens is that you throw overboard the built-in rules of GNU make (see output of `make -np`) and define your own. I would suggest that you either use the built-in ones if you want to rely on the respective variables to be sufficient to control the build or that you still split it up into compilation and link step for the sake of brevity.
Brief explanation: GNU make comes with a rule that states how to make a `.o` file from a `.cpp` (or `.c`) file. So your make file could perhaps be rewritten to (approx.)
```
# Testing cURL
# MAKEFILE
# C++ Compiler (Default: g++)
CXX = g++
CFLAGS = -Wall -Werror
# Librarys
INCLUDE = -I/usr/local/include
LDFLAGS = -L/usr/local/lib
LDLIBS = -lcurl
# Details
SOURCES = src/main.cpp
OUT = test
.PHONY: all
all: build
$(OUT): $(patsubst %.cpp,%.o,$(SOURCES))
```
This should generate the binary with the name `test` (contents of `OUT`) and makes otherwise use of the built-in rules. Make infers from the use of `.o` files that there must be source files, will look for them and compile them. So implicitly this build will run one invocation for each `.cpp` file and one for the linking step. | You are missing slashes at the start of the paths below
```
-I/usr/local/include
-L/usr/local/lib
``` |
103,089 | Can a Trojan horse hide its activity from [TCPView](https://technet.microsoft.com/en-us/library/bb897437.aspx)?
I've done a little research before asking, but I still can't find the answer for this.
I know that a Trojan horse can hide from the Windows [Task Manager](http://en.wikipedia.org/wiki/Windows_Task_Manager) through various methods. Also, less frequently, it can hide its activity from the [`netstat`](https://en.wikipedia.org/wiki/Netstat) command (mostly replacing the program with their own version). I guess is less frequently because (I expect) any non-compromised antivirus protect and alert for changes in system files (not sure if I'm being naive).
Even though, If the Trojan uses a Windows process (not it's own name) to connect to the Internet, many times you can identify what isn't an expected connection to some random IP address.
Many websites recommend using TCPView to check for unusual connections, and I wonder if a Trojan can hide its activity from TCPView. I'm not sure if TCPView is just a graphic interface using the netstat program. In that case, if there's any method to hide from `netstat`, it will be hidden from TCPView of course.
I don't think that a Trojan horse would be specifically coded to hide from TCPView (or it is TCPView so popular that this happens?), but maybe there's a method to hide its activity from any program trying to check the current Internet connections (even [Wireshark](http://en.wikipedia.org/wiki/Wireshark)) and to hide what programs or Windows processes (even [`svchost`](https://en.wikipedia.org/wiki/Svchost) or system) are establishing those connections as well.
If you know specific methods used to hide from TCPView could you mention them?
I want to know this, because I'm not sure that using TCPView or Wireshark to check for unusual connections is a bulletproof test to confirm that activity. | 2015/10/19 | [
"https://security.stackexchange.com/questions/103089",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/89602/"
] | It's absolutely possible that someone is developing malware which is capable of hiding packets from sniffers. As most sniffers on Windows systems depend on `WinPCAP` as a capture driver, it would for example be possible to manipulate the drivers to hide specific packets that are traveling the wire.
This is why I use my laptop as a bridge to capture packets when it comes to potentially compromised systems. You can easily do this using the `bridge-utils` package on most linux systems. | Anything can be manipulated in Windows with skilled reverse engineering. An generic [RAT](https://en.wikipedia.org/wiki/Remote_administration_software) hiding TCP from Wireshark is extremely unlikely, but it's possible. Don't just rely on your antivirus software (AV) as they are very unreliable and don't have very good heuristic techniques in my opinion.
You could write yourself some malicious program and upload it to <https://www.virustotal.com/>, and I bet you most AVs wouldn't detect what you've written. File system changes are not logged by all AVs, and it would be a time-consuming initial task as it would have to hash known system files.
If you want bulletproof checks for networking you'll want to log the traffic on the router, but make sure your router isn't compromised before you do the network logging. |
1,699,451 | I am using `SHA1` so i want to convert the output of this `SHA1` to integer | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206672/"
] | This question is hard to answer without the full context, but i'll give it a try.
What i've been forced to do a few times is this:
1. Check out a fresh copy Backup my WC
2. Delete all .svn directories in my WC
3. Overwrite the fresh copy in (1) with my WC files.
4. Commit
Other techniques are (after making a backup of course)
Revert WC and then put the edited files in.
Update (which probably will not work in your case)
This is pretty awkward and if there is a better way i'd be very interested to learn it as well.
The problem seems to appear due to revisions of deleted/added files that are in the wrong order. | FWIW, I wound up using this:
```
find . -name ".svn" -type d -exec rm -rf {} \;
```
to remove all the .svn files and re-importing. I wasn't losing any history, really, so that seemed easiest....
Several of the other answers here seem viable, as well. |
9,210,187 | i get the following error when trying to run my spring 3.1.0 MVC app via Tomcat 7:
>
> The matching wildcard is strict, but no declaration can be found for
> element 'mvc:annotation-driven'.
>
>
>
Here is my mvc-config.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc/
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven />
<!-- the application context definition for the springapp DispatcherServlet -->
<mvc:view-controller path="/" view-name="index" />
</beans>
```
And here is my servlet
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<import resource="mvc-config.xml" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<context:component-scan base-package="com.jr.freedom.controllers"></context:component-scan>
</beans>
```
Finally, here is the full exception from tomcat 7
```
> org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
> Configuration problem: Failed to import bean definitions from relative
> location [mvc-config.xml] Offending resource: ServletContext resource
> [/WEB-INF/FreedomSpring-servlet.xml]; nested exception is
> org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
> Line 11 in XML document from ServletContext resource
> [/WEB-INF/mvc-config.xml] is invalid; nested exception is
> org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching
> wildcard is strict, but no declaration can be found for element
> 'mvc:annotation-driven'. at
> org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
> at
> org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
> at
> org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
> at
> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:271)
> at
> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:196)
> at
> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:181)
> at
> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
> at
> org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
> at
> org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
> at
> org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
> at
> org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
> at
> org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
> at
> org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
> at
> org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
> at
> org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
> at
> org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
> at
> org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
> at
> org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
> at
> org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:522)
> at
> org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
> at
> org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
> at
> org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
> at
> org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
> at
> org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
> at
> org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
> at
> org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
> at javax.servlet.GenericServlet.init(GenericServlet.java:160) at
> org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
> at
> org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
> at
> org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
> at
> org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
> at
> org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
> at
> org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
> at
> org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:897)
> at
> org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:873)
> at
> org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
> at
> org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
> at
> org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
> at java.util.concurrent.Executors$RunnableAdapter.call(Unknown
> Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown
> Source) at java.util.concurrent.FutureTask.run(Unknown Source) at
> java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source)
```
Edit. here is my build.xml
```
<?xml version="1.0"?>
<project name="springapp" basedir="." default="usage">
<property file="build.properties"/>
<property name="src.dir" value="src"/>
<property name="web.dir" value="war"/>
<property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
<property name="name" value="FreedomSpring"/>
<path id="master-classpath">
<fileset dir="${web.dir}/WEB-INF/lib">
<include name="*.jar"/>
</fileset>
<!-- We need the servlet API classes: -->
<!-- * for Tomcat 5/6 use servlet-api.jar -->
<!-- * for other app servers - check the docs -->
<fileset dir="${appserver.lib}">
<include name="servlet*.jar"/>
</fileset>
<pathelement path="${build.dir}"/>
</path>
<target name="usage">
<echo message=""/>
<echo message="${name} build file"/>
<echo message="-----------------------------------"/>
<echo message=""/>
<echo message="Available targets are:"/>
<echo message=""/>
<echo message="build --> Build the application"/>
<echo message="deploy --> Deploy application as directory"/>
<echo message="deploywar --> Deploy application as a WAR file"/>
<echo message="install --> Install application in Tomcat"/>
<echo message="reload --> Reload application in Tomcat"/>
<echo message="start --> Start Tomcat application"/>
<echo message="stop --> Stop Tomcat application"/>
<echo message="list --> List Tomcat applications"/>
<echo message=""/>
</target>
<target name="build" description="Compile main source tree java files">
<mkdir dir="${build.dir}"/>
<javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
deprecation="false" optimize="false" failonerror="true">
<src path="${src.dir}"/>
<classpath refid="master-classpath"/>
</javac>
</target>
<target name="deploy" depends="build" description="Deploy application">
<copy todir="${deploy.path}/${name}" preservelastmodified="true">
<fileset dir="${web.dir}">
<include name="**/*.*"/>
</fileset>
</copy>
</target>
<target name="deploywar" depends="build" description="Deploy application as a WAR file">
<war destfile="${name}.war"
webxml="${web.dir}/WEB-INF/web.xml">
<fileset dir="${web.dir}">
<include name="**/*.*"/>
</fileset>
</war>
<copy todir="${deploy.path}" preservelastmodified="true">
<fileset dir=".">
<include name="*.war"/>
</fileset>
</copy>
</target>
<!-- ============================================================== -->
<!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
<!-- ============================================================== -->
<path id="catalina-ant-classpath">
<!-- We need the Catalina jars for Tomcat -->
<!-- * for other app servers - check the docs -->
<fileset dir="${appserver.lib}">
<include name="catalina-ant.jar"/>
</fileset>
</path>
<taskdef name="install" classname="org.apache.catalina.ant.DeployTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>
<taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>
<taskdef name="list" classname="org.apache.catalina.ant.ListTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>
<taskdef name="start" classname="org.apache.catalina.ant.StartTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>
<taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>
<target name="install" description="Install application in Tomcat">
<echo message="deploy path = ${deploy.path}/${name}"/>
<install url="${tomcat.manager.url}"
username="${tomcat.manager.username}"
password="${tomcat.manager.password}"
path="${deploy.path}/${name}"
war="${deploy.path}/"/>
</target>
<target name="reload" description="Reload application in Tomcat">
<reload url="${tomcat.manager.url}"
username="${tomcat.manager.username}"
password="${tomcat.manager.password}"
path="/${name}"/>
</target>
<target name="start" description="Start Tomcat application">
<start url="${tomcat.manager.url}"
username="${tomcat.manager.username}"
password="${tomcat.manager.password}"
path="${deploy.path}/${name}"/>
</target>
<target name="stop" description="Stop Tomcat application">
<stop url="${tomcat.manager.url}"
username="${tomcat.manager.username}"
password="${tomcat.manager.password}"
path="${deploy.path}/${name}"/>
</target>
<target name="list" description="List Tomcat applications">
<list url="${tomcat.manager.url}"
username="${tomcat.manager.username}"
password="${tomcat.manager.password}"/>
</target>
<!-- End Tomcat tasks -->
</project>
``` | 2012/02/09 | [
"https://Stackoverflow.com/questions/9210187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/444668/"
] | You need this in your schema location:
```
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
``` | @jonney
The missing library is spring-webmvc.
Maven dependency :
org.springframework
spring-webmvc
${spring.version} |
13,632 | My German teacher told me that the email I sent her contained a threat. What I wrote was "Allerdings komme ich morgen." She didn't tell me why, just asked me to research about this, but I can't find anything on the Internet. Can someone please explain why she felt threatened?
Here's the whole exchange:
>
> First email: Liebe Frau X. Ich würde gern einen Termin mit Ihnen ausmachen.
>
> Answer: Könntest du morgen um 13 Uhr kommen?
>
> Second email: Allerdings, wir sehen uns morgen um 13 Uhr.
>
>
>
She then told me that *allerdings* was perceived as a threat. So it doesn't have anything to do with viruses or other sentences. It was *allerdings*, and I can't figure out why. | 2014/06/24 | [
"https://german.stackexchange.com/questions/13632",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/8701/"
] | It depends on the context. If you wrote
>
> Ich kann heute leider nicht kommen. Allerdings komme ich morgen.
>
>
>
then there is absolutely no threat. You say that you can't come today, however you'll come tomorrow. On the other hand, in
>
> Ob ich morgen komme? Allerdings komme ich morgen.
>
>
>
it means "*indeed* I will come" and might indeed be considered a threat. | "Allerdings" means "Indeed" and is an affirmation. ("Das ist Dir wohl wichtig." -- "Allerdings ist mit das wichtig!")
It depends on the context if you see it as a threat, but I usually would not. |
13,306,670 | I am using Bootstrap from twitter. What I want is to make a prepended text, and input field and a button, but I want my input field have the max available width so that the right edge of the submit button was near the right edge of the well. From the bootstrap documentation there is the **.input-block-level** class that lets any or element behave like a block level element, but applying it to the input gives in result the central input the size of the well. <http://jsfiddle.net/Uc4CE/>
```
<div class="well">
<div class="input-prepend input-append">
<span class="add-on">Some text</span>
<input class="input" type="text" name="xxx" value="xxx" />
<input type="hidden" name="next" value="xxx" />
<input type="submit" value="xx" class="btn btn-info" />
</div>
</div>
``` | 2012/11/09 | [
"https://Stackoverflow.com/questions/13306670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1811899/"
] | I was looking for something similar and this solution from <https://gist.github.com/mattjorn/5020957> worked for me - add `.input-block-level` to your outer div, e.g.,
`<div class="input-prepend input-append input-block-level">`
and then extend the bootstrap CSS like this:
```
.input-prepend.input-block-level {
display: table;
width: 100%;
}
.input-prepend.input-block-level .add-on {
display: table-cell;
background-color: white;
}
.input-prepend.input-block-level > input {
box-sizing: border-box;
height: 30px;
display: table-cell;
width: 100%;
border-left-style: none;
}
``` | may be use for `div class="input-prepend input-append"` additional style `margin-right`
result for your code:
```
<div class="well">
<div class="input-prepend input-append" style="margin-right: 108px;">
<span class="add-on">Some text</span>
<input class="input-block-level" type="text" name="xxx" value="xxx" />
<input type="hidden" name="next" value="xxx" />
<input type="submit" value="xx" class="btn btn-info" />
</div>
</div>
```
<http://jsfiddle.net/Uc4CE/1/> |
20,981,075 | How can I write a query to find all records in a table that have a null/empty field? I tried tried the query below, but it doesn't return anything.
```
SELECT * FROM book WHERE author = 'null';
``` | 2014/01/07 | [
"https://Stackoverflow.com/questions/20981075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892302/"
] | As far as I know you cannot do this with `NULL`.
As an alternative, you could use a different empty value, for example the empty string: `''`
In that case you could select all books with an empty author like this (assuming the author column is appropriately indexed):
```
SELECT * FROM book WHERE author = '';
``` | If **your\_column\_name** in **your\_table** is a text data type then following should work,
```
SELECT * FROM your_table WHERE your_column_name >= '' ALLOW FILTERING;
``` |
7,397,078 | I have to display a set of data in the following manner:

Which ASP.NET 3.5 control best matches my requirement?
If one matches, could you please give me an idea about how to format it to view like the image? | 2011/09/13 | [
"https://Stackoverflow.com/questions/7397078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441343/"
] | This is official documentation of libpq.
<http://www.postgresql.org/docs/8.1/static/libpq.html> | You can try third-party C++ libraries for database connectivity like [SOCI](http://soci.sourceforge.net/) |
57,300,501 | I have a couple of Specflow's features file which contain multiple scenarios and I want to execute them against multiple environments (DEV, TEST, and SIT).
So, my question here is - what is the best way to pass environment specific data from feature file to step definition. As you can see in the example below employee records are different in each environment.
```
Scenario Outline: Employee Search
Given Application is logged
And Search for employee record with <EmployeeName>, <EmployeeID>, <Company>, <Designation> and <Environment>
Examples:
| EmployeeName| EmployeeID| Company | Designation | Environment |
| John Smith 1| 123 | ABC | Analyst | DEV |
| John Smith 2| 456 | DFG | Manager | TEST |
| John Smith 3| 789 | XYZ | Sr Analyst | SIT |
[When(@"Search for employee record with (.*), (.*), (.*), (.*) and (.*)")]
public void WhenSearchEmployee (string EmployeeName, string EmployeeID, string Company, string Designation, string Environment)
{
if (Environment== "DEV")
{
EmployeeRecord.SearchEmployee(EmployeeName, EmployeeID, Company, Designation);
}
else if (Environment== "TEST")
{
EmployeeRecord.SearchEmployee(EmployeeName, EmployeeID, Company, Designation);
}
else if (Environment== "SIT")
{
EmployeeRecord.SearchEmployee(EmployeeName, EmployeeID, Company, Designation);
}
}
```
**Edits**
* I'm identifying the environment with `app.config` file
Basically, I want to execute the same test case in multiple environments (one at a time) with different data. Also if I have two rows in `examples` table, how to execute only once based on the environment.
Is this the right approach? Thanks. | 2019/08/01 | [
"https://Stackoverflow.com/questions/57300501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2524202/"
] | If you can't create on demand each time, here is another way.
Create a data.cs file.
```
public class EnvData
{
public EnvData()
{
{
defaultEmail = "test@gmail.com";
defaultPassword = "MyPass123";
}
if(ConfigurationManager.AppSettings["Env"] == "Test")
{
empName = "John Smith";
EmployeeID = "1234";
Company = "McDonalds";
Designation = "McManager";
}
else if (ConfigurationManager.AppSettings["Env"] == "Dev")
{
empName = "Joe Smith";
EmployeeID = "3456";
Company = "McDonalds";
Designation = "FryGuy";
}
}
public static string defaultEmail;
public static string defaultPassword;
public static string empName;
public static string EmployeeID; //can be an int
public static string Company;
public static string Designation;
}
}
```
Then in your step file we use context injection - <https://specflow.org/documentation/context-injection/>
```
private readonly EnvData _envData;
public MyClassName(EnvData envData)
{
_envData = envData;
}
```
The reason you do it this way is that if you need to change the data, you change it in one area and not in each test case.
```
Scenario: Employee Search
Given Application is logged
And Search for an employee
[When(@"Search for employee]
public void WhenSearchEmployee ()
{
//would look something like this...
EmployeeRecord.SearchEmployee(envData.empName, envData.EmployeeID, envData.Company, envData.Designation);
}
```
So in the above, the step will hit envData and based on the appconfig value for the environment, it will pull whatever employee info you set. This works great if your data is static. I still prefer creating the search criteria first and then searching so you do not have to do all this lol. | Since you are already passing the environment in the step, I would personally pass that value to a database object constructor that switches the connection string from your app.config based on the constructor input.
Example using Entity Framework:
```
public void WhenSearchEmployee (string EmployeeName, string EmployeeID, string Company, string Designation, string Environment) {
using (var context = new SomeContext(Environment)) {
// Search Employee code here
}
}
```
Then you can pass that value to the DbContext base class which can select your environment by matching the name parameter from your app.config `<connectionStrings>`. EF will do this automatically, but if you're using ado.net you can still do something similar.
```
public partial class SomeContext : DbContext {
public SomeContext(string dbName) : base($"name={dbName}") {
}
}
```
In the end, anytime you need to use an environment specific database for your steps, calling this context and passing the environment name will make all your steps generic enough to not care which environment they are executing against. |
194,184 | I'd like to know how to emulate the ICANON behavior of ^D: namely, trigger an immediate, even zero-byte, read in the program on the other end of a FIFO or PTY or socket or somesuch. In particular, I have a program whose specification is that it reads a script on stdin up until it gets a zero byte read, then reads input to feed the script, and I'd like to automatically test this functionality.
Simply writing to a FIFO doesn't result in the right thing happening, of course, since there's no zero byte read. Help?
Thanks! | 2015/04/03 | [
"https://unix.stackexchange.com/questions/194184",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/109074/"
] | As far as I know, systemd won't deal with this particularly well. As I understand it, you want to override the behavior of `sshd.service`, right?
Luckily for you, systemd is designed for this kind of thing. Simply put your service definition in `/etc/systemd/system/ssh.service`, execute `systemctl daemon-reload` to reload unit files, and systemd will automatically use that configuration instead of the system `ssh.service`.
Want to have `systemctl enable mysshd.service` work, too? No problem. In the `[Install]` section of your unit file, add a line that says `Alias=mysshd.service`. Then execute `systemctl reenable ssh.service` to have systemd fix the unit symlinks, and you're golden.
Now, you haven't given details on what `mysshd.service` is supposed to do. If it's completely different from the normal `ssh.service`, great! Use the method above. However, if you just want to change one small thing, then you're using the wrong approach. systemd allows you to create "snippets" of unit files that will be applied on top of the normal unit files. This lets you add or override individual directives while allowing the rest of the unit file to receive updates from the package manager. To do this, simply create `/etc/systemd/system/ssh.d/my-custom-config.conf` (you can change `my-custom-config.conf` to be whatever you want, and you can also have multiple override files). In that file, place whatever directives you want to change or add to the usual `ssh.service`. You can even add `Alias=` directives, so that `systemctl start mysshd.service` works! Just remember to execute `systemctl daemon-reload` after you're done (and, if you used `Alias=`, `systemctl reenable ssh.service`).
As an aside, never, *ever* change systemd unit files in `/usr/lib/systemd`. Ever! The Filesystem Hierarchy Standard [requires](http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#THEUSRHIERARCHY) that `/usr` is treated as read-only. In practice, this means that the package manager handles `/usr` (except for `/usr/local`), and you don't touch what the package manager handles - especially because whatever you change will probably eventually be overwritten. Instead, put your stuff in somewhere like `/etc`. | Others have answered this question, however no one pointed out that you cannot create symbolic links to units that live in a user's home directory. They must live outside of it. Even if its owned by root, configured for 644 permissions, it will not work. Must be outside of /home.
@evandrix pointed out that you can use the --user flag. The process is more complicated than that. "--user" can only be applied to systemd units that are enabled in the user's directory. This allows users to control their own services outside of the --system domain. Be aware only specific version of systemd (I forget which ones but 2.37 and above are working for me) employee the --user domain. I recommend reading this post:
<https://nts.strzibny.name/systemd-user-services/>
Also this arch page gives good info too:
<https://wiki.archlinux.org/title/systemd/User>
**Quick breakdown of how to do it:**
1. User account must have a password. This will not work if the account does not have a password
2. perform a `ps -aux | grep systemd` You should see a "/usr/lib/systemd/systemd --user" for the specific user. This service is started when the user logs in for the firs time by pam.d
3. Does /home/YourUserName/.config/systemd/user/ directory exist? If it does, put your unit files in there. If it does not create it, and put your units in there.
4. Log out and log back in after moving your units to the above directory.
5. Perform these commands
```
$ systemctl --user enable myuser.service
$ systemctl --user daemon-reload
```
Now you can run all systemctl commands as the user, but you need to include the --user flag.
```
$ systemctl --user status myuser.service
$ systemctl --user start myuser.service
$ systemctl --user restart myuser.service
$ systemctl --user stop myuser.service
```
Be aware your "User" and "Group" settings in your unit's [Service] section need to set appropriately. Also when using --user, do not use `systemctl link myuser.service` this will not work as it only works in the system domain. The symbolic links for users are built when running `systemctl --user enable myuser.service` and links to `/home/YourUserName/.config/systemd/user/multi-user.target.wants/` |
119,914 | I prepare myself for ielts speaking test on these days and my topic is "what do you think about friendship?". In this case, I'm talking about people that I met in summer in different country.
>
> It wasn't important where they are from
>
>
> It wasn't important where are they from.
>
>
>
Can you tell me which one is correct? If two of them are wrong or inappropriate, how can I say in appropriate way? | 2017/02/19 | [
"https://ell.stackexchange.com/questions/119914",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/49463/"
] | >
> It was not important where they **were** from.
>
>
>
Since you are not **asking** about their homeland or the city they live in, you need to use the assertive form. (In interrogative form, the question would end with question mark "?", so you have to use the first one.)
Also, since you used the past "was" you should use *were*. | I'm going to nitpick a bit. You should use "where they are from," as this is perfectly normal in speech. But technically, it is incorrect to end a sentence with a preposition like "from." A strictly correct usage would be something like, "it doesn't mater from which country they come," although so few people use this rule that it seems out of place in everyday language. |
4,288,367 | Hy, I am currently trying to make a first person game.what i was able to do was to make the camera move using the function gluLookAt(), and to rotate it using glRotatef().What I am trying to to is to rotate the camera and then move forward on the direction i have rotated on, but the axes stay the same,and although i have rotated the camera moves sideways not forward. Can someone help me ? this is my code:
```
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(cameraPhi,1,0,0);
glRotatef(cameraTheta,0,1,0);
gluLookAt(move_camera.x,move_camera.y,move_camera.z,move_camera.x,move_camera.y,move_camera.z-10,0,1,0);
drawSkybox2d(treeTexture);
``` | 2010/11/26 | [
"https://Stackoverflow.com/questions/4288367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521765/"
] | This requires a bit of vector math...
Given these functions, the operation is pretty simple though:
```
vec rotx(vec v, double a)
{
return vec(v.x, v.y*cos(a) - v.z*sin(a), v.y*sin(a) + v.z*cos(a));
}
vec roty(vec v, double a)
{
return vec(v.x*cos(a) + v.z*sin(a), v.y, -v.x*sin(a) + v.z*cos(a));
}
vec rotz(vec v, double a)
{
return vec(v.x*cos(a) - v.y*sin(a), v.x*sin(a) + v.y*cos(a), v.z);
}
```
Assuming you have an orientation vector defined as {CameraPhi, CameraTheta, 0.0}, then if you want to move the camera in the direction of a vector v with respect to the camera's axis, you add this to the camera's position p:
```
p += v.x*roty(rotx(vec(1.0, 0.0, 0.0), CameraPhi), CameraTheta) +
v.y*roty(rotx(vec(0.0, 1.0, 0.0), CameraPhi), CameraTheta) +
v.z*roty(rotx(vec(0.0, 0.0, 1.0), CameraPhi), CameraTheta);
```
And that should do it.
Keep Coding :) | `gluLookAt` is defined as follows:
```
void gluLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ,
GLdouble centerX, GLdouble centerY, GLdouble centerZ,
GLdouble upX, GLdouble upY, GLdouble upZ
);
```
The camera is located at the `eye` position and looking in the direction from the `eye` to the `center`.
`eye` and `center` together define the axis (direction) of the camera, and the third vector `up` defines the rotation about this axis.
You don't need the separate phi and theta rotations, just pass in the correct `up` vector to get the desired rotation. `(0,1,0)` means the camera is upright, `(0,-1,0)` means the camera is upside-down and other vectors define intermediate positions. |
32,664,939 | This code is to print the series of prime number up to given limit but when I am trying to execute this,it goes into infinite loop.
```
import java.io.*;
class a
{
public static void main(String s[]) throws IOException
{
int count=1;
String st;
System.out.println("how many prime no. do you want");
BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
st=obj.readLine();
int n=Integer.parseInt(st);
while(count!=n)
{
int num=2;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
count++;
break;
}
}
num++;
}
}
}
``` | 2015/09/19 | [
"https://Stackoverflow.com/questions/32664939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5352896/"
] | After correction i got the series of prime numbers.
```
import java.io.*;
class a
{
public static void main(String s[]) throws IOException
{
int count=1,count1=0;
String st;
System.out.println("how many prime no. do you want");
BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
st=obj.readLine();
int n=Integer.parseInt(st);
int num=2;
while(count<=n)
{
count1=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
count1++;
}
}
if(count1==0)
{
System.out.println(num);
count++;
}
num++;
}
}
}
``` | ```
import java.util.*;
class Prime
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the no of prime nos want: ");
int n2 = sc.nextInt();
int flag = 1 ;
int count = 0 ;
for (int i =2; i<99999;i++ )
{
for (int j=2; j<i;j++ )
{
if (i%j == 0)
{
flag = 0;
break;
}
else
{
flag =1;
}
}
if (flag == 1)
{
System.out.print(i +"\t");
count++ ;
}
if (count == n2)
{
break ;
}
}
}
}
``` |
58,909,540 | **Specifications:**
Laravel Version: 5.4
PHP Version: 7.0.9
Composer version 1.9.0
XAMP
**Description:**
*In Connection.php line 647:*
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table `users` (`id` int unsigned not null auto\_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null,
`password` varchar(255) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` tim
estamp null) default character set utf8mb4 collate utf8mb4\_unicode\_ci)
*In Connection.php line 449:*
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists
**Problem:**
I have created models and tables of user and Product. It successfully created both migrations and tables but failed to migrate on phpmyadmin sql.
**Steps I tried:**
I have dropped all database and recreated it but still it gives error.
I have also used tinker but error is same.
**code:**
```
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
``` | 2019/11/18 | [
"https://Stackoverflow.com/questions/58909540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8100732/"
] | >
> Try to add the following condition before **Schema::create()**
>
>
>
```
if (!Schema::hasTable('users')) {
Schema::create('users',...)
}
``` | Check your migration table if the "User" Table is recorded there, delete it and then do a single migration using this artisan command
```
php artisan migrate:refresh --path=/database/migrations/fileName.php
```
Or Do reset the migration using the following and then migrate again
```
php artisan migrate:reset
``` |
6,486,888 | I need help with the following code that requires me to:
* Declare 3 `double` type variables, each representing one of three sides of a triangle.
* Prompt the user to input a value for the first side, then
* Set the user’s input to the variable you created representing the first side of the triangle.
* Repeat the last 2 steps twice more, once for each of the remaining 2 sides of the triangle.
* Use a series of nested `if` / `else` statements to determine if the triangle having side-lengths as set by the user is an EQUILATERAL, ISOSCELES, or SCALENE triangle.
[Note: look to the Wikipedia page on ‘triangle’ for definitions of these three types of triangles.]
* Print the resulting triangle type to the console.
* Ensure your Triangle detector works by running it 5 times as in the example above. You may use the same values as in the example.
I currently have:
```
//lab eleven program code on triangles
#include <iostream.h>
main()
{
//variables
float aside, bside, cside;
//enter side a
cout<<"enter the length of side a "<<endl;
cin>>aside;
//enter side b
cout<<"enter the length of side b "<<endl;
cin>>bside;
//enter side c
cout<<"enter the length of side c "<<endl;
cin>>cside;
// all sides equal
if(aside==bside && bside==cside)
cout << "Equilateral triangle\n";
// at least 2 sides equal
else if(aside==bside || aside==cside || bside==cside)
cout << "Isosceles triangle\n";
// no sides equal
else
cout << "Scalene triangle\n";
}
```
But I need help with the `if` and `else if` statements to determine the type triangle. Our professor has not covered this topic in class.
We use the program Ch 6.3 on Windows. | 2011/06/26 | [
"https://Stackoverflow.com/questions/6486888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/816538/"
] | As your professor suggested, you should look at:
<http://en.wikipedia.org/wiki/Triangle#Types_of_triangles>
You should also look at:
<http://www.teacherschoice.com.au/maths_library/trigonometry/solve_trig_sss.htm>
Algorithm:
```
Solve for all angles, a1, a2, a3 (see the article above)
If you can't find a solution:
Output "Error: Not a valid triangle"
Else:
If (a1 == a2) && (a2 == a3):
Output "EQUILATERAL" and stop
If (a1 == a2) || (a2 == a3) || (a1 == a3):
Output "ISOSCELES" and stop
Output "SCALENE" and stop
```
Also note: Be careful about "equality" with floating point (`float`/`double`) values (such as angles). If you are doing such a comparison, you should usually use this instead:
```
abs(x - y) < epsilon
```
Where `epsilon` is a "sufficiently small value". | To complete this program you will need the following:
Make sure input is valid. In this case, input must be greater than 0. You could catch your input using a loop like
```
while (invar <= 0)
{
cout<<"Enter length"<<endl;
cin>>invar;
if (invar <= 0)
{
cout<<"invalid input"<<endl;
}
}
```
I am not sure if this is proper c++ syntax, I haven't used it in about 8 years.
you can do this for all 3 inputs. I would probably make a function to determine the triangle using 3 input variables and 1 return variable. The following is pseudo-code
```
if (a + b <= c) or (a + c <= b) or (b + c <= a)
{
return "you don't have a triangle."
}
else
{
if (a == b) or (a == c) or (b == c)
{
if (a == b and b == c)
{
return "equilateral"
}
return "isosceles"
}
return "scalene"
}
return -1
``` |
61,822,117 | I've tried [this](https://linuxconfig.org/how-to-install-viber-on-ubuntu-20-04-focal-fossa-linux) description. Installation using snap was successfull, but after configuring Viber, the following error message came:
```
Qt: Session management error: None of the authentication protocols specified are supported
sh: 1: xdg-mime: not found
Qt WebEngine ICU data not found at /snap/viber-mtd/17/opt/viber/resources. Trying parent directory...
Qt WebEngine resources not found at /snap/viber-mtd/17/opt/viber/resources. Trying parent directory...
[15972:15972:0515/162634.438831:FATAL:credentials.cc(155)] Check failed: NamespaceUtils::DenySetgroups(). : Permission denied
#0 0x7fa98b6aa11e base::debug::StackTrace::StackTrace()
#1 0x7fa98b6babde logging::LogMessage::~LogMessage()
#2 0x7fa98b6bae99 logging::ErrnoLogMessage::~ErrnoLogMessage()
#3 0x7fa98c3acf7c sandbox::(anonymous namespace)::SetGidAndUidMaps()
#4 0x7fa98c3ad5d5 sandbox::Credentials::CanCreateProcessInNewUserNS()
#5 0x7fa98b31dde5 content::ZygoteHostImpl::Init()
#6 0x7fa98afd0314 content::BrowserMainLoop::EarlyInitialization()
#7 0x7fa98afd4190 content::BrowserMainRunnerImpl::Initialize()
#8 0x7fa98add9d19 QtWebEngineCore::WebEngineContext::WebEngineContext()
#9 0x7fa98addb135 QtWebEngineCore::WebEngineContext::current()
#10 0x7fa98ad78931 QtWebEngineCore::BrowserContextAdapter::defaultContext()
#11 0x7fa993091618 QQuickWebEngineProfile::defaultProfile()
#12 0x0000006ac8bf ApplicationPrivate::preRunningInitialization()
#13 0x0000006a6504 ViberApplication::start()
#14 0x00000067e25b ViberMain()
#15 0x7fa987d7e830 __libc_start_main
#16 0x0000004d7047 <unknown>
Qt WebEngine ICU data not found at /snap/viber-mtd/17/opt/viber/resources. Trying parent directory...
Qt WebEngine resources not found at /snap/viber-mtd/17/opt/viber/resources. Trying parent directory...
shm_open() failed: Permission denied
shm_open() failed: Permission denied
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib control.c:954:(snd_ctl_open_noupdate) Invalid CTL
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib control.c:954:(snd_ctl_open_noupdate) Invalid CTL
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib control.c:954:(snd_ctl_open_noupdate) Invalid CTL
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib control.c:954:(snd_ctl_open_noupdate) Invalid CTL
ALSA lib conf.c:3750:(snd_config_update_r) Cannot access file /usr/share/alsa/alsa.conf
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM
shm_open() failed: Permission denied
PulseAudioService: pa_context_connect() failed
shm_open() failed: Permission denied
PulseAudioService: pa_context_connect() failed
Assertion 'pthread_mutex_unlock(&m->mutex) == 0' failed at pulsecore/mutex-posix.c:108, function pa_mutex_unlock(). Aborting.
```
After it, I've removed it, and tried the second method (install from deb package). But the referred libssl package was not found.
Any idea? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61822117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576961/"
] | The location of the libssl package was not correct.
Visit the <http://archive.ubuntu.com/ubuntu/pool/main/o/openssl1.0/> site, and download one of the libssl file. At the moment I visited, there was a **libssl1.0.0\_1.0.2n-1ubuntu5.3\_amd64.deb** file, I've downloaded.
And after it:
```
sudo dpkg -i libssl1.0.0_1.0.2n-1ubuntu5.3_amd64.deb
wget https://download.cdn.viber.com/cdn/desktop/Linux/viber.deb
sudo dpkg -i viber.deb
```
If there is some dependency requirements, also run:
```
apt-get install -f
```
And it will work :) | To fix the Snap, you need to allow it permission to use the audio systems. There is a command line way to do it (snap connections) but I used the Software app, found the Viber snap and clicked "Permissions". |
35,997,541 | I'm using Hibernate 5.1.0.Final with ehcache and Spring 3.2.11.RELEASE. I have the following `@Cacheable` annotation set up in one of my `DAO`s:
```
@Override
@Cacheable(value = "main")
public Item findItemById(String id)
{
return entityManager.find(Item.class, id);
}
```
The item being returned has a number of assocations, some of which are lazy. So for instance, it (eventually) references the field:
```
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "product_category", joinColumns = { @JoinColumn(name = "PRODUCT_ID") }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID") })
private List<Category> categories;
```
I notice that within one of my methods that I mark as `@Transactional`, when the above method is retrieved from the second level cache, I get the below exception when trying to iterate over the categories field:
```
@Transactional(readOnly=true)
public UserContentDto getContent(String itemId, String pageNumber) throws IOException
{
Item Item = contentDao.findItemById(ItemId);
…
// Below line causes a “LazyInitializationException” exception
for (Category category : item.getParent().getProduct().getCategories())
{
```
The stack trace is:
```
16:29:42,557 INFO [org.directwebremoting.log.accessLog] (ajp-/127.0.0.1:8009-18) Method execution failed: : org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.mainco.subco.ecom.domain.Product.standardCategories, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:579) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:203) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:558) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:131) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
at org.mainco.subco.ebook.service.ContentServiceImpl.getCorrelationsByItem(ContentServiceImpl.java:957) [myproject-90.0.0-SNAPSHOT.jar:]
at org.mainco.subco.ebook.service.ContentServiceImpl.getContent(ContentServiceImpl.java:501) [myproject-90.0.0-SNAPSHOT.jar:]
at sun.reflect.GeneratedMethodAccessor819.invoke(Unknown Source) [:1.6.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_65]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_65]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at com.sun.proxy.$Proxy126.getContent(Unknown Source)
```
I understand what the Hibernate session is closed — I do not care about why this happens. Also, it is NOT an option o make the above association eager (instead of lazy). Given that, how can I solve this problem?
**Edit:** Here is how my ehccahe.xml is configured …
```
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd" updateCheck="false">
<!-- This is a default configuration for 256Mb of cached data using the JVM's heap, but it must be adjusted
according to specific requirement and heap sizes -->
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="86400"
timeToLiveSeconds="86400"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
<cache name="main" maxElementsInMemory="10000" />
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
multicastGroupPort=4446, timeToLive=32"/>
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=localhost, port=40001,
socketTimeoutMillis=2000"/>
</ehcache>
```
and here is how I’m plugging it into my Spring context …
```
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="org.mainco.subco" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="dataSource" ref="dataSource"/>
<property name="jpaPropertyMap" ref="jpaPropertyMap" />
</bean>
<cache:annotation-driven key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="org.mainco.subco.myproject.util.CacheKeyGenerator" />
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"
p:shared="true" />
<util:map id="jpaPropertyMap">
<entry key="hibernate.show_sql" value="false" />
<entry key="hibernate.hbm2ddl.auto" value="validate"/>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<entry key="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<entry key="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<entry key="hibernate.cache.use_second_level_cache" value="true" />
<entry key="hibernate.cache.use_query_cache" value="false" />
<entry key="hibernate.generate_statistics" value="false" />
</util:map>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
``` | 2016/03/14 | [
"https://Stackoverflow.com/questions/35997541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235929/"
] | Take a look at a [similar question](https://stackoverflow.com/questions/34763402/proper-cache-usage-in-spring-hibernate). Basically, your cache is not a Hibernate second-level cache. You are accessing a lazy uninitialized association on a detached entity instance, so a `LazyInitializationException` is expected to be thrown.
You can try to play around with [`hibernate.enable_lazy_load_no_trans`](https://stackoverflow.com/a/11913404/4754790), but the recommended approach is to configure [Hibernate second level cache](http://howtodoinjava.com/hibernate/hibernate-ehcache-configuration-tutorial/) so that:
* Cached entities are automatically attached to the subsequent sessions in which they are loaded.
* Cached data is automatically refreshed/invalidated in the cache when they are changed.
* Changes to the cached instances are synchronized taking the transaction semantics into consideration. Changes are visible to other sessions/transactions with the desired level of cache/db [consistency guarantees](https://stackoverflow.com/a/28291194/4754790).
* Cached instances are automatically fetched from the cache when they are navigated to from the other entities which have associations with them.
**EDIT**
If you nevertheless want to use Spring cache for this purpose, or your requirements are such that this is an adequate solution, then keep in mind that Hibernate managed entities are not thread-safe, so you will have to store and return detached entities to/from the custom cache. Also, prior to detachment you would need to initialize all lazy associations that you expect to be accessed on the entity while it is detached.
To achieve this you could:
1. Explicitly detach the managed entity with [`EntityManager.detach`](http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#detach-java.lang.Object-). You would need to detach or cascade detach operation to the associated entities also, and make sure that the references to the detached entities from other managed entities are handled appropriately.
2. Or, you could execute this in a separate transaction to make sure that everything is detached and that you don't reference detached entities from the managed ones in the current persistence context:
```
@Override
@Cacheable(value = "main")
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Item findItemById(String id) {
Item result = entityManager.find(Item.class, id);
Hibernate.initialize(result.getAssociation1());
Hibernate.initialize(result.getAssociation2());
return result;
}
```
Because it may happen that the Spring transaction proxy (interceptor) is executed before the cache proxy (both have the same default `order` value: [transaction](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html#order--); [cache](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/EnableCaching.html#order--)), then you would always start a nested transaction, be it to really fetch the entity, or to just return the cached instance.
While we may conclude that performance penalty for starting unneeded nested transactions is small, the issue here is that you leave a small time window when a managed instance is present in the cache.
To avoid that, you could change the default order values:
```
<tx:annotation-driven order="200"/>
<cache:annotation-driven order="100"/>
```
so that cache interceptor is always placed before the transaction one.
Or, to avoid ordering configuration changes, you could simply delegate the call from the `@Cacheable` method to the `@Transactional(propagation = Propagation.REQUIRES_NEW)` method on another bean. | I used simple type cache with this config as below:
```
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
spring.jpa.open-in-view=true
spring.cache.type=simple
``` |
20,542,369 | I am building a news website where one of the views is a webview of articles.
I had installed `push woosh` but when i send out notifications with URLs in them tapping the URL opens the web page in the native browser, is there any way i can set it so that the pages open in the webview in the app? | 2013/12/12 | [
"https://Stackoverflow.com/questions/20542369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016026/"
] | Here is what I did to test my code using Mockito and Apache HttpBuilder:
**Class under test:**
```
import java.io.BufferedReader;
import java.io.IOException;
import javax.ws.rs.core.Response.Status;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusApiClient {
private static final Logger LOG = LoggerFactory.getLogger(StatusApiClient.class);
private String targetUrl = "";
private HttpClient client = null;
HttpGet httpGet = null;
public StatusApiClient(HttpClient client, HttpGet httpGet) {
this.client = client;
this.httpGet = httpGet;
}
public StatusApiClient(String targetUrl) {
this.targetUrl = targetUrl;
this.client = HttpClientBuilder.create().build();
this.httpGet = new HttpGet(targetUrl);
}
public boolean getStatus() {
BufferedReader rd = null;
boolean status = false;
try{
LOG.debug("Requesting status: " + targetUrl);
HttpResponse response = client.execute(httpGet);
if(response.getStatusLine().getStatusCode() == Status.OK.getStatusCode()) {
LOG.debug("Is online.");
status = true;
}
} catch(Exception e) {
LOG.error("Error getting the status", e);
} finally {
if (rd != null) {
try{
rd.close();
} catch (IOException ioe) {
LOG.error("Error while closing the Buffered Reader used for reading the status", ioe);
}
}
}
return status;
}
}
```
**Test:**
```
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class StatusApiClientTest extends Mockito {
@Test
public void should_return_true_if_the_status_api_works_properly() throws ClientProtocolException, IOException {
//given:
HttpClient httpClient = mock(HttpClient.class);
HttpGet httpGet = mock(HttpGet.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
//and:
when(statusLine.getStatusCode()).thenReturn(200);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(httpClient.execute(httpGet)).thenReturn(httpResponse);
//and:
StatusApiClient client = new StatusApiClient(httpClient, httpGet);
//when:
boolean status = client.getStatus();
//then:
Assert.assertTrue(status);
}
@Test
public void should_return_false_if_status_api_do_not_respond() throws ClientProtocolException, IOException {
//given:
HttpClient httpClient = mock(HttpClient.class);
HttpGet httpGet = mock(HttpGet.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
//and:
when(httpClient.execute(httpGet)).thenThrow(HttpHostConnectException.class);
//and:
StatusApiClient client = new StatusApiClient(httpClient, httpGet);
//when:
boolean status = client.getStatus();
//then:
Assert.assertFalse(status);
}
}
```
What do you think folks, do I need to improve something? (Yeah, I know, the comments. That is something I brought from my Spock background :D) | In your unit test class you need to mock `defaultHttpClient`:
```
@Mock
private HttpClient defaultHttpClient;
```
Then you tell mockito (for example in `@Before` method) to actually create your mocks by:
```
MockitoAnnotations.initMocks(YourTestClass);
```
Then in your test method you define what `execute()` method should return:
```
when(defaultHttpClient.execute(any()/* or wahtever you want here */)).thenReturn(stubbed JSON object);
``` |
37,520,248 | Can I access [Cloud Foundry REST API](https://apidocs.cloudfoundry.org/237/) on Bluemix? If yes, how can I access it (cannot find any documentation)? | 2016/05/30 | [
"https://Stackoverflow.com/questions/37520248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4890411/"
] | You can access the Cloud Foundry REST API on Bluemix as you would normally do with CF. In addition to that, if you need it and you are already familiar with *cf curl* you can take a look at the *bluemix curl* command. For example if you want to retrieve the information for all organizations of the current account:
```
bluemix curl /v2/organizations
```
Please see the [Docs](https://console.ng.bluemix.net/docs/cli/reference/bluemix_cli/index.html) for more information. | In order to access CF API you have to get the authentication token. Then add it to each request in the headers.
```
oauthTokenResponse = requests.post(
f'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token?grant_type=password&client_id=cf',
data={'username': <your username>, 'password': <your password>, 'client_id': 'cf'},
auth=('cf', '')
)
auth = oauthTokenResponse.json()['token_type'] + ' ' + oauthTokenResponse.json()['access_token']
appsResponse = requests.get(f'{self.api_endpoint}/v2/apps',
headers={'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': auth}
)
apps = json.loads(appsResponse.content)
``` |
51,797,719 | I started hazelcast server using
```
java -jar hazelcast-3.10.1/lib/hazelcast-3.10.1.jar
```
which started server on
```
Members {size:1, ver:1} [
Member [127.0.0.1]:5701 - f7cf5a82-c89c-4341-8e72-0f446df422ad this
]
```
after that I started mancenter as below
```
java -jar hazelcast-management-center-3.10.1/mancenter-3.10.1.war 8080 mancenter
```
then I tried to connect my spring boot application to mancenter as below
```
@Bean
public Config mancenterConfig() {
Config cfg = new Config();
cfg.getManagementCenterConfig().setEnabled(true).setUrl("http://localhost:8080/mancenter");
return cfg;
}
```
But it does not connect to already started server, it starts a new hazelcast server on port 5702 as below
```
Members {size:1, ver:1} [
Member [127.0.0.1]:5702 - f7cf5a82-c89c-4341-8e72-0f446df422ad this
]
```
How can I connect mancenter to already started hazelcast server on port 5701 instead of starting a new hazelcast server on port 5702? | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9766007/"
] | You can't, the connection is initiated from the Hazelcast Server to the Hazelcast Management Center, so the server has to have the management server URL enabled when it starts.
See <http://docs.hazelcast.org/docs/management-center/3.10.2/manual/html/index.html#change-url> | As Neil said, the cluster members initiate the connection back to the Management Center and the Management Center URL needs to be set in the members before they start. Reasons for this design are both performance and security related.
If you really need to have the Man Center url dynamic though, you can usually achieve this through network setup. On a small scale, you can simply use the host file on the member machines to map the configured name to an IP or DNS name. If the members can't connect to Management Center at start up, they will continue to try at intervals, so a change in the host file will eventually be picked up. On a larger scale, you might make changes in your DNS system to point the members to the proper address. |
11,323,617 | Today I found an article where a `const` field is called *compile-time constant* while a `readonly` field is called *runtime constant*. The two phrases come from 《Effective C#》. I searched in MSDN and the language spec, find nothing about *runtime constant*.
No offensive but I don't think *runtime constant* is a proper phrase.
```
private readonly string foo = "bar";
```
creates a variable named "foo", whose value is "bar", and the value is readonly, here it is a variable, no business on `constant`. A readonly variable is still a variable, it can't be a constant. Variable and constant are mutually exclusive.
Maybe this question goes overboard, still I want to listen to others' opinions. What do you think? | 2012/07/04 | [
"https://Stackoverflow.com/questions/11323617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323924/"
] | I believe that author means the following:
Consider example:
```
public class A {
public const int a = Compute();
private static int Compute(){
/*some computation and return*/
return some_computed_value;
}
}
```
this, **will not** compile, as you have to have constant value to assign to `a` .
So **this is** a meaning of *compile-time constant* .
Instead if you change this to
```
public class A {
public readonly int a = Compute();
private static int Compute(){
/*some computation and return*/
return some_computed_value;
}
}
```
this **will** compile. It at *runtime* makes a computation and assign it to `a`.
This is a meaning of *runtime constant* | A readonly variable can only be changed in its constructor and can be used on complex objects. A constant variable cannot be changed at runtime, but can only be used on simple types like Int, Double, String. Runtime constant is somewhat accurate, but confuses the issue, there are very explicit differences between a constant and a readonly, and so naming one similar to another is probably not a good idea, even though often they are used to the same purpose.
A quick summary of the differences [here](http://weblogs.asp.net/psteele/archive/2004/01/27/63416.aspx) |
296,020 | Mac OS X has the `Darwin 10.6.0` Kernel, and Ubuntu has the `Linux 2.6` Kernel, so in Windows what is it called? | 2011/06/12 | [
"https://superuser.com/questions/296020",
"https://superuser.com",
"https://superuser.com/users/70695/"
] | Well, it tends to be Microsoft Windows Version [6.1.7601] for windows 7 - the main change should be the numbers which are MajorVersion.MinorVersion.Build. Vista was 6.0.xxxx, and XP was 5.1.2600 for SP3.
You can find this with the 'ver' command | Windows:
* Windows 7 - Click Start or the Windows logo -> right click Computer -> then click Properties. Look in System.
* Windows Vista and Windows Server 2008 - Click Start or the Windows logo depending on what you have -> then click Control Panel -> System and Maintenance -> System.
You could also try Clicking Start or the Windows logo -> then if you have a "Start Search" field type winver -> then Double-click winver.exe from the results. If you had a run box instead of search just click Run -> type winver -> click OK.
* Windows XP and Windows Server 2003 - Click Start -> Run -> Type winver then click OK. You could also try typing msinfo32 or sysdm.cpl if you like. Lastly you might try typing dxdiag. Windows might prompt you to verify drivers click No. |
189,430 | I am learning python and want to improve my skills in it. So could someone advice of how to improve the code below (this is a simple programming problem taken from one of the web sites). I feel like my code is not really Pythonic.
**Problem:** Using the Python language, have the function `LetterChanges(str)` take the `str` parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
```
from sets import Set
def LetterChanges(str):
vowels = Set(['a', 'e', 'i', 'o', 'u'])
new_str = ''
for i in str:
cur_char = i.lower()
if cur_char == 'z':
new_str += 'A'
elif ord(cur_char) >= 97 and ord(cur_char) < 122:
new_char = chr(ord(i) + 1)
new_str += (new_char if new_char not in vowels else new_char.upper())
else:
new_str += i
return new_str
if __name__=='__main__':
print(LetterChanges(raw_input()))
``` | 2018/03/12 | [
"https://codereview.stackexchange.com/questions/189430",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/163005/"
] | Instead of having those `if`s you could use a translation table to speed things up (see [`str.maketrans`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) and [`str.translate`](https://docs.python.org/3/library/stdtypes.html#str.translate)).
```
import string
def _build_translation_table():
ascii_vowels = 'aeiou'
d = {c: chr(ord(c)+1) for c in string.ascii_lowercase}
d['z'] = 'a' # z is a special case
for k, v in d.items(): # and so are vowels
if v in ascii_vowels:
d[k] = v.upper()
return str.maketrans(d)
_TABLE = _build_translation_table()
def LetterChanges(s):
"""Change letters in string s using a special algorithm.
Replace every letter in the string with the letter following it in the
alphabet (ie. c becomes d, z becomes a) ...
>>> LetterChanges('qwertyuiop')
'rxfsUzvjpq'
>>> LetterChanges('1234567890')
'1234567890'
>>> LetterChanges('zxcvbnm')
'AydwcOn'
"""
return s.translate(_TABLE)
if __name__ == '__main__':
import doctest
doctest.testmod()
```
I took the liberty to rename the parameter `str` to `s` for reasons already mentioned by others. `_build_translation_table` and `_TABLE` start with an underscore because it doesn't make much sense for them to be "public".
I also took some tests from [Josay's answer](https://codereview.stackexchange.com/a/189433/1208) and put them into the documentation string of the function, so that the [`doctest`](https://docs.python.org/3/library/doctest.html) module can run them.
```
# python3 letterchanges.py -v
Trying:
LetterChanges('qwertyuiop')
Expecting:
'rxfsUzvjpq'
ok
Trying:
LetterChanges('1234567890')
Expecting:
'1234567890'
ok
``` | Here are some improvements that I'd make (supposing that your code is using Python 2.x):
* I'd indent the code so that it'll be a multiple of four
* There's no reason to make the vowels a `Set()`. A string should work just fine as strings are iterable in python
* rename the `str` argument to something else as that's a builtin keyword in python
* I'd simplify the chained comparison: `ord(cur_char) >= 97 and ord(cur_char) < 122` to `97 <= ord(cur_char) < 122`
That being said you'd have so far:
```
def LetterChanges(str_):
vowels = 'aeiou'
new_str = ''
for i in str_:
cur_char = i.lower()
if cur_char == 'z':
new_str += 'A'
elif 97 <= ord(cur_char) < 122:
new_char = chr(ord(i) + 1)
new_str += (new_char if new_char not in vowels else new_char.upper())
else:
new_str += i
return new_str
if __name__ == '__main__':
print(LetterChanges(raw_input()))
``` |
63,833,194 | I'm trying to find all of the top players "arena pts" (the in game competative point system) from this website: `https://www.epicgames.com/fortnite/competitive/en-US/hype-leaderboard?sessionInvalidated=true`
I'm using requests to get the information and bs4 to sort through it, but I'm having trouble using bs4. Here's what I have so far:
```py
page = requests.get('https://www.epicgames.com/fortnite/competitive/en-US/hype-leaderboard?sessionInvalidated=true')
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find_all('td', class_ = "asdt-points")
print(len(results))
```
When ran, the program outputs 0, meaning it didn't find anything.. from doing research online I haven't found any groundbreaking information that could help me, and I'm using stack as a last resort. Any help would be amazing! Thank you! | 2020/09/10 | [
"https://Stackoverflow.com/questions/63833194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13905088/"
] | You wont able to do it using requests lib, because the page is asking api for those stats, which can be found in browser console "network" tab
```
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.epicgames.com/fortnite/competitive/en-US/hype-leaderboard?sessionInvalidated=true')
soup = BeautifulSoup(page.content,features="lxml")
soup.find("div", {"class": "ApiStandingsDetailsTables"}).text
'Loading'
```
So instead lets just ask the api
```
import requests
api_url='https://www.epicgames.com/fortnite/competitive/api/leaderboard/persistent/Hype_S14/undefined'
data_to_parse=requests.get(api_url).json()
resulting_list_of_dictionaries=[{'rank':i.get('rank'), 'name':i.get('players')[0]['displayName'], 'hype':i.get('pointsEarned')} for i in data_to_parse['entries']]
resulting_list_of_dictionaries
00:{'hype': 75434, 'name': 'Marzz_Ow', 'rank': 1}
01:{'hype': 50160, 'name': 'Its Filipе', 'rank': 2}
02:{'hype': 45821, 'name': 'たいちゃん0216', 'rank': 3}
03:{'hype': 42827, 'name': 'Fishy R2L2', 'rank': 4}
04:{'hype': 41806, 'name': 'Claw FA', 'rank': 5}
05:{'hype': 41379, 'name': '必ずアニキ救って来いやァァァァァ', 'rank': 6}
06:{'hype': 40511, 'name': 'えすぼん.', 'rank': 7}
07:{'hype': 39566, 'name': 'LG Slackes', 'rank': 8}
``` | This is a problem that would require using selenium, since the table is loaded dynamically with Javascript. Bs4 can only work, and would work in your case, if the data were already loaded. What is happening is that when requests gets the page, there are indeed no td.asdt-points elements. you can see that by using:
```py
print(page.text)
``` |
27,582,145 | ```
#include<stdio.h>
int main(void)
{
int x = 3;
float y = 3.0;
if (x == y)
printf("x and y are equal\n");
else
printf("x and y are not equal\n");
return 0;
}
```
As per the mathematics, both are equal!
How does the compiler recognize both are equal?
**(I am totally new to programming sorry if anything is wrong in my question)**
Thanks in advance. | 2014/12/20 | [
"https://Stackoverflow.com/questions/27582145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4344438/"
] | int x=3 ;
The above variable x is stored as normal binary format i.e. 0000 0011, because of int
float y=3.0 ;
the above variable y is stored in IEEE 754 floating point format. i.e the value y is stored in a memory location with three different groups with sign bit, exponent and mantissa
here compiler will generate a executable file and it will add information about the two variables such that x variable is a integer type and y variable is float type.
So, when it is stored in memory for execution those variables are stored as per the compiler's executable file suggests. | The compiler will convert one of the two variables to the other type, let's say y to int, now both are of same type and can be compare.
The next step is an internal subtraction of both value and a test for the ZERO flag. If both values are equal, the subtraction result will 0 which causes the ZERO flag to be set. |
3,995,492 | I have no clue how to do this, I manage to get I get that $11^{36} \equiv 1 \hspace{0.1cm} \text{mod} (13)$ but I can't get anywhere from there. | 2021/01/22 | [
"https://math.stackexchange.com/questions/3995492",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/841487/"
] | If $11^{36}=1$ in $\Bbb Z/13$, then $11^{35}=11^{-1}$. But since $6\cdot 11=66=1$ in $\Bbb Z/13$, we have $11^{-1}=6$.
Here I just write $a=b$ in the ring $\Bbb Z/n$ for $a\equiv b\bmod n$, so that we see it a bit easier.
For $n=13$, $\Bbb Z/n$ is a field and all nonzero elements have an inverse. | What were your efforts ? However, if you proved that $11^{36} \equiv 1 \hspace{0.1cm} (13)$ then you have that $11^{35}\cdot 11 \equiv 1 \hspace{0.1cm}(13)$. In this line it is written that $11^{35}$ is the inverse of $11$ by definition, by uniqueness you only have to prove that $6$ does the same job, i.e $6 \cdot 11 \overset{?}{\equiv} 1 \hspace{0.1cm}(13)$, which is true, and you have the desired result. |
404,301 | In a Debian server, and after intallation and removal of SquirrelMail (with some downgrade and upgrade of php5, mysql...) the MySQL extension of PHP has stopped working.
I have php5-mysql installed, and when I try to connect to a database through php-cli, i connect successfully, but when I try to connect from a web served by Apache I cannot connect.
This script, run by php5-cli:
```
echo phpinfo();
$link = mysql_connect('localhost', 'user, 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
```
Prints the phpinfo, which includes "/etc/php5/cli/conf.d/mysql.ini", and also the MySQL section with all the configuration: SOCKET, LIBS... And then it prints "Connectes successfully".
But when run by apache accessed by web browser, it displays the phpinfo, which includes "/etc/php5/apache2/conf.d/mysql.ini", but has the MySQL section missing, and the script dies printing "Fatal error: Call to undefined function mysql\_connect()".
Note that both "/etc/php5/cli/conf.d/mysql.ini" and "/etc/php5/apache2/conf.d/mysql.ini" are in fact the same configuration, because I have in debian the structure:
```
/etc/php5/apache2
/etc/php5/cgi
/etc/php5/cli
/etc/php5/conf.d
```
And both point at the same directory:
```
/etc/php5/apache2/conf.d -> ../conf.d
/etc/php5/cli -> ../conf.d
```
Where /etc/php5/conf.d/mysql.ini consists of one line:
```
extension=mysql.so
```
So my question is: why is the MySQL extension for PHP not working if I have the configuration included just in the same way as in php-cli, which is working?
Thanks a lot! | 2012/07/03 | [
"https://serverfault.com/questions/404301",
"https://serverfault.com",
"https://serverfault.com/users/126927/"
] | This probably isn't a configuration issue. I'm not familiar with how things are done in Debian (regarding upgrading/downgrading PHP) but it seems the PHP used by Apache and the PHP CLI are in fact using different PHPs.
You can verify this by doing a `phpinfo()` from browser and a `php -i` on the commandline. If Apache and CLI are using the same PHP, the results should be exactly the same (same configure options, compile time, libraries enabled, etc.). | Assuming that webserver PHP is running as mod\_php, the 2 most likely causes are:
1) the permissions on the php.ini file or the .so file do not allow the webserver uid access to the file(s)
2) the webserver is running chroot
You can easily test this from PHP using 'is\_readable' and, in the case of php.ini use file\_get\_contents() to check the file contains what you expect, and in the case of mysql.so, use dl() to load the file. |
19,587,945 | I'm having some trouble understanding how OOP, Abstract Classes and lists. My current project is in Processing - Just for prototyping of course.
My problem is that I've a list of objects with some of the same variables. So I created an abstract class for them and then a list of all the objects (Abstract class as list) and then added the variant objects to the "abstract" list.
Here is the code - The whole deal can be found just beneath:
```
ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();
void setup() {
vehicles.add(new Motorcycle());
vehicles.add(new Motorcycle(2,"Yamaha"));
vehicles.add(new Truck());
vehicles.add(new Truck(4,"ASU AC2",2));
print(vehicles);
vehicles.get(3).dropLastTrailer();
}
```
Truck:
```
class Truck extends Vehicle {
int numOfTrailers;
Truck() {
super();
numOfTrailers = 0;
}
Truck(int size, String name, int numOfTrailers) {
super(size, name);
this.numOfTrailers = numOfTrailers;
type = "Truck";
}
void dropLastTrailer() {
numOfTrailers--;
println("Dropped one trailer, the truck now got " + numOfTrailers + " trailers");
}
}
```
Vehicle:
```
abstract class Vehicle {
int speed, size;
String name;
String type;
Vehicle() {
this((int)random(0,6),"Unknown Vehicle");
type = "Vehicle";
}
Vehicle(int size, String name) {
this.size = size;
this.name = name;
}
String toString() {
return (name + " is " + size + "m long " + type);
}
}
```
**The code works up until I try to call the "dropLastTrailer" function where it says the method doesn't exist. I guess this is properly because it thinks it's *just* a Vehicle object, and not a Truck.**
How can I fix this?
Full Code can be found here:
<https://github.com/Jalict/processing-experiments/tree/master/oop_abstract_list> | 2013/10/25 | [
"https://Stackoverflow.com/questions/19587945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2919214/"
] | How would you expect the compiler to know that it *is* a `Truck`? You've declared a list of vehicles. Imagine if you were using `list.get(0)` instead of `list.get(3)` - then the value would be a reference to a `Motorcycle`, not a `Truck`.
You can fix this by casting:
```
((Truck) vehicles.get(3)).dropLastTrailer();
```
... but at that point your code is *assuming* the type of an object within the list, which isn't ideal. You could make this conditional:
```
Vehicle mightBeTruck = vehicles.get(3);
if (mightBeTruck instanceof Truck) {
Vehicle truck = (Truck) mightBeTruck;
truck.dropLastTrailer();
}
```
That's safer, but it's still not great from a design perspective. Unfortunately the sample given doesn't have enough context to apply it to a real world task - *sometimes* things like this really are necessary. Usually there are cleaner approaches, but it depends on what you're trying to achieve. | Dumb fix: cast
```
((Truck)vehicles.get(3)).dropLastTrailer();
```
but that's kind of dangerous. How do you know whether that element in a list is indeed a truck?
Better:
```
Vehicle v = vehicles.get(3);
if (v instanceof Truck) {
// then we can safely cast
((Truck)v).dropLastTrailer();
}
``` |
341,661 | What application do the same what [shazam](http://www.shazam.com/music/web/getshazam.html) or [soundhound](http://www.soundhound.com/) does on android?
[Shazam](https://en.wikipedia.org/wiki/Shazam_%28service%29) for windows and MacOs, I don't like wine, plus it is commercial. You can verify about 2-5 songs and must pay to continue.
[SoundHound](https://en.wikipedia.org/wiki/SoundHound) - closely mobile Os's app.
What kind of application for Linux/Ubuntu can do the same?
```
$ soundhound song.mp3
The Beatles - Let it be - imdb index#
```
I found this question but answers are about mp3 tag only:
[Application for finding song names](https://askubuntu.com/questions/235658/application-for-finding-song-names) | 2013/09/05 | [
"https://askubuntu.com/questions/341661",
"https://askubuntu.com",
"https://askubuntu.com/users/187795/"
] | OK so it is a little bit of a hack.
First go to:
1. [Directly to the flash program on the Midomi site](http://www.midomi.com/objects/midomiLandingVoiceSearch.swf)
This will be annoying probably because you cant click on the accept microphone button because adobe is annoying. Using `Tab` you can move around but it still doesn't seem to let you allow with `Enter`. So enter on the "?". Adobe flash player has seen you have interacted with this dialogue.
2. [Now go to the settings manager page of the Adobe site](http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager06.html)
The picture is not a picture but settings. This one works and you can tell it to always allow midomi. This should be here because of using midomi before. (If not play with the stupid broken dialoge on the midomi site 1-2 more times then restart firefox). Once you have selected Allow for midomi on the Adobe page restart firefox and fo back to the flash program and it should work! | Just discovered MusicBrainz Picard, you can just easily install it with `sudo apt-get install picard`. It creates an audio ID of your song and looks it up in a database, did help me a lot. |
47,692,263 | I need to make a script do a specific action on first loop iteration.
```
for file in /path/to/files/*; do
echo "${file}"
done
```
I want this output:
```
First run: file1
file2
file3
file4
...
``` | 2017/12/07 | [
"https://Stackoverflow.com/questions/47692263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9053600/"
] | A very common arrangement is to change a variable inside the loop.
```
noise='First run: '
for file in /path/to/files/*; do
echo "$noise$file"
noise=''
done
``` | You can create an array with the files, then remove and keep the first element from this array, process it separately and then process the remaining elements of the array:
```
# create array with files
files=(/path/to/files/*)
# get the 1st element of the array
first=${files[0]}
# remove the 1st element of from array
files=("${files[@]:1}")
# process the 1st element
echo First run: "$first"
# process the remaining elements
for file in "${files[@]}"; do
echo "$file"
done
``` |
7,596,632 | All, Im having the age old problem with character encoding...
I have a mySQL DB with a field set to `utf8_unicode_ci`. My PHP page as the header entry `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />`. When I use a simple form to POST data with Cyrillic characters to the DB, e.g. 'гыдлпоо', the characters display correctly in the textarea, and are added to the DB where they display correctly.
When fetching the characters from the DB, my page only displays a series of question marks. I've used `mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);` and the content is UTF-8, however the characters do not display.
I've searched around (including on SO) and tried any number of solutions, to no avail- any help would be much appreciated.
Many thanks | 2011/09/29 | [
"https://Stackoverflow.com/questions/7596632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404335/"
] | Try using [mysql\_set\_charset](http://php.net/manual/en/function.mysql-set-charset.php)() function before fetching data from database. | Do this right after mysql\_connect() and mysql\_select\_db():
```
mysql_query("SET NAMES 'utf8'");
``` |
10,904 | I am really confused about this and wanted to share/learn.
I was talking with one of my Canadian friends with whom I would like to hang out, about a song and I wanted to say:
>
> "What a good song is this!" (i don't know if it needs to end with "!"
> or "?")
>
>
>
But something within me said it's not a good usage of English, so I decided to say
>
> "Isn't it a good song?"
>
>
>
and now I am stuck right at that point because none of the above sounded right.
Which way can I tell my friend that I liked this song and ask him if he liked it or not? | 2013/10/01 | [
"https://ell.stackexchange.com/questions/10904",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/2726/"
] | *Morning* is a common English word, as you know. *Forenoon*, on the other hand, is so rare that I'm not sure many native speakers of English will even **recognize** the word.
How rare is it? To find out, I searched [*the Corpus of Contemporary American English (COCA)*](http://corpus.byu.edu/coca/?c=coca&q=33239565) for both *morning* and *forenoon*. Here are the results I got:
```
Search term Number of results
-------------------------------------------
morning 128954
forenoon 16
```
That makes *morning* roughly **eight thousand** times more common than *forenoon*. It's safe to say you should stick to *morning* and avoid *forenoon* entirely.
But wait! Is it possible *forenoon* is only used in dialects of English other than US English? To find out, I searched [the Corpus of Global Web-Based English (GloWbE)](http://corpus.byu.edu/glowbe/?c=glowbe&q=33239622), which contains samples of English from twenty countries. And in **none** of those countries was it substantially more common than in the US; the numbers in every country were less than one occurrence per million words. And the few results that I do find are mostly in fiction.
So yes, it is safe to say: avoid *forenoon*. Use *morning* instead. | I am a British, native speaker of English, living in Denmark. I like the word 'forenoon' and sometimes use it, particularly in writing. I do not regard it as archaic, but I may however be influenced in this by Danish, a language I speak every day and fluently. In Danish, we distinguish between 'morgen' (morning) and 'formiddag' (forenoon). We say 'God morgen!' (Good morning!), but only up until about 09.30 or 10.00 hrs. After that, we switch to 'Goddag!' (Good day!).
I have always regarded 'forenoon' as a word much more used and favoured in Scotland than in England, and I admit that it is generally speaking far more used by older people than younger ones. 'Forenoon' has a nice ring to it, I feel. :-) |
42,657,214 | I want to run an existing MEAN Stack Project. The steps I am following are first I am running `npm install` and then `npm run typings -- install` because I can't see any typings folder. But I am getting these errors.
```
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "typings" "--" "install"
npm ERR! node v6.9.5
npm ERR! npm v3.10.10
npm ERR! missing script: typings
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
npm ERR! /home/sami/projects/myappadmin/npm-debug.log
```
I am not sure how to get rid of this I spent a lot of time on google and tried different solutions but nothing worked for me.
My node version is `v6.9.5`. nodejs version is `v4.4.7`. MongoDB shell `version: 3.0.9`. npm `3.10.10`. nvm `0.31.1` ubuntu : `15.10`. | 2017/03/07 | [
"https://Stackoverflow.com/questions/42657214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2243996/"
] | Or you can also use your `Controller` to display such view. By this you'll write your routes more cleaner. Let's say we have an `AdminController` that handles all admin processes and functions. Put your `dashboard.blade.php` inside `views/admin` directory.
The route:
```
Route::get('/admin', 'AdminController@index');
```
The controller:
```
class AdminController extends Controller
{
public function index()
{
return view('admin.dashboard'); // in views->admin->dashboard.blade.php
//add some data here
}
}
``` | Just keep 'blade' in view file name if you don't plan to use controller, e.g.:
```
resources/views/admin/index.blade.php
``` |
17,648,551 | I need to replace a file on a zip using iOS. I tried many libraries with no results. The only one that kind of did the trick was zipzap (<https://github.com/pixelglow/zipzap>) but this one is no good for me, because what really do is re-zip the file again with the change and besides of this process be to slow for me, also do something that loads the whole file on memory and make my application crash.
PS: If this is not possible or way to complicated, I can settle for rename or delete an specific file. | 2013/07/15 | [
"https://Stackoverflow.com/questions/17648551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1792699/"
] | After getting a response from SagePay I have found the following important notes:
* You can use Form/Server/Direct integration interchangeably on the same vendor's account, without needing to change settings or register anything
* The 4020 error genuinely is an IP restriction error and is not masquerading another error
The issue here was that the IP address of the web server (www.mysite.com), being on a VPS, turned out to *not* be the same address as the one used when `curl` requests were made. I made a test PHP page that mailed the IP in `$_SERVER['REMOTE_ADDR']` to myself and put it on another server. I then used `curl` to grab that script and low and behold it was a different IP. Putting (a zero padded version of) this in to the `Valid IPs` section in My SagePay control panel (logged in with the admin account) it sprung to life immediately.
Update
======
You can use:
```
curl icanhazip.com
```
Like so:
```
[user@host ~]# curl icanhazip.com
177.12.41.200
```
to display the correct IP to use, from the command line of the server you're hosting the web site on, instead of uploading files and all that malarkey. [More information and usage here](https://major.io/icanhazip-com-faq/). | You have to add your IP address into SagePay control panel.
Other suggestions:
* You can double-check your IP address at www.whatismyip.com and compare which what you added,
* Make sure that your address didn't change since you added it (e.g. you have dynamic addressing),
* Check if your Apache user is configured to use some different IP address, |
19,159,195 | OK, So PHP has a built-in [getopt()](http://php.net/manual/en/function.getopt.php) function which returns information about what program options the user has provided. Only, unless I'm missing something, it's completely borked! From the manual:
>
> The parsing of options will end at the first non-option found, anything that follows is discarded.
>
>
>
So `getopt()` returns an array with the *valid and parsed* options only. You can still see the entire original command-line by looking at `$argv`, which remains unmodified, but how do you tell *where* in that command-line `getopt()` stopped parsing arguments? It is essential to know this if you want treat the remainder of a command-line as other stuff (like, e.g., file names).
Here's an example...
Suppose I want to set up a script to accept the following arguments:
```
Usage: test [OPTION]... [FILE]...
Options:
-a something
-b something
-c something
```
Then I might call `getopt()` like this:
```
$args = getopt( 'abc' );
```
And, if I ran the script like this:
```
$ ./test.php -a -bccc file1 file2 file3
```
I should expect to have the following array returned to me:
```
Array
(
[a] =>
[b] =>
[c] => Array
(
[0] =>
[1] =>
[2] =>
)
)
```
So the question is this: How on Earth am I supposed to know that the three unparsed, non-option `FILE` arguments start at `$argv[ 3 ]`??? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19159195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424221/"
] | Starting with PHP 7.1, `getopt` supports an optional by-ref param, `&$optind`, that contains the index where argument parsing stopped. This is useful for mixing flags with positional arguments. E.g.:
```
user@host:~$ php -r '$i = 0; getopt("a:b:", [], $i); print_r(array_slice($argv, $i));' -- -a 1 -b 2 hello1 hello2
Array
(
[0] => hello1
[1] => hello2
)
``` | The following may be used to obtain any arguments following command line options.
It can be used before or after invoking PHP's `getopt()` with no change in outcome:
```
# $options = getopt('cdeh');
$argx = 0;
while (++$argx < $argc && preg_match('/^-/', $argv[$argx])); # (no loop body)
$arguments = array_slice($argv, $argx);
```
`$arguments` now contains any arguments following any leading options.
Alternatively, if you don't want the argument(s) in a separate array, then `$argx` is the index of the first actual argument: `$argv[$argx]`.
If there are no arguments, after any leading options, then:
* `$arguments` is an empty array `[]`, and
* `count($arguments) == 0`, and
* `$argx == $argc`. |
16,619,015 | I have this on welcome.jsp
```html
<c:set var="pgTitle" value="Welcome"/>
<jsp:include page="/jsp/inc/head.jsp" />
```
And this in head.jsp:
```html
<title>Site Name - ${pgTitle}</title>
```
But the variable is blank, and the output is merely
```
Site Name -
```
I have read many articles, and I cannot figure out what the problem is. If I echo `${pgTitle}` elsewhere within the same welcome.jsp, then it outputs fine.
I am including the core tag library on both pages. | 2013/05/17 | [
"https://Stackoverflow.com/questions/16619015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684311/"
] | This is because the `pgTitle` variable is set in page scope. Check it [here](http://www.tutorialspoint.com/jsp/jstl_core_set_tag.htm)(sorry I can't get an official documentation for this).
If you want to make this work, you have to set the variable in request scope at least. To set your variable in request scope, use the `scope` attribute on `<c:set>`:
```html
<c:set var="pgTitle" value="Welcome" scope="request" />
```
---
Per your comment, in web development, the scope of the variables matter because it defines where the variable can be used (similar to a variable declared as field in a class and a variable declared locally in a method). There are four scopes in JSP known as context:
* Page scope (handled by [PageContext](http://docs.oracle.com/javaee/6/api/javax/servlet/jsp/PageContext.html)). The variables can only be reached if set as attributes in the current page. This means, only current page can access these attributes, included pages are different pages, so they can't access these attributes.
* Request scope (handled by [ServletRequest](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html)). The variables can only be reached if set as attributes in the current request. This means, every page handled in the same request can access to these attributes. **Important Note**: A redirect implies a new request/response process. This means, if you set attributes on the request and execute a redirect, these attributes won't be set as attributes on the new request.
* Session scope (handled by [HttpSession](http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSession.html)). The variables can only be reached if set as attributes in the current user session. This means, every page used in the same user session can use these attributes until they are removed or the session expires.
* Application scope (handled by [ServletContext](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html)). The variables can only be reached if set as attributes in the current context. This means, every page on every session attribute can access to these variables until they are removed from SessionContext or the web application is undeployed.
More info:
* [What are the different scopes in JSP?](http://www.java-samples.com/showtutorial.php?tutorialid=1009)
>
> Is this the right way to accomplish what I am trying to do?
>
>
>
If there's a Servlet or another controller that handles the attributes to be set in the request (e.g. `@Controller` from Spring MVC or JSF managed bean), then set the attribute there and not in your page directly.
Personally, it takes some time to earn experience and define the best scope of the variables when used on web applications. Basic examples:
* The split of a `String` by comma for presentation purposes will affect only to current view, so this can be set in page scope.
* Error and successful messages are best suited in request scope. If user updates the page, he/she probably must not see the same messages unless the data is re-processed.
* User info as name, nickname and preferences can be set in session scope.
* If you have to display a list of Countries (that should not change in few days), you can store this list in application scope. | One way is to pass variables to an include via query params:
```
<jsp:include page="/WEB-INF/views/partial.jsp?foo=${bar}" />
<jsp:include page="/WEB-INF/views/partial.jsp">
<jsp:param name="foo" value="${bar}" />
<jsp:param name="foo2" value="${bar2}" />
</jsp:include>
```
You can then access those params with `${param.foo}`
Another would be to use custom tags:
**/WEB-INF/tags/head.tag**
```
<%@ attribute name="title" %>
<head>
<title>${title}</title>
</head>
```
**somePage.jsp**
```
<%@ taglib prefix="layout" tagdir="/WEB-INF/tags" %>
<html>
<layout:head title="myRadTitle" />
<body></body>
<html/>
``` |
15,985,498 | I am developing iPad app, in which am using a `UITabBarController`. How do I customize the space between the items?
I tried this code, but it is not working:
```
self.window.rootViewController = self.tabContoroller;
[tabContoroller setFrame:CGRectMake(0,-10, 1038, 54)];
```
 | 2013/04/13 | [
"https://Stackoverflow.com/questions/15985498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190083/"
] | For iOS 7 and above, you can now use the property `itemSpacing` in combination with `itemPositioning` set to `UITabBarItemPositioningCentered` | I just create a subclass of the tabbar and rewrite the layoutSubviews.
There is a property call [titlePositionAdjustment](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITabBarItem_Class/#//apple_ref/occ/instp/UITabBarItem/selectedImage). We can add space by changing the position. |
26,235,907 | I want to load a struct with 3 values into a struct with only 2 values.
```
typedef struct {
double x;
double y;
} twod;
typedef struct {
double x;
double y;
double z;
} threed;
```
The 2nd struct contains arrays of coordinates for the 3d plane. The goal is to just load the `x` and `y` coordinates into the 1st struct from the 2nd struct.
Is that possible considering they are different typedefs? How would a solution be implemented? | 2014/10/07 | [
"https://Stackoverflow.com/questions/26235907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3901898/"
] | No, of course it's not directly possible since it won't fit.
But you can copy the fields manually, of course:
```
twod atwod;
threed athreed;
athreed.x = 1.0;
athreed.y = 2.0;
athreed.z = 3.0;
atwod.x = athreed.x;
atwod.y = athreed.y;
```
You can make scary assumptions and use `memcpy()` but it won't be worth it.
Of course, you can also go all inheritance-based and re-structure `threed`:
```
typedef struct {
twod xy;
double z;
} threed;
```
Then you can do:
```
atwod = athree3.xy;
```
But accesses to `threed` become less clear. | You'd do it simply with the = operator:
```
threed a = {1.0, 2.0, 3.0};
twod b;
b.x = a.x;
b.y = a.y;
``` |
20,727,268 | I have one archive file that contains multiple subfolders in it.
For example : `C:\Documents and Settings\Owner\Desktop\Macro\Intermediación Financiera\2013\12\BCO_Ind.zip`
In the **BCO\_Ind.zip** contains this subfolder `scbm\2013\09\fileThatIWant.xls`
These subfolder are different for each archive file although it has the same name.
the things is i want the last file from the last subfolder.
I modified the code from <http://excelexperts.com/unzip-files-using-vba> and from www.rondebruin.nl/win/s7/win002.htm
The problem is I get an error which is:
`run-time error -2147024894(80070002)': Method 'Namespace' of Object 'IShellDispatch4' failed`.
I try to search all from the website but I didn't find the solution for almost a week.
Here is the code:
```
Sub TestRun()
'Change this as per your requirement
Call unzip("C:\Documents and Settings\Owner\Desktop\Macro\Intermediación Financiera\2013\12\", "C:\Documents and Settings\Owner\Desktop\Macro\Intermediación Financiera\2013\12\BCO_Ind.zip")
End Sub
Public Function unzip(targetpath As String, filename As Variant, Optional SCinZip As String, _
Optional excelfile As String) As String '(targetpath As String, filename As Variant)
Dim strScBOOKzip As String, strScBOOK As String: strScBOOK = targetpath
Dim targetpathzip As String, excelpath As String
Dim bzip As Boolean: bzip = False
Dim oApp As Object
Dim FileNameFolder As Variant
Dim fileNameInZip As Object
Dim objFSO As Scripting.FileSystemObject
Dim filenames As Variant: filenames = filename
If Right(targetpath, 1) <> Application.PathSeparator Then
targetpathzip = targetpath & Application.PathSeparator
Else
targetpathzip = targetpath
End If
FileNameFolder = targetpathzip
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oApp = CreateObject("Shell.Application")
''-----i get an error in here
For Each fileNameInZip In oApp.Namespace(filenames).Items
If objFSO.FolderExists(FileNameFolder & fileNameInZip) Then
objFSO.DeleteFolder FileNameFolder & fileNameInZip, True: Sleep 1000
End If
''-----i get an error in here too
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(filename).Items.item(CStr(fileNameInZip))
bzip = True
Next fileNameInZip
If bzip Then
excelpath = findexactfile(targetpath) ' this will go to the function that find the file from subfolders
Else
excelpath = ""
End If
searchfolder = FileNameFolder & fileNameInZip
finish:
unzip = excelpath
Set objFSO = Nothing
Set oApp = Nothing
End Function
```
I also tick some tools>references in development macro but it still get the same error. I really stress+frustrated right now. Please help me to fix it. Also, is there have a simple code as my references to find the file from subfolder after the file is extract? I really appreciate it if someone can share the code. | 2013/12/22 | [
"https://Stackoverflow.com/questions/20727268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851376/"
] | There are two different types of array to consider:
* `[D` is a **primitive** double array, equivalent to Java `double[]`
* `[Ljava.lang.Double;` is an array of `Double` **references**, equivalent to Java `Double[]`.
(the odd notation is because this is the internal representation of these types in Java bytecode... it's a bit odd that this gets exposed in Clojure but you just have to live with it)
Because these are different types, they are treated differently with Clojure protocols.
The primitive double arrays usually offer better performance, assuming you stick to primitive double operations and avoid any unnecessary boxing. You can think of the primitive arrays as an array of unboxed values, and the reference arrays as an array of boxed values.
The main reason to use the reference arrays are if your values are already boxed when you receive them, and/or if you plan to pass them to other functions or collections that require boxed values. In this case, it is inefficient to unbox the doubles and then box them again, so it can be sensible to leave them in boxed form.
FWIW, there are several libraries that make it easy to do things with double arrays. In particular you should check out [HipHip](https://github.com/prismatic/hiphip) (specialised array operations), [core.matrix](https://github.com/mikera/core.matrix) (supports vector/matrix operations on many types including double arrays) and [vectorz-clj](https://github.com/mikera/vectorz-clj) (works with core.matrix, wraps double arrays as general purpose vectors) | The double-array is unboxed. When you access an item from the array, Clojure automatically boxes it, unless you access it using a type-hinted function expecting that type. |
1,214 | I have a 2 node cluster (NODE-A & NODE-B) with 2 SQL instances spread between them. INST1 prefers NODE-A, INST2 prefers NODE-B. INST1 started generating errors then, failed over to NODE-B. Migrating INST1 back to NODE-A generates the connection errors after it logs a "Recovery is complete." message.
Win 2008 R2 Ent.
SQL 2008 R2 Ent.
Errors from the Event Log after first failure:
```
[sqsrvres] CheckQueryProcessorAlive: sqlexecdirect failed
[sqsrvres] printODBCError: sqlstate = HYT00; native error = 0; message = [Microsoft][SQL Server Native Client 10.0]Query timeout expired
[sqsrvres] OnlineThread: QP is not online.
[sqsrvres] printODBCError: sqlstate = 08S01; native error = 0; message = [Microsoft][SQL Server Native Client 10.0]The connection is no longer usable because the server failed to respond to a command cancellation for a previously executed statement in a timely manner. Possible causes include application deadlocks or the server being overloaded. Open a new connection and re-try the operation.
[sqsrvres] ODBC sqldriverconnect failed
[sqsrvres] checkODBCConnectError: sqlstate = HYT00; native error = 0; message = [Microsoft][SQL Server Native Client 10.0]Login timeout expired
[sqsrvres] checkODBCConnectError: sqlstate = 08001; native error = ffffffff; message = [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
``` | 2011/02/14 | [
"https://dba.stackexchange.com/questions/1214",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/247/"
] | I expect the way to do this is with [SSIS](http://msdn.microsoft.com/en-us/library/ms141026.aspx), connecting over your existing ODBC. It's tailor-made for pulling data from diverse sources into SQL Server, for subsequent consumption by, for example, [SSRS](http://msdn.microsoft.com/en-us/library/ms159106.aspx). My advice would be to do a bit of background reading on these tools and see if they can be applied to your situation, if not you will at least then have a clearer idea of what features you need that it doesn't have and can go shopping with that. | Knight's Microsoft Business Intelligence 24-Hour Trainer is a book DVD combo. This is another good place to get started in Microsoft BI. |
428,085 | I want to score DNA sequence
```
A = 1 T = 2 C = 3 G = 4
```
---
My input is
```
ATGGCGATTGA
AGCTTAGCCAG
AGCTTAGGGAA
```
---
My output should be
```
seq_number 1 has score = 28
seq_number 2 has score = 28
seq_number 3 has score = 27
```
---
edited my input is .txt file | 2018/03/04 | [
"https://unix.stackexchange.com/questions/428085",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/269005/"
] | ```
sed -e 's/A/./g' -e 's/T/../g' \
-e 's/C/.../g' -e 's/G/..../g' file |
awk '{ printf("seq_number %d has score = %d\n", NR, length) }'
```
Output:
```
seq_number 1 has score = 28
seq_number 2 has score = 28
seq_number 3 has score = 27
```
The `sed` command replaces each base by a number of dots that represents the score. The `awk` command prints the number of lines read so far and also calculates the length of the line, which is the total score for that line.
The first `sed` expression, `s/A/./g`, in not actually needed for the result to be correct.
---
Variation (tiny bit shorter, just for fun):
```
sed -e 's/G/TT/g;s/C/TA/g;s/T/AA/g' file |
awk '{ printf("seq_number %d has score = %d\n", NR, length) }'
```
---
Variation that gives only the scores, one per line:
```
tr 'ATCG' '1234' <file | awk -F'\0' -vOFS="+" '$1=$1' | bc
```
This first replaces each letter with the digit that is the score for that letter, and then, with `awk`, inserts `+` between each digit. The calculation of the total score for each line is then handled by `bc`.
And finally, a variation of the last one but with only `sed` and `bc` (again, only the scores are printed):
```
sed 'y/ATCG/1234/;s/\(.\)/+\1/g;s/^+//' file | bc
```
---
Sundeep came up with
```
sed 'y/ATCG/1234/;s/./+&/2g' file | bc
```
which is a shorter variation of my last thing.
It first changes the letters to the corresponding digits with the `y` command, and then replaces each character (from the second one onwards) with itself prepended by `+`, so for the input string `ACCA` you'll get `1+3+3+1` as output. `bc` is then used to evaluate this arithmetic expression.
His solution works only in GNU `sed` as standard `sed` does not like getting both `2` and `g` as substitution flags at the same time. | well, since this question is getting answered anyway, here's some `perl/ruby` one-liners
```
$ perl -MList::Util=sum0 -lne 'print "seq_number $. has score = ", sum0 split //, tr/ATCG/1234/r' ip.txt
seq_number 1 has score = 28
seq_number 2 has score = 28
seq_number 3 has score = 27
$ ruby -ne 'puts "seq_number #{$.} has score = #{$_.tr("ATCG", "1234").chars.sum(&:to_i)}"' ip.txt
seq_number 1 has score = 28
seq_number 2 has score = 28
seq_number 3 has score = 27
```
The idea is same, and applicable as long as letters translate to single digit number
* so, first use `tr` to change `ATCG` to corresponding `1234`
* then split the string on characters, and sum the digits
And an `awk` version using return value of `split`
```
$ awk 'BEGIN{a["A"]=1; a["T"]=2; a["C"]=3; a["G"]=4}
{score = 0; for(k in a) score += (split($0, n, k)-1)*a[k];
print "seq_number " NR " has score = " score}' ip.txt
seq_number 1 has score = 28
seq_number 2 has score = 28
seq_number 3 has score = 27
``` |
126,279 | I am using 74LS154 4 to 16 decoder [Link to \*.pdf here](http://www.ti.com/lit/ds/symlink/sn74154.pdf). It has two ACTIVE LOW 'ENABLE' pins at the input. What is the use of two ENABLE input pins is the question.
Most of the 74 series IC's used in the lab has two ENABLE pins.. | 2014/08/23 | [
"https://electronics.stackexchange.com/questions/126279",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/51876/"
] | It's just simply to reduce the "glue logic" needed to implement the device. It's simple enough to just tie the one input to low and to use the other pin as a single input and this gives more flexibility in implementation.
If you look at the package you realize that without the extra /enable that package would have an NC pin. I suspect the first designers decided that having a little extra functionality for "free" (i.e. in pin count) would be an enhancement. | That's interesting that they would have two active-low enable pins and no active-high enable pins. I'm not entirely sure what you would need that for. I suppose it acts like a free AND or OR gate on the enable input, depending on how you want to look at it, which could be uselful in some applications. However, the 3 to 8 line decoders generally have 3 enable lines - one active-high and two active-low. You can use the active high pin on one chip and the active low pin on another chip to cascade two 3-to-8 decoders into a 4-to-16 decoder as the 4th input line drives the complementary enable lines. |
34,809,874 | I'm trying to create an multidimensional and associative array. I'm tried a PHP-like syntax but it doesn't work. How to solve?
```
var var_s = ["books", "films"];
var_s["books"]["book1"] = "good";
var_s["books"]["book2"] = "bad";
var_s["films"]["films1"] = "bad";
var_s["films"]["films2"] = "bad";
``` | 2016/01/15 | [
"https://Stackoverflow.com/questions/34809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5576116/"
] | Use objects:
```
var var_s = {"books":{}, "films": {}};
var_s["books"]["book1"] = "good";
-> {books: {book1: "good"}, films: {}}
``` | You want object literal syntax:
```
var_s = {
books: {
book1: "good",
book2: "bad"
},
films: {
film1: "good",
film2: "bad"
}
}
```
Retrieving a value:
```
var myBook = var_s.books.book1
```
Setting:
```
var_s.books.book3 = "terrible"
```
I recommend reading [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) for a good crash course in JS basics. [Chapter 2 of Book 1](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20&%20going/ch2.md) specifically covers objects and initialization, |
56,372,471 | Can I ask if is this is the only way to check if a variable is false in VB.net?
here is my code
```
if a = true and b = true and c = true then
msgbox("ok")
else if a= true and b = true and c = false then
msgbox("c has errors")
else if a= true and b = false and c = true then
msgbox("b has errors")
else if a= false and b = true and c = true then
msgbox("a has errors")
end if
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56372471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801763/"
] | It's more for the code review section, but I give the answers anyway...
For my aesthetics it is ugly to write `If (a = True) Then` or `If (a = False) Then`, I would rather use `If (a) Then` and `If (Not a) Then`.
In your code, if a + b have errors, nothing happens, as this case is not handled. A Rolls-Royce implementation could look like this:
```
Public Class Application
Public Sub DoSomething()
'... get the results from 3 calls to other methods
Dim a As Boolean = MethodA()
Dim b As Boolean = MethodB()
Dim c As Boolean = MethodC()
Dim myErrors As String = GetErrorMessage(a, b, c)
If (myErrors Is Nothing) Then
MsgBox("ok")
Else
MsgBox(myErrors)
Environment.Exit(-1)
End If
End Sub
Private Function GetErrorMessage(a As Boolean, b As Boolean, c As Boolean) As String
If (a AndAlso b AndAlso c) Then Return Nothing
Dim myList As New List(Of String)(3)
If (Not a) Then myList.Add(NameOf(MethodA))
If (Not b) Then myList.Add(NameOf(MethodB))
If (Not c) Then myList.Add(NameOf(MethodC))
Select Case myList.Count
Case 1
Return $"{myList(0)} has errors!"
Case 2
Return $"{myList(0)} and {myList(1)} have errors!"
Case Else
Return $"{String.Join(", ", myList.Take(myList.Count - 1))} and {myList(myList.Count - 1)} have errros!"
End Select
End Function
Private Function MethodA() As Boolean
'Does something
Return True
End Function
Private Function MethodB() As Boolean
'Does something
Return False
End Function
Private Function MethodC() As Boolean
'Does something
Return False
End Function
End Class
```
As a general recommendation, I would not return a boolean from the 3 calls but implement them as Sub instead and throw an exception if something goes wrong, that allows you to give more accurate feedback and also to handle the error higher up the call stack if you prefere. Here an example of such an implementation:
```
Public Class Application
Public Sub DoSomething()
Dim myErrors As List(Of String) = Nothing
Try
MethodA()
Catch ex As Exception
If (myErrors Is Nothing) Then myErrors = New List(Of String)(3)
myErrors.Add($"{NameOf(MethodA)}: {ex.Message}")
End Try
Try
MethodB()
Catch ex As Exception
If (myErrors Is Nothing) Then myErrors = New List(Of String)(2)
myErrors.Add($"{NameOf(MethodB)}: {ex.Message}")
End Try
Try
MethodC()
Catch ex As Exception
If (myErrors Is Nothing) Then myErrors = New List(Of String)(1)
myErrors.Add($"{NameOf(MethodC)}: {ex.Message}")
End Try
If (myErrors Is Nothing) Then
MsgBox("OK")
Else
MsgBox($"The following errors occurred:{vbCrLf}{vbCrLf}{String.Join(vbCrLf, myErrors)}")
End If
End Sub
Private Sub MethodA()
'Does something
End Sub
Private Sub MethodB()
'Does something
Throw New NotImplementedException()
End Sub
Private Sub MethodC()
'Does something
Throw New NotSupportedException()
End Sub
End Class
``` | My approach would be to put the Booleans in an array. The loop through checking for the value = False. The index of the False values are added to lstIndexes.
```
Dim lstIndexes As New List(Of Integer)
Dim bools = {a, b, c}
For i = 0 To bools.Length - 1
If Not bools(i) Then
lstIndexes.Add(i)
End If
Next
``` |
18,513,780 | I have SMS API that supports JSON AND XML via HTTP protocal, what it does it it receives SMS request from clients in either JSON or XML format and forward it to MNO using [Kannel SMS Gateway](http://www.kannel.org/ "Kannel SMS Gateway"). Now I have the client whose requirement is that he want to connect to us via SMPP protocol. My question is how do I create SMPP server so that other client could connect to my application using SMPP? Any resources to get me started will much be appreciated.
The process is like this.
1. Receive request from the client via SMPP
2. Validate client information
3. Forward the message to the MNO
4. Send status response to the client. | 2013/08/29 | [
"https://Stackoverflow.com/questions/18513780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577446/"
] | Well I managed to create SMPP server using [Shorty Nodejs SMPP client and server](https://github.com/Roave/shorty "Shorty") | WELL to get you started with some ground too information refer this
[LINKS which will help](http://www.activexperts.com/sms-component/smpp-specifications/introduction/)
[THE HOW TO U were asking for](http://www.activexperts.com/sms-component/howto/smpp-send/php/) |
2,781,570 | Basically, what the title says. I have several properties that combine together to really make one logical answer, and i would like to run a server-side validation code (that i write) which take these multiple fields into account and hook up to only one validation output/error message that users see on the webpage.
I looked at scott guthries method of extending an attribute and using it in yoru dataannotations declarations, but, as i can see, there is no way to declare a dataannotations-style attribute on multiple properties, and you can only place the declarations (such as [Email], [Range], [Required]) over one property :(.
any ideas on how to go about this? preferably without having to go the whole AssociateValidatorProvider route? as i found thisdifficult to grasp mainly since people never tell you 'why' they are doing what they are doing in enough detail to make me feel comfortable.
at the moment, i've tried ot create a dummy hidden field on the form with the [Required] attribute on it, and i set it to an empty string when my multi-field custom validation code predicts an error, which shoudl trigger an error message, but not even that works, because when i change the values of these fields AFTER the action is received, the modelstate isn't updated with this info so presumes submitted values, and doing an UpdateModel fails with an error. on top of these errors, i suppose it isn't the elegant way to do things. so i'm listening to anything you guys suggest. | 2010/05/06 | [
"https://Stackoverflow.com/questions/2781570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220064/"
] | You can add those validation messages into the ModelState errors and display them on client side using Jquery/JavaScript.
If your action method return JsonResult then return the errors as JsonResult else set the errors into ViewData and then access and display them at the client side.
You can add the custom errors into the model state as follows :
```
if(your custom validation fails....)
{
ModelState.AddModelError("Error1", "Your Error message1");
ModelState.AddModelError("Error2", "Your Error message2");
}
if (!ModelState.IsValid)
{
return new JsonResult() { Data = GetModelStateErrors(ModelState)};
}
private static Collection<string> GetModelStateErrors(ModelState modelState)
{
Collection<string> errors = new Collection<string>();
foreach (var item in modelState.Values)
{
foreach (var item2 in item.Errors)
{
if (!string.IsNullOrEmpty(item2.ErrorMessage))
{
errors.Add(item2.ErrorMessage);
}
}
}
return errors;
}
``` | You can add an validation attribute to the class:
<http://msdn.microsoft.com/en-us/magazine/ee336030.aspx>
However I haven't been able to test this myself. |
360 | I would like to use my Raspberry Pi as a file server (NAS/SMB).
Will I be able to attach a SATA/RAID controller? | 2012/06/16 | [
"https://raspberrypi.stackexchange.com/questions/360",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/35/"
] | Since the chip does not have SATA support. Your only option is to connect a SATA HD enclosure through the USB port. | To build a custom SATA controller for the GPIO pins would not be a simple job, but may happen, one day. Then the Pi could be used as a NAS.
A NAS device would also be a great solution as the Network port is faster than USB. |
8,646,441 | I have a String and I want to get the words before and after the " - " (dash). How can I do that?
example:
String:
```
"First part - Second part"
```
output:
```
first: First part
second: Second part
``` | 2011/12/27 | [
"https://Stackoverflow.com/questions/8646441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068827/"
] | Easy: use the [`String.split`](http://java.xiruibin.com/String.html#split%28java.lang.String%29) method.
**Example :**
```
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
final String after = s.split("-")[1]; // "After"
```
Note that I'm leaving error-checking and white-space trimming up to you! | use [`indexOf()`](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) and [`substring()`](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int,%20int%29) method of `String` class, for the example given you can also use [`split()`](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29) method |
12,544,249 | longtime listener, first time caller.
I need to use Node as a *client* to connect to a realtime data stream that uses long polling and do stuff with each item as the data is received.
I've found plenty of info on using Node as a long polling server, but not as the client.
I know how to use the "Request" module to load a URL, but my problem is the only callback I know of is the "oncomplete" callback, which only fires after the connection is closed. It doesn't allow me to access the data being received in real time while the connection is held open. I only get to use it when the connection terminates.
Is there a way for Node to open an HTTP connection to a remote server, then fire events whenever data is received?
Or I suppose another question is... is there a way to access whatever buffer all that data is going into while the HTTP connection is in progress?
Thanks!!! | 2012/09/22 | [
"https://Stackoverflow.com/questions/12544249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985688/"
] | I basically revised your whole setup. Tested under PostgreSQL 9.1.5.
### DB schema
* I think that your table layout has a major logical flaw (as also pointed out by @Catcall). I changed it the way I suspect it should be:
Your last table `measurement_data_value` (which I renamed to `measure_val`) is supposed to save a value per `parameter` (now: `param`) for every row in `measurement_data_index` (now: `measure`). See below.
* Even though "a device has a unique name" use an integer surrogate primary key anyway. Text strings are inherently bulkier and slower to be used as foreign keys in big tables. They are also subject to **collation**, which can slow down queries significantly.
[Under this related question](https://stackoverflow.com/q/9888096/939860) we found that joining and sorting on a medium sized `text` column was the major slow-down.
If you insist on using a text string as primary key, read up on [collation support](http://www.postgresql.org/docs/current/interactive/collation.html) in PostgreSQL 9.1 or later.
* Don't fall for the anti-pattern of using `id` as name for a primary key. When you join a couple of tables (like you will have to do a lot!) you end up with several columns name `id` - what a mess! (Sadly, some ORMs use it.)
Instead, name a surrogate primary key column after the table somehow to make it meaningful on its own. Then you can have foreign keys referencing it have the same name (that's a good, as they contain the same data).
```
CREATE TABLE spot
( **spot\_id** SERIAL PRIMARY KEY);
```
* Don't use super-long identifiers. They are hard to type and hard to read. Rule of thumb: as long a necessary to be clear, as short as possible.
* Don't use `varchar(n)` if you don't have a compelling reason. Just use [`varchar`, or simpler: just `text`](http://www.postgresql.org/docs/current/interactive/datatype-character.html).
All this and more went into my proposal for a better db schema:
```
CREATE TABLE device
( device_id serial PRIMARY KEY
,device text NOT NULL
);
CREATE TABLE param
( param_id serial PRIMARY KEY
,param text NOT NULL
);
CREATE INDEX param_param_idx ON param (param); -- you are looking up by name!
CREATE TABLE spot
( spot_id serial PRIMARY KEY);
CREATE TABLE measure
( measure_id serial PRIMARY KEY
,device_id int NOT NULL REFERENCES device (device_id) ON UPDATE CASCADE
,spot_id int NOT NULL REFERENCES spot (spot_id) ON UPDATE CASCADE
,t_stamp timestamp NOT NULL
,CONSTRAINT measure_uni UNIQUE (device_id, spot_id, t_stamp)
);
CREATE TABLE measure_val -- better name?
( measure_id int NOT NULL REFERENCES measure (measure_id)
ON UPDATE CASCADE ON DELETE CASCADE -- guessing it fits
,param_id int NOT NULL REFERENCES param (param_id)
ON UPDATE CASCADE ON DELETE CASCADE -- guessing it fits
,value text NOT NULL
,CONSTRAINT measure_val_pk PRIMARY KEY (measure_id, param_id)
);
CREATE INDEX measure_val_param_id_idx ON measure_val (param_id); -- !crucial!
```
I renamed the bulky `measurement_data_value` to `measure_val`, because that's what's in the table: parameter-values for measurements. Now, the **multi-column pk** makes sense, too.
But I added a **separate index on `param_id`**. The way you had it, column `param_id` was the second column in a multi-column index, which leads to poor results for `param_id`. Read all the [gory details about that under this related question on dba.SE](https://dba.stackexchange.com/q/6115/3684).
After implementing this alone, your query should be faster. But there is more you can do.
### Test data
This fills in the data **much faster**. The point is that I use set-based DML commands, executing mass-inserts instead of loops that execute individual inserts, which takes forever. Makes quite a difference for the considerable amount of test data you want to insert. It's also much shorter and simpler.
To make it even more efficient, I use a [data-modifying CTE](http://www.postgresql.org/docs/current/interactive/queries-with.html#QUERIES-WITH-MODIFYING) (new in Postgres 9.1) that instantly reuses the massive amount of rows in the last step.
```
CREATE OR REPLACE FUNCTION insert_data()
RETURNS void LANGUAGE plpgsql AS
$BODY$
BEGIN
INSERT INTO device (device)
SELECT 'dev_' || to_char(g, 'FM00')
FROM generate_series(1,5) g;
INSERT INTO param (param)
SELECT 'param_' || to_char(g, 'FM00')
FROM generate_series(1,20) g;
INSERT INTO spot (spot_id)
SELECT nextval('spot_spot_id_seq'::regclass)
FROM generate_series(1,10) g; -- to set sequence, too
WITH x AS (
INSERT INTO measure (device_id, spot_id, t_stamp)
SELECT d.device_id, s.spot_id, g
FROM device d
CROSS JOIN spot s
CROSS JOIN generate_series('2012-01-06 23:00:00' -- smaller set
,'2012-01-07 00:00:00' -- for quick tests
,interval '1 min') g
RETURNING *
)
INSERT INTO measure_val (measure_id, param_id, value)
SELECT x.measure_id
,p.param_id
,x.device_id || '_' || x.spot_id || '_' || p.param
FROM x
CROSS JOIN param p;
END
$BODY$;
```
Call:
```
SELECT insert_data();
```
### Query
* Use explicit `JOIN` syntax and table aliased to make your queries easier to read and debug:
```
SELECT v.value
FROM param **p**
JOIN measure_val **v USING (param\_id)**
WHERE p.param = 'param_01';
```
The `USING` clause is just for simplifying the syntax, but not superior to `ON` otherwise.
This should be **much faster** now for two reasons:
* Index `param_param_idx` on `param.param`.
* Index `measure_val_param_id_idx` on `measure_val.param_id`, like explained in detail [here](https://dba.stackexchange.com/q/6115/3684).
### Edit after feedback
My major oversight was that you already had added the crucial index in form of `measurement_data_value_idx_fk_parameter_id` further down in your question. (I blame your cryptic names! :p ) On closer inspection, you have more than 10M (7 \* 24 \* 60 \* 5 \* 10 \* 20) rows in your test setup and your query retrieves > 500K. I only tested with a much smaller subset.
Also, as you retrieve 5% of the whole table, indexes will only go so far. I was to optimistic, such an amount of data is bound to take some time. Is it a realistic requirement that you query 500k rows? I would assume you aggregate in your real life application?
### Further options
* [Partitioning](http://www.postgresql.org/docs/current/interactive/ddl-partitioning.html).
* More RAM and settings that make use of it.
>
> A virtual Debian 6.0 machine with 1GB of RAM
>
>
>
is way below what you need.
* [Partial indexes](http://www.postgresql.org/docs/current/interactive/indexes-partial.html), especially in connection with **index-only scans** of PostgreSQL 9.2.
* [**Materialized views**](http://en.wikipedia.org/wiki/Materialized_view) of aggregated data. Obviously, you are not going to display 500K rows, but some kind of aggregation. You can compute that once and save results in a materialized view, from where you can retrieve data much faster.
* If your queries are predominantly by parameter (like the example), you could use [**`CLUSTER`**](http://www.postgresql.org/docs/current/interactive/sql-cluster.html) to physically rewrite the table according to an index:
```
CLUSTER measure_val USING measure_val_param_id_idx
```
This way all rows for one parameter are stored in succession. Means fewer block to read and easier to cache. Should make the query at hand much faster. Or `INSERT` the rows in favorable order to begin with, to the same effect.
Partitioning would mix well with `CLUSTER`, since you would not have to rewrite the whole (huge) table every time. As your data is obviously just inserted and not updated, a partition would stay "in order" after `CLUSTER`.
* Generally, **PostgreSQL 9.2** should be great for you as its [improvements focus on performance with big data](http://www.postgresql.org/docs/current/interactive/release-9-2.html#AEN110346). | It seems from the numbers that you are being hit by timing overhead. You can verify this by using [pg\_test\_timing](http://www.postgresql.org/docs/9.2/static/pgtesttiming.html) or adding `timing off` to your explain parameters (both are introduced in PostgreSQL version 9.2). I can approximately replicate your results by turning setting my clocksource to HPET instead of TSC.
With HPET:
```
Nested Loop (cost=8097.73..72850.98 rows=432000 width=12) (actual time=29.188..905.765 rows=432000 loops=1)
Buffers: shared hit=56216
-> Seq Scan on parameter (cost=0.00..1.25 rows=1 width=4) (actual time=0.004..0.008 rows=1 loops=1)
Filter: ((name)::text = 'param_01'::text)
Rows Removed by Filter: 19
Buffers: shared hit=1
-> Bitmap Heap Scan on measurement_data_value (cost=8097.73..68529.73 rows=432000 width=16) (actual time=29.180..357.848 rows=432000 loops=1)
Recheck Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=56215
-> Bitmap Index Scan on measurement_data_value_idx_fk_parameter_id (cost=0.00..7989.73 rows=432000 width=0) (actual time=21.710..21.710 rows=432000 loops=1)
Index Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=1183
Total runtime: 1170.409 ms
```
With HPET and timing off:
```
Nested Loop (cost=8097.73..72850.98 rows=432000 width=12) (actual rows=432000 loops=1)
Buffers: shared hit=56216
-> Seq Scan on parameter (cost=0.00..1.25 rows=1 width=4) (actual rows=1 loops=1)
Filter: ((name)::text = 'param_01'::text)
Rows Removed by Filter: 19
Buffers: shared hit=1
-> Bitmap Heap Scan on measurement_data_value (cost=8097.73..68529.73 rows=432000 width=16) (actual rows=432000 loops=1)
Recheck Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=56215
-> Bitmap Index Scan on measurement_data_value_idx_fk_parameter_id (cost=0.00..7989.73 rows=432000 width=0) (actual rows=432000 loops=1)
Index Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=1183
Total runtime: 156.537 ms
```
With TSC:
```
Nested Loop (cost=8097.73..72850.98 rows=432000 width=12) (actual time=29.090..156.233 rows=432000 loops=1)
Buffers: shared hit=56216
-> Seq Scan on parameter (cost=0.00..1.25 rows=1 width=4) (actual time=0.004..0.008 rows=1 loops=1)
Filter: ((name)::text = 'param_01'::text)
Rows Removed by Filter: 19
Buffers: shared hit=1
-> Bitmap Heap Scan on measurement_data_value (cost=8097.73..68529.73 rows=432000 width=16) (actual time=29.083..114.908 rows=432000 loops=1)
Recheck Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=56215
-> Bitmap Index Scan on measurement_data_value_idx_fk_parameter_id (cost=0.00..7989.73 rows=432000 width=0) (actual time=21.667..21.667 rows=432000 loops=1)
Index Cond: (fk_parameter_id = parameter.id)
Buffers: shared hit=1183
Total runtime: 168.869 ms
```
So your slowness seems to be mostly caused by instrumentation overhead. However, selecting huge amounts of rows won't be extremely fast in PostgreSQL. If you need to do number crunching on large swathes of data it might be a good idea to structure your data so you can fetch it in larger chunks. (e.g. if you need to always process at least a days worth of data, aggregate all measurements for one day into an array)
In general, you have to have a idea of what your workload is going to be to do tuning. What is a win in one case might be a big loss in some other case. I recommend checking out [pg\_stat\_statements](http://www.postgresql.org/docs/9.2/static/pgstatstatements.html) to figure out where your bottlenecks are. |
91,916 | I have a small DC gear motor which spools a plastic line. Once I've engaged the motor to tighten the line, I want to lock it in place so that the line doesn't unspool. I would then like it to remain in this position mechanically so that I do not have to apply holding current. When I'm ready to release the line, I'd then like to be able to electrically reverse the process and disengage the lock. Is there a standard design that fits this requirement? | 2013/11/26 | [
"https://electronics.stackexchange.com/questions/91916",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/33266/"
] | A common way of doing this is with a [self-locking worm drive](http://www.brighthubengineering.com/machine-design/65703-what-is-a-self-locking-worm-gear-how-does-it-work/)
The worm drive has a gear ratio that provides high mechanical advantage and depending on the helix angle of the gear, the output can't backdrive the input, so it is self locking. You can find one here at [Servo city](http://www.servocity.com/html/vertical_shaft_worm_drive_gear.html) or try to DIY with hardware store threaded rod and an off the shelf gear.
Another suggestion is a [ratchet and pawl mechanism](http://en.wikipedia.org/wiki/Ratchet_%28device%29) that may be easier to DIY than a worm drive and much cheaper than purchasing it. Note that the rachet can only be driven in one direction.
There are other ideas I can think of such as using a solenoid to lock/unlock a catch that holds the belt in place when the motor is stopped, but they are more complex than what I describe above.
Please post back here if you do build one of these. I love mechanisms but find that few people are interested in building them. | You want a DC motor with a mechanical brake.
You can electrically brake (permanent magnet) motors by shorting the contacts together, but the braking force of this isn't very strong for small motors.
For your cord application, I'd look into some sort of clamp applied to the cord itself with a servo. Especially if it's safety-critical; I can't tell from the description whether this is the sort of cord used for opening curtains or the sort that might have heavy objects or people hanging from it. |
21,355,285 | To start things off, here is my code:
```
.header{
width: 100%;
height: 10%;
background-color: #FF4545;
}
.headertext{
font-family: 'Duru Sans', sans-serif;
font-size: 65px;
float:left;
margin-top: 0px;
margin-bottom: 0px;
}
.headermenu{
font-family: 'Duru Sans', sans-serif;
font-size: 65px;
float: right;
margin-top: 0px;
margin-bottom: 0px;
}
```
So both the .headertext and the .headermenu are html p statements that are embedded within the .header div. Now, the .header div has a bg color. When I resize my window, the div resizes (very clearly with the bg color) however the text does not resize. It makes sense that the text doesn't resize given that I have assigned a concrete font size for them. I wanted to ask how I can have the font size dynamically scale so that the text is always kept within the div? At this point it pokes out the bottom when you resize, meaning half the text is within the bg colored div and half of it is sticking out into whitespace. I hope this is clear enough, thanks! | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Create a new Helper file and put these two methods in you helper.
```
public static function globalXssClean()
{
// Recursive cleaning for array [] inputs, not just strings.
$sanitized = static::arrayStripTags(Input::get());
Input::merge($sanitized);
}
public static function arrayStripTags($array)
{
$result = array();
foreach ($array as $key => $value) {
// Don't allow tags on key either, maybe useful for dynamic forms.
$key = strip_tags($key);
// If the value is an array, we will just recurse back into the
// function to keep stripping the tags out of the array,
// otherwise we will set the stripped value.
if (is_array($value)) {
$result[$key] = static::arrayStripTags($value);
} else {
// I am using strip_tags(), you may use htmlentities(),
// also I am doing trim() here, you may remove it, if you wish.
$result[$key] = trim(strip_tags($value));
}
}
return $result;
}
```
Then put this code in the beginning of your before filter (in Laravel 4 it should be in app/filters.php).
```
App::before(function($request)
{
Helper::globalXssClean();
});
``` | There is also another package for XSS filter for laravel which can be downloaded [here](https://github.com/waiylgeek/laravel-xss-cleaner)
Usage Example:
Simple form code snippet
```
{{Form::open(['route' => 'posts.store'])}}
{{Form::text('title')}}
{{Form::textarea('body')}}
{{Form::submit('Post')}}
{{Form::close()}}
```
Filter package usage
```
$rules = ['title' => 'required|min:13', 'body' => 'required|min:150'];
$validator = Validator(Input::all(), $rules);
if($validator->passes()){
$xss = new XSS;
$xss->clean(Input::all());
$input = $xss->get();
$post = new Post;
$post->title = $input->title;
$post->body = $input->body;
// to test the results you can dd($input); & happy coding everyone!
}
``` |
15,351,634 | In essence, I am coding an algorithm that involves summing all numbers in a big array, each of which takes a parameter. And I have a bunch of parameters to run. To me, the summing of all numbers can be a good candidate of leveraging fork/join in Java, and running the algorithm with different parameter can be effectively done with fixed pool of executor service.
However, anyone knows how to combine those two? Or is it possible to combine them, considering that they are both thread pools and we should not have two pools at the same time?
Any suggestions would be very much appreciated. | 2013/03/12 | [
"https://Stackoverflow.com/questions/15351634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2159018/"
] | I would remove the unwanted records by creating a query as follows:
**Replace:**
```
Set MailList = db.OpenRecordset("MyEmailAddresses")
```
**With:**
```
Dim qd As DAO.QueryDef
Set qd = db.CreateQueryDef("")
qd.SQL = "SELECT * FROM MyEmailAddresses WHERE email IS NOT NULL And Len(Trim(email)) > 0 And OptOut <> 1"
Set MailList = qd.Openrecordset()
' adding them to e-mails and sending them.
Do Until MailList.EOF
... your emailing code ...
``` | I'm not 100% certain this is correct because I'm rusty in VBA.
You'll need to make sure the fields are named correctly because I took a guess.
Jump to
```
If (MailList("email") <> "" AND MailList("opt_out") <> 1) Then
```
and make sure that it has the correct fields.
Second, when you do
```
db.OpenRecordset("MyEmailAddresses")
```
(that bit is before the block of code I pasted) Make sure that query includes the opt out field.
```
Do Until MailList.EOF
If (MailList("email") <> "" AND MailList("opt_out")) Then
' This creates the e-mail
Set MyMail = MyOutlook.CreateItem(olMailItem)
' This addresses it
MyMail.To = MailList("email")
'This gives it a subject
MyMail.Subject = Subjectline$
'This gives it the body
MyMail.HTMLBody = MyBodyText
'If you want to send an attachment
'uncomment the following line
'MyMail.Attachments.Add "c:myfile.txt", olByValue, 1, "My Displayname"
' To briefly describe:
' "c:myfile.txt" = the file you want to attach
' olByVaue = how to pass the file. olByValue attaches it, olByReference creates a shortcut.
' the shortcut only works if the file is available locally (via mapped or local drive)
' 1 = the position in the outlook message where to attachment goes. This is ignored by most
' other mailers, so you might want to ignore it too. Using 1 puts the attachment
' first in line.
' "My Displayname" = If you don??t want the attachment??s icon string to be "c:myfile.txt" you
' can use this property to change it to something useful, i.e. "4th Qtr Report"
'This sends it!
MyMail.Send
'Some people have asked how to see the e-mail
'instead of automaticially sending it.
'Uncomment the next line
'And comment the "MyMail.Send" line above this.
'MyMail.Display
'And on to the next one...
End If
MailList.MoveNext
Loop
``` |
73,729 | I ask because of noting how chapter 1 of Romans deals with the person of Christ – who he is – while not dealing with what he has done to save sinners until chapter 3. Could this be significant? I read the following comments in a magazine yesterday:
>
> “The evangel of God, (which he had promised afore by his prophets in
> the holy scriptures,) concerning his Son *Iesous-christos* our Lord,
> which was made of the seed of David according to the flesh; and
> declared to be the Son of God with power, according to the spirit of
> holiness, by the resurrection from the dead.” Romans 1:1-4
>
>
> "In these opening verses of the epistle to the saints at Rome Paul
> summarizes the evangel. One thing stands out above everything else:
> the evangel is concerned exclusively with the Son of God... In the
> apostolic evangel the person precedes the work and that is how it is
> preached... The cross is in chapter three but the Crucified is in
> chapter one. The blood of propitiation is in chapter 3:25 but the
> Propitiatory himself is in chapter 1:3,4. The evangel does not start
> with the work of *Christos,* it starts with the Worker, *Christos*
> himself. Apostolic preaching does not commence with what the Son of
> God has done. It commences with whom he is; it declares his person."
> (Article 'The Son of God' in *'The Ministry'*, Spring 2020.)
>
>
>
Is Paul's intent to deliberately present the person of Christ before explaining the gospel of Christ, perhaps because that one has to be believed in first before his gospel can be believed?
This question requires ***exegesis into the apostle Paul's writing at the start of Romans, the first 4 verses.*** It will also require spotting a subtle change in the topic from chapter 1 and the start of chapter 3. The topic is still Jesus Christ. Why does he not make the gospel of Christ the start in chapter 1? No personal opinions will help with this question for it requires examining the author's intent, not the reader's personal opinion. | 2022/01/20 | [
"https://hermeneutics.stackexchange.com/questions/73729",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/25449/"
] | This evangel that was promised before is concerning God's Son. It shows he is like all men, a union of two elements flesh, and spirit. As to his flesh he was a descendent of David, but as to His spirit, He was from God.
>
> For as the Father has life in Himself, so also He has granted the Son to have life in Himself. John 5:26
>
>
>
He never entered the presence of death without vanquishing it. The only man that was ever raised out of the dead.
Paul starts out this gospel with good news of a man being raised out of the dead. People need to know the name of this man. Jesus Christ.
Jesus Christ is alive.
That is with the first four verses in Romans bring to light.
A man that was raised out of the dead and is alive now… Yes you can speak to Him now and call on his name. He hears because He is alive.
It's his resurrection that is so important and here's another example in Scripture of the resurrection of a man that evokes mockery of people or others wanting to hear more.
Acts 17:22-31 Is a great way that Paul Witness to the pagans in Athens. It was at the end of his speech talking to them when he told them about this man who had been raised from the dead that caused such a reaction. Some mocked about someone being raised from the dead and others wanted to hear more. It's important that people know that Jesus was a man who had been resurrected from the dead.
>
> He has given proof of this to everyone by raising Him from the dead.”
>
>
>
>
> 32When they heard about the resurrection of the dead, some began to mock him, but others said, “We want to hear you again on this topic.” Acts 17:32-34
>
>
>
When people want to hear more then you can tell them about themselves as stated in Romans 1 -2 and then share the good news in Romans three.
>
> I am not ashamed of the gospel, because it is the power of God for salvation to everyone who believes, Rom 1:6
>
>
> | The “**Who**” of the Savior and the “**What-He-Did-for-Saving**” are completely inseparable, for we know the first through the second, that is to say, we empirically observe His words and deeds, and through Holy Spirit understand that He is God and cannot be anybody less than God, but also, not identifiable with God the Father, thus “Son of God” being the best theological title and appellation to Him, for every son bears the entirety of the father’s essence, being essentially 100% equal to the father.
Now, the very beginning of the Romans show this, for we have a clear cause-effect relationship between the deeds and the Person, for the appellation of "Son of God" is conditioned and caused by the fact, the empirically observable and observed and believable as empirically observed (by the first witnesses) fact, that He rose up from the dead through power of the Holy Spirit: (περὶ τοῦ υἱοῦ αὐτοῦ ....τοῦ ὁρισθέντος υἱοῦ Θεοῦ ἐν δυνάμει κατὰ πνεῦμα ἁγιωσύνης ἐξ ἀναστάσεως νεκρῶν /Romans 1:3/). For who can have authority to rise His own body from dead unless God (John 10:18).
Exactly this is in complete compliance with the logic of the Gospels, for the very reason for which the Lord Himself reprimands Jews in not believing Him is that they turn their blind eye to His deeds, exactly which deeds show and reveal Him as the Son of God: **"If I had not done among them the works no one else did, they would not be guilty of sin. As it is, they have seen, and yet they have hated both me and my Father"** (John 15:24). And also words, for He speaks as somebody who is above the words spoken by the holy prophets themselves, not simply quoting them and then interpreting, but as the one holding authority (Matthew 7:29), that is to say, changing the very wording of the prophetic *logia*, legislating new laws and testaments (Matthew 26:28) different from them ("I give you new law" /John 13:34/), which only a blasphemer or God can be authorized to do and Christ is not the former to be sure.
Now, is it possible to do His commandments without believing who He is, that is to say, the Son of God and God? Absolutely impossible by His own words, for He says that without Him we cannot do His commandments (John 15:5), and to do His commandments with Him means that He Himself works within our hearts, inside the very depths of our essences as Paul says clearly (Colossians 1:29), for His grace and His power must dwell within us that we may be able to do His deeds (2 Cor. 12:9) in *synergy* (1 Cor. 3:9) with Him. And without doing His commandments we cannot love Him (John 14:15), and if we do not have Son for not loving Him, neither shall we have the Father (1 John 2:23), for all benevolences of the Father to humans are in and through Him (2 Cor. 1:20), and nobody can be saved without receiving the benevolences from Him through and only through the Son (which is ontological necessity),for the very verb "be saved" and its derivative noun "salvation", means being full of divine benevolences.
In fact, Jesus Christ leaves us not a slightest possibility of considering Him as a plain tolerable man without honoring Him just as the Father is honored (John 5:23), for either we honor Him on equal grounds with the Father, that is to say, as God, or we condemn and anathematize Him, but then we cannot be doing this anathematizing in Holy Spirit, for the presence of the Latter in us necessitates our inability of anathematizing Christ, and also, our confession of His Godhead (1 Cor. 12:3).
Thus: **no salvation with wrong Christology**, be it Arian (and its modern heir Jehovah Witnesser) or Nestorian, or Monophysite, or Monothelite etc. |
62,419 | I asked a professor to write a reference letter for me and he agreed to it; however, the deadline is coming up and he has yet to submit the letter.
As I am not experienced with the process, I wanted to ask if, based on your experience, it is typical for professors to delay submitting references to the last minute. | 2016/01/28 | [
"https://academia.stackexchange.com/questions/62419",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/47154/"
] | I cannot speak for the US, but in the UK the submission of the reference is not too time critical and becomes relevant only after shortlisting.
However, be careful not to nag the prof too often. You seem to know that the prof hasn't submitted it - if you speak to them in person, you can ask them about it. I would expect a reminder a few days before the deadline, and, if not confirmed, on the day of the deadline should be enough.
It's not clear what "constant reminding" means in your case, but it would really depend on the prof - usually they know it is important to write references and will not forget. If they forget, they are unreliable, but I am not sure constant nagging will help there. | A deadline means two things: 1) you may not submit after it; 2) you need not submit (too) ahead of it. The importance of the latter cannot be overstated when you're juggling with many such deadlines. |
36,185,914 | I am trying to reproduce the [Long-term Recurrent Convolutional Networks paper.](http://arxiv.org/abs/1411.4389)
I have used their [given code](https://github.com/LisaAnne/lisa-caffe-public/tree/lstm_video_deploy). And followed their instructions and generated the single frame model. But when trying to train the LSTM hybrid network it fails. I have already made necessary changes as mentioned in the [instructions.](http://www.eecs.berkeley.edu/~lisa_anne/LRCN_video)
The command i run is the `caffe train -solver lstm_solver_flow.prototxt -weights singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000.caffemodel`
the output I get is
```
I0323 18:16:30.685951 9123 net.cpp:205] This network produces output loss
I0323 18:16:30.685967 9123 net.cpp:446] Collecting Learning Rate and Weight Decay.
I0323 18:16:30.685976 9123 net.cpp:218] Network initialization done.
I0323 18:16:30.685982 9123 net.cpp:219] Memory required for data: 817327112
I0323 18:16:30.686339 9123 solver.cpp:42] Solver scaffolding done.
I0323 18:16:30.686388 9123 caffe.cpp:86] Finetuning from singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000.caffemodel
I0323 18:16:33.377488 9123 solver.cpp:247] Solving lstm_joints
I0323 18:16:33.377518 9123 solver.cpp:248] Learning Rate Policy: step
I0323 18:16:33.391726 9123 solver.cpp:291] Iteration 0, Testing net (#0)
Traceback (most recent call last):
File "/home/anilil/projects/lstm/lisa-caffe-public/examples/LRCN_activity_recognition/sequence_input_layer.py", line 220, in forward
new_result_data = [None]*len(self.batch_advancer.result['data'])
KeyError: 'data'
terminate called after throwing an instance of 'boost::python::error_already_set'
*** Aborted at 1458753393 (unix time) try "date -d @1458753393" if you are using GNU date ***
PC: @ 0x7f243731bcc9 (unknown)
*** SIGABRT (@0x23a3) received by PID 9123 (TID 0x7f24389077c0) from PID 9123; stack trace: ***
@ 0x7f243731bd40 (unknown)
@ 0x7f243731bcc9 (unknown)
@ 0x7f243731f0d8 (unknown)
@ 0x7f2437920535 (unknown)
@ 0x7f243791e6d6 (unknown)
@ 0x7f243791e703 (unknown)
@ 0x7f243791e976 (unknown)
@ 0x7f2397bb5bfd caffe::PythonLayer<>::Forward_cpu()
@ 0x7f243821d87f caffe::Net<>::ForwardFromTo()
@ 0x7f243821dca7 caffe::Net<>::ForwardPrefilled()
@ 0x7f243822fd77 caffe::Solver<>::Test()
@ 0x7f2438230636 caffe::Solver<>::TestAll()
@ 0x7f243823837b caffe::Solver<>::Step()
@ 0x7f2438238d5f caffe::Solver<>::Solve()
@ 0x4071c8 train()
@ 0x405701 main
@ 0x7f2437306ec5 (unknown)
@ 0x405cad (unknown)
@ 0x0 (unknown)
run_lstm_flow.sh: line 8: 9123 Aborted (core dumped) GLOG_logtostderr=1 $TOOLS/caffe train -solver lstm_solver_flow.prototxt -weights singleframe_flow/snaps/snapshots_singleFrame_flow_v2_iter_50000.caffemodel
Done.
```
This is my changed [sequence\_input\_layer.py](http://pastebin.com/ZuRb3tQR) and [prototext](http://pastebin.com/Ha4S1ZBU) files.
My input train and test txts to the network is of this [format](http://pastebin.com/4gNPFssb).
I think the main problem is the `##rearrange the data: The LSTM takes inputs as [video0_frame0, video1_frame0,...] but the data is currently arranged as [video0_frame0, video0_frame1, ...]`
I was not able to solve this is confused me quite a bit.
But I might be wrong. | 2016/03/23 | [
"https://Stackoverflow.com/questions/36185914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527680/"
] | I know I am a bit late, hope my answer helps someone in future. I too faced the same error. The problem was with scikit-image version. I was using some version newer than scikit-image 0.9.3. Following line
```
processed_image = transformer.preprocess('data_in',data_in)
```
uses scikit-image library functions being imported by `lisa-caffe-public-lstm_video_deploy/python/caffe/io.py`. With newer version, `transformer.preprocess()` was crashing, and therefore `processImageCrop()` function didnot return and thus `KeyError: 'data'`.
In short, you should use scikit-image-0.9.3 to get rid of your error :)
Hope that helps :) | I encounter the same question. I adapt several places in `sequence_input_layer.py` and it works well for me at now:
1. I change line 95 and remove `%i` at the end since I don't know what it is used for. i.e., change
`frames.append(self.video_dict[key]['frames'] %i)`
to
`frames.append(self.video_dict[key]['frames'])`
2. I change line around 157 to make sure the `frames` variable is right for my data since the data directory of author is different of mine.
Hope this will be helpful. |
32,510,904 | I would like to conjoin elements inside a vector into some vectors which are inside a parent vector.
```
example:
;; I have a vector [["1" "2" "3"] ["4" "5"]]
;; and another vector ["6" "7"]
```
I did this:
```
(map (fn [row]
(conj row ["6" "7"]))
[["1" "2" "3"] ["4" "5"]])
;;=> (["1" "2" "3" ["6" "7"]] ["4" "5" ["6" "7"]])
```
but I would like my result in this format:
```
;;=> (["1" "2" "3" "6" "7"] ["4" "5" "6" "7"])
```
Please kindly point me in the right directioin. | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065320/"
] | Your original code is very close. `conj` adds each element you pass. So you basically just lacked an `apply`:
```
user=> (map (fn [row] (apply conj row ["6" "7"])) [["1" "2" "3"] ["4" "5"]])
(["1" "2" "3" "6" "7"] ["4" "5" "6" "7"])
``` | I think the following is a bit simpler solution. It uses
the `glue` function from [the Tupelo Core library](https://github.com/cloojure/tupelo), along with a `for` statement:
```
(ns xyz
(:require [tupelo.core :as tc]....
(def data [ [1 2 3] [4 5] ] )
(tc/spyx
(for [curr-vec data]
(tc/glue curr-vec [6 7] )))
;=> (for [curr-vec data] (tc/glue curr-vec [6 7])) => ([1 2 3 6 7] [4 5 6 7])
``` |
79,146 | Is it feasible that we have a layer of API simply for the reason so that people in the team don't have to understand the actual implementation of the individual components each of us are working on?
I had this thought because I started to find that some times when working a project with a team of people (I am new to working in a group), it is kind of difficult to know where to start from.
We want to split a huge application into parts so that each of us can concentrate on our own part while at the end of the day, we still want these parts to all work together without having every member to know thoroughly about the actual implementation of every parts.
But an API to me, usually serves as an interface for "external" developers to extend on or build new things from our work without having to go directly into the core part. Since we all working in a team, having an API for each components just for us to work among ourselves seems a little overkill and funny.
So what is the usual practise when it comes to situations like this? Although I am using Java in my case, I think a correct practise for such situations work for projects of all languages, right? | 2011/05/25 | [
"https://softwareengineering.stackexchange.com/questions/79146",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/26189/"
] | Think of it this way: When a brand-spanking-new developer joins the team, you're going to assign him to a given area of the project. Wouldn't you like him to be able to get up to speed on *that section* of the project so he can complete his assignment, or do you want him to spend three months learning the whole massive edifice?
Or from your side - suppose you spend a lot of time on another project and need to fix a bug, wouldn't you like to be able to limit the scope of your debugging efforts?
(There is a method here, just hang on.)
API stands for Application Programming Interface. Nothing in that name defines at what scope it is defined for. In my opinion, *every class* has an API. By always thinking about how the class would be used from elsewhere, you can make each class, package, web service, and so on easy to use and maintain.
As you plot your design at first, you will see several large sections. For example, in a shopping application, you can break it down into Inventory, Billing, and Shipping. Each of those will have specific things they need to communicate with each other. Each of those in turn can be broken down further. You end up with a tree. The easiest to maintain applications do not communicate across branches in this tree in undefined ways, like using public fields, public statics and singletons. They only have to worry about the fields and objects they own, through those object's public interface: its *API*.
Everything has an API. What you should be worrying about is whether or not that API is easy to use, maintainable, and testable, not whether you need one. A well-defined interface helps you limit the scope of feature additions, bug squashing, and everyone's learning curve. | I think it would be overloading "API" to say you need to do that here, but certainly focusing on the public interfaces that will integrate and co-maintaining test cases are very helpful things to do up front. This way we literally have a conversation that goes like this "these are the methods I expect your classes to provide, and here are some specs they would need to pass in order to provide the functionality I'm expecting". |
37,778 | My friend didn't know that an agent gave him a fake work permit. He was not stopped at the Calcutta Airport and was cleared to board the Emirates Plane to Dubai.
After reaching Dubai Airport T-3, the immigration officer said the visa is not matching on their system and he was deported on the first Emirates plane back to Calcutta.
How did the immigration officer check the visa in Calcutta and allow him to travel? And if the visa was fake then is it possible to book flight ticket? | 2014/10/22 | [
"https://travel.stackexchange.com/questions/37778",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/20282/"
] | Typically, at the point of departure, it is only the airline that checks if the person to fly has the necessary documentation to enter the country of destination. They may or may not have access to systems to verify the validity of the visa - but this is also not their task to do. All they need to check is if they the documentation is "obviously" not enough.
The home-country immigration officer will only check the right to leave the home country.
Booking a ticket has nothing to do with having a visa - you can book a flight to where ever you want. The airline just won't allow you to board if you don't show any proof at the **time of departure**. | Immigration officers from the country you are leaving usually do not care much. I guess some might do something if they notice a problem but checking whether you are likely to get in trouble later on is not their mission. Note that some countries don't have any formal immigration check on exit…
Airlines everywhere do check whether passengers have appropriate documentation for their journey but that's mostly to avoid being fined by the destination state, not to help travellers. So what airlines have to do is merely checking that the visa “looks” right, to the extent required to avoid liability if a passenger is refused entry afterwards. They do not and cannot check if your name is in one database or another or whether you will actually be granted entry.
Do note that there are countless combinations (hundreds of potential destinations, each with several types of visas and different sets of visa requirements) and it would be very complex to check them thoroughly, let alone ensure that countries share information with all other countries on the globe. |
5,917,304 | I would like to know when a interface has been disabled.
If I go into the windows manager and disable one of the 2 enabled connections, GetIfTable() only returns status about 1 interface, it no longer sees the disconnected one.
(Returns 1 table)
How can I get something to return that the disabled **interface still exists** but is *currently* disabled?
Thanks.
<http://msdn.microsoft.com/en-us/library/aa365943%28VS.85%29.aspx> | 2011/05/06 | [
"https://Stackoverflow.com/questions/5917304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52256/"
] | I think you would just need to read the registry.
For example, this is a snippet found on the web of what things should look like:
```
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{1E6AF554-25FF-40FC-9CEE-EB899472C5A3}\Connection]
"PnpInstanceID"="PCI\\VEN_14E4&DEV_1696&SUBSYS_12BC103C&REV_03\\4&3A321F38&0&10F0"
"MediaSubType"=dword:00000001
"Name"="Lan Name"
"ShowIcon"=dword:00000000
"IpCheckingEnabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{1E6AF554-25FF-40FC-9CEE-EB899472C5A3}\Connection]
"PnpInstanceID"="PCI\\VEN_14E4&DEV_1696&SUBSYS_12BC103C&REV_03\\4&3A321F38&0&10F0"
"MediaSubType"=dword:00000001
"Name"="Lan Name"
"ShowIcon"=dword:00000000
"IpCheckingEnabled"=dword:00000001
``` | The IP\_ADAPTER\_ADDRESSES structure hold an OperStatus member.
See [MSDN documentation](http://msdn.microsoft.com/en-us/library/aa366058%28v=vs.85%29.aspx)
I think it can be used to detect disabled NICs. I didn't try.
Here is a test code:
```
ULONG nFlags= 0;
if (WINVER>=0x0600) // flag supported in Vista and later
nFlags= 0x0100; // GAA_FLAG_INCLUDE_ALL_INTERFACES
// during system initialization, GetAdaptersAddresses may return ERROR_BUFFER_OVERFLOW and supply nLen,
// but in a subsequent call it may return ERROR_BUFFER_OVERFLOW and supply greater nLen !
ULONG nLen= sizeof (IP_ADAPTER_ADDRESSES);
BYTE* pBuf= NULL;
DWORD nErr= 0 ;
do
{
delete[] pBuf;
pBuf= new BYTE[nLen];
nErr= ::GetAdaptersAddresses(AF_INET, nFlags, NULL, (IP_ADAPTER_ADDRESSES*&)pBuf, &nLen);
}
while (ERROR_BUFFER_OVERFLOW == nErr);
if (NO_ERROR != nErr)
{
delete[] pBuf;
TCHAR czErr[300]= _T("GetAdaptersAddresses failed. ");
REPORT(REP_ERROR, _T("GetAdapterInfo"), GetSysErrStr(nErr, czErr, 300));
return false;
}
const IP_ADAPTER_ADDRESSES* pAdaptersAddresses= (IP_ADAPTER_ADDRESSES*&)pBuf;
while (pAdaptersAddresses) // for each adapter
{
TCHAR czAdapterName [500]; str_cpy(czAdapterName , 500, pAdaptersAddresses->AdapterName );
TCHAR czDesc [500]; str_cpy(czDesc , 500, pAdaptersAddresses->Description );
TCHAR czFriendlyName[500]; str_cpy(czFriendlyName, 500, pAdaptersAddresses->FriendlyName);
const IF_OPER_STATUS& Stat= pAdaptersAddresses->OperStatus; // 1:up, 2:down...
...
pAdaptersAddresses= pAdaptersAddresses->Next;
}
``` |
594,080 | I use *Kali Linux* as a virtual machine in *VMware Workstation Player* with *Windows 10 Home* as host.
The *Player* has the option to pick a *Windows* folder to be used as a shared folder.
I set this up, it says it's enabled, but in *Kali Linux* this shared folder should be present in `/mnt/hgfs`. `/mnt` exists, but is empty. I'm stuck here. | 2020/06/20 | [
"https://unix.stackexchange.com/questions/594080",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/418924/"
] | Both *stackprotector's* AND *petoetje59's* answer helped with this issue.
1. `cd /mnt/hgfs`
2. **If the folder is missing** --> `sudo mkdir hgfs`
3. `sudo vim /etc/fstab`
4. Enter `vmhgfs-fuse /mnt/hgfs fuse defaults,allow_other 0 0` at the end of the file and save
5. `sudo reboot now`
6. `ls /mnt/hgfs`
7. The Shared Folder you enabled in VMware Fusion Settings will appear | The short of it is below, but here's a little [ten minute video](https://www.youtube.com/watch?v=bUDup4RibEs) that goes through a good step by step process.
Even if the hgfs folder was present, it would be empty. The host has made the files available to the vm, but the vm still needs to be told about their presence. The same thing happens occasionally when you plug in a thumb drive. To do this, from the Kali command line you use the mount command. After you're done working with the shared folder I would use umount, so that I wouldn't have a persistent connection across my operating systems. Keep us updated on your fix. |
29,888,850 | I'm plotting a bar chart using MPAndroid chart. Now all my bars have the same color but I want different colors for the bars based on Y axis values, like if value >100. color = red, like in the picture below. Is that possible? someone please help me.

Regards. | 2015/04/27 | [
"https://Stackoverflow.com/questions/29888850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067264/"
] | You can find out the documentation about setting colors in MPAndroidChart from [this link](https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Colors)
```
LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
// sets colors for the dataset, resolution of the resource name to a "real" color is done internally
setComp1.setColors(new int[] { R.color.red1, R.color.red2, R.color.red3, R.color.red4 }, Context);
LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");
setComp2.setColors(new int[] { R.color.green1, R.color.green2, R.color.green3, R.color.green4 }, Context);
``` | **Update**
form [m4n3k4](https://stackoverflow.com/a/31851986/8926845) answer
```
public class MyBarDataSet extends BarDataSet {
public MyBarDataSet(List<BarEntry> yVals, String label) {
super(yVals, label);
}
@Override
public int getColor(int index) {
if(getEntryForIndex(index).getY() ==40) // less than 95 green
return mColors.get(0);
else if(getEntryForIndex(index).getY() ==30) // less than 100 orange
return mColors.get(1);
else // greater or equal than 100 red
return mColors.get(2);
}
}
```
and in JavaCode
```
set1.setColors(ContextCompat.getColor(StepCountsActivity.this, R.color.purple),
ContextCompat.getColor(StepCountsActivity.this, R.color.light_purple),
ContextCompat.getColor(StepCountsActivity.this, R.color.blue));
}
``` |
8,750,986 | I've been learning IoC, Dependency Injection etc. and enjoying the process. The benefits of decoupling and programming to interfaces are, to me, a no-brainer.
However, I really don't like binding myself to a specific framework like Unity or Autofac or Windsor - because I'm still learning and haven't yet decided which is best for my purposes.
So, how can I wrap around something like Unity so I could easily swap in Windsor at a later date? (or whatever). And don't you dare say use another one to inject the first one ;)
Thanks!
R.
P.s. I tagged Unity as that's my current personal preference (I just lurve Entlib). | 2012/01/05 | [
"https://Stackoverflow.com/questions/8750986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479971/"
] | >
> A DI Container should only be referenced from the [Composition Root](http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx).
> All other modules should have no reference to the container.
>
>
>
-Mark Seemann (author of [Dependency Injection in .NET](http://manning.com/seemann/))
In other words, you should only need to change one class if you change DI containers.
Constructor injection is normally the right way to go, as others have mentioned. You can inject factory interfaces or `Func<T>` delegates if you need to create objects on the fly.
I'd also suggest avoiding XML configuration whenever possible. | As some other folks have mentioned, prefer constructor injection. This will solve many of your problems.
If your classes have direct dependencies on the IoC container itself, it tends to be a variant of using the service locator (anti-)pattern. In this particular case, isolate which types are being resolved via the service locator, and abstract that dynamic resolution with a factory interface. So, for instance, replace this:
```
public class Foo
{
private MyIoCContainer _container;
public Foo(MyIoCContainer container)
{
this._container = container;
}
public void DoSomething()
{
// have to do this at runtime for whatever reason
var myObj = this._container.Resolve<ISomeType>();
myObj.DoSomething();
myObj.DoSomethingElse();
}
}
```
with this:
```
public class Foo
{
private IObjFactory _provider;
public Foo(IObjFactory _provider)
{
this._provider = provider;
}
public void DoSomething()
{
var myObj = _provider.GetObj();
myObj.DoSomething();
myObj.DoSomethingElse();
}
}
public interface IObjFactory
{
ISomeType GetObj();
}
```
Now, you have an `IObjFactory` that can encapsulate the dynamic, runtime nature of constructing objects that implement `ISomeType`. If you are constructing many different types of object from the container/service locator, then you should have at least as many `*Factory` interfaces (in accordance with the [Interface Segregation Principle](http://en.wikipedia.org/wiki/Interface_segregation_principle)). |
16,210,558 | Here is what i want to do. I want to store de data from a Http response, headers and data. I figured an easy way to do this would be to store the response and the data as a pair. The data is fetched from a LRU-cache. The LRU cache takes a key(string) and the pair. The HTTPResponse is in the form of a POCO C++ HTTPResponse object. But i cant get the string from the second argument of the pair!
```
this->clientCache = new LRUPersistentCache<string, pair<HTTPResponse, string > >(3,cachePath);
pair<HTTPResponse,string> tmp = (*this->clientCache->get(headKey));// Get the pair
cout << ((string*)tmp.second()).c_str(); //Should get the second object of the pair!
// But gives: Type std::basic_string<char> does not provide a call operator.
```
Writing it like below gives the same error:
```
cout << (*this->clientCache->get(headKey)).second().c_str();
```
What am I doing wrong here? | 2013/04/25 | [
"https://Stackoverflow.com/questions/16210558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1641868/"
] | ```
cout << ((string*)tmp.second()).c_str();
^^
```
you are casting to a `string*`. It should be just `string` (or nothing at all) because the `second` of `pair<HTTPResponse,string>` is just a `string`.
and second is a just member not a member function so it should be `tmp.second`
---
```
cout << tmp.second.c_str();
``` | `second` is a memeber value not function defined in standard as
20.3.2 Class template pair
==========================
>
> namespace std {
>
> template
>
> struct pair {
>
> typedef T1 first\_type;
>
> typedef T2 second\_type;
>
> T1 first;
>
> T2 second;
>
>
>
thus correct usage of second member value is `second` not `second()`. Unless it is functor you are going to use, which is not your case. |
38,198 | `celsius = (5.0/9.0) * (fahr-32.0);`
Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something? | 2008/09/01 | [
"https://Stackoverflow.com/questions/38198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | ```
celsius = (5.0/9.0) * (fahr-32.0);
```
In this expression, `5.0`, `9.0`, and `32.0` are `double`s. That's the default type for a floating-point constant - if you wanted them to be `float`s, then you would use the `F` suffix:
```
celsius = (5.0F/9.0F) * (fahr-32.0F);
```
Note that if `fahr` was a `double`, then the result of this last expression would *still* be a `double`: as Vaibhav noted, types are promoted in such a way as to avoid potentially losing precision. | The reason that the expression is cast to double-precision is because the literals specified are double-precision values by default. If you specify the literals used in the equation as floats, the expression will return a float. Consider the following code (Mac OS X using gcc 4.01).
```
#include <stdio.h>
int main() {
float celsius;
float fahr = 212;
printf("sizeof(celsius) ---------------------> %d\n", sizeof(celsius));
printf("sizeof(fahr) ------------------------> %d\n", sizeof(fahr));
printf("sizeof(double) ----------------------> %d\n", sizeof(double));
celsius = (5.0f/9.0f) * (fahr-32.0f);
printf("sizeof((5.0f/9.0f) * (fahr-32.0f)) --> %d\n", sizeof((5.0f/9.0f) * (fahr-32.0f)));
printf("sizeof((5.0/9.0) * (fahr-32.0)) -----> %d\n", sizeof((5.0/9.0) * (fahr-32.0)));
printf("celsius -----------------------------> %f\n", celsius);
}
```
Output is:
```
sizeof(celsius) ---------------------> 4
sizeof(fahr) ------------------------> 4
sizeof(double) ----------------------> 8
sizeof((5.0f/9.0f) * (fahr-32.0f)) --> 4
sizeof((5.0/9.0) * (fahr-32.0)) -----> 8
celsius -----------------------------> 100.000008
``` |
6,586,302 | I want to add some space to the right of an `<input type="text" />` so that there's some empty space on the right of the field.
So, instead of , I'd get .
So, same behavior just some empty space to the right.
I've tried using `padding-right`, but that doesn't seem to do anything.
Is there a way to do this (or fake it)? | 2011/07/05 | [
"https://Stackoverflow.com/questions/6586302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/515160/"
] | You can provide padding to an input like this:
HTML:
```
<input type=text id=firstname />
```
CSS:
```
input {
width: 250px;
padding: 5px;
}
```
however I would also add:
```
input {
width: 250px;
padding: 5px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
```
Box sizing makes the input width stay at 250px rather than increase to 260px due to the padding.
[For reference](http://css-tricks.com/box-sizing/). | ```
<input class="form-control search-query input_style" placeholder="Search…" name="" title="Search for:" type="text">
.input_style
{
padding-left:20px;
}
``` |
20,117,290 | My local machine is not connected to internet. However, I have a server on local network which I can connect via SSH. This server is directly connected to internet. I do not have the admin privileges on the server, so I cannot install a browser on it. However, I can download web pages on it using wget. I was wondering if there exists a way so that I can browse internet using a regular browser installed on my local machine. | 2013/11/21 | [
"https://Stackoverflow.com/questions/20117290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164609/"
] | This problem happens to me after SDK updates when I am using any device based directly on the default Device definitions.
Furthermore: any new virtual device created with the default device definitions (Nexus 7, Nexus S, etc) gives directly the same error.
My solution is to duplicate these definitions:
1. In Android Virtual Device Manager / Device definitions -> select the definition to use, and press Edit. Provide a new name and press the button 'Clone Device'.
2. Now, create the new virtual device using this cloned configuration.
3. The new device does not raise any longer the invalid configuration error messages. | the answer by @coderazzi is correct, but those who are new to intellij and are facing problems in finding appropriate settings here's some images
1. Open AVD Settings
2. Open Device Definitions and select any device definitions eg. Nexus S 
3. Click on Clone and then add a new name
4. Create a new AVD using the new definitions "**Bug Free Nexus S**". Now use this as your target emulator and you will face no problems. |
31,652,572 | With my compiler, `c` is 54464 (16 bits truncated) and `d` is 10176.
But with `gcc`, `c` is 120000 and `d` is 600000.
What is the true behavior? Is the behavior undefined? Or is my compiler false?
```
unsigned short a = 60000;
unsigned short b = 60000;
unsigned long c = a + b;
unsigned long d = a * 10;
```
Is there an option to alert on these cases?
Wconversion warns on:
```
void foo(unsigned long a);
foo(a+b);
```
but doesn't warn on:
```
unsigned long c = a + b
``` | 2015/07/27 | [
"https://Stackoverflow.com/questions/31652572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5160343/"
] | First, you should know that in C the standard types do not have a specific precision (number of representable values) for the standard integer types. It only requires a **minimal** precision for each type. These result in the following **typical bit sizes**, the [standard](http://port70.net/~nsz/c/c11/n1570.html#6.2.6.2) allows for more complex representations:
* `char`: 8 bits
* `short`: 16 bits
* `int`: 16 (!) bits
* `long`: 32 bits
* `long long` (since C99): 64 bits
Note: The actual limits (which imply a certain precision) of an implementation are given in [`limits.h`](http://port70.net/~nsz/c/c11/n1570.html#5.2.4.2.1).
Second, the type an operation is performed is determined by the types of the operands, not the type of the left side of an assignment (becaus assignments are also just expressions). For this the types given above are sorted by *conversion rank*. Operands with smaller rank than `int` are converted to `int` first. For other operands, the one with smaller rank is converted to the type of the other operand. These are the [usual arithmetic conversions](http://port70.net/~nsz/c/c11/n1570.html#6.3.1.8).
Your implementation seems to use 16 bit `unsigned int` with the same size as `unsigned short`, so `a` and `b` are converted to `unsigned int`, the operation is performed with 16 bit. For `unsigned`, the operation is performed modulo 65536 (2 to the power of 16) - this is called wrap-around (this is **not** required for signed types!). The result is then converted to `unsigned long` and assigned to the variables.
For gcc, I assume this compiles for a PC or a 32 bit CPU. for this`(unsigned) int` has typically 32 bits, while `(unsigned) long` has at least 32 bits (required). So, there is no wrap around for the operations.
**Note:** For the PC, the operands are converted to `int`, not `unsigned int`. This because `int` can already represent all values of `unsigned short`; `unsigned int` is not required. This can result in unexpected (actually: *implementation defined*) behaviour if the result of the operation overflows an `signed int`!
If you need types of defined size, see `stdint.h` (since C99) for `uint16_t`, `uint32_t`. These are `typedef`s to types with the appropriate size for your implementation.
You can also cast one of the operands (not the whole expression!) to the type of the result:
```
unsigned long c = (unsigned long)a + b;
```
or, using types of known size:
```
#include <stdint.h>
...
uint16_t a = 60000, b = 60000;
uint32_t c = (uint32_t)a + b;
```
Note that due to the conversion rules, casting one operand is sufficient.
**Update** (thanks to @chux):
The cast shown above works without problems. However, if `a` has a larger conversion rank than the typecast, this might truncate its value to the smaller type. While this can be easily avoided as all types are known at compile-time (static typing), an alternative is to multiply with 1 of the wanted type:
```
unsigned long c = ((unsigned long)1U * a) + b
```
This way the larger rank of the type given in the cast or `a` (or `b`) is used. The multiplication will be eliminated by any reasonable compiler.
Another approach, avoiding to even know the target type name can be done with the `typeof()` gcc extension:
```
unsigned long c;
... many lines of code
c = ((typeof(c))1U * a) + b
``` | In C the types `char`, `short` (and their unsigned couterparts) and `float` should be considered to be as "storage" types because they're designed to optimize the storage but are not the "native" size that the CPU prefers and they **are never used for computations**.
For example when you have two `char` values and place them in an expression they are first converted to `int`, then the operation is performed. The reason is that the CPU works better with `int`. The same happens for `float` that is always implicitly converted to a `double` for computations.
In your code the computation `a+b` is a sum of two unsigned integers; in C there's no way of computing the sum of two unsigned shorts... what you can do is store **the final result** in an unsigned short that, thanks to the properties of modulo math, will be the same. |
39,245,755 | I have a div with 3 images :
```css
.main_block {
width: 800px;
}
.main_block: before, .main_block: after {
overflow: hidden;
content: "";
display: table;
}
.main_block: after {
clear: both;
}
.inner_block {
display: inline-block;
float: left;
padding-left: 20px
}
.inner_block img {
height: auto;
vertical-align: middle;
}
```
```html
<div class="main_block">
<div class="inner_block">
<img src="img/features/1.png"/>
</div>
<div class="inner_block">
<img src="img/features/2.png"/>
</div>
<div class="inner_block">
<img src="img/features/3.png"/>
</div>
</div>
```
And it allways align to the left of the page, i tried to add position relative to the main div but it's still align to the left | 2016/08/31 | [
"https://Stackoverflow.com/questions/39245755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/679099/"
] | I use flexbox for this:
`display:flex` is the key
here is the [code](https://jsfiddle.net/MaciejWojcik/bk1wdmpb/)
```css
.main_block {
width: 100%;
display:flex;
justify-content:space-between;
}
.inner_block {
display: inline-block;
margin: 0 auto;
}
```
```html
<div class="main_block">
<div class="inner_block">
<img src="http://html5doctor.com/wp-content/themes/html5doctor2/images/HTML5_Badge_64.png"/>
</div>
<div class="inner_block">
<img src="http://html5doctor.com/wp-content/themes/html5doctor2/images/HTML5_Badge_64.png"/>
</div>
<div class="inner_block">
<img src="http://html5doctor.com/wp-content/themes/html5doctor2/images/HTML5_Badge_64.png"/>
</div>
</div>
``` | I think it works
.main\_block {
width: 800px;
margin: 0 auto
} |
3,343,292 | Let $J\_{0,1}:=[0,1]$.
Let's start with the construction of the Cantor set.
>
> **Step 1.** We remove the central open interval $I\_{0,1}=\big(\frac{1}{3},\frac{2}{3}\big)$. We denote with $J\_{1,1}:=\big[0,\frac{1}{3}\big]$ and with $J\_{1,2}:=\big[\frac{2}{3},1\big]$.
>
>
> We define $K\_1:=J\_{1,1}\cup J\_{1,2}$.
>
>
> **Step 2.** We remove from $J\_{1,1}$ and $J\_{1,2}$ the central open interval of length $\frac{1}{9}$. Then we define what remains with $K\_2:=J\_{2,1}\cup J\_{2,2}\cup J\_{2,3}\cup J\_{2,4}$, where $J\_{2,1}=\big[0,\frac{1}{9}\big]$, $J\_{2,2}=\big[\frac{2}{9},\frac{1}{3}\big]$, $J\_{2,3}=\big[\frac{2}{3},\frac{7}{9}\big]$, $J\_{2,4}=\big[\frac{8}{9}, 1\big]$.
>
>
> At the end of step $n$ we will have $2^n$ close interval $J\_{n,k}$ for $k=1,\cdots, 2^n$ of length $1/3^n.$
>
>
> For all $n\in\mathbb{N}$ we define $$K\_{n}:=\bigcup\_{k=1}^{2^n} J\_{n,k}$$
> We define the Cantor set $K$ in the follow way $$K:=\bigcap\_{n=1}^{+\infty} K\_n.$$
>
>
>
I have already shown that: $$\text{If}\quad x\in K\Rightarrow x=\sum\_{k=1}^{+\infty}\frac{2\varepsilon\_k}{3^k}\quad\text{where}\quad \{\varepsilon\_k\}\subseteq\{0,1\}^{\mathbb{N}}$$
**Problem** We suppose that exists $\overline{n}\in\mathbb{N}$ such that for all $k>\overline{n}$ $\varepsilon\_k=0$ then, $$x=\sum\_{k=1}^{\overline{n}}\frac{2\varepsilon\_k}{3^k}\quad\text{where}\quad \{\varepsilon\_k\}\subseteq\{0,1\}^{\mathbb{N}}$$
We can say that $x\in J\_{\overline{n},k}$ where $k=1,2,\dots,2^{\overline{n}}$.
My book said that, in this case, $x\in J\_{\overline{n},\overline{k}}$, where
$$\overline{k}=\bigg(\sum\_{k=1}^{\overline{n}}\varepsilon\_k2^{\overline{n}-k}\bigg)+1\tag1$$
>
> **Question.** Where can I deduce the expression $(1)$?
>
>
>
Thanks! | 2019/09/03 | [
"https://math.stackexchange.com/questions/3343292",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/554978/"
] | The tool that unlocks a lot of powerful intuition about this type of constructions is called **coding**. You can find a very thorough introduction (together with its applications to the Cantor set and other dynamical systems settings) in Chapter 7 of [A First Course in Dynamics](https://www.cambridge.org/core/books/first-course-in-dynamics/46B75AA48693D96EF48C544A06623247), by Hasselblatt and Katok.
Here is a summarised application to your problem. We can give each point in the Cantor set an *address*: if a point $x$ is in the Cantor set, then it's in $K\_1$ and, in particular, is in either $J\_{1,1}$ or $J\_{1,2}$. If it's in $J\_{1,1}$, we define the first symbol of the address as $a\_1=0$; if it's in $J\_{1,2}$, we define it as $a\_1=1$.
Now, at the second level, there is again a choice. If $x$ was in $J\_{1,1}$, it may be in $J\_{2,1}$ or $J\_{2,2}$; we associate another symbol of the address, $a\_2=0$ or $a\_2=1$ respectively. If $x$ was $J\_{1,2}$, it may be instead in $J\_{2,3}$ or $J\_{2,4}$. The symbols we associate here are not $a\_2=2$ or $a\_2=3$, but again $a\_2=0$ or $a\_2=1$ respectively. Therefore:
* a point in $J\_{2,1}$ will have $a\_1=0, a\_2=0$;
* a point in $J\_{2,2}$ will have $a\_1=0, a\_2=1$;
* a point in $J\_{2,3}$ will have $a\_1=1, a\_2=0$;
* a point in $J\_{2,4}$ will have $a\_1=1, a\_2=1$.
Since we are making a binary choice on each level (whether to look in the left or the right sub-interval), we only need a binary digit for the address.
Repeating this *ad infinitum* we find that each point of the Cantor set corresponds to a unique infinite address (you can formalise this by proving the Cantor set is totally disconnected, therefore two different points of the set eventually end up in different intervals, see Hasselblatt and Katok). Therefore I can write any point of the Cantor set uniquely as
$$x\_{a\_1 a\_2 a\_3 \cdots}$$
where $a\_i\in\{0,1\}$. For a finite string of symbols $a\_1a\_2\cdots a\_n$, we can define the set
$$X\_{a\_1a\_2\cdots a\_n}$$
as the set containing all elements of the Cantor set whose addresses begin with $a\_1a\_2\cdots a\_n$. This set is exactly equal to one of the $J\_{n,k}$ sets. How to see which one?
Let's try $n=2$ for simplicity, consider $X\_{a\_1 a\_2}$. By checking against the examples above, you can see
* $X\_{00} = J\_{2,1}$;
* $X\_{01} = J\_{2,2}$;
* $X\_{10} = J\_{2,3}$;
* $X\_{11} = J\_{2,4}$.
We see $k= 1 + a\_2 + 2a\_1$. With a little induction work, you can show that, in general:
$$
X\_{a\_1a\_2\cdots a\_n} = J\_{n,k},
\qquad k = 1 + \sum\_{i=1}^{n} a\_i 2^{n-i}.
$$
What is nice about the logic above is that it works for *any* Cantor-type set, as long as we are removing a part of each interval on each iteration. Of course, for *the* Cantor set (the *middle-third* Cantor set), we get a little more. The address of a point of the Cantor set corresponds uniquely to its base-3 decimal expansion, which is given by letting $\varepsilon\_i=a\_i$ and using the formula you have already shown.
Summarising, given a point $$x\_{a\_1 a\_2 a\_3 \cdots}$$ in the Cantor set, we see it belongs in a series of sets, $X\_{a\_1}, X\_{a\_1 a\_2}, \cdots$, and we can identify each of those sets with one of the sub-intervals $J\_{n,k}$. In particular, if you take a point $$x\_{a\_1 a\_2 a\_3 \cdots a\_n 0 0 0 0 0 \cdots},$$ as required by your question, it belongs in $X\_{a\_1 a\_2 a\_3 \cdots a\_n}$ corresponding exactly to $J\_{n, \bar{k}}$ where $\bar{k}$ is given by the formula above.
Do take a look at Hasselblatt and Katok if you get the chance, it's a fantastic book. I hope this helps! | You can define the Cantor set recursively.
What I mean is that you take the interval $[0,1]$, divide it in 3 equal parts $[0,1/3]$, $[1/3,2/3]$ and $[2/3,1]$ and consider the rightmost an the leftmost.
They are interval just as the initial $[0,1]$, so in each of them you can repeat the same operations.
With this slightly different point of view, it is easy to see that for every $k$, the value of $\varepsilon\_k$ tells us if the point is in the left interval ($\varepsilon=0$), or the right ($\varepsilon\_k=1$).
If you fix $\bar{n}$, you have $2^\bar{n}$ intervals.
Half of them will be in $J\_{1,1}$ and the other half in $J\_{1,2}$.
If $\varepsilon\_1=0$ the interval in which the point is must be in $J\_{1,1}$, so the index of the interval must be between 1 and $2^{\bar{n}-1}-1$.
If $\varepsilon\_1=1$, instead the point must be in $J\_{1,2}$, so the index of the interval must be between $2^{\bar{n}-1}$ and $2^{\bar{n}}$.
Inductively you can use this reasoning to prove the formula. |
48,524,870 | I am passing a component as a prop.
This is defined as below.
```
export type TableProps<T> = {
contents: T[],
loadContents: () => Promise<T[]>
};
```
This works fine, but I'd like to update this definition to say, at least above props should exist, but to allow additional props.
Is there a definition I can use to do this. For instance, I'd like a component with the following signature to be accepted.
```
type Props = {
onChangeMark: (val: string) => void,
...TableProps<Attendance>
};
```
I've tried defining them as an interface but they are still being rejected.
```
interface TableProps<T> {
contents: T[],
loadContents: () => Promise<T[]>
};
```
**Update**
I think this demostrates the issues I am having [Link](https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVZOoJYDsAuApgE5QCGAxoWALICeAkgSeVWAN5gAeAXGLgFcAtgCMSYAL4BudPjoAHagGE4Q+XFyECYALxgAFPOJx5fekyKlKhAJS6AfGDK46M9KjmKwABWPyAzrq0jMxWbABkHGB0fIKi4tLoUAK4FPjYGmAAolxkajCEDPmEQlr4ZOka+pxcQQCMADTRQQBMEny+Jv527KgS7gBuZMRgFKrqmgR8KmoaZUE5efIFRcslZRUZuDJAA)
**Update 2**
@Rajesh 's solution doesnt seem to work , have tried [here](https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVZOoJYDsAuApgE5QCGAxoWALICeAkgSeVWAN5gAeAXGLgFcAtgCMSAGjABtANaE6fAM75ieAOYBdPmVx0wAXwDc6fHQAO1AMJwhZuLkIEwAXjAAKM8Thm+9JkVJKQgBKFwA+MB06Y1QoAVwKfGx7MABRLjJbGEIGLMIhR3wyJPsARjdOLhcwUoNfRmZAqlD2VH0MTE6u7p7ertj4xOTcNIy83LNsgoJi4YAmCu5q0sk9Vzn9ev8WIJa29GBgbAATQjIYGD1sAHJjsBhsOTB8OGfzanwAC2psPOmikq4RRgZReXBqS5gSRfahkERwABu1HSmUmOT+hVm9jmYHI2BgwK+cAEak+kQJrxM7zAAAUvGZga5OAp+MIxMQDGAAGS0BoBViEYxxBKA0ao7ITKaYwEAZkWVVcKzAazAGz4dO8ij27T6ur1fVQCLIHIoNjsDgIpT41ls9kK1RR4wxM0BpWMRpNZrtBDm1q9FvwDrGaMl+Wl83dxrApttAZlftj9tcjpDzoBwxlhiAA) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48524870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168012/"
] | You can try something like this:
```js
interface IDummy {
value: string;
propName: string;
[key: string]: any;
}
```
What this will do is, it will force you to pass `value` and `propName` properties in object but you can have any other properties.
[Sample](https://www.typescriptlang.org/play/#src=interface%20IDummy%20%7B%0D%0A%09value%3A%20string%3B%0D%0A%20%20propName%3A%20string%3B%0D%0A%20%20%5Bkey%3A%20string%5D%3A%20any%3B%0D%0A%7D%0D%0A%0D%0Afunction%20test(obj%3A%20IDummy)%7B%0D%0A%09console.log(obj)%0D%0A%7D%0D%0A%0D%0Atest(%7B%0D%0A%20%20%20%20value%3A%20'value'%2C%0D%0A%20%20%20%20propName%3A%20'key'%2C%0D%0A%20%20%20%20foo%3A%20'foo'%0D%0A%7D)%0D%0A%0D%0Atest(%7B%0D%0A%20%20%20%20foo%3A%20'foo'%0D%0A%7D)) | May be this could help.
```
type MyInterface ={| x: number |};
type Props = {| ...MyInterface, ...{| y: number |} |}
``` |
22,518,586 | I want to play a bit with the recently released Java 8 on OS X Mavericks, but have problems configuring the `compiler compliance level` to anything beyond `1.7`.
I tried this with a recent Luna build (4.4.0M6) as well as with Kepler (4.3 SR2), patched with [this](http://download.eclipse.org/eclipse/updates/4.3-P-builds/).
What am I doing wrong? | 2014/03/19 | [
"https://Stackoverflow.com/questions/22518586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305532/"
] | I think I got it right now. I just re-installed the patch from [here](http://download.eclipse.org/eclipse/updates/4.3-P-builds/) and now `1.8` is shown as compiler level.
I think while the "About" dialog showed me that the patch was installed, it probably wasn't done properly, because it updated other plugins / the IDE to SR2 at the same time.
Anways, this is solved. | I had some problems getting Java SE 8 to work in Eclipse too. I followed the [Instructions in the Eclipse wiki](https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler) for the Eclipse Kepler SR2 (4.3.2) version.
After that, I could choose version 1.8 instead of 1.7, which solved the problem. The instructions seem to link to the same patch you used, though, but maybe you missed something important. |
380,629 | Is there an extension, custom user stylesheet, etc. that will disable or revert the customization of scrollbars in Webkit based browsers like Google Chrome? I like the plain, native scrollbars but I cannot seem to find a combination of CSS to make them come back once they have been styled by CSS. | 2012/01/20 | [
"https://superuser.com/questions/380629",
"https://superuser.com",
"https://superuser.com/users/114552/"
] | I took @bumfo's answer, and fixed this security issue on chrome: <https://stackoverflow.com/questions/49161159/uncaught-domexception-failed-to-read-the-rules-property-from-cssstylesheet>
If you paste this in your console, you'll get your scroll bars back:
```
for (var sheetI = 0; sheetI < document.styleSheets.length; ++sheetI) {
var sheet = document.styleSheets[sheetI];
try {
var ruleSet = sheet.rules || sheet.cssRules;
for (var i = 0; i < ruleSet.length; ++i) {
var rule = ruleSet[i];
if (/scrollbar/.test(rule.selectorText)) {
sheet.deleteRule(i--);
}
}
} catch (e) {
console.warn("Can't read the css rules of: " + sheet.href, e);
}
};
```
Here's a chrome extension with this: <https://chrome.google.com/webstore/detail/default-scrollbar/nkjmoagfbmeafonfhbkeicjdhjlofplo>
And its github repo: <https://github.com/ubershmekel/default-scrollbar> | As discussed [here](https://www.reddit.com/r/userstyles/comments/qjwlet), it does not seem feasible to reset Chrome scrollbars with CSS, but you can always override them.
```css
/* Adjust as desired */
*::-webkit-scrollbar {
all: initial !important;
width: 15px !important;
background: #d8d8d8 !important;
}
*::-webkit-scrollbar-thumb {
all: initial !important;
background: #7c7c7c !important;
}
*::-webkit-scrollbar-button { all: initial !important; }
*::-webkit-scrollbar-track { all: initial !important; }
*::-webkit-scrollbar-track-piece { all: initial !important; }
*::-webkit-scrollbar-corner { all: initial !important; }
*::-webkit-resizer { all: initial !important; }
``` |
7,796 | I'm working on a project to detect a road sign from the Image. Consider the sample image below:

I'm using a heuristic search to detect the road sign within an image. Basically, I want some weak features (colour, shape, zero symmetry within road signs) which can be calculated very fast and their weighted average can be used recognize the road sign.
Currently, I'm searching the entire image to find the road sign which could be of different scale. Since the domain of search is a lot, I tried to reduce it bu by using some heuristics:
1. Location of sign detect in previous frame (its mostly likely to be near)
2. Road signs are usually on right sign
3. Road sign contains enough white pixels
But eventually search needs to stop when it finds the region that contains a road sign. For this purpose, I'm relying on some fast and robust local features that predicts likelihood of containing road sign within given region of an image. Currently, I'm relying mainly on colour and some region props that Matlab provides.
I tried looking for lines and corners within edge map of the region even tried thresholding and looking for rectangle using morphology. But seems like they are too binary either its YES or its NO. In fact in most cases it fails, so my questions what are some nice local features that I could rely on to detect road sign?


I would really appreciate if somebody you guide in the right direction or provide some links or papers that could be helpful for this problem. | 2013/02/09 | [
"https://dsp.stackexchange.com/questions/7796",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/3527/"
] | You could take a look at recent publications by Segvic et al, I know they have been working on the problems of traffic sign detection.
The basic idea was to use the Viola-Jones framework for object detection, which was later improved by adding some temporal and spatial constraints. If I remember correctly, they achieved a nearly 100% recall rate with just 2 false positives on 10000 frames (I might be wrong with the numbers, but they are something like that).
The best is to refer to the papers directly (sorted by year):
[Sinisa Segvic, Karla Brkic, Zoran Kalafatic, Vladimir Stanisavljevic, Marko Sevrovic, Damir Budimir and Ivan Dadic. A computer vision assisted geoinformation inventory for traffic infrastructure. ITSC, Madeira, Portugal, September 2010: 66-73](http://www.zemris.fer.hr/~ssegvic/pubs/segvic10itsc.pdf)
[Sinisa Segvic, Karla Brkic, Zoran Kalafatic, Axel Pinz. Exploiting temporal and spatial constraints in traffic sign detection from a moving vehicle. Machine Vision and Applications (accepted for publication)](http://www.zemris.fer.hr/~ssegvic/pubs/segvic12mva.pdf)
[Sinisa Segvic, Zoran Kalafatic, Ivan Kovacek. Sliding Window Object Detection without Spatial Clustering of Raw Detection Responses. IFAC SYROCO 2012](http://www.zemris.fer.hr/~ssegvic/pubs/segvic12syroco.pdf)
In case I forgot to link something relevant, see the other publications [here](http://www.zemris.fer.hr/~ssegvic/pubs_en.html). | I think something worthy for you to have a try is the pixel co-occurrence model. Roughly speaking, this is something based on pixel intensities. So you can quickly skip all unlikely positions and concentrate on those interested ones. Search for articles about skin models.
Meanwhile, there are some HAAR orthogonal projection based recognition algorithms (this idea is published on CVPR and PAMI). Although I have not used it before, it is not surprising that this algorithm is quite fast, because its computations are integral image-like. In other words, you can match an arbitrary size of rectangular ROI in a target image. |
51,851,998 | I have query returning few rows. There is column with consecutive numbers and nulls in it.
For example, it has values from 1-10 then 5 nulls, then from 16-30 and then 10 nulls, then from 41-45 and so on.
I need to update that column or create another column to create groupId for consecutive columns.
Meaning as per above example, for rows 1-10, groupID can be 1. Then for 5 nulls nothing and then from 16-30 groupId can be 2. Then for 10 nulls nothing. Then from 41-45 groupId can be 3 and so on.
Please let me know | 2018/08/15 | [
"https://Stackoverflow.com/questions/51851998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094183/"
] | This was a fun one. Here is the solution with a simple table that contains just integers, but with gaps.
```
create table n(v int)
insert n values (1),(2),(3),(5),(6),(7),(9),(10)
select n.*, g.group_no
from n
join (
select row_number() over (order by low.v) group_no, low.v as low, min(high.v) as high
from n as low
join n as high on high.v>low.v
and not exists(select * from n h2 where h2.v=high.v+1)
where not exists(select * from n l2 where l2.v=low.v-1)
group by low.v
) g on g.low<=n.v and g.high>=n.v
```
Result:
```
v group_no
1 1
2 1
3 1
5 2
6 2
7 2
9 3
10 3
``` | Typical island & gap solution
```
select col, grp = dense_rank() over (order by grp)
from
(
select col, grp = col - dense_rank() over (order by col)
from yourtable
) d
``` |
2,725,579 | $$
\begin{cases}
2x^2-4y^2-\frac{3}{2}x+y=0 \\
3x^2-6y^2-2x+2y=\frac{1}{2}
\end{cases}
$$
I multiplied the first with $-6$ and the second with $4$ and get two easier equations:
$9x-6y=0 \land -8x+8y=2 $ and out of them I get that $x=\frac{1}{2}$ and that $y=\frac{3}{4}$ but when I put it back into the original systems equation I dont get the right answer. Can somebody explain why? | 2018/04/06 | [
"https://math.stackexchange.com/questions/2725579",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/478783/"
] | If $2x^2-4y^2-\frac32x+y=0$ and $3x^2-6y^2-2x+2y=\frac12$, then$$3\times(2x^2-4y^2-\frac32x+y)-2\times(3x^2-6y^2-2x+2y)=-1;$$in other words, $-\frac x2-y=-1$. So, replace $y$ with $1-\frac x2$ in the first equation, and you'll get a quadratic equation whose roots are $-3$ and $1$. So, the solutions of the system are $\left(-3,\frac52\right)$ and $\left(1,\frac12\right)$. | It looks like you took the two scaled equations $$-12x^2+24y^2+9x-6y = 0 \\ 12x^2-24y^2-8x+8y=2$$ and then simply lopped off the common quadratic parts to produce two linear equations that are entirely unrelated to the original system. Once you’ve scaled the two equations so that the coefficients of their squared terms match, you eliminate those terms by actually adding the two equations together, producing the *single* linear equation $x+2y=2$. |
4,425,400 | I'm looking for an expression that will cause the interpreter to exit when it is evaluated.
I've found lots of implementation-specific ones but none in the HyperSpec, and I was wondering if there were any that I wasn't seeing defined in the specification. I've found that `(quit)` is recognized by both CLISP and SLIME, and `(exit)` is recognized only by CLISP, but I can't find any documentation that references either of these. | 2010/12/13 | [
"https://Stackoverflow.com/questions/4425400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306257/"
] | As far as I know, this is not covered by the Spec, and you will have to use the implementation-specific solutions, or maybe try and look if someone has already written a trivial-quit lib (or start one on [CLiki](http://www.cliki.net)).
If you only care about interactive use, `,q` in SLIME will always do the right thing. Otherwise, you may use read-time conditionals like this:
```
(defun my-quit ()
#+sbcl (sb-ext:quit)
#+clisp (ext:exit)
#+ccl (ccl:quit)
#+allegro (excl:exit)) ;; and so on ...
```
[`#+`](http://www.lispworks.com/documentation/HyperSpec/Body/02_dhq.htm) checks, if the following symbol is in `*features*`. If not, the following form will be treated as white-space. (There is also [`#-`](http://www.lispworks.com/documentation/HyperSpec/Body/02_dhr.htm) for the opposite). | There is an [ASDF library called shut-it-down](http://verisimilitudes.net/2017-12-30) that provides a `quit` function that works by just having cases for the common CL implementations. |
33,755 | I'm rather pleased with my latest attempt to remind my 4 year old to ask for things nicely - if she asks/demands something without saying "please" then I ask her to count to 10 and ask again.
It seems effective, and she even seems to quite enjoy it, but I wonder if there are any downsides I hadn't thought about? | 2018/04/25 | [
"https://parenting.stackexchange.com/questions/33755",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/7304/"
] | There's an awful lot of things going on here, goodness me.
>
> Right now, she's a single-parent. She rarely takes action because of work, due to tiredness and partying. She only has time for her during weekend. I told her about it.
>
>
>
First of all- this is awful. I won't go into an opinion-based view here, but clarity on if the Mother has any actual involvement here would be helpful.
Does your Daughter live with you, or in her own place?.
Edit: If the Mother is involved at all with her Daughter, she has a role to play here as well. She needs to be included in making sure that whatever goals, objective and routines are put in place, that she works with rather than against you so that there's clear "teamwork" going on here.
>
> She always goes to sleep at around 3 to 7 in the morning. This has been going on for a month now. She wakes up around 5 to 7 in the afternoon. Before, she barely even slept in the afternoon.
>
>
> Every time she's gonna wake up "Where's my iPad?"
>
>
> usual series of tantrums. Scream, cry and throwing the pillows out of the couch.
>
>
> I always have no choice but to just give it to her.
>
>
> Later on. She's gonna ask for a chocolate drink. She doesn't like white milk. I don't know. Is it because of the chocolate drink?
>
>
> When we are at the table, her eyes are at the TV busy. She eats very slow. Like take a bite then wait for 3 minutes before another bite.
>
>
>
Before we begin- to put things bluntly, you're going to have to turn this situation around harder and faster than engine-powered merry-go-round. You're going to have to grit your teeth here. A lot.
Ok, simply- you are effectively playing the role of parent here from the sounds of all the issues you're having.
As a result of this, you need to act like a parent. This is a child, you are an adult- who should be listening to who? You're being put upon by your Daughter from the sounds of it and now put upon by your Granddaughter too, being walked all over. This is unacceptable.
Now, this child is being raised to think that her throwing a tantrum is going to get her whatever she wants, whenever she wants it. You can decide for yourself right now if you're going to allow this to continue, or directly move into action and start acting against it to try and help raise a well-balanced and responsible person or not.
The iPad? You do have a choice. You're the adult in the picture here. All of this is down to personal preference but reallistically it's unhealthy for her to be on it all the time, so begin to perhaps impose a limit.
My own son gets a strict "hour only" policy- it's up to him when, but there's an actual hours timer on it that will stop him using it after an hour, so he can have half an hour in the morning and half later- whatever he likes. If he wants to go on it longer, I have to unlock it. He knows that if it gets broken, it won't be replaced- simple. If he's not behaved that day at school or home, he plain won't get it.
Base it on behaviour, how polite she's being, goals she's achieved throughout the day- you'll have to decide yourself, but the policy of "want gets" has got to stop.
The next thing is sleep- it's scientific fact that children need sleep, even Teenagers need a certain amount of sleep- we all do. Electronics such as TV, Tablets, Monitors- they all emit a particular wavelength of light that has been proven to keep your brain engaged and fooled into thinking that it's still daytime, so letting her use any of these is going to make matters worse.
Her going to sleep between 3-7 in the morning though? How does she even function at school? Does she go to any kind of school? I fail to see how she can learn or operate at all under these circumstances.
There needs to be a blanket ban of all electronics, distractions and otherwise from a set period- say she goes to bed at 8PM, by no later than 10PM then all lights are off, it's time for sleep. That's more than generous.
In terms of Chocolate drinks and diet- this is another case of needing to stop. Everyone needs a balanced diet and this isn't being encouraged here- I'm sure that every kid in existence would love to have what they'd like all the time, but this needs to change. Limit the drink to....say a bottle, carton or however it comes twice a week- once it's run out, it's run out. That way she can have it still, but will have to seek an alternative.
When eating, well it's simple- don't let the TV be on! Many families around the world enjoy Dinner as a family activity, not all staring at a TV. I had a similar problem with my Son so we just turn it off- no distractions, dinner doesn't go cold, everyone's happy. Once it's finished, it can come back on once things are cleared away, etc.
There's a lot of solutions here and not all may work for you- it sounds to me like this girl needs a lot of love, patience but also to be taught that authority and respect are something she needs to understand.
She needs to reduce the time on the iPad, show respect and be polite, reduce the intake of just chocolate drinks, go to bed and actually *sleep* at a reasonable time and be shown how to act like she should be.
If the developmental cycle she's already exibiting continues, she's going to grow older and older thinking this is normal and will treat other people the same way, which I'm sure everyone can agree is not a good thing. | I really like SnyperBunny's answer.
I would like to add:
Go outside. Nature. Parks. Sports. Music Lessons. Let her expierience real life adventures. Back at home you could use these adventures in your night time routine. Talk to her about what you did this day and what was funny, beautiful, nice, scary and so on. What she learned. There is a very nice world out there. Also, real life adventures are enforcing that day time is for fun and games and night time is for sleep.
Hiking, swiming and activities like that wear kids out and make them tired. |
12,322,414 | Since this question is from a user's (developer's) perspective I figured it might fit better here than on Server Fault.
I'd like an ASP.NET hosting that meets the following criteria:
* The application seemingly runs on a single server (so no need to worry about e.g. session state or even static variables)
* There is an option to scale storage, memory, DB size and CPU-power up and down on demand, in an "unlimited" way
I researched but there seems not to be such a platform, that completely abstracts the underlying architecture away and thus has the ease of use of a simple shared hosting but "unlimited" scalability. | 2012/09/07 | [
"https://Stackoverflow.com/questions/12322414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220230/"
] | ```
//#region Test
//#endregion
```
That works in Android Studio & IntelliJ. | Dart does not support regions as part of the language specification. However, many IDE tools offer this feature using formatted comments. See the answer below identifying Android Studio and IntelliJ as two such examples. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.