INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Attaching a location value to a list when printed
So i have a adventure game and i created a list of locations
rooms = [ "You are in the garden. Darkness everywhere.",
"You are in the bathroom. You sound some noise.",
"You are in the hall. You almost fall. Stairs east",
"You are in the kitchen. You can hear voices.",
"You are in the upstairs hallway. It's quiet. Stairs North.",
"You are in your room. You're safe." ]
For each line if it executes i want it to print lets say
Location 0
You are in the garden. Darkness everywhere.
I am confused on how to go about it. I know how to just make it say something like
Location 0 You are in the garden. Darkness everywhere.
but that is not required. | For each line in the format you want: `Location 0 You are in the garden. Darkness everywhere.`, the number is the index of the string within the `room` list.
Doing a loop such as this:
for i in range(len(rooms)):
print('Location %d %s' % (i, rooms[i]))
Will give you the desired output for all of the strings in the list.
In that code segment, `%d` represent a formatted number variable, in this case being the number of the location, and `%s` representing the string to be printed, being the string within that location of the list. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, python 3.x"
} |
Django templates: model.image.url gets relative url, how to get full domain url?
I'm new to Django and I've been trying to get my images to show on a site I'm building.
On my templates I use `<img src="{{ model.image.url }}" />` and I get the `MEDIA_URL` \+ `IMAGE_PATH`.
Something like this: `upload/gallery/zips/thumbnails/zips.png`. `upload/` is my `MEDIA_URL`.
How can I get my url to look something like: ` without having to append it like this: `<img src=" gallery.thumbnail.url }}" />`?
So sorry if this is the stupidest question ever asked on SO. | You can prepend your media url using the request object:
<img src="{{ request.get_host }}{{ model.image.url }}" />
*Note - you'll want to make sure you have `request` in your template context processors:
'django.template.context_processors.request' | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, django"
} |
Vim - delay when exiting visual mode
If I press ESC to exit Visual Mode after I select some text, there's a noticeable delay before the text gets unselected and I'm returned to Normal Mode (even if I only select 1-2 characters). Can this delay be avoided? | This can be caused by being mapped to some additional functionality. For example, I use the tabbar plugin and it maps 0-9 to switch to the number buffer. Whenever a key is mapped to additional functionality like this, vim waits a few seconds after it is pressed to see if you're going to press any additional keys.
To see if has any additional mappings, run `:map` and look for `<Esc>` in the first column. When ran without any parameters, `:map` will list all the custom mappings. If you want to list only the mappings while in visual mode, run `:vmap`.
If does have additional mappings, I do not know of a way to remove the pause, besides removing the mappings. The pause is necessary for vim to unambiguously know what action you intend it to take. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 8,
"tags": "vim, delay"
} |
Select Multiple Columns into One
I want to be able to take three columns from one table and put them into a single column in another.
So I want to do this query,
SELECT Ref.Gender_Id,
NHS1.Name,
NHS2.Name,
NHS3.Name
FROM DDS.Referrals Ref
LEFT JOIN DDS.NHSCommunicationNeed NHS1 ON NHS1.Id = REF.NHSCommunicationNeed1_Id
LEFT JOIN DDS.NHSCommunicationNeed NHS2 ON NHS2.Id = REF.NHSCommunicationNeed2_Id
LEFT JOIN DDS.NHSCommunicationNeed NHS3 ON NHS3.Id = REF.NHSCommunicationNeed3_Id
And insert it into a table like this
#Tbl(GenderId, Value) | insert into Tbl (GenderId, Value)
select Ref.Gender_Id,
coalesce(NHS1.Name, '') || coalesce(NHS2.Name, '') || coalesce(NHS3.Name, '')
from ...
Concatenate the names. ANSI SQL uses `||`, but some products have `+` or `concat()` instead.
Use `coalesce()` to avoid null values. (ANSI SQL's concatenation returns null if one of the arguments is null.) (However, some dbms return a value anyway when concatenating with a null value, so you can perhaps skip coalesce.) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "sql"
} |
Help with Level 16's lazers
In Untrusted, how can I get past the lasers? I'm assuming I need to use my phone, but even removing the strokes of the lazers still makes me get hit by them.
!enter image description here | You can use the code below to display the lasers (in their correct color) and also give your phone the ability to change your color. As you move, use `Q` to cycle through your colors until you can pass through the lasers. Cycle goes: (Green ->) Red -> Yellow -> Teal -> Red
var ctx = map.getCanvasContext();
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 5;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
map.getPlayer().setPhoneCallback(function(){
if(player.getColor()=='red')
player.setColor('yellow');
else if(player.getColor()=='yellow')
player.setColor('teal');
else
player.setColor('red');
});
!enter image description here | stackexchange-gaming | {
"answer_score": 4,
"question_score": 1,
"tags": "untrusted"
} |
Integrate Gutenberg as a Standalone App
I'm thinking about integrating the new awesome WordPress block editor (Gutenberg) outside of its environment (WordPress core), so is there any way to get just the text editor code and use it for example in another CMS or framework or just a simple HTML page? | Yes, You can use Gutenberg as a standalone app or CMS agnostic app. Drupal using Gutenberg as a npm module and then integrating in their own CMS. Drupal Gutenberg is decoupling Gutenberg from WordPress and using as JS editor Gutenberg JS. This way, developers can build block for Gutenberg and port it to two different CMS. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 8,
"tags": "block editor"
} |
if \ else vs. switch \ case в C#
Что лучше использовать: if\else или switch\case?
int a = 3;
if (a == 1)
{
...
}
else if (a == 2)
{
...
}
else
{
...
}
switch(a)
{
case 1:
...
break;
case 2:
...
break;
default:
...
break;
}
* Какая из этих конструкций работает быстрее? Почему?
* Когда лучше использовать то или другое? | Оба условных оператора работают с одинаковой скоростью. Так как на уровне машинных команд они преобразуются в одни и те же инструкции.
Выбирать имеет смысл только по вкусу и по задаче.
`switch` может работать только с одной переменной. У `if` таких ограничений нет.
На мой взгляд, язык C# слишком высокоуровневый для такого рода оптимизаций.
Пишите читаемый код ;) | stackexchange-ru_stackoverflow | {
"answer_score": 12,
"question_score": 5,
"tags": "c#"
} |
Change App Logo in Flutter with png or jpeg?
I want to change the logo of my app but I dont know whats the right format to use. For Example when my Logo is the Apple logo. Should I use a jpeg file with a background color or should I only use a png of the Apple and add a background color later on? | There are standards for everything, when you are in a confusion you should always look for those.
iOS's standards: <
Android's standards: < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "flutter, dart"
} |
Is it possible to place custom metadata in the offset Number in a scheduled path in a flow?
I have a question about whether it is possible to place a variable in the offset number in the scheduled path? A Variable that can be modified outside the flow to avoid stopping the flow and modified it when is in production? I use this schedule path to send an email alert 31 days before the end working date. Can it be performed with apex? Or practically that requirement cannot be accomplished? , and specify the metadata:
# (Warning End Date): Returns Date
EndWorkingDate__c - $CustomMetadata.TimeDelay__mdt.DefaultValue.Offset__c
Then, in your Flow, specify (0 Days Before) (Warning_End_Date__c). A word of caution, though; records that are saved before the offset value are changed will not honor the new date unless they are edited before the scheduled path executes. | stackexchange-salesforce | {
"answer_score": 1,
"question_score": 1,
"tags": "visual workflow, scheduled"
} |
Paired Bluetooth device does not connect, 14.04 Desktop
I have a bluetooth GPS device which has successfully paired, shows in the list of bluetooth devices.
However, I seem unable to connect to it to allow my satnav software to use it (PC Navigator 14 free via wine).
Have I missed something here?
OK, I found a useful link here and, using blueman software have definitely connected bluetooth to the GPS device and created a symbolic link to com1. BUT... the software doesn't seem to recognise the com port!
ANybody else seen this? | OK, I've discovered why wine couldn't see the bluetooth ports:
1. Used blueman bluetooth manager to connect to the device and set up a serial port /dev/rfcomm0
2. Create a link to the serial port in ~/.wine/dosdevices:
ln -s /dev/rfcomm0 com1
3. Add myself to dialout group so I can access the ports created in /dev:
sudo gpasswd -a steve dialout
wine apps can now see serial ports.
I still have a problem with the app not keeping hold of the com port but that's another question! | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "wine, bluetooth"
} |
Как передать обьект с сервера в activity через dagger?
Начал применять Dagger2 в своем проекте на mvp(moxy) истолкнулся с проблемой.
Я получаю от сервера список объектов с полным содержимым, которые отображаю в списке; при нажатии на элемент открывается activity с детальным просмотром этого обьекта (сейчас сделано через extras). Как я могу через dagger передать в новую activity выбранный объект? | Вы не можете передать данный объект в вашу активити с помощью дагера. Вы можете создать сущность которая будет получать этот объект с сервера. А вот эту сущность вы можете уже передать с помощью дагера в активити как зависимость.
Исходя из того что вы задаете такие вопросы, вы не очень понимаете что такое DI (Внедрение зависимостей). Я рекомендую вам уделить этому внимание. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android, mvp, dagger2, moxy, di"
} |
Use existing Java classes from Jython REPL?
I have a massive, unfamiliar Java codebase that I need to use in one of my projects, and unfortunately it's one of those situations where almost nothing is documented, and the very few things that are documented are of the "`setFoo(Foo foo) - sets the foo.`" variety. So the documentation generated with `javadoc` is not as helpful as it could be.
I'm more of a Lisp and Python guy myself, so my first thought was that I could learn a lot by interactively playing with some of the relevant classes. Enter the Jython REPL. The problem is that I can't figure out how to set the...the whatever (classpath?) to use them. Assume that I have two directories containing the subdirectories containing the `.java` files: `~/project/foo/src/` and `~/project/bar/src/`.
Thanks in advance. | It sounds like you first need to _compile_ those Java classes (you've referenced `src` directories in your question).
Once you have classes compiled, you can reference them via the classpath.
e.g.
>>> import sys
>>> sys.path.append(r'C:\temp\sample.jar')
>>> from org.my.package import MyClass
More info in this document | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, classpath, jython, read eval print loop"
} |
How do I navigate backwards forwards when there's no physical or screen buttons?
I went on a movie streaming site and a bunch of "popups" came up, like suddenly I was in the appstore or some completely different tab. The real tab I wanted to go to is probably somewhere opened too, but what do I do now? | You were probably switched to the App Store app through a URI scheme. The web page will still be open in Safari. You can either switch back to Safari normally using the home screen or through multitasking. | stackexchange-apple | {
"answer_score": 2,
"question_score": 2,
"tags": "safari, iphone"
} |
Why does `python -c 'print('howdy')'` produce an error (in zsh), but `python -c 'print("howdy")'` does not?
When, in `zsh`, I execute `python -c 'print('howdy')'` from the command line, it produces the following error.
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'howdy' is not defined
However, this `python -c 'print("howdy")'` does not, and instead produces the output expected by me, namely, `howdy` (as a string) is sent to `stdout`?
I thought python was agnostic on single or double quotes | Zsh is first parsing the command, following its own rules on quotes. To zsh, the command `python -c 'print('howdy')'` looks something like the following:
* We're calling the program `python`
* The first argument is `-c`
* The second argument is `'print('` enclosed in quotes, followed by `howdy`, followed by `')'` enclosed in quotes.
Zsh is "expanding" this second argument to `'print(howdy)'`. If you run this command in python you get the error you describe. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": -1,
"tags": "zsh, double quotes, single quotes"
} |
rules on instantiation of existential variables in coq
I'm working through programming language foundations and am confused by this line:
"Existential variables cannot be instantiated with terms containing ordinary variables that did not exist at the time the existential variable was created. "
Why not? Could I have an example of this that exhibits unwanted behavior?
Thanks. | Here's an illustrative example:
(* An empty type *)
Inductive empty : Type := .
(* A proposition quantifying existentially over an empty type can only be false... *)
Lemma this_cannot_be_true : exists x : empty, (forall y : empty, x = y).
Proof.
eexists. (* I'm telling you there is such an x, just put an evar ?x for now. *)
intros y. (* Now we must prove a universal property, so we introduce a new variable... *)
Fail instantiate (1 := y). (* Oh look, y : empty, let's instantiate our evar with it! *)
(* If this didn't fail, we would have the goal (y = y), which would be proved by reflexivity. Luckily, the previous tactic failed. *)
Abort.
(* To clear out any doubt that the above proposition is false. *)
Lemma empty_type_is_empty {P : empty -> Prop} : (exists x : empty, P x) -> False.
Proof.
intros [[]].
Qed. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "coq"
} |
Поиск окна по имени и классу
Подскажите, существуют ли в WinAPI функции для поиска определенного окна, если известны его имя и класс, и передачи найденному окну фокуса(выводу его поверх остальных окон)? | Думаю, для поиска правильнее было бы воспользоваться функцией FindWindowEx.aspx) c более широкими возможностями. А для отображения окна поверх остальных функцией SetForegroundWindow. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "windows, winapi"
} |
Requirements for a clan war?
I am currently in a clan with three members. When we tried to initiate a clan war it said we had insufficient clan requirements. Does anyone know what the full requirements are? Is there a minimum clan member requirement? | The only requirement is that a clan must have at least 5 members eligible for war. (This used to be 10, but 5 vs 5 war size is also available now.)
Members who are **new to your clan** will be **ineligible** for war if they left their previous clan while a war was in progress. They will become eligible for war again when the previous war is completed. You can check your clan member list to see if any members are ineligible for war, and see when they will be eligible again. If you start the clan war while members are still ineligible, those members will not be able to participate.
You can see when players will be eligible in their profile through clan's chat room.
!enter image description here | stackexchange-gaming | {
"answer_score": 14,
"question_score": 14,
"tags": "clash of clans"
} |
Facebook share button
I want that if person clicks the share button, there would appear the referal link in his wall. How can I do it? Because there is no such a thing like share in facebook like it was before. Thanks. | Facebook has deprecated its Share button in favor of the Like button. Check out the Facebook Like Button API at < \- this will answer any and all of your questions. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, facebook"
} |
How to make scapy UI in color
How can I make scapy be colored, like this: <
When I am trying to edit the color theme with the following commad:
conf.color_theme = ColorOnBlackTheme()
It makes everything gibberish:
<
How can I fix it? | See <
1- Make sure you're using the latest version (or try the github version)
2- Make sure you have IPython Installed | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "scapy"
} |
Oracle ORDS REST - how to return collection query for a handler in PL/SQL mode?
A query can be returned in a "collection query" mode as a JSON, simply as `SELECT * FROM SOMETABLE`.
In PL/SQL however, this is not possible. How would the equivalent be implemented in this mode? | Easiest way is to return a `refcursor` from your procedure, as a RESULTSET parameter type.
For example:
DECLARE
cur SYS_REFCURSOR;
BEGIN
OPEN cur FOR
SELECT * FROM myTable ORDER BY id;
:result := cur;
END;
With your OUT parameter set to bind `result`.
. Other than that is there any particular or very important reason behind using logging? | Logging is writing data to some stream to keep a record of events that occur in an application. Note that you don't necessarily have to log to a file. You can log to a console, for example.
Some applications require an "Audit Log" of user activity in the system. This is a case where logging is fulfilling a very specific business requirement.
Note you can write to a file and NOT be logging. If you use the presence of a file to create a lock for a process, for example, you have written to a file, but you are not logging.
In general though, logging is just writing event data somewhere. "started up", "entered method x", "exception occurred" are all **events**. I think that really what defines a "log" vs a file with different semantics. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java"
} |
SQL execution time took more time when database is in the different server
SQL execution time took more time to complete when database is in the different server compare if the web and database are on the same server
if the database and web server are in one server only: Execution time is 3mins
if the database and web server are in different servers: Execution time is 12mins
What are the things to check? | There are many factors that delay or slowdown the SQL execution, Size of data, network bandwidth, poor execution plan etc are few of them, You can start looking around with these factors and narrow down your analysis. I would suggest to start from comparing execution plan from both servers. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "sql server"
} |
How to delete unique constraint in Mysql?
my code
alter table mytable drop unique constraint uk_mytable;
but shows the following error...
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unique constraint username' at line 1" | Try this
alter table mytable drop uk_mytable; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql"
} |
How to change Eclipse Preferences programmatically
What approach should be to change Eclipse Preferences?
They are stored in `<workspace>/.metadata/.plugin/org.eclipse.core.runtime/.settings`
But I hope to find Java API and a way to discover any preference ID. | Somewhat confusingly there are several APIs a plugin can use for preferences.
If your plugin activator extends `AbstractUIPlugin` then you can call
IPreferenceStore prefStore = getPreferenceStore();
in the activator to get the preference store for your plugin.
You can also use
IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode("node id");
to get a slightly different interface to the preferences.
There is also the `org.eclipse.equinox.preferences.preferences` extension point which lets you define an 'initializer' to set the default values for preferences. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "eclipse, eclipse rcp, eclipse plugin"
} |
Will Sergius Turrianus ever stop giving you quests?
In the College of Winterhold, the professor Sergius Turrianus can give you a quest where you go to a random person and pick up an item (as well as a quest where you give him some soul gems). My question is: is it possible to ever "complete" these quests, or will he continue to give you them forever (even after he starts giving you the same people over again)? By complete I mean he will have no more fetch quests left for you to do and will never give you the chat option to do them again.
Also, if it is possible, what is the "ending" dialouge he gives you in congragulations (if there is one)? | No, he won't stop. These are Radiant quests and are part of why Bethesda advertised "infinite quests" in the hype for Skyrim's release. They are infinitely generated, though repetitive. | stackexchange-gaming | {
"answer_score": 7,
"question_score": 1,
"tags": "the elder scrolls v skyrim"
} |
Unreal engine - complaints for needing 8 GB of memory even though I have 8GB memory
I have a Mac OS X with 8 GB 1600 MHz DDR3 RAM and when I start unreal engine it complaints about Low RAM and asks that for best performance I should have at least 8 GB of RAM.
I'm not sure why is this is case, is it possible that its getting a lower share of RAM or something similar?
The Unreal Editor version is 4.7.5
Edit: The processor is 2.3 GHz Intel Core i7, and is 64 bit.
Edit: The graphic processor is Intel Iris Pro 1024 MB. | Why would UE4 not be able to access all of your RAM? I do not consider that case very likely.
Also, I would not worry about the RAM usage of UE4 too much. I do a lot of work with the engine and it rarely uses more than 3GB of RAM. Just make sure that your system as a whole has enough RAM for the running processes to prevent swapping.
Anyway, the bottleneck in your system is probably the graphics processor, so if your engine runs too slowly you should reduce the performance setting inside the engine. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "macos, unreal engine4"
} |
Python how to sum duplicates in list?
I have this list
['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
And i want to know, how many OE21-k and how many OE28-k have. Is there any way to sum and calc how many duplicates are there? | If you want to count the occurrences just use the `count()` method.
['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k'].count('OE21-k')
e.g.
occurences = {}
l = ['OE21-k', 'OE28-k', 'OE21-k', 'OE-31-k', 'OE21-k', 'OE21-k', 'OE28-k']
for item in l:
if item not in occurences.keys():
occurences[item] = l.count(item) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "python, python 3.x"
} |
AngularJS - load data before loading any controller
I'm making a single page application (SPA). I made a controller called `InitialControler` to load the data from the server at this url (local.app/init).
I want this url to be opened before any other url. I'm using ui-router, I did a `$state.go('init')` in the `.run()` function but it still load the requested page before the `'init'` page | One way to do is, in config declare only 'init' state. And in InitialController, after data is loaded(resolve function of service call), configure other states. But in this approach, whenever you refresh the page, the url will change to local.app.init.
To stay in that particular state even after reloading, the solution I found is to have a StartUp app in which I loaded the required data and after that I bootstraped the main app manually by angular.bootstrap. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "angularjs, load, single page application"
} |
How to delete a word accidentally added to the Pages dictionary?
I told Pages to learn the spelling of a character name I was writing about, without noticing there was a misspelling in the name.
Is there anyway to delete or correct the spelling of the name from the Dictionary now that I added it by mistake? | Right click on the misspelled word and select “Unlearn Spelling”.
As Pages uses OS X’ global spelling services, you can use this method anywhere text input is spell checked by it (more or less any text area, with the notable exceptions of MS Office, OpenOffice / LibreOffice, Firefox and a few other apps ported from the non OS X world).
If a misspelled word is not underlined in red and the “Unlearn Spelling” option is missing from the context menu, it may be that you originally used “Ignore Spellin” rather than “Learn Spelling”. In that case, try opening a new document and pasting in the misspelled word – the red underline will appear in the new document if you ignored the spelling in the original document. | stackexchange-apple | {
"answer_score": 5,
"question_score": 4,
"tags": "macos, pages, dictionary"
} |
DAC BLC objects
How I can access objects of DAC and BLC?
class BaseDACExtension : PXCacheExtension<BaseDAC>
{
public void SomeMethod()
{
BaseDAC dac = Base;
}
} | Assuming I understand your question correctly, just call `GetExtension` on either your base DAC or base Graph...
For DAC extensions: _(where baseDac is an instance of BaseDac)_
var dacExt = baseDac.GetExtension<BaseDACExtension>();
For Graph extensions: _(where baseGraph is an instance of BaseGraph)_
var graphExt = baseGraph.GetExtension<BaseGraphExtension>(); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "acumatica, dac"
} |
How are the category id of app notification determined on ANCS?
I know that LINE, Facebook Messanger belong to CategoryIDSocial. How does the category id determine? Can an app developer define it?
Category ID List < | Looks like they are defined by Apple so you would have no control over it.
Could it loosely be tied to the AppStore categories you have to choose when submitting application to AppStore?
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, ancs"
} |
Finding a divergent sequence with exactly one convergent partial infinite limit
This is a challenge given by a teacher that said that he himself doesn't know an answer and doesn't know if it can be disproven.
The challenge is as follows: find a real sequence $\\{a_n\\}_{n=1}^\infty$ for which $PL(a_n)=\\{L\\}$* when $L=+\infty$ and $\\{a_n\\}$ is unbounded and does not converge to $L$.
This series should be solidly defined (that is, no "every $k$-th member is a random number").
*($PL$ being the set of partial limits - limits of converging sub-sequences of $\\{a_n\\}$) | If $a_n$ is a real sequence whose only subsequential limit is $\infty,$ then $a_n\to \infty$ must hold. Proof sketch: Show that if $a_n\to \infty$ fails, then there exists a finite $M$ such that $a_n<M$ for infinitely many $n.$ Thus there is a subsequence $a_{n_k}$ lying in $(-\infty,M].$ Any such subsequence will itself have a subsequential limit in $[-\infty,M].$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "real analysis"
} |
Node, BodyParser bad json
I have this code in javascript:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/test', function (req, res) {
console.log(req.body);
})
var server = app.listen(8080, function () {
})
From a rails app I am suppose to receive this json in the body:
{"content": "some content", "test":"some tests"}
but instead I receive this one:
{ '{"content":"some content","test":"some test"}' : ''}
Any idea of what I am doing wrong??
This is the way the JSON is sent:
response = JSON.parse RestClient.post("#{test_runner_url}/test", {content: content, test: test}.to_json) | So the answer was:
RestClient.post("#{test_runner_url}/test", {content: content, test: test}, :content_type => 'application/json') | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, json, node.js, body parser"
} |
How do I pass arguments to a public class in C#?
How do I pass arguments to a public class in C#. I am new to C#, so please forgive the n00b question.
Given this sample class:
public class DoSomething
{
public static void Main(System.String[] args)
{
System.String apple = args[0];
System.String orange = args[1];
System.String banana = args[2];
System.String peach = args[3];
// do something
}
}
How do I pass the requested arguments?
I would expect to write something like:
DoSomething ds = new DoSomething();
ds.apple = "pie";
But this fails. | The `String[] args` parameter of the `Main` method is populated when you launch the application via command line:
`/your/application/path/DoSomething.exe arg1 arg2 arg3 ...`
If you want to pass these arguments programmatically you have to set your variables as public Properties, so for example:
public class DoSomething
{
public string Apple { get; set; }
public string Orange { get; set; }
public string Banana { get; set; }
// other fruits...
}
Then you can do:
public class Test
{
public static void Main(System.String[] args)
{
DoSomething ds = new DoSomething();
ds.Apple = "pie";
// do something
}
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "c#, .net, arguments, console application"
} |
Convertir cadena a Array de Numpy
Estoy leyendo de un fichero información de este estilo línea a línea
[[[106.23706131 74.19983673 53.1510033 ]]]
[[[59.24701176 41.45938749 29.7537066 ]]]
Esto quiero pasarselo a otras variables, pero se leen en formato string y necesito que sean arrays de numpy. Debido a que cuando les doy uso obtengo el siguiente error:
numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'subtract' output from dtype('<U45') to dtype('float32') with casting rule 'same_kind'
¿Como puedo hacerlo? | Se agregaron comillas para poder emular un string, aunque no las veo en tu código, pero tú dices que estan en ese formato.
Sin bibliotecas, puede que obtengas el resultado de la siguiente forma, como un objeto tipo lista:
arrayPrueba = [[['106.23706131 74.19983673 53.1510033']]]
print(type(arrayPrueba))
print(len(arrayPrueba))
for i in arrayPrueba:
print(type(i))
for j in i:
print(type(j))
for k in j:
print(type(k))
splitResult = k.split()
print(splitResult)
print(type(splitResult))
print("Lista:",splitResult)
Saludos | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "array, string, numpy"
} |
How to insert data on SQL Server Database in VB.NET?
has anyone know how to insert some data on SQL Server database?? i've tried this code, but it not works for me.. here's the code:
Dim constring As String = "Data source=.\sqlexpress;attachDbFilename=|DataDirectory|\Database1.mdf;integrated security=true;connect timeout=30;user instance=true"
Dim connection As SqlConnection = New SqlConnection(constring)
Dim query As SqlCommand
Dim s As String
connection.Open()
s = "insert into login values(@un,@pass)"
query = New SqlCommand(s, connection)
query.Parameters.AddWithValue("@un", "111")
query.Parameters.AddWithValue("@pass", "222")
query.ExecuteNonQuery()
connection.Close() | Your syntax to create a login is incorrect. You are looking for:
CREATE LOGIN <loginName>
WITH PASSWORD = 'YourPassword'
More information about `Create Login` can be found on MSDN | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql server, vb.net, sql server 2008"
} |
What Limitations Does SubtractSides Have When Applied to an Equation?
I can't figure this out. SubtractSides says
/8]
!Mathematica graphics
But this works
SubtractSides[x - 2 == y/8]
!Mathematica graphics
What Am I missing?
V 13.1 on windows 10 | `(1 - y)/8 + 1/8 (-1 + y)` is zero:
(1 - y)/8 + 1/8 (-1 + y) // Simplify
(* 0 *)
So `SubtractSides` doesn't fail, it just gives an output that looks a bit funny. If I have to guess, it gives this output because:
# - # &[(y - 1)/8]
(* (1 - y)/8 + 1/8 (-1 + y) *) | stackexchange-mathematica | {
"answer_score": 3,
"question_score": 1,
"tags": "linear algebra"
} |
TypeError: only length-1 arrays can be converted to Python scalars when use pyplot
I have such Python code:
import matplotlib.pyplot as plt
import numpy as np
import cmath
X1=np.arange(1,6+0.05,0.05)
X2=np.arange(1,6+0.05,0.05)
[x1,x2]=np.meshgrid(X1,X2)
f=cmath.sqrt(1+x1**2)+cmath.sqrt(1+x2**2);
plt.contour(x1,x2,f,20)
plt.show()
And such error:
File "g:/python-code/numerical-optimization/nt.py", line 9, in <module>
f=cmath.sqrt(1+x1**2)+x2**2
TypeError: only length-1 arrays can be converted to Python scalars
How can I fix?Thanks in advance. | `x1` and `x2` are both of type `np.ndarray`. Therefore, cmath cannot be used on them. Use `np.sqrt` instead of `cmath.sqrt`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
Do minor GC with G1GC result in global pause?
We currently have JDK1.7 installed and configured to use G1GC. What i want to know is this.
Are stop the world pauses only a characteristic of Major GC? Or Minor GC has that issue as well? | To answer my own question,
YES, minor GC activity causes a global pause.
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "g1gc"
} |
GridView onItemClickListener never gets invoked
I have a `GridView` with custom `View` in it, which is a `Button` and a `TextView`. I defined the `setOnItemClickListener` but it looks like it never invoked, please see peaces of code below.
gridview = (GridView) findViewById(R.id.main_gridview);
gridview.setAdapter(new GridAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), "gadsfadsf",
Toast.LENGTH_SHORT).show();
Log.d("Main", "onItemClick");
}
}); | I had the same issue. While I've not yet figured out why it never gets invoked, I can propose a workaround.
Instead of setting the onClickListener on your GridView, set it on the Button itself inside your GridAdapter, inside your getView() method.
That worked for me! | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "java, android, android gridview"
} |
How to highlight a currently selected item/section in Wordpress with CSS (maybe PHP too)?
I would like to have the currently displayed **Page** or **Recent post** highlighted with CSS.
Something like this:
PAGES:
...Home
... **About** <\--current page
...Contact
RECENT POSTS:
... **post1** <\-- current post the user is seeing.
...post2
...post 3
I used to accomplish that assigning an unique id to the `body` tag to make each page unique for CSS, and change the color of the navigation link.
In word press, for instance, all the recent posts are using the same body so I can't figure out how to do it.
Any suggestions? | If you're using `wp_list_pages()`, you can use the classes `current_page_item`, `current_page_ancestor` and `current_page_parent` to target the active nodes.
Otherwise a bit of manual labour is at stake - you could echo the current slug on the `body` tag, either as a class or ID, or print an 'active' class on the navigation item if it's the current page;
function active_class($page)
{
if (is_page($page))
echo ' class="active"';
}
And put into play;
<ul>
<li<?php active_class('about'); ?>><a href="/about/">About</a></li>
<li<?php active_class('contact'); ?>><a href="/contact/">Contact</a></li>
</ul> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, css, wordpress"
} |
Is it safe to blow on a baby's face?
I've seen some parents blowing on their baby's face when crying. The baby suddenly stops crying but he looked very surprised. I wonder if this could harm the baby in some way. | Blowing on the face is a common trick. It triggers a reflex to hold the breath for a short moment. That stops the crying, and can also be used when washing the child's face etc.
I am not aware of any consequences of this, neither positive nor negative. | stackexchange-parenting | {
"answer_score": 17,
"question_score": 15,
"tags": "newborn, crying"
} |
How can I show enemy health using console?
In PC Gamer's Prospekt review console is used to compare enemy base health values between Half-Life 2 and a HL 2 mod:
> from Prospekt's first combat encounter, it felt to me like something was off. The breaking point came during a battle at the start of chapter five, when, in a fit of frustration, I quit out, loaded up Half-Life 2, and used the command console to check out a hunch. Sure enough, the Combine Overwatch Soldier and Elite—the two enemy types you fight throughout the majority of Prospekt—have been given significantly more health.
I would like to do my own tests, for example MINERVA mod may have increased the enemy health. | From what I have found, it seems like Prospekt used the console command `impulse 103` while looking at the enemies, as this command will tell you the stats of a "monster".
From here
> Prints AI state of the NPC the player is looking at to the console. Requires developer mode.
I'm not entirely sure what is meant by "AI state", as this, to me, implies "hostile" vs. "friendly", but from other sites, it seems that this is what will reveal enemy health to you.
From here:
> While looking at amonster, displays stats.
And here:
> Monster Stats, While Looking at Monster
>
> impulse 103
And here:
> Show monster stats impulse 103 | stackexchange-gaming | {
"answer_score": 2,
"question_score": 3,
"tags": "source engine, half life 2"
} |
how to create a temp file from a base64 string
im trying to upload an image (base64 string) gotten from a canvas element using javascripts .toDataURL() method:
var cropped_base64 = $crop_canvas[0].toDataURL('image/jpeg');
cropped_base64 = cropped_base64.replace('data:image/jpeg;base64,','');
$.ajax({
url:the_url,
data:{
base64_string: cropped_base64
},
type:'POST',
success:function(data){
console.log(data)
},
error:function(data){
console.log(data)
}
});
and my server side code decodes it:
my $base64_string = param('base64_string')
or return 'error no base 64';
my $image_decoded = MIME::Base64::decode_base64($base64_string)
or return 'error couldnt decode base64';
I need this image as a temporary file, to pass to another routine.
how can I generate this? I cant install modules like Image::magick... | You've got the decoded content in a scalar. Print that scalar to a file:
open ( my $image, '>:raw', '/path/to/image.png' ) or die $!;
print {$image} $image_decoded;
close ( $image );
If you want to avoid potential race conditions with it, you'll have to do something about unique-naming. `File::Temp` is probably a good way to approach this.
E.g.:
use File::Temp qw/ tempfile /;
my ( $output_fh, $filename ) = tempfile();
binmode $output_fh;
print {$output_fh} $image_decoded;
This won't auto-delete, because you asked for a filename (which you can then pass on to something else). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, perl"
} |
Python truncate a long string
How does one truncate a string to 75 characters in Python?
This is how it is done in JavaScript:
var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
var info = (data.length > 75) ? data.substring[0,75] + '..' : data; | info = (data[:75] + '..') if len(data) > 75 else data | stackexchange-stackoverflow | {
"answer_score": 568,
"question_score": 344,
"tags": "python"
} |
[Proof Verification]: Closure of a set is the union of the set with its boundary.
Let $X$ be a topological space, and $A$ a subset of $X$. I want to show that $\bar{A}= A \cup \partial A$.
My proof probably isn't the simplest, but I'm just beginning to write proofs seriously and I want to know if this one holds up. I'll show one inclusion here but the other is almost identical.
Suppose $x\in\bar{A}$ but $x\not\in A \cup \partial A$. Then since $x\not\in\partial A$, there exists a neighbourhood $N$ of $x$ which either does not intersect $A$ or $X\setminus A$. Since $x\in \bar{A}$, every neighbourhood of $x$ intersects $A$, so $N$ must not intersect $X\setminus A$. But this is absurd, since $x\in X\setminus A$. | It's a bit roundabout, as you say, but it looks OK. I'd prove it like this (no proof from contradiction): let $x \in \overline{A}$. If $x \in A$ we're done: $x \in A \cup \partial A$, and if not, every neighbourhood of $x$ intersects $A$ (from being in its closure) and $X\setminus A$ (in $x$ itself at least), so $x \in \partial A$ and we're done too. Same arguments in a more "positive" form.
The reverse is similar: if $x \in A \cup \partial A$, then $x \in A \subseteq \overline{A}$ and we're done or $x \in \partial A \subseteq \overline{A}$ (if every neighbourhood of $x$ intersects both $A$ and its complement, a fortiori every neighbourhood intersects $A$) and we're done again. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "general topology, solution verification"
} |
Can I be notified about DDL command execution from MariaDB
ALL,
It is not possible inside mySQL, but maybe it can be done inside MariaDB?
TIA!
[EDIT]
ON MS SQL Server it can be achieved by using `CREATE QUEUE + CREATE SERVICE + CREATE EVENT NOTIFICATION` and then query the notification queue.
It is also possible to use `LISTEN/NOTIFY` in recent PostgreSQL to do the same.
It looks like mySQL/MariaDB do not support this feature and the only way to check is to query the information_schema.tables and compare the number of tables you get with the number of tables you have initially.
[/EDIT] | MariaDB has the same security constraints.
You can always get the list of tables by `SELECT ... FROM information_schema.tables ...`
Another way to check:
mysqldump --no-data --routines
then diff the output from the previous dump of the schema.
However, I would not want to do this too often, no more than once a minute, for fear that it would interfere with other things too much. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mariadb, ddl"
} |
If $k(G) > \frac{\vert G\vert}{p}$, prove that $Z(G) \neq 1$
> Let $G$ be a non-trivial finite group and let $p$ be the least prime divisor of $\vert G\vert $. If $k(G) > \frac{\vert G\vert}{p}$, prove that $Z(G) \neq 1$.
Suppose for a contradiction that $Z(G) = \lbrace 1\rbrace$. Then the Class Equation reads $\vert G\vert = 1 + \sum_{i=2}^{k} [G : C_G(x_i)]$. Where do I go from here in placing a bound on this? I cannot seem to arrive at a contradiction. | If $Z(G)=1$, every non-identity conjugacy class must have size $>1$ and hence $\geq p$. Thus the class equation gives $\\# G\geq (k(G)-1)p+1$. But that is a little too much to ask for, since $k(G)-1\geq\frac{\\# G}{p}$ (recall $k(G)$ is an integer and $p\mid \\# G$) | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "group theory, finite groups"
} |
calcular la ubicación mas corta entre dos puntos gps en sql
estoy intentando sacar la distancia mas cercana entre dos puntos (latitud y longitud) pero al intentar filtrarla en mysql me sale cualquiera (a veces la mas cercana y otras otra dependiendo de la ubicación que le dé)
Las ubicaciones de latitud y longitud están expresadas en números enteros. **ubicacion actual:** Latitud: 31248099 Longitud: 64108629
select locgps_codigo, locgps_id, locgps_localidad_id, localidad_nombre, locgps_latitud, locgps_longitud, locgps_tipo, locgps_nombre,
locgps_latitud - 31248099 diflat, locgps_longitud - 64108629 diflog
from localidad_gps
left join localidad on locgps_localidad_id = localidad_id where locgps_tipo = 4
and locgps_nombre <>'' and locgps_longitud > locgps_latitud
Y estos son los resultados que me trae.  + abs(locgps_longitud - 64210136) diflog
FROM localidad_gps
left join localidad on locgps_localidad_id = localidad_id where locgps_tipo = 4
and locgps_nombre <>"" and locgps_longitud > locgps_latitud
ORDER BY diflog | stackexchange-es_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, gps"
} |
Store UserID in session?
To present user specific data, where do I store the userID of the user currently logged in? the Session? | Yes, the session would be an appropriate place for that information. Assuming you are using the authentication features baked into the ASP.NET framework, you will either be loading the user ID from HttpContext.Current.User.Identity.Name or looking it up from that value. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "session"
} |
How can I develop production iPhone apps and iPad apps on the same machine?
It seems that in the future, we can just use the non-beta iPhone SDK to develop for both at once.
But for now, the only way to develop for iPad seems to be to use the SDK 3.2 beta. However, if I install that, Apple clearly states I should not submit apps to the app store with it.
I'm an independent, one-machine developer. Is there a way I can continue to upgrade my existing iPhone apps while still developing for iPad? | The Best way to do this is to install the 3.2 SDK beta in a location other than '/Developer'. On the 'Custom Install on Macintosh HD', select 'Other' from the Popup button, and point the installation to somewhere like: '/Developer-Beta'.
You can then run Xcode from /Developer/Applications for your iPhone apps, and Xcode from /Developer-Beta/Applications for your iPad apps. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "iphone, xcode, ipad"
} |
cannot invoke '!=' with an argument list of type (@lvalue Bool, ($T5))
The title is the error message that I get while compiling this code snippet @ line3:
var categoryMatch = (scope == "All") || (candy.category == scope)
var stringMatch = candy.name.rangeOfString(searchText)
return categoryMatch && (stringMatch != nil);
Whats the problem here?
Thanks | The issue is `rangeOfString:` returns a `NSRange` that cannot be equatable to `nil`. Instead of that check the `location` property of `NSRange`.
You need to change your return statement like:
return categoryMatch && (stringMatch.location != NSNotFound)
References:
* rangeOfString:
* NSRange | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "xcode, swift, nsstring, nsrange"
} |
java.lang.IllegalArgumentException: Could not create a component
java.lang.IllegalArgumentException: Could not create a component with id 'com.mydomain.example.ExampleSearcher'. Tried to load class directly, since no bundle was found for spec: basic-search-java. If a bundle with the same name is installed, there is a either a version mismatch or the installed bundle's version contains a qualifier string.
Getting above error during the deployment of application in Vespa. | This is most likely caused by deploying the wrong application package. If this is the basic-search-java sample application, you have probably done vespa-deploy on the `src/main/application` folder rather than the `target/application.zip` after building the application with maven.
See < for exact steps for deploying this application.
Cheers! | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "maven, vespa"
} |
Run different Animation on different touches
I've several animations which I want to run on touch of different body parts in unity. Like when arm is being touched , I want to run arm animation and when leg is touched , I want to run leg animation. How I know that which part of body user have touched?
, and put this into a quick-fix list in vim?
All the docs I found so far assume that you run `make` or `vimgrep`, but in this case I just want to use a text file created elsewhere. | You're looking for `:cfile` / `:cgetfile`:
>
> :cf[ile][!] [errorfile] Read the error file and jump to the first error.
>
The file you're reading naturally must be in a format that can be parsed by the `'errorformat'` option. | stackexchange-stackoverflow | {
"answer_score": 24,
"question_score": 13,
"tags": "vim"
} |
Paso y recepcion de variables por GET [PHP]
No puedo recoger mi variable $_GET correctamente.
Tengo un boton que a traves de javascript me redirige a una url
$(".btnSeeGlossary").click(function() {
let idGlossary = $(this).attr("idGlossary");
window.location = "glossary?id=" + idGlossary;
})
Una vez redirigido, digamos que la url quedo ` estoy en el sitio maquetado, quiero obtener el id de la siguiente manera:
$value = $_GET["id"];
var_dump($value);
> Var dump me retorna NULL =(
Si cambio por
$value = $_GET;
var_dump($value);
> Value retorna "glossary"
>
> Edit: Dejo el htaccess por si esto pueda estar afectando.
Options All -Indexes
RewriteEngine On
RewriteRule ^([-a-zA-Z0-9]+)$ index.php?route=$1 | > Finalmente, era el `htaccess`. Si reescribo las url debo agregar la bandera `[QSA]`
RewriteRule ^([-a-zA-Z0-9]+)$ index.php?route=$1 [QSA]
solucionó el problema. | stackexchange-es_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, javascript, .htaccess, get"
} |
Can a convention be mandatory?
I am referring to the following meaning of the word _convention_
> [C1] a usual or accepted way of behaving ...
[Cambridge Dictionary]
I think that a _convention_ cannot be mandatory but I would like to get some other opinions.
## EDIT
Perhaps some background will help provide more context.
I am a computer programmer. There are many computer programming languages. Each language has syntax. If a program is written that does not use correct syntax, it cannot run. So I would say that syntax is mandatory. Apart from syntax, there are conventions. The idea behind the conventions is to make it easier for computer programmers to read each other's code. Some programmers insist that these conventions are mandatory. I don't think they are. Hence my question. | I'd say that it would be unacceptable to speak of a 'mandatory convention' in the sense of 'convention' I'm sure you're intending. But more suitable definitions are
> **convention** [noun] ...
>
> (5) a rule, method, or practice established by usage; custom:
>
> * _the convention of showing north at the top of a map._
>
and the related non-count usage:
> (6) general agreement or consent; accepted usage, especially as a standard of procedure.
[Dictionary.com]
I'd say that these definitions largely cut across a legally enforced practice. Though as @John Lawler's driving example shows, a convention may be encoded into law. | stackexchange-english | {
"answer_score": 4,
"question_score": 2,
"tags": "meaning"
} |
eloquent query with orderBy subquery
How to convert the following query to eloquent
DB::select("SELECT fp.*
FROM forum_posts fp
ORDER BY (
SELECT( CASE WHEN MAX(fa.created_at) > fp.created_at THEN MAX(fr.created_at) ELSE fp.created_at END )
FROM forum_answers fa
WHERE fp.id_post = fa.id_post
)
DESC");
Just to exemplify what I'm trying to achieve
Post::orderBy(
'SELECT( CASE WHEN MAX(fa.created_at) > fp.created_at THEN MAX(fr.created_at) ELSE
fp.created_at END )', 'DESC'
)->get() | @josei, Eloquent order method supports subqueries and there is a number of ways you can use to achieve the same result
Post::select('forum_posts.*')->orderByRaw('...')
// or
Post::query()->select('forum_posts.*')->orderByDesc(
Post::where() ...
)
// or
Post::query()->select('forum_posts.*')->orderBy(DB::raw('...'))
Hope this helps, good luck! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "laravel"
} |
Entity Framework many to many relationship Question
I have 3 tables:
-Users (UserId(pk), Email, Password)
-Roles (RoleId(pk), RoleDescription)
-UsersInRole (UserId(pk), RoleId(pk))
I defined the relationships Users->UsersInRole and Roles->UsersInRole in the DB. When I created the edmx file in Visual Studio, it shows only two classes: Users and Roles joined by a many to many relationship (the UsersInRole table is not shown as a class I'm guessing because that table is there to break the many to many DB issue).
Now, I'm trying to define a method that given a role, it should return a list of users. This does not work:
public List<User> usersPerRole(string role)
{
return from u in entities.Roles where u.RoleID == role select u.Users.ToList();
}
Can anyone out there give me an example of the correct way to do this?
Thanks, | A coupling table "UsersInRole" (without any other than two foreign keys that together form the primary key of the table) will be translated into navigation properties on "both sides" of the foreighn keys. So in the user and in the role entity. In Users it will be User.RolesForThisUser and in Roles it will be Role.UsersWithThisRole. Adding any complemnetary column in the coupling table will result in a specific entity for that table and lossing the navigation properties as explained.
Now for your question yuo can simpy do:
public List<User> usersPerRole(string role)
{
using(Entities context is new Entities())
{
return context.Role.FirstOrDefault<Role>(r => r.ID == role).Include("UsersInRole")
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, entity framework"
} |
How to use javascript to preform various functions on a website
I'm trying to log in to an account, visit a particular URL, click on something at that URL, and then log in to the next account for a list of about 100 accounts. I'm not quite sure where to start here. Any guidance on where I can look to teach myself how to do things like this? | This is quite a broad request... You tagged the post as Javascript so I am going to assume you want the solution in that language.
What you are probably looking for is something called browser automation library. One such is called Selenium <
It has support for multiple languages such as Python, Java, JavaScript and more!
It allows you to launch a browser window and control it using code. Have a look around the internet, there will be many examples out there. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript"
} |
how to check with angular.js what is the type of an element
I received an html node and store it as angularjs element:
var el=angular.element(e.target);
How can i check if that element is of type "textarea" or "input" without using jQuery? | You can easily find it by using :-
el[0].tagName=="INPUT" or el[0].tagName=="TEXTAREA"
Small example:-
<div ng-controller="MyCtrl">
<input type="text" name="name" id="name"/><br>
<textarea id="check"></textarea>
</div>
Controller:-
var e1=angular.element(document.querySelector("#name"));
var e2=angular.element(document.querySelector("#check"))
console.log(e1[0].tagName);
console.log(e2[0].tagName);
Fiddle | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 5,
"tags": "angularjs"
} |
match image tags with regEx
I am having some trouble with this regex:
<img(.+)src="_image/([0-9]*)/(.+)/>
Global and case insensitive flags is on.
The problem is that it also grabs Image n (see string below), but I want it only to match the image tags in the string.
<p>Image 1:<img width="199" src="_image/12/label" alt=""/> Image 2: <img width="199" src="_image/12/label" alt=""/><img width="199" src="_image/12/label" alt=""/></p>
It works if I put a newline before Image n :)
Can anyone point out for me what I am doing wrong?
Thanks in advance bob | Use a non-greedy regexp:
<img . _? src="_image/(\d+)/(.+?)/._?> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, regex, replace"
} |
Series expansion of harmonic numbers derivation.
I can get,
$$h_n \approx \ln n+\gamma$$
By, saying
$$\frac{h_{n}-h_{n-1}}{n-(n-1)}=\frac{1}{n}$$
Then letting $h_n=h(n)$ be continuous and differentiable on $(0,\infty)$. So that,
$$h'(n) \approx \frac{1}{n}$$
And thus,
$$h_n \approx \ln n+C$$
Where we will let $C$ give us the best approximation as $n \to \infty$ that is,
$$C=\lim_{n \to \infty} (h_n-\ln n)$$
What about the other terms, I'm curious to see how they are derived. | Let $x_n=H_n-(\ln n+\gamma)$ with $H_n=\sum_{k=1}^n\frac{1}{k}$ and evaluate the following limit by using the Stolz-Cesaro Theorem ($\ast/0$ case), $$\lim_{n\to \infty}\frac{x_n}{1/n}=\lim_{n\to \infty}\frac{x_{n+1}-x_n}{1/(n+1)-1/n}=\lim_{n\to \infty}\frac{1/(n+1)-\ln(1+1/n)}{1/(n+1)-1/n}=\frac{1}{2}.$$ Hence $H_n=\ln(n)+\gamma+\frac{1}{2n}+o(1/n)$.
More terms can be found in a similar way (a general formula involves the Bernoulli numbers). Another method to find the asymptotic expansion of the harmonic numbers employs Euler–Maclaurin formula. | stackexchange-math | {
"answer_score": 4,
"question_score": 4,
"tags": "calculus, asymptotics, harmonic numbers"
} |
HRESULT:0x80040154 for registered COM object
I have some probles with call COM object.
szProgID = Imctrl.Section
HRESULT hr = CLSIDFromProgID(szProgID, &clsid);
After execution, hr = S_OK, clsid = "CLSID_Section Class".
But when i try create an object, CoCreateInstance returned error : "Class not Registered". Although "Imctrl.Section" exist in registry.
hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&p);
Same error for other clases from this dll. | The problem was not related to 32-bit vs. 64-bit.
Using the utility software " **depends.exe** " I found this DLL dependencies with some third-party DLL, which did not allow to access the object. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "com, atl"
} |
Displaying a hundredth set of characters from a buffer in C
Read TDT.txt (70 characters at a time) and display every hundredth set of 70 characters read.
So, I'm stuck on how to take the characters placed in this character buffer and print them to the screen where only every hundredth set is displayed. Here is my approach so far
int fileOpen = open("TDT.txt",2);
int fileClose = 0;
char read70[70];
int fileEnd = lseek(fileOpen,0,2);
int test1 = lseek(fileOpen, 0,0);
for(i = 0; i < fileEnd; i++)
{
fileRead = read(fileOpen,read70,70);
count++;
if(count == 100)
{
printf("%s",read70[i]);
count = 0;
}
}
I'm not sure how to display the hundredth set of 70 characters. My above approach is just an attempt. I ended up getting a seg fault but im not sure why. | I suppose it is meant that every 100th bucket, each comprising 70 characters, shall be printed out. See the code below, which does exactly this.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
char buffer[71]; // 70 + 1 just for the sake of using printf later on...
buffer[70] = '\0';
int myFile = open("TDT.txt",O_RDONLY);
if (myFile < 0)
return 1;
size_t charRead = 0;
int nrOfSets=0;
charRead = read(myFile, &buffer, 70);
while (charRead == 70) {
nrOfSets++;
if (nrOfSets % 100 == 0) // every 100th set read in?
printf("set: %s\n", buffer);
charRead = read(myFile, &buffer, 70);
}
close (myFile);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c, file, unix, io, buffer"
} |
Comparing comma separated numbers in cells
I am trying to compare the numbers in the `Reachability Set` column with the numbers in the same row of the `Antecedent Set` column and return the common values in the corresponding cells of the `Intersection Set` column.
**_Screenshot:_** , you can use the following **array-entered** formula.
=TEXTJOIN(",",TRUE,IFERROR(1/(1/(ISNUMBER(FIND(","&TRIM(MID(SUBSTITUTE(B2,",",REPT(" ",99)),seq_99,99))&",",","&A2&","))))*TRIM(MID(SUBSTITUTE(B2,",",REPT(" ",99)),seq_99,99)),""))
**seq_99** is a **Named Formula**
Refers to: =IF(ROW(INDEX($1:$65535,1,1):INDEX($1:$65535,255,1))=1,1,(ROW(INDEX($1:$65535,1,1):INDEX($1:$65535,255,1))-1)*99)
To enter an array formula, after entering the formula in the cell, confirm by holding down `ctrl` \+ `shift` while hitting `enter`. If you do it correctly, Excel will place braces `{...}` around the formula.
 | > os.execute("echo "..returnString.." >>/tmp/dump.txt")
This translates into the command line:
echo x,y; >> /tmp/dump.txt
Can you see why that wouldn't work? | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "linux, lua, concatenation"
} |
How to make pictures next each other in the center in side html tag
I have this code
<?php
echo '<p style="text-align: center;"><a href="tran.php?page=A"><img src="tran.png"/></a></p>';
echo '<p style="text-align: center;"><a href="course_list.php?page=A"><img src="courselist.png"/></a></p>';
?>
but when I run it show me this icons(pictures) under each other like this
ICON1
ICON2
How I can make it next each other like this and I want the icons still in the middle of the page.
ICON1 ICON2 | Use one `p` tag.
<?php
echo '<p style="text-align: center;"><a href="tran.php?page=A"><img src="tran.png"/></a> ';
echo '<a href="course_list.php?page=A"><img src="courselist.png"/></a></p>';
?> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, html, css"
} |
GIT how to split up commits from branch into different branches?
I have a single branch with commits for feature A, B, C, D. I have about 40 commits, and each of the commits are in mixed order. I have made a pull request, but I need to split up this branch into branch A, branch B, etc. with the commits associated with each feature. So feature A commits in branch A.
Unfortunately, i'm new to git and it still confuses me. How do you pull out the commits from a single branch and put them inside their own branch? | You can use `git cherry-pick` Create new branch for feature A, checkout on it and use: `git cherry-pick a_commit_hash`. Repeat it for all your commits | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "git"
} |
Regular expression to parse id
I'm looking for a regular expression to parse the id of a record in MongoDB:
{"$oid":"5527b117d3d511091e1735e2"}
I'm trying with the following one but it fails:
private static final Pattern p = Pattern.compile("\\{\"([a-zA-Z\\d]+)\"\\}");
Matcher m = p.matcher("{\"$oid\":\"5527b117d3d511091e1735e2\"}");
if(!m.find()) {
throw new IllegalArgumentException("The id should be within parenthesis and quotes.");
}
Any help ? | You need to include the key part also in the regex or just `"\\{\"([a-zA-Z\\d$]+)\":"` because `[a-zA-Z\\d]+` won't match the inbetween `:` and there isn't a closing curly brace immediately following the key part.
final Pattern p = Pattern.compile("\\{\"([a-zA-Z\\d$]+)\":\"([^\"]*)\"\\}");
Matcher m = p.matcher("{\"$oid\":\"5527b117d3d511091e1735e2\"}");
if(m.find())
{
System.out.println("Key : " + m.group(1));
System.out.println("Value : " + m.group(2));
}
**Output:**
Key : $oid
Value : 5527b117d3d511091e1735e2 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, regex"
} |
Clion, Autotools and JNI
I'm trying to setup a little JNI demo with Autotools using the Clion IDE. The problem is: I don't know how to tell Autotools to include jni.h. Also Clion does not resolve the #include <jni.h>.
This is the bare minimun example I'd like you to tell me how to fix demo. | The $JAVA_HOME must be set.
The fixed configure.ac looks like this:
AC_INIT([helloworld], [0.1], [[email protected]])
AX_JNI_INCLUDE_DIR
for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
do
CFLAGS="$CFLAGS -I$JNI_INCLUDE_DIR"
done
AM_INIT_AUTOMAKE
AC_PROG_CC
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
CLion will then include the jni.h correctly. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, c, java native interface, clion, autotools"
} |
Should I build my own parts for making PCB with eagle or is there a database somewhere?
I'm trying to build a custom PCB for a project I'm working on. I'm building a small robot that navigates using a color sensor and moves using two motors. For logic I'm using an Arduino Nano. My problem is that I can't find the following parts:
1. 28BYJ-48 5V Stepper Motor.
2. TCS3200 color sensor.
I've found this site, but cant find them there. I also tried to search github, but with out any luck.
It seems strange to my, if nobody else have made a stepper motor and then shared it?! So I'm wondering if I'm looking in the wrong places?
Another question is of its worth the trouble to learn to make my own parts with Eagle? | Parts are difficult to make standard; depending on technology used to make a PCB certain features must be resized while certain other features must stay the same. Also, the libraries included with the editor are often too large to be useful - you spend more time looking for a part than what it would take to draw one from scratch. On the other hand, redrawing everything would be silly. Make your own libraries, copy included parts as needed, i.e., only ones you're actually using, and draw the parts which are not included. Sparkfun has nice tutorials on Eagle libraries. | stackexchange-electronics | {
"answer_score": 1,
"question_score": 0,
"tags": "pcb design, components, stepper motor, eaglecad"
} |
Подписка на событие от Yandex Map
Хочу подписаться на событие `Update` в Yandex Map. Не могу понять как? В доках не указанно. Если просто написать
map.Update = UpdateHandler;
Не катит. При этом
map.Update()
Это уже вызов ф-и `Update`. | Надо делать так:
YMaps.Events.observe(map, map.Events.Click, UpdateHandler);
Подробно можно посмотреть в примерах. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "yandex maps api"
} |
Qt - how to detect what application is in focus
Is it possible to know what application is in focus using Qt ? | You'll need to use some Win32 API functions. Mainly GetActiveWindow(). Search MSDN for the function. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, qt, qt4"
} |
recurring condition blocks SQL
> I want to create a recurring IF ELSE or FOR LOOP condition blocks as per below conditions
>
> I have a "created Date" column in a Data Table
I want to implement below condition
0-5 days from created date
print text1
6-10 from created date
print text2
11-15
print text3
16-20
print text4
21-25
print text1
26-30
print text2
> and so on..
> so after 20 days 1st text gets gets printed again and like that for 4 set of text after every 5 days. | In SQL Server you can use CASE WHEN
SELECT name, total,
CASE
WHEN datediff(day, createdDate, getdate()) <5 THEN 'Almost Due'
WHEN datediff(day, createdDate, getdate()) BETWEEN 6 AND 10 THEN 'Due Now'
...
WHEN datediff(day, createdDate, getdate()) >20 THEN 'PAY NOW!!'
END as discount from invoice
or in you complex issue
SELECT name, total,
CASE (datediff(day, createdDate, getdate()) % 25)
WHEN <5 THEN 'Almost Due'
WHEN BETWEEN 6 AND 10 THEN 'Due Now'
...
WHEN >20 THEN 'PAY NOW!!'
END as discount from invoice | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, loops, if statement, for loop"
} |
Silverlight DataGrid databinding problem
Say I have a table name is MyData, the I have a column have the same name MyData. so the table looks like
MyData(ID, MyData, Col3, ....)
Using EF and Ria Service to get data from DB and bind data to a datagrid like:
<data:DataGridTextColumn Header="ID" Binding="{Binding ID}" />
<data:DataGridTextColumn Header="MyData" Binding="{Binding MyData}" />
<data:DataGridTextColumn Header="Col3" Binding="{Binding Col3}" />
...
then run it, I can get all data displayed for all other columns except MyData column. Nothing displayed for Mydata.
How to resolve this problem? | It looks like you have an object called MyData and then a property with exactly that name, try change the name of your table and see if it works... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "silverlight"
} |
Moving the bounds of a Word commentary
Can I somehow change the bounds of an existing comment in Word (2003)? Rewriting parts of the text that are marked by the comment removes that text from the comment's selection, but that's not what I want. | I understand that you want to expand the selection of text which marked by a comment without removing and adding that comment again.
I haven't found any way to do this other than deleting the text (which is not a good solution). I see there is another open question about the same thing where someone created a macro for the task which might be of help to you. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "microsoft word, microsoft word 2003"
} |
What causes the 'uncertainty' when a block is still relatively new
I am currently looking into bitcoin and the underlying blockchain technology for an internship. More specifically, I am trying to grasp the confirmation process. Many sources I have used for my research state that after 6 blocks, a transaction is 99.9% valid.
My question is: where does the 0.01% uncertainty about a transaction stem from?
Many thanks in advance. | An attacker could try to mine a chain of 7 blocks that would not include that transaction. That chain would replace the one where the transaction happened and "undo" it.
However, doing this is very hard, it requires the attacker to control a significant amount of hashpower and isn't guaranteed to work 100% of the time since while the attacker is mining, the other honest miners are also mining. Satoshi ran some numbers (albeit his calculations were off) in the whitepaper, section 11.
The more blocks your transaction is buried under, the higher the certainty is. It exponentially increases with every block that confirms your transaction. | stackexchange-bitcoin | {
"answer_score": 0,
"question_score": 0,
"tags": "transactions, unconfirmed transactions, confirmations"
} |
Set default net type to none only for one file
In SystemVerilog, you can set the default net type to `none` like this:
`default_nettype none
That affects the rest of the compilation units, which may consist of multiple source files. If you want it to only affect the current file, you have to set it back to `wire` at the end:
`default_nettype none
// Your code here
`default_nettype wire
But, that is not ideal. It will always reset it to `wire` even if it was already `none`. Is there a way to restore the value that it had before it was set to `none`? Similar to C++'s `#pragma push()`. | This is a general problem with all compiler directives in SystemVerilog, not just ``default_nettype`. There is no pre-processor stack. There are a couple of things you can do to work around this problem.
* Set up your compilation scripts to separately compile your files, or
* Some tools have setting similar to C compilers that compile each file on the command line into a separate compilation unit.
* If you still need everything in one compilation unit, you could do
`define MY_GLOBAL_NETTYPE \
`default_nettype none
* Then use that macro and the end of the file | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "system verilog"
} |
Simple trigonometrical equations
I'm having difficulties in solving the simultaneous equations $$ \begin{cases} \sin(x+y)=\frac{1}{\sqrt{2}}\\\ \cos(2x+y)=\frac12 \end{cases} $$ for $0^{\circ}\le x,y\le 90^{\circ}$.
The answer is $x=15^{\circ}$ degrees and $y= 30^{\circ}$. | $x+y=45$
$2x+y=60$
Solving, we get $x=15, y=30$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "trigonometry, systems of equations"
} |
Windows 7 access rights - Remote desktop connection vs. "real" login
Is there any (implicit) difference of access right depending on whether
1. I directly logon to a Win 7 system
2. or whether I do this via a remote desktop connection
as the same user.
I wonder, because I cannot delete some files, message is that I "require permission from xyz to make changes to this folder". But this exactly the user I am using for the remote desktop connection.
The Win 7 system is not part of a domain, I use "computer\xyz" for login. | There is no difference. Windows 7 does not have "remote" and "console" sessions as such, in laymens terms, it _only_ has remote sessions, and then it attaches that remote session to your local keyboard/monitor/mouse. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "windows 7, remote desktop, access control"
} |
Covariance of three dice rolls
I understand this question has been asked but I have a different comment to make on the matter and wondering if someone could help me.
Let Z1,Z2,Z3 be values resulting from three tosses. X=Z1^2+Z2^2+Z3^3 and Y=4X-7. What is the correlation coefficient. Now I've reduced the Covariance equation to be 4Var(X) making the correlation coefficient 4Var(X)/(S.D(X)*S.D(Y).
My question is there a simpler way to calculate the variance of X and Y rather than compute all the different possibilities by hand and compare them to the expected values of X and Y which I have computed properly.
So could the variance of x = V(Z1)^2+V(Z2)^2+V(Z3)^3
Sorry if this is dumb I feel I'm missing a much simpler way of calculating these rather than computing every combination of Z1,Z2,and Z3 and comparing it to the expected value.
Thanks! | You're almost there. The useful rule is the following: $$ \text{Var}(aX+bY+c)=a^2\text{ Var}(X)+b^2\text{ Var}(Y)+2ab\text{ Cov}(X,Y) $$ Apply it to your $Y$ variable: $$ \text{Var}(Y) = \text{Var}(4X-7)=4^2\text{ Var}(X) = 16\text{ Var}(X)\\\ \sigma(Y) = 4\sigma(X) $$ Now write the correlation coefficient: $$ \rho(X,Y) = \dfrac{\text{Cov}(X,Y)}{\sigma(X)\sigma(Y)}=\dfrac{\text{Cov}(X,4X-7)}{\sigma(X)\sigma(4X-7)}=\dfrac{4\text{Cov}(X,X)}{4\sigma(X)\sigma(X)}=1. $$ | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "correlation, covariance"
} |
Make last view fit to bottom of screen
is there any possibility to change the properties of the last view in the layout to change its size to fit to the bottom of the whole screen (in any screen density).
Here is a sample image of my layout:
!enter image description here
The layout contains a ScrollView with a LinearLayout as only child. The last item in this LinearLayout is a TableView with a grey gradient as background. | You can try setting `layout_height` of your items to `"fill_parent"` and change their sizes via changing `layout_weight` property, that should work. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, layout"
} |
ASP.NET Web API 2 compatibility
I´m working with web servicesrest, I now that exist web api 2 but the question is,
Is it possible to install WEB API II on a Windows Server 2012 64BITs, with framework 4.5, ISS v.8? | Yes, ASP.NET Web API 2 is supported on IIS 8. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "asp.net web api2, iis 8, windows server 2012, asp.net 4.5"
} |
What's wrong with this amount and Paypal?
I am passing **122.385** as an amount to paypal and the response is
> The link you have used to enter the PayPal system contains an incorrectly formatted item amount.
Where is the problem?
Thanks in advance | The number of decimal places needs to be exactly what the payment vendor is expecting, it seems that paypal expects to be given a rounded figure of 2 d.p.
Reference: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "paypal"
} |
superimposed histograms in matplotlib
I know how to make histograms but I wanted to reproduce this image:
!Imgur
The original is form a PNAS (journal) paper by Andrew Karplus et al. 2011.
I have the following image from my own histogram:
 How can I start the plot with histogram smoothed out?
2) How can I superimpose but yet not distort the color as I have done in my plot (2nd image), that is omit the points in the exterior plot that are in the interior one as well to produce a clean superimposition? | You could use `fill_between`:
import numpy as np
import matplotlib.pyplot as plt
def gaussian(x, x0, y0, variance):
return y0 * np.exp(-(x - x0) ** 2 / variance)
x = np.linspace(150, 210, 100)
plt.fill_between(x, 0, gaussian(x, 180, 5000, 30), color='red', zorder=0)
plt.fill_between(x, 0, gaussian(x, 181, 4500, 10), color='blue', zorder=1)
plt.show()
yields
!enter image description here
* * *
Above I used `gaussian` to generate a substitute for your data; you can replace `gaussian(...)` with your actual histogram values. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, matplotlib, histogram"
} |
Custom Table Mapping with Sequel gem
Been spinning my wheels. How would one specify a custom table mapping with the sequel gem?
I've done the following
init.rb
OTHER_DB = Sequel.connect(:adapter => 'tinytds', :host => 'host1', :database => 'mydatabase', :user => 'myuser', :password => 'mypassword')
Namespace::MyModel.db = OTHER_DB
MyModel.rb
module Namespace
class MyModel < Sequel::Model('myschema.MyModelTable')
end
end
It complains about the 'myschema.MyModelTable' in the constructor. I've also tried set_dataset('myschema.MyModelTable') with no success.
The docs seem to be a bit opaque on how to do this | I solved this with the following code
module Namespace
class MyModel < Sequel::Model(Sequel.qualify(:myschema,:MyModelTable))
end
end
More examples can be found in the tests here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby, sequel, sequel gem"
} |
HyperV Migration and DHCP Reservation
In my company network we've 2 HyperV-2012 host with DAS, every server has a DHCP reservation in the DHCP server (windows server 2008).
Yesterday we've migrated (using shared with nothing migration) several virtual server from Host A to Host B.
The migration run smoothly but when a migrated Virtual Server was rebooted it didn't take the correct ip from DHCP because its mac address was regenerated dynamically by HyperV.
How can i resolve or mitigate the problem?
Consider my DHCP runs on windows server 2008 r2 (a domain controller) so i don't have access to the latest DHCP features introduced by Windows server 2012 (which howerver don't seem to help with my situation/scenario)
Thank you in advance for your kind replies. | Set the MAC address on the VM vNIC to static in the Advanced Features of the vNIC. The MAC address should then persist across all hosts for that VM. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "hyper v, dhcp, windows server 2012, dhcp server, hyper v server 2012"
} |
Node.js script not executing from crontab
I have a crontab entry that is supposed to execute a node.js script like this:
`*/5 * * * * node /home/campaigns/reporting/UNIT_TESTS/testCron.js > /home/campaigns/reporting/UNIT_TESTS/cron.log`
However, it doesn't execute and the log file isn't updated. When I run the script manually, everything works though. Any ideas??
Thank you, Igor | Try making a script with the command:
`script.sh`:
#!/usr/bin/env sh
node /home/campaigns/reporting/UNIT_TESTS/testCron.js > /home/campaigns/reporting/UNIT_TESTS/cron.log
and then adding that to cron:
*/5 * * * * /path/to/script.sh
make sure to make the script executable (`chmod +x script.sh`) | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": "node.js, cron"
} |
JQuery: A div content that scrolls endlessly?
I have a simple JQuery function that makes a DIV's content scroll sideways, endlessly. It works fine, but when it reaches the end of the content, it keeps scrolling but nothing is shown, which is to be expected since the content is finished. I want to make it repeat, so it will never stop scrolling and when the content is done, it repeat itself.
So far, the only way that way I figured to do this is by duplicating the div content by many times, ie:
var element = $("#divContent")
for(var x=0; x<=50; x++)
element.html( element.html + element.html );
I think this will work, but there's gotta be a better way of doing this. | If you initially create 2 versions of the content - when the first item goes completely out of view you can move it to become the last item using css (you can just use a relative or absolute positioning). I've made an animation to illustrate how it works. You have to set `overflow:hidden` on the parent container (#wrapper in the example) and restrict it's width for this to work properly.
!animation | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery"
} |
Unmanaged 64-bit DLL copied to SysWOW64 and not System32 by Visual Studio
I have a driver I have written in unmanaged C++ using Visual Studio 2010. When compiling the DLL on a 64-bit Windows 7 the post-build step is:
echo Copying $(TargetFileName) to the OS's 64-bit system folder ...
xcopy $(TargetPath) $(SystemRoot)\System32\. /Y /Q
However, the dll is copied to $(SystemRoot)\SysWOW64\ instead, which supposedly only happends to 32-bit assemblies.
BUT! If I copy the dll to System32 using Windows Explorer or with xcopy from a command shell the dll is correctly placed in the System32 folder. What am I doing wrong? Is it because Visual Studio is a 32-bit program and the POST-BUILD event is run in context of that 32-bit process? | Your script is being run from a 32-bit process. As a sort of band-aid solution you should be able to replace `system32` with `sysnative` and the WOW64 layer should do the right thing.
**Update:** Sorry, maybe this instead: `%windir%\sysnative\cmd.exe /C "xcopy ..."` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c++, visual studio 2010, windows 7, 32bit 64bit, unmanaged"
} |
Shopify: Adding customer[tags] on login form
At registration i add a language tag using the customer[tags]
<input type="hidden" name="customer[tags]" value="lng:fr">
I added the same script to customer_login form to update old customer but it does not seem to work.
Any idea ? | You can't add tags on login, only at register.
This is limitation set by Shopify.
If you like to create a tag on login you will be required to create a custom APP that will handle this, there is no default way to achieve this only liquid. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "shopify, shopify template, shopify api"
} |
Get the associated name of two database columns of the same type
My schema is as follows:
* The `airports` table holds airport names. It's primary key is an integer, `id`.
* The `flights` table holds flight data. It has two foreign keys, `departure_airport_id` and `arrival_airport_id`
I am trying to get the names of both the departure- and arrival airport on a flight. Right now my SQL is as follows:
SELECT name AS departure_airport, name AS arrival_airport FROM flights, airports WHERE departure_airport_id = airports.id OR arrival_airport_id = airports.id
I can see how this is ambiguous since the database can't know that by `departure_airport` I mean the name of `departure_airport_id` and by `arrival_airport` I mean the name of 'arrival_airport_id', but what is the correct way to get the names of both airports on a flight record? | JOIN twice from flights onto the airports table, like so:
SELECT dep.name AS departure_airport, arr.name AS arrival_airport
FROM flights f
JOIN airports dep ON f.departure_airport_id = dep.id
JOIN airports arr ON f.arrival_airport_id = arr.id | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql"
} |
How could I switch data connections in case of server failover?
Here is the scenario. I want to be able to switch the end users database connections automatically in case we ever have to switch to our backup SDE server. My first thought was to set up sde connections to the backup server on the users machines, then write a batch file that would simply rename the connections to the users standard connections. I'm hoping to find a more automated solution. Ideally find some way to tell if a connection can't be made, then switch to the alternate connections. Has anyone implemented something like this? Any help much appreciated. | I think you'll have to configure some major database pooling, so that your two servers appear as one. Then, connecting clients won't (and shouldn't) know which server they are actually connecting to, and you can tinker with the back ends as much as you like.
Now, this is only an ideal solution if your backup is for availability - or if you want to take the machines offline and online as you see fit. If your backups are for data integrity (recovering from the oops-I-deleted-it-all), then pooling won't work, as the accidental deletes will automatically be propagated to all nodes. | stackexchange-gis | {
"answer_score": 5,
"question_score": 6,
"tags": "arcgis server, arccatalog"
} |
How to call onDraw from onChange of TextEdit
I am using the solution provided by the accepted answer in this question:
Android - How to make all lines in an edittext underlined?
The problem is that the `onDraw()` method is only drawing lines when loading the view using the following count
int count = (height-paddingTop-paddingBottom) / lineHeight;
This will not draw lines when the user keeps writing until we exceeds the number of counted lines. I need to execute the `onDraw()` again or find a better brilliant way to draw a new line whenever the user starts a new one.
!enter image description here | In this case is your View updated only when application is loading or when screen configuration changes. If you want to update the View at specific time you do not call onDraw() directly, but you call method View.invalidate(). Then UI thread will redraw the view as soon as possible. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android"
} |
Identify connector - fan header
I am trying to identify the following male connector to find a female counterpart. I do not believe it is a JST connector, and the website I found the matching picture on for my part does not list the connector type. It's typically used on small form factor fans.
;
void setSampleProperty(int sampleProperty);
}
public interface ModelFactory extends AutoBeanFactory {
AutoBean<SamplePojo> getSamplePojo();
}
And SamplePojo has a int property that we always want to default to 5. | AutoBeans should be seen as low-level, mapping straight to/from JSON. With that in mind, you don't want `getSampleProperty()` to _be_ 5, you rather want to detect the absence of specific value for the property and _use_ 5 in that case.
So, if `0` (the default value of an `int`) is not an acceptable value for the property, then simply "use 5 if the property is 0". Otherwise, change the return type to `Integer` and "use 5 if the property is `null`". | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "gwt, autobean"
} |
Safely generalize ST return value
I have an ST extractor `foo :: (forall s . ST s a) -> b` for some concrete `a` and `b`. Could I safely make another function `fooC :: (forall s . ST s (a, c)) -> (b, c)`, which would allow me to return some additional value out of the ST computation? Can there be a generic transformation `addC :: ((forall s . ST s a) -> b) -> (forall s1 . ST s1 (a,c)) -> (b,c)` which would be safe to use? | I'm not really sure I understand what you're trying to accomplish, but this has the right type:
addC :: ((forall s . ST s a) -> b)
-> (forall s1 . ST s1 (a,c)) -> (b,c)
addC f m = runST $ (\(a,c) -> (f (pure a), c)) <$> m
Note that `(forall s. ST s a)` is isomorphic to `a` (as witnessed by `pure` and `runST`), so maybe you should just take a function `a -> b` and a value `(a, c)`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "haskell"
} |
What is this circular orange spot in GNOME's top bar menu?
My cat walked through the keyboard and now there is this weird orange dot/spot/circle alongside the network, Bluetooth, sound and battery icons:
![Alongside with network, Bluetooth, sound and battery notifications, there appears an orange dot.](
What is this? | It means that you are **recording your screen** , the keyboard shortcut to start / stop it is `CTRL`+`ALT`+`Shift`+`R`.
As pomsky suggests: The videos get saved to a default folder, which, in most cases, is your **Videos** directory. | stackexchange-askubuntu | {
"answer_score": 15,
"question_score": 14,
"tags": "gnome shell, indicator"
} |
Subsets and Splits