INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
how do I bzr branch to an existing directory?
I would like for my collaborators to be able to branch a project to an existing directory, since many already have the 'dir' directory which mirrors my own and I would prefer to minimize path lengths...
However, bzr won't let me do this:
mkdir dir
bzr branch ~/project/trunk dir
Is there a way around this? | mkdir dir
bzr branch ~/project/trunk dir --use-existing-dir | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "bazaar"
} |
How do I make my Eclipse project a Java project?
I am again at the point where I believe my uni wants to freak me out. My uni just threw this eclipse project at me and I am supposed to run it as a java application. My uni says this is trivial but for me it is not!
So here it goes: They gave me a zip archive and I imported it by `Import` `Existing Projects into Workspace` and then selecting the zip archive. It all went well, however, I am not able to run it as a Java application. Also, I noted that the folder `JRE System Library` was missing.
Can someone explain me what this all means and how I can solve this problem? My uni did feel like explaining a lot... | Right-click the project, and select properties. On the build path menu, add the system library->JRE.
You can then try to run the project as follows: Click the dropdown arrow next to the run button, and pick run configurations. On the left, add a new configuration, and select its project to be the project you imported. Also select the main class accordingly. You can now run this configuration and it should run the project.
Edit: This may not work depending on the configuration. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "java, eclipse"
} |
Is it possible to create an artificial bee hive?
I play Terraria with a 1.2 generated world. It has a lizhard temple but it doesn't have any bee hive, so I need a way to create it, with or without map editing tools like TEdit. | If you can import a hive wand, some hive blocks, hive walls and many buckets of honey you can sort of build a hive, but it will not contain a Queen Bee summoning object. If you just want to fight the Queen Bee for her drops, you can create an Abeemination with imported or cheated-in materials and use it to summon her. | stackexchange-gaming | {
"answer_score": 2,
"question_score": 3,
"tags": "terraria"
} |
Is there a free way to activate SCL RHEL 7
I wish to use the software collection of RHEL 7, but it seems theres is not free way to do that. Anyone knows ?? | You need to register as a developer to download the SCL | stackexchange-unix | {
"answer_score": 2,
"question_score": 1,
"tags": "rhel, scl"
} |
Pug dynamic image src interpolation
I have stored a dynamic url link into a pug variable #{img}. Now I want to include that variable into my image element. Can anyone help me fill in the blank?
#{img} //some dynamic url
img(src=" ") //want to set src = #{img} | do it like this
- var img = "img/test.jpg"
img(src=img)
and read this | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 5,
"tags": "pug, pugjs"
} |
flutter 'MySQL' is not recognized as an internal or external command
I got interested in flutter and went ahead to install as per the guide on the website and go this error during running it on CMD
'MySQL' is not recognized as an internal or external command,
operable program or batch file.
'MySQL' is not recognized as an internal or external command,
operable program or batch file.
Error: Unable to find git in your PATH.
That's really weird since Flutter doesn't use MySql in any way. My `git` runs fine with no problems and also `node` is fine. I have seen the issue filed with no answer. GITHUB
If you have fixed this issue please post your answer. | Unfortunately, the Zip provided on flutter.io gave me a problem. To avoid this error, I had to use the GitHub repository following the following procedure.
1. Go to C:\ Drive and create a folder called flutter.
2. Go to that folder and start git bash
3. Type `git clone -b beta and enter
4. After its complete, add the path `C:\flutter\flutter\bin` in environment variables
5. Finally, start CMD and type flutter doctor and the error is disappeared
* * * | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "flutter"
} |
Export database from control panel or Sequel Pro? What's the difference?
Since I am involved in a multi-developer, version-controlled setup, I do a lot of database importing and exporting from environments.
I notice today that when I export a database from one of our sites using the control panel "Backup Database" function, it comes out at about 3.6MB and takes about 5 minutes to import.
When I export from Sequel Pro, the database dump comes out at about 1.6MB and imports within 30 seconds.
Note, I always dump the existing tables before import.
Just wondering what the difference is here that there is such a difference in file size and import time and which way is best?
Thanks! | The difference in both size and speed is likely because Sequel Pro (and any other MySQL client) is likely using mysqldump, which is a native CLI command and highly optimized.
Craft can't rely on that for a variety of reasons (PHP might have have exec permissions, the account Craft uses to connect to the database might not have the permissions necessary to perform a backup, etc.)
So Craft has it's own fallback where it manually analyzes the database's DML and DDL and writes it out to a file.
Slower? Yes. Larger file size? Yes. More reliable for Craft? Yes.
It is on our list somewhere to check if Craft has the ability to access `mysqldump` and use that, if not fall back to our current method. | stackexchange-craftcms | {
"answer_score": 10,
"question_score": 7,
"tags": "database, multi environment"
} |
How to get all records within the last Two Days from the current Date using EF 4?
EF 4 in C#.
I have my query, at the moment I'm able to filter the result by the current Date (just date not considering TIME).
I need to filter the result **FROM the last two days TO the current Date** (no idea how to do it).
I tried in my query `currenteDate - 2` but without success.
Could you please give me an example? Thanks for your time on this.
DateTime currenteDate = DateTime.UtcNow.Date;
var contents = from cnt in context.CmsContents
where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date == currenteDate
orderby cnt.ContentId descending
select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent }; | For changing current date you need use `currenteDate.AddDays(-2)`. And use `>=` instead of `==` to get all records from 2 days before and till the last record
DateTime currenteDate = DateTime.UtcNow.Date.AddDays(-2);
var contents = from cnt in context.CmsContents
where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date >= currenteDate
orderby cnt.ContentId descending
select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent }; | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 7,
"tags": "c#, linq, entity framework, entity framework 4"
} |
math.stackexchange has so many good mathematicians, were you all good at maths since school?
I'm afraid this question will be kicked out but I have to ask this. Were you all mathematicians brilliant and had good maths brain since you were kid? I was very bad in maths when I was in grade 8 then got better at it till high school. But I've been programming for 6 years after graduation and now getting back to do Research degree. I find myself to be stuck, can't make sense of anything, even basic stuffs. Does that mean I am not good at maths? or may be it isn't my cup of tea? | Without knowing more about your background and your teachers and the curriculum that you've been subjected to, it's hard to say much in specific. However, I **highly recommend** that you read (at least the first dozen pages of) Paul Lockhart's essay: _A Mathematician's Lament_.
Enjoying mathematics is key, and the world is awash with misconceptions about what that is. Creativity and an appetite for solving problems is probably more important than having excellent memorization and procedural skills; the latter skills are, unfortunately, often mistaken for being "good" at math. | stackexchange-math | {
"answer_score": 10,
"question_score": 12,
"tags": "soft question, education"
} |
How can I create a Date Range from a single column?
I am trying to query a database that has these params:
Transaction Date, User Email Address
The resultant table I want is these params:
Email Address, dateDiff
For dateDiff, I want to find the difference between the earliest transaction date and latest transaction date.
How would I go about doing this?
My code (clearly not correct)
SELECT [Email Address], DATEDIFF(day, [Transaction Date],[Transaction Date]) AS 'dateDiff'
FROM [DB].[TABLE]
ORDER BY [dateDiff] Desc | You need an aggregation to get the minimum and maximum values for each email, before doing `datediff()`:
SELECT [Email Address],
DATEDIFF(day, min([Transaction Date]), max([Transaction Date])) AS 'dateDiff'
FROM [DB].[TABLE]
GROUP BY [Email Address]
order by 2 desc; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "sql, sql server"
} |
Is there a way to force install4j auto updater to update the current version?
I've been iterating versions of my application trough beta and install4j auto-updater was updating successfully trough versions (2.1 -> 3.0b0 -> 3.0b1 -> 3.0b2). Now I've published version 3.0 and auto-updater is refusing to recognize the new version. Now, I know that there is an option that allows you to customize update scheme but it's too late now since I didn't know that when I was publishing older versions. I've played around with it and it updates to 4.0 and 3.0b3 but fails to recognize 3.0, 3.1.
So, is there a way to force auto updater to update by manipulating the new update.xml file?
EDIT: I have version 4.2.8 of install4j installed. | Unfortunately not. install4j 5 will correctly update from 3.0b2 to 3.0, but in install4j 4 you would have to modify the updater logic, so you would first have to release a 3.0b4 to do that. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "auto update, install4j"
} |
CRM- Getting total of field from all related entity from parent entity
Hi I have a parent entity "Entity A" and it has a one to many relationship with "Entity B". I have a specific integer field which exists in all instances of the related Entity B that I would like to total in "Entity A". How would I achieve this through CRM Javascript? I am thinking it needs a loop to grab all instances of Entity B, and then retrieve the value into an array. Any examples?
In short: Entity A needs a field that shows the total of specific value from related entities.
If anyone has an example, I will award bounty. | To answer my own question, I used a retrieveMultiple to do this and pushed the values into the parent entity. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "javascript, entity, relationship, crm"
} |
Programmatically rewrite URL with Java
My app is built with Google Guice for handling mappings of servlets.
Is it possible to map a resource:
`user.myapp.com` to `myapp.com/user` without using Apache Mod Rewrite and any Server container component like it?
The idea being my backend is Google App Engine (GAE). | GAE allows the use of Servlet filters. Hence, I suggest you make use of that by configuring the UrlRewriteFilter. Essentially it's `mod_rewrite` for Java. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, servlets, jax rs, guice"
} |
Confusion in perl print behaviour
I am confused with the behaviour of 'print' function. The below one is my code :-
$var1 = "VARIBLE";
@arr = ();
push (@arr,$var1);
And when I add print function to the above code,
print @arr;
It gives 'VARIBLE' as output. But When I replace the above line with the below line,
print @arr."\n";
It gives out '1' as output. Could someone tell me what is actually going on? | It is because you are _concatenating_ `@arr` with `\n`. This essentially says that you want to treat `@arr` as a scalar so that it can be concatenated to another scalar, which is `1` in this case because there is one element in the array. See here for more information about how context affects the interpretation of a variable.
What you probably want is:
print @arr, "\n"; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "perl, printing"
} |
Cisco Catalyst 2960 X MAC access list
I am using a MAC access list on this switch, so I go about it by first creating the MAC access list:
#conf t
#mac access-list extended aclname
# permit host XXXX.XXXX.XXXX any
Then, I tie this list to all/one port:
#conf t
#interface gigabit 1/0/Y
# mac access-group aclname in
So, any traffic coming towards port Y gets checked against the MAC access list, to check if the source is allowed to enter.
Then i do a `#clear mac address-table dynamic`
I have done this to many site offices, but there is this particular site which has about 80+ devices that is driving me crazy, this site has a larger number of devices than the rest sites. So everytime i add a mac, another device gets disconnected.
I guess my question is: Is there any limitation on this access list? How many? How do you propose I overcome this? | It sounds like you are running out of the limited TCAM space. You could change the SDM. If you are not using this as a layer-3 switch with routing, you could use the `sdm prefer access` command to increase the TCAM space for ACLs. This command requires you to reload the switch for it to take effect.
This seems like a lot of work for little to no gain. It is very simple to spoof or change a MAC address in a host. Trying to restrict access based on MAC addresses is a fool's game. Anyone could waltz in there and clone a MAC address for his device to connect to your network. There are much better ways to do this. See this question, its comments, and its answers. There are also other question and answer on this site if you search. | stackexchange-networkengineering | {
"answer_score": 3,
"question_score": 4,
"tags": "cisco, switch, mac address, cisco catalyst, security"
} |
Creating a Parse.File with Javascript SDK
I've followed the letter of the law (Javscript SDK) along with numerous variations but thus far I have not been able to save an image to a Parse.File. I'm starting think this is code they never finished before they abandoned the platform?
This is my error: Failed to construct 'File': 2 arguments required, but only 0 present.
This is my code:
var base64 = $base64.encode(unescape(encodeURIComponent('a string')));
var file = new Parse.File("logo.png", { base64: base64});
file.save().then(function(){
var newLogo = new Parse.File();
newLogo.set('step2.png', file);
newLogo.save().then(function(){
offer.set("Alogo.png", newLogo);
offer.save();
}).then(function(){}, function(error){console.log(error);});
});
It saves no image or note of 'Alogo.png' or anything dealing with a logo in my ParseDB. Any help you could offer would be much appreciated! | For once, Parse was right on point. The issue was not with my code but with Angular and it's lack of recognition of 'file' tags in html. This post/tutorial proved very useful as it has a directive that enables angular to recognize post tags so that angular can add files to the model.
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, parse platform"
} |
How to Insert data into a table with sqlmap using its sql-query command
I'm using sqlmap on a test site and I wanted to modify some of the data inside of a table. Using the switch `--sql-query`.
* What is the correct syntax?
example: is it `--sql-query="My_query_here"`?
or maybe it's `--sql-query='myqueryhere'`?
* How would I be able to modify multiple rows of data?
example: Say I wanted to replace all data with the words. Game Over
* Is it possible to drop in a shell? | Most databases do not allow you to just insert data using SQL Injection (Unless of course you are already in an insert query and even then you usually can't control the table name). You can't simply stack queries, that is only allowed in Microsoft SQL Server, PostgreSQL and comic books (like xkcd). You can use a sub-select or union select to access data from another table, and SQLMap is doing this behind the scenes.
SQLMap's real strength is in data exfiltration, and it has some tricks to get RCE. But, If you want something more complex, like a multi-staged attack that gives you a shell, then you need to write a multi-staged SQLi exploit like this one, which I wrote. If you want a deeper understanding of security then you need to write exploits to have that experience, take off the training wheels and be man (or woman or whatever). | stackexchange-security | {
"answer_score": 17,
"question_score": 13,
"tags": "sql injection"
} |
evaluate integral the simplest way possible
I want to evaluate the integration $\int \limits x \sqrt{\frac{x-1}{x+1}}dx$ ?
I tried putting $t = \sqrt{\frac{x-1}{x+1}}$ but that did not help !
Is there a quick and smart way to evaluate. | For the square root to be defined you need for instance $x\ge 1$, this suggest a substitution $x=\cosh(u)$.
The integral becomes $$I=\int\cosh(u)\sinh(u)\sqrt{\frac{\cosh(u)-1}{\cosh(u)+1}}\mathop{du}$$
Now using $\cosh(u)^2-\sinh(u)^2=1$ we get
$\displaystyle\int\frac{\cosh(u)\sinh(u)\sqrt{\cosh(u)^2-1}}{\cosh(u)+1}\mathop{du}=\int\frac{\cosh(u)\sinh(u)^2}{\cosh(u)+1}\mathop{du}=\int\cosh(u)^2-\cosh(u)\mathop{du}$
Just linearise the $\cosh(u)^2$ to get the result $$I=\frac u2-\sinh(u)+\frac 14\sinh(2u)$$
Finally use $\sinh(\cosh^{-1}(x))=\sqrt{x^2-1}\quad$ and $\quad\sinh(2\cosh^{-1}(x))=2x\sqrt{x^2-1}$
To get $$I=\frac 12\cosh^{-1}(x)+\sqrt{x^2-1}\left(\frac x2-1\right)+C$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "calculus, integration, rational functions"
} |
$\sin{x}$ or $\mathrm{sin}\ x$
I have been answering questions on Math S.E as well as Physics S.E.
Today I was pointed out for using `\mathrm` instead of using `\sin` by a fellow user.
So my question stands that, which of them is more visually appropriate for a reader and more acceptable:
# 1\. $\sin t$
# 2\. $\mathrm{sin}\ t$
as represented below:
? | Compare:
\documentclass{article}
\begin{document}
\[ x\sin^{2} (t) + x\cos^{2} (t) = x\]
\[ x\mathrm{sin}^{2}\ (t) + x\mathrm{cos}^{2}\ (t) = x\]
\end{document}
 in a code that looks like this
<div class="block">
<div></div>
<div></div>
<div></div>
<div>
<div></div>
<div></div>
<div>this one</div>
</div>
</div>
I tried `.block:last-child:last-child` but it didn't work. PS: I can't add css classes | You can use `.block div:last-child div:last-child`
.block div:last-child div:last-child{
background-color:yellow;
}
<div class="block">
<div>not</div>
<div>not</div>
<div>not</div>
<div>
<div>not</div>
<div>not</div>
<div>this one</div>
</div>
</div> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "css, css selectors"
} |
How to create a downloadable URL for a file placed in unix server?
I have a requirement where I need to create a downloadable URL for a file placed in the unix server and mail the link to multiple users.
I tried using :- - but the link is not working... Any help will be appreciated.. | If you want to serve a file via `http` you need to setup an http server like Apache to do that.
Maybe this digitalocean tutorial will help you to do that. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "file, unix, url, download"
} |
Условия на тип возвращаемого значения метода при использовании await?
Есть метод:
public async T Method()
{
T result = await doSomeStuff();
return result;
}
Какие условия должны быть выполнены для `T`, чтобы этот метод можно было вызвать:
public async void AnotherMethod()
{
await Method();
} | По идее, `await` можно использовать для любого типа, в котором есть метод `GetAwaiter`, возвращающий реализацию интерфейса `INotifyCompletion`:
public AlexsAwaiter GetAwaiter()
{
return new AlexsAwaiter();
}
class AlexsAwaiter : INotifyCompletion
{
public bool IsCompleted
{
get
{
...
}
}
public void OnCompleted(Action continuation)
{
...
}
public void GetResult()
{
...
}
}
Тип, возвращаемый `GetResult` и будет возвращаться из `await`.
Подробнее лучше почитать например в книге
> Дэвис Д. - Асинхронное программирование в C# 5.0 - 2013г.
или тут | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "c#, async await, tpl"
} |
why my image is moved instead of creating multiple images
I'm trying to show the same image on a few locations on my newly opened window using this:
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
for i in range(len(entities) + 1):
img = ImageTk.PhotoImage(Image.open(path))
panel = tkinter.Label(root, image = img)
panel.grid(row = i, column = i)
This indeed displays the first image, but only moves it around, instead of creating new images. How can I fix that? | found it!
I used a list instead, to store the images and then treat each one separately by changing my code to:
entity_images = []
for i in range(len(entities)):
img = ImageTk.PhotoImage(Image.open(path))
entity_images.append(img)
panel = tkinter.Label(root, image = entity_images[i])
panel.grid(row = i, column = i) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, tkinter"
} |
duplicate component onclick React
I"m new to react, I'm creating a registration from. I want the user to be able to click a button to add an additional person to the registration. I have a "person" component which holds the form fields, onclick I want to duplicate that component.
import React, { useRef } from 'react'
import Person from './Person'
function BookingForm() {
const registrationForm = useRef()
console.log(registrationForm.current)
let handleAddPerson = (e) => {
e.preventDefault()
registrationForm.appendChild(<Person/>)
}
return (
<>
<form ref={registrationForm} id='registrationForm'>
<Person/>
<button onClick={handleAddPerson} className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
</form>
</>
)
}
export default BookingForm | I would like to recommend you implement it using `state` instead of `ref`. Like below:
import React, { useState } from 'react'
import Person from './Person'
function BookingForm() {
const [persons,setPerson] = useState([<Person key={0} />]);
let handleAddPerson = (e) => {
e.preventDefault()
setPerson([...persons,<Person key={persons.length} />]);
}
return (
<>
<form id='registrationForm'>
{persons}
<button onClick={handleAddPerson} className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
</form>
</>
)
}
export default BookingForm;
Hope this will help you. Using state is better in this case. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "javascript, reactjs, jsx, redux toolkit"
} |
Get Service name from code
Hi All am trying to get current service name from my project installer i have added a basic installer to my service application and wrote my service name and Display name but i need to get the service name from code
i have tried to add method in project installer then call it but it does not work :<
public static string getname()
{
return ProjectInstaller1.ServiceName;
}
my error:=
> An object reference is required for the non-static field, method, or property 'myservice.ProjectInstaller.ProjectInstaller1' | If you're insisting on the `public static string getname()` definition, this _should_ work:
//assuming ProjectInstaller1 can be instantiated
return new ProjectInstaller1().ServiceName; | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "c#, service"
} |
solidity: stack limit reached 1024(1023) when trying to burn
my code is throwing that weird error when I try to call the _burn() function. I have tried everything but nothing seems to fix it.
Code: < | The EVM stack has 1024 slots available and every time a function calls another function, it reserves some space on the stack to store arguments, return values and local variables. The deeper is the call chain, the more slots you need and you eventually run out of slots if you go too deep.
Normally 1024 slots is plenty and this does not happen. The most common situation where you can get this error is if you have a bug that results in infinite recursion. I haven't analyzed your code in detail but at a glance I see some potential for a call loop that would go like this: `_burn()` -> `_transfer()` -> `_transferStandard()` -> `_reflectFee()` -> `_burn()` -> ... Or, instead of `_transferStandard()`, it could also go through one of the other`_transferXXX()` functions. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "ethereum, solidity"
} |
Return back from youtube to my android app
In my app, on a particular button click, the youtube application starts and some video gets played. This is the code for the same.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:0ee3R3tfdd4"));
startActivity(i);
Is it possible to close the youtube app when the video is finished and return back gracefully to my app (without the user pressing the back button) ? | **No** , it's not possible.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:0ee3R3tfdd4"));
startActivity(i);
Using this code you are open a third party youtube application, So you don't have any type of control over it.
You have to press Back Button to coming back to your application. Or integrate Your own `VideoView` in your application for display youtube video. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "android, android intent, youtube"
} |
How to set AutoFit() to all sheets of Excel in c#
How to set `AutoFit()` to all columns and all sheets of Excel in c#???
Excel.Range usedrange = wrkst.UsedRange;
int ct = usedrange.Columns.Count;
for (int i = 1; i <= ct; i++)
{
app.Columns[i].AutoFit();
}
the above code is not working for all columns and all sheets | Use this if you want to autofit for columns:
Excel.Range usedrange = wrkst.UsedRange;
usedrange.Columns.AutoFit();
if you also want for rows:
usedrange.Rows.AutoFit();
**Update**
You have to iterate through each sheet and set it
foreach (Excel.Worksheet wrkst in workBook.Worksheets)
{
Excel.Range usedrange = wrkst.UsedRange;
usedrange.Columns.AutoFit();
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "c#, excel"
} |
Golang exported type
Suppose I have a package within a package `github.com/user/foo`:
foo/
main.go (package main)
bar/
bar.go (package bar)
Now, within `bar.go` I would like to use an exported type from `main.go`.
package main
type FooBar struct {}
If I try to `import "github.com/user/foo"` I get cycled imports not allowed error. Is there any way to do this, other than to create own repo for `bar`, which I don't want. | You can separate it like:
foo/
main.go (package main)
foo/
foo.go (package foo)
bar/
bar.go (package bar)
then `import "path/foo/foo"` in bar.go | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "go"
} |
Determine the location(s) in character vector that match maximum number of matches from a match vector [R]
How can I test which element of a character vector (testvec) has the most words from another character vector (matchvec)?
testvec <- c("making words up here for a test significant words",
"this one is really important and significant/crucial",
"can you see which has most significant/important words?",
"this one isn't desired at all")
matchvec <- c("important", "significant", "crucial")
desired_result (since the second from testvec has the most words from matchvec)
[1] 2
If I change it so that two have the same max I want to return both indexes:
matchvec2 <- c("important", "significant")
desired_result2 (since the second/third from testvec have the most words from matchvec2)
[1] 2
[2] 3 | One possibility using `stringr` could be:
count <- str_count(testvec, paste(matchvec, collapse = "|"))
which(count == max(count))
[1] 2
The same with just `base R`:
count <- rowSums(sapply(matchvec, function(x) grepl(x, testvec)))
which(count == max(count))
Or if there are repeated words (as proposed by @Henrik):
count <- lengths(gregexpr(paste(matchvec, collapse = "|"), testvec))
which(count == max(count)) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "r, string, match"
} |
new OnClickListener() vs new View.OnClickListener()
When I want to add an argument to setOnClickListener for such as a button, I click on View.OnClickListener() from eclipse alarm, but eclipse types **new OnClickListener()** instead of **new View.OnClickListener()**. What is difference between these codes?
button.setOnClickListener(new OnClickListener() ...)
and
button.setOnClickListener(new View.OnClickListener() ...) | Eclipse automatically imports `View.OnClickListener` so you don't have to use the `View.` prefix.
If you `import android.view.View.OnClickListener;` you can just use `OnClickListener`
**but**
if you `import android.view.View;` you have to use `View.OnClickListener`
Check how your imports list changes and it'll make more sense. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, android, eclipse, onclicklistener"
} |
numpy where with array of tuples
Why can't I find the location of a tuple in an array? Afterall, the bottom expression prints `True`
foo = numpy.array([(5, 30), (5,), 5])
bar = numpy.where(foo==foo[0])
print(bar)
Prints `(array([], dtype=int64),)`
print((5,30)==foo[0])
Prints `True` | It's because:
import numpy
foo = numpy.array([(5, 30), (5,), 5])
bar = numpy.where(foo==foo[0])
print(foo==foo[0])
False
That's why you're getting an empty array. A list comprehension alternative is `[v for v in foo if v == foo[0]]` will result in `[(5, 30)]` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python, numpy, tuples"
} |
Open .tiff, set projection, then re-save in Python with GDAL
I am trying to set the projections of a .tiff file from another file with GDAL in Python. I successfully set the projections, but how do I re-save the .tiff afterwards?
Here is my code:
ds = gdal.Open('satellite_image.tif')
prj = ds.GetProjection()
roads = gdal.Open('road_lines.tiff')
roads.SetProjection(prj) | You need to open the second file in update mode, then dereference it to save and close it.
roads = gdal.Open('road_lines.tiff', gdal.GA_Update)
roads.SetProjection(prj)
del roads # save, close
Another method to apply a projection to a GeoTIFF file is to use the geotifcp utility. | stackexchange-gis | {
"answer_score": 5,
"question_score": 2,
"tags": "python, coordinate system, gdal, osgeo"
} |
mysql current time with 0 seconds
I want to insert/update data into a table with the current time, but I want the seconds to be 0, for example, '2014-06-27 23:36: **00** '. How do I achieve this?
I think MAKETIME() could somehow be involved, but I really have no idea how.
`CURDATE() + INTERVAL HOUR() HOUR + INTERVAL MINUTE() MINUTE` unfortunately doesn't work, which is not surprising.
Edit: final solution - `DATE_FORMAT(CURTIME(), '%Y-%m-%d %H:%i:00')`. | mysql> select date_format(current_timestamp(), '%Y-%m-%d %H:%i:00') as ts_zero_seconds;
+---------------------+
| ts_zero_seconds |
+---------------------+
| 2014-06-27 02:06:00 |
+---------------------+ | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "mysql"
} |
Firefox addon: How to show notification bar at the top of the webpage?
Can someone tell me how to popup a notification message inside a firefox addon like the one that Firefox displays to offer to store passwords? I am not talking about the alert boxes... | I think you want a notification box and notifications.
See this previous question for some example code. How are firefox notifications implemented? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "firefox addon, notifications"
} |
x-auth token in requests module
Here is my sample curl requests.
curl -g -i -X 'GET' ' -H 'User-Agent: ceilometerclient.openstack.common.apiclient' -H 'X-Auth-Token: {SHA1}e8198c33b3d1b0748fa3db5cd6821d33951d67c8'
I want to replicate the same requests using Python request module.
request.get('< is what im using but im not sure on how to pass the x-auth-token. | As @bereal suggest a simple search in the DOC and you will figure it out.
import requests
headers = {'User-Agent': 'ceilometerclient.openstack.common.apiclient',
'X-Auth-Token': '{SHA1}e8198c33b3d1b0748fa3db5cd6821d33951d67c8'
}
r = requests.get(" | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 2,
"tags": "python, python requests"
} |
Does a lambda call another lambda go through internet?
I have a lambda which needs to call another lambda in the same account. It could be in the same region or multiple regions. The call is direct lambda call `invokeLambda`. And both lambdas are not in VPC. I don't know whether the call is going through internet? Or the call is just inside internal network. | It goes over the internet. And the reason is that your function must invoke a **public** lambda endpoint:
> To connect programmatically to an AWS service, you use an endpoint.
This is the same reason why if one lambda is in a VPC, it can't invoke second one without NAT - can't access lambda public endpoint. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "amazon web services, aws lambda"
} |
Touchend event, back to touchstart state animated
I'm currently working with webkit and touch events.
I can get an element to swipe along the touch move, and get it back on touchend.
But whatever I try, it gets back to its original state without animation, so it's ugly.
var obj = document.getElementById('element');
obj.addEventListener('touchmove', function(event) {
event.preventDefault();
if (event.targetTouches.length == 1) {
var touch = event.targetTouches[0];
obj.style.left = touch.pageX + 'px';
}
}, false);
obj.addEventListener('touchend', function(event) {
???
}, false);
I've tried startnode, style, webkit-animation-name (that works outside touch events) and some other weirds ways, but it's still unanimated as hell.
Thanks for your help. | You can set an element to have a transition so that when you set a position it will take X amount of time for the element to move to that location.
.class {
-webkit-transition: left ease 3s;
}
During drag you will want to set it to 0s so that it follows your finger without a delay.
Example:
var obj = document.getElementById('element');
obj.addEventListener('touchmove', function(event) {
event.preventDefault();
if (event.targetTouches.length == 1) {
obj.style.webkitTransition = 'left ease 0s';
var touch = event.targetTouches[0];
obj.style.left = touch.pageX + 'px';
}
}, false);
obj.addEventListener('touchend', function(event) {
obj.style.webkitTransition = 'left ease 3s';
//Set position here
}, false); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, animation, touch"
} |
get a random query result and then sort it
I need to run an ORDER BY RAND query and then sort the resulting data set numerically. In other words I want a random set of data (in this case 7 numbers), but then I need to sort those 7 results numerically.
**After this code runs:**
if ($today == "Oct 31") {
$dayList = "halloween";
$stmt = $pdo->query("SELECT `rand` FROM `jukebox2014`
WHERE `class` = '$dayList' ORDER BY RAND() LIMIT 7");
}
**I need to sort the 7 results.**
Any ideas?
Thanks. | As simple as:
SELECT `rand`
FROM (
SELECT ... ORDER BY RAND() LIMIT 7
)
ORDER BY `rand`
Not that `ORDER BY RAND() LIMIT 7` is a rather inefficient method to select random data; more efficient methods will depend on your exact data. Search Stackoverflow for many questions regarding this topic. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, pdo"
} |
Ubuntu SDK: How do I implement a “onClick” for an image in QML?
I have a background image for my page, and I want to implement a sort of page refresh when the background is clicked. However, I didn't find any actions for the image element in QT quick.
What's the right way to implement this? | You need to use MouseArea to handle click events.
Image {
source: "myimage.png"
MouseArea {
anchors.fill: parent
onClicked: {
// do what you want here
}
}
} | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "qt, qt creator, qml"
} |
User Groups and Advanced Settings in 15.04
Ubuntu used to allow me to change user's groups and advanced settings within the "User Settings" GUI. These options are gone now in 15.04. Where do I go to find these settings?
(Using the command line is not an option for my use cases.)
This is the old dialog with "Manage Groups" and "Advanced Settings" buttons. !The old interface | sudo apt-get install gnome-system-tools
How to manage users and groups? | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 1,
"tags": "users, gui, settings, 15.04, groups"
} |
Netbeans on new build or run, terminate previous ones
I would like to terminate all things I've done when i execute a task - build, run. With that i mean tasks - process, which are shown below in tabs. | If I understand you correctly, you need to close the tabs by pressing the 'x' in the top right of the output window. This is found in the menu bar at the top 'Window-->Output'. The tab for output will contain the word 'run:' and will have a title similar to Output - Example(run)#1. Then at the bottom of Netbeans on the status bar there should be a progress bar with an 'x' at the end indicating any running projects. You need to close this also.
Or you can go to the menu bar at the top and select 'Run-->Stop Build/Run' | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "netbeans"
} |
Is iced coffeescript supporting or going to support promises?
As a node.js practitioner, I am actively using coffeescript and functions based on promises. Recently I have found out iced coffeescript, and I wonder whether my approach can go along with "iced await defer" one.
So here is my question, **is there any support for the promises implemented or planned for the iced coffeescript**? Or would rather iced coffeescript made me come back to the callback functions world?
Also as a side question, as far as my knowledge goes, there is an ECMAscript 7 draft to introduce await async patten to solve the issue. Is iced coffeescript team planning to blend on it if it will become standard?
Cheers. | Iced CoffeeScript development has stagnated lately. I regard ICS as interesting experiment - given its current adoption I would not really recommend using it. As for support or planned support there is none - there might be in the future but the issue tracker shows no issues discussing it have been opened.
ECMAScript 7 indeed has async functions - since those use promises there is no reason to assume any work is done in ICS to support them. Again - no one can tell the future and there might be work on those at a future point in time. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "node.js, coffeescript, promise, iced coffeescript"
} |
How do you implement 'EXIT_CODES' in python?
Initially i thought to do something like:
#EXIT CODES
class ExitCode(object):
(USERHOME_INVALID, \
USERHOME_CANNOT_WRITE, \
USERHOME_CANNOT_READ, \
BASHRC_INVALID) = range(-1, -5, -1)
But than I've realized that I'll have to know exactly the total number of EXIT_CODES, so that I can pass it to the range() function. Let's suppose I'll have 87 (arbitrary) EXIT_CODES... I don't want to count to 87 (not that it's hard) but I am looking for a more elegant solution.
Any suggestions ?
EDIT: EXIT_CODE is a negative int that will be passed to sys.exit . Instead of writing the number I prefer to use some sort of constants (something like #defines or enums in C, or enums in Java). | Sounds like what you want is the Python equivalent of an enumeration in C# or other similar languages. How can I represent an 'Enum' in Python? provides several solutions, though they still require the number of items you have. EDIT: How can I represent an 'Enum' in Python? looks _way_ better.
Or you could try something like this (probably not the best solution, though):
class _ExitCode:
_exit_codes=["EXIT_CODE","EXIT_CODE_TWO"]
def __getattr__(self, name):
if name in _ExitCode._exit_codes:
return -(_ExitCode._exit_codes.index(name)+1)
raise AttributeError("Exit code %s not found" % name)
ExitCode=_ExitCode()
print ExitCode.EXIT_CODE #-1 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python, exit code"
} |
Overlaying two fading circles using TikZ
I have the following MWE which draws two fading filled circles:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\fill[inner color=red,outer color=white] (0,0) circle (1.8);
\begin{scope}[xshift=4cm]
\fill[inner color=red,outer color=white] (0,0) circle (1.8);
\end{scope}
\end{tikzpicture}
\end{document}
I would like to change the scope `xshift` to 3cm. The problem is that the circles overlap with the right circle placed on top of that on the left circle. I want the colour intensity to instead add constructively.
A seperate question: How can I add a Gaussian function on top of the circles without the axes? The examples I saw on the TikZ site used the pgfplots package which draws the axes. | We use the `fadings` library (search the `\tikzfading` documentation in the PGF/TikZ manual.)
## The output
 circle (1.8);
\fill[myCircle, blue,] (\a,0) circle (1.8);
\draw plot [samples=200] (\x, {exp(-.5*(\x)^2)}) ;
\end{tikzpicture}
\end{document} | stackexchange-tex | {
"answer_score": 5,
"question_score": 5,
"tags": "tikz pgf, pgfplots, graphics"
} |
how to specify directory paths in gitignore
part of my gitignore file looks like this:
phoenix/config/ProjectConfiguration.class.php
StatsFile.txt
phoenix/StatsFile.txt
phoenix/config/*
phoenix/config/propel.ini
phoenix/data/*
phoenix/lib/filter/*
phoenix/lib/form/*
phoenix/lib/model/*
so the full path of for ex. the data directory will be:
/home/helloises/github_mira/rainbow_code/phoenix/data
my gitignore is in directory: /home/helloises/github_mira/rainbow_code
it is not ignoring anything i have in my excerpt above??? am i misunderstanding how .gitignore works? how must i specify the paths?? thanks | Is it possible the gitignore file has a typo?
It should be _.gitignore_ with a leading . in front. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "git"
} |
Rotating a GUI.Label relatively
Learning Unity for 2D development, I want to create a text label.
So far, I have been using `GUI.Label` to write the text. It is above my sprite:
!enter image description here
I would like to **rotate** the label relatively to the monster. In other words:
!enter image description here
How can I achieve this? I have a feeling that `OnGUI()` is probably the wrong solution. | You could get the rotation of the monster and then pass it into RotateAroundPivot before drawing the text. Alternatively if it's an option you could use the world space UI in Unity 4.6 beta to child the text to the monsters transform. | stackexchange-gamedev | {
"answer_score": 4,
"question_score": 3,
"tags": "unity"
} |
I need to print an input on the same line and not below (which is a new line). Can someone fix my code?
I need to have an output like this:
**Enter player name: Mark**
**Mark, choose a column: 2**
and this is my code:
**player = raw_input("Enter player name: ")**
**print player, ", choose a column: "; column = int(input())**
this is the output of my code:
**Enter player name: Mark**
**Mark, choose a column:**
**2**
Can someone help me fix my code? By the way, I'm using python 2.7.6 | `column = int(input(player+ ", choose a column: "))` I guess you can do it in this way | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "string, output, newline, line breaks"
} |
ACF query for custom field in relation
There's a custom post type called "events" and another post type called "venues". The post type "events" has a relation field for "venues" so that the user can select the venue when setting up an event.
"venue" has a custom text field "city".
I need now to search for all events that are in a specific city. With meta_query it doesn't work, the results are always empty:
$query->set('meta_query', array(
array(
'key' => 'city',
'value' => 'New York',
'compare' => 'LIKE',
),
));
How can I find all events where the city of the connected venue is equal to "New York"? Thanks a lot! | Get your venues from the desired city first...
$args = array(
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => 'venues',
'meta_query' => array(
array(
'key' => 'city',
'value' => '"New York"',
'compare' => 'LIKE',
)
),
);
$venues_ids = get_posts($args);
Then query your events from the matched venues
$args = array(
'posts_per_page' => -1,
'post_type' => 'events',
'meta_query' => array(
array(
'key' => 'venues',
'value' => $venues_ids,
'compare' => 'IN',
)
),
);
$events = get_posts($args); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "wordpress, advanced custom fields, acfpro"
} |
How to save login and password in Firefox, when website has not remeber credentials feature?
I use the website on daily basis and it does not have "save login and password" feature. I don't use Firefox's password manager. Is it possible to bypass login page, to save the cache, where the credentials are stored of that specific site? | I found a Firefox add-on, Cookie Manager to edit cookies. It can edit the expiration date. | stackexchange-superuser | {
"answer_score": 1,
"question_score": -1,
"tags": "firefox, passwords, cache, auto login, autosave"
} |
Rails: Correct routing for namespaced resources
If you add a resource map to a namespace in your `routes.rb` in Rails 2.3, how do you make `link_to` (and `form_for`, etc) understand that it should get the namespaced controller instead of one in the root namespace?
For example...
With this in `routes.rb`:
map.namespace :admin do |admin|
admin.resources :opt_in_users
end
And this in the view:
<%= link_to @anOptInUser %>
That `link_to` should use `link_for_admin_opt_in_user`, but instead it tries to use `link_for_opt_in_user`, which fails. | With namespaced resources, as with nested resources, you can use an array with a symbol:
link_to 'Click here', [:admin, @opt_in_user]
or
form_for [:admin, @opt_in_user] do |form| .... | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "ruby on rails"
} |
css, lock html a tag with image inside
is there a way to lock with only CSS pictures that when someone have 800x600 resolution they will not float one under another.
now:
resolution 1600x900
pic1 pic2 pic3
resolution 800x600
pic1
pic2
pic3
wanted result:
pic1 pic2 pic3
in both resolution. With scroll if needed in smaller resolution. | You can use several tips
## Best solution
on the parent div, add a min-width corresponding of the sum of the size of its children. you may need an additional grand parent div with overflow:auto to show scrollbar.
## Good solution but depending on your case
specify size of floating div in %
## If none of these solution is acceptable for your case
on the children div, you can use display: table-cell. It will render as a cell table which cannot be "destroy" by minimal resolution | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "html, css"
} |
Rename a tag with misspelled name
Following this post (How to rename a tag?), may I ask a moderator to rename a tag I created on Stack Overflow? I misspelled the name of a R package. envstat should be envstats. | Since the tag was just created by you, and has very few questions, you can handle it yourself in the following way:
1. Remove that tag from all questions
2. Wait for a day. The tag should then be deleted
3. Create the correct tag
4. Add the tag back to all questions | stackexchange-meta_stackoverflow | {
"answer_score": 13,
"question_score": 10,
"tags": "support, tags"
} |
Show yaxis out the plot in highstock
I would like that both yAxis and their labels in charts located at where displayed out the plot (not overflow in chart) as you can see in this chart < but I don't find the difference or the correct options. I think that the difference is that demo is highchart and mine is highstock but I'm not sure.
Could anybody help me?
Thank ins advance, txetxu. | Set `yAxis.labels.align` to right, and manipulate x/y values, see: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "highcharts"
} |
MacOSX: new mail with attachment
I want to create a new mail with the default mail client and attach a file automatically to it.
To create a new mail to `[email protected]` with subject `foo` and body `bar`, I can do the following:
open "mailto:[email protected]?subject=foo&body=bar"
How can I attach a file now?
If this is not possible this way (with `open`), what are my alternatives?
I would prefer a solution which works in Java as well as in native languages (C++, ObjC). So if there is a way via shell to do this, this would make it easy as I can just spawn such a progress.
Otherwise I would have to fall back to some SMTP engine and just write an own small mail sender. | You can do this via AppleScript, e.g.
tell application "Mail"
set msg to make new outgoing message with properties {subject:"Test", visible:true}
tell msg to make new to recipient with properties {address:"[email protected]"}
tell msg to make new attachment with properties {file name:"Macintosh HD:Users:me:my_file.txt" as alias}
end tell
If you don't have any way to run AppleScript directly then you can use `osascript` via the command line, e.g.
osascript <<EOF
tell application "Mail"
set msg to make new outgoing message with properties {subject:"Test", visible:true}
tell msg to make new to recipient with properties {address:"[email protected]"}
tell msg to make new attachment with properties {file name:"Macintosh HD:Users:me:my_file.txt" as alias}
end tell
EOF | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 5,
"tags": "macos, email, smtp"
} |
How do i define and select random user in wordpress database config in wp-config.php?
$randomuser = array("user","user1","user2","user3","user4","user5");
shuffle($randomuser);
/** MySQL database username */
define('DB_USER', $randomuser);
How do i make the above code to work in wp-config.php ? Thanks. | You can set how many random users you want to get in 2nd argument too:
$random_users = array_rand($random_user,5); //gets 5 random users from array | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, database, wordpress"
} |
Resolution problems on 14.04- will not install guest additions
I started using a Ubuntu from Virtual Box today because I was interested in Linux (I am not that good in coding, however) and found the design to be appealing.
People say to install 'guest additions' to the computer, but whenever I try to I get an error saying I can't mount the disk image.
How can I get the fullscreen effect?
I am running:
* Linux Ubuntu 14.04
* Virtual Box from oracle
Does anyone have any idea how I can get past this?
### Can you make it noob-friendly, as I just started Ubuntu today? | You installed `virtualbox`, but did you install `virtualbox-guest-additions-iso virtualbox-guest-dkms virtualbox-guest-utils`?
* `sudo apt-get install virtualbox-guest-additions-iso virtualbox-guest-dkms virtualbox-guest-utils`
Here is an Answer that has instructions on how to make `virtualbox` fullscreen, as well as a more detailed explanation of how to get Guest Additions installed. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "14.04, virtualbox, resolution"
} |
Convert current page class to select menu 'selected'
I've currently got a jQuery function that converts wp_list_pages to a select menu which navigates to the selected page when you select the page. What I am wondering is can I use the 'current_page_item' class & convert this to set the current page as option 'selected'? My current code is below:
$('li.current_page_item').attr('selected', 'selected');
alert($('ul.selectdropdown')[0].selectedIndex );
$(function() {
$('ul.selectdropdown').each(function() {
var $select = $('<select />');
$(this).find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
$select.change(function() { window.open($select.find(':selected').val(), '_top'); });
});
$(this).replaceWith($select);
});
}); | Try this:
$('li.current_page_item').attr('selected', 'selected');
alert($('ul.selectdropdown')[0].selectedIndex );
$(function() {
$('ul.selectdropdown').each(function() {
var $select = $('<select />');
$(this).find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
// Check for current page
if(window.location.href == $(this).attr('href'))
{
$option.prop('selected',true).addClass('current_page_item');
}
$select.append($option);
$select.change(function() { window.open($select.find(':selected').val(), '_top'); });
});
$(this).replaceWith($select);
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, html, wordpress"
} |
Can I transfer the value stored in my CharlieTicket into a CharlieCard?
As noted here, it seems much better to get a CharlieCard rather than a CharlieTicket. Unfortunately, I didn't know this and bought a stored value CharlieTicket. Is there any way I can transfer the amount in my CharlieTicket into a CharlieCard instead, so I don't pay the higher ticket prices? Will the fare machines let me do this? | As usually, the MBTA is quite obtuse about this. Apparently this did work at some time (< but there is no current information whether this is still the case or not.
They are pretty clear that you can't redeem the remaining value of a Charlie Card for cash. It's a pretty devious system actually: the Charlie Ticket subway fare is $2.65 and the smallest default value at the vending machine is $5.00 (although you can select "other amount"). There are probably quite a few Charlie Tickets $2.35 remaining value been thrown away.
Your best shot is to go to the Charlie Card store in Downtown Crossing and ask. | stackexchange-travel | {
"answer_score": 4,
"question_score": 6,
"tags": "public transport, tickets, boston"
} |
pymongo.MongoClient did not connect on making instance
I keep seeing examples of using MongoClient like this (simplified):
import pymongo
try:
conn=pymongo.MongoClient(‘localhost’,27017)
print('connected')
except:
print('not connected')
But there is no connection, because when I do this
import pymongo
print(pymongo.MongoClient('blabla'))
I get:
MongoClient(host=['blabla:27017'], document_class=dict, tz_aware=False, connect=True)
The actual connection is going on when I call for example `.find()`.
This seem very weird and confusing to me. | From <
> Note Starting with version 3.0 the MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. You can check if the server is available like this: | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python 3.x, mongodb, pymongo"
} |
resizing widget in pygtk
I have a scrolled window, which contains a drawing area in pygtk. I would like to change the size of the drawing area, and keep the scrolled window as it is. I don't find a function that works on widgets. I can get the size and so on, but I can't set it. Could someone give me a pointer to the solution?
Thanks,
v923z | It sounds like `.set_size_request()` is what you need. An example would be:
drawingarea.set_size_request(400, 400)
The values are the width and height of the canvas. Assuming you're ScrolledWindow is setup correctly, the scrollbars should adjust automatically to the size of the DrawingArea. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "widget, size, pygtk"
} |
Sending mail through DB or through service call from a CLR
I've a scenario where I've to send a mail after checking a condition after every insert in a table.
* Is trigger the right way to do it?
My second question would be as to what approach to take
* Should I directly send a mail from the DB. (Note: My DBserver and Mail server are in different networks, might've to create firewall rule exception)
* Should I have a CLR-sproc. From the DB, I call the CLR-sproc and CLR-sproc calls a service and from there sends the mail.
Is there a better approach? | Both SQL Server DBMail and a CLR proc will use SMTP to send the email. So, why add complexity?
In addition, sending an email via DBMail or CLR will require processing on INSERT. Note that DBMail uses a queue so will impact less than running a CLR procedure.
A trigger is a good way to do it. However, consider using a stored procedure to do the ISNERT with the email sent outside of the transaction (you'll have an implicit one because of the INSERT). Sending in a trigger means it is _part_ of the implicit transaction for the INSERT.
From a security perspective, SQLMachine still needs access to SMTPMachine, whether using DBMail or a service call by a CLR Proc. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql server, sql server 2005, email"
} |
data table or list in selecting data from db
i have max 50 employee each has 40 field which is better using data table or list, what i want to do is read all employees from database and load them to data grid view , then user can select any employee and edit or delete , so if he want to edit employee record will passed to employee edit form to display the employee data ? so which is better ? pass record from list as object or from data table. | If you are speaking from a performance view, DataTables are more expensive that Lists in both processor time and memory allocation.
However with a sample size of 50 Objects with 40 Properties each, the difference will be minor and you can use whichever structure you are more comfortable with. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "c#, .net"
} |
AGOL tiling creates multiple labels
I create a webmap and use publish it on ArcGIS Online. Unfortunately the tiling engine of AGOL creates multiple labels for the same item. How can I prevent this? Same label problems occured, when I created the tiles locally. , you might occasionally see duplicate labels in your cache tiles. These should not occur any more frequently than 4,096 pixels in any direction. You can eliminate all duplicate labels by using annotation. When you use annotation, labels are associated with one point on the map and duplicates do not occur.
Much more detail in this help topic. | stackexchange-gis | {
"answer_score": 1,
"question_score": 2,
"tags": "arcgis online, web mapping, tiles, arcgis pro"
} |
Integrate Firebase web chat seamlessly with an existing application
I need to integrate Firebase web chat in an existing web application. The integration has to be seamless . I would not like to store the username and password of a user in the Firestore database. Can this be done? If yes, then how? | All Firebase products are fully hosted services. While some of them have local emulators, they can currently not be run locally to receive traffic from published apps. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "firebase, google cloud firestore"
} |
How can a high voltage flyback transformer burn pieces of paper?
Why is it possible to burn pieces of paper by holding the output of a high-voltage flyback transformer near them? How is the circuit completed if there's no electrical connection between the paper and the flyback's reference?
I would guess the strong electric field at the output tip creates a displacement current in the paper, which is a bad conductor and therefore heats until burning up. So there's no closed circuit. Is this right?
I mean, for example, an old color CRT TV, with the output touching a piece of paper **on the table, away from the TV's ground** :
Smack library. So far so good. Now, what I can't wrap my head around is how to notify the user of received chats when the app is closed, the same way all other chat apps do. I was reading into push notifications but all examples I find have a server component as well, which I obviously don't since my app is just a client for GTalk.
Should I be using GCM and implement the server side for this? Should I instead attempt to start a service that will listen for incoming messages at boot time (similar to this example)? | Service is definitely the way to go, you can keep it running so that your XMPP connection remains open.
From the server you can receive the messages and through a Broadcast Receiver you can show your notification if the app is closed, when it's opened you disable the previous Broadcast Receiver and you register a new one to manage messages in your activity for example.
This is pretty much my implementation.
Thumbs up appreciated!
Enjoy | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "android, xmpp, smack, asmack, google talk"
} |
Sending APN from node server to device
I have an express app that is configured to send notification to a designated device token and I am able to send and receive the notifications.
My issue is, I am currently manually sending the notifications to the device from my server by entering device token. I can fetch the token from the firebase DB that's connected to my app.
How do i send token of individual device for each event to which the db changes are made. I dont have a specific user assigned in the database(or I am not able to figure out how can the express app keep track of any user). Is there a way I can manage to fetch the particular user, Get his token and then send the desired notification. The contents of notification are present in the DB Document of user.
Can I put an observer/Listener. Or is there any other way. I am new to APNS.
P.S : I am using node-apn npm for APNS connectivity.
I hope I am clear. Thanks! | You would need following:
1). A new table “device” to store all device token of users along with the following:
userId
deviceType (should be enum [“android”, “ios”])
deviceId (string, id)
2). Two api’s for mobile app side:
**_Register a specific mobile device_** \- Mobile App will send the “userId” and “deviceId” immediately after login in the app. Server to check if record for same “userId” and “deviceId” exists or not and if not then it has to create one in the “Device Table”
**_Deregister a specific mobile device_** \- Mobile App will send the “deviceId” to free on logout from app. ( This is done because sometimes 2 different users can login the mobile app on the same device ) Back-end would delete the record for same device id.
_Ultimately When you get any event to send push to a user, retrieve device token from the table and send push to that token._ | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, node.js, express, firebase realtime database, apple push notifications"
} |
MySQL User() return only so many characters
I am using the User() to populate a table which returns something like (admin@localhost).
How would I return
1) only the items to the left of the @ (if possible)
and
2) only the first 10 characters (if something like AnnaMariaSmith@localhost, just return AnnaMariaS)
Thanks | Something like this perhaps?
SELECT LEFT(USER(), LOCATE('@',USER()) - 1)
## See it in action
If you want only the first 10 characters of the result above, just another `LEFT` function:
SELECT LEFT(LEFT(USER(), LOCATE('@',USER()) - 1), 10) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, character"
} |
Linker error on same named constants in different scopes
I have a constant named "ID_KEY" that is declared at the top of 3 separate .m files, neither of which include the other files.
The declaration is as follows:
#import "PublicGamesResponse.h"
NSString *const ID_KEY = @"id";
...
@implementation PublicGamesResponse
And similarly for the two other classes. However I am getting a linker error complaining about multiple definitions of the same name(If I was to comment out two of the definitions, this goes away).
My question is why on earth is the linker complaining about this? Each definition of ID_KEY is outside of the scope of all of the others, so I don't see why the linker is complaining.
As a disclaimer, I cleaned the project and restarted xCode, and looked for similar questions on the site, but had no luck. | When you define variables or constants outside a function, they are placed in the _global_ scope. Linker resolves global references, and it complains when it finds the same name more than once.
To give the constants a scope of their compilation unit (i.e. the file where they are defined) add `static` in front of their definitions:
static NSString *const ID_KEY = @"id";
This way all functions and methods inside the same file will have access to `ID_KEY`, but the name would remain in the scope of the file. Essentially, `static` "hides" the the name from the linker. | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 6,
"tags": "ios, objective c, xcode"
} |
Add X number of columns to a data.frame
I would like to add a varying number (X) of columns with 0 to an existing data.frame within a function.
Here is an example data.frame:
dt <- data.frame(x=1:3, y=4:6)
I would like to get this result if X=1 :
a x y
1 0 1 4
2 0 2 5
3 0 3 6
And this if X=3 :
a b c x y
1 0 0 0 1 4
2 0 0 0 2 5
3 0 0 0 3 6
What would be an efficient way to do this? | A second option is `cbind`
f <- function(x, n = 3) {
cbind.data.frame(matrix(
0,
ncol = n,
nrow = nrow(x),
dimnames = list(NULL, letters[1:n])
), x)
}
f(dt, 5)
# a b c d e x y
#1 0 0 0 0 0 1 4
#2 0 0 0 0 0 2 5
#3 0 0 0 0 0 3 6
NOTE: because `letters` has a length of 26 the function would need some adjustment regarding the naming scheme if `n > 26`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r, dataframe"
} |
How can I write and read to and from a application.yaml at runtime using java code in a spring boot application?
I want to write to an **application.yml** file as well as read from it respectively, after value has been written in a spring boot application during runtime. It can be **application.properties** file as well. The property's key can be written dynamically or it can be entered manually by the developer(Doesn't matter).
The key-value pair must me accessible after it has been written to the **yaml/properties** file.
I don't have much information about the above mentioned concept. So, haven't implemented it yet. Hence, there is no source code for it. I tried to search on the web but didn't get expected information, so posting it here.
Since I don't know the way it is done, if someone knows whether it is the same way or different ways to write to both( **properties/yaml** ) files, preferred way is using the yaml file.
Any helpful links or tutorials are welcome.
Thank You | I used @ConfigurationProperties in my project to solve this problem. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, spring boot, properties, yaml, runtime"
} |
convert bootstrap click to hammer tap
How to convert bootstrap click handler, with hammer.js `tap` event?
Because touch devices have a delay before executing click event, and that's boring for users. | You can use FastClick to process 300ms delay:
<
If FastClick used, you can just use `click`, it will be processed automatically. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, twitter bootstrap, hammer.js"
} |
Split column string with delimiters into separate columns in azure kusto
I have a column 'Apples' in azure table that has this string: "Colour:red,Size:small".
Current situation:
|-----------------------|
| Apples |
|-----------------------|
| Colour:red,Size:small |
|-----------------------|
Desired Situation:
|----------------|
| Colour | Size |
|----------------|
| Red | small |
|----------------|
Please help | This query gave me the desired results: `| parse Apples with "Colour:" AppColour ", Size:" AppSize`
Remember to include all the different delimiters preceding each word you want to extract, e.g ", Size". Mind the space between.
This helped me then i used my intuition to customize the query according to my needs:
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "azure data explorer, kql"
} |
Vector Resizing in C++ works only when adding cout statement?
vector<string> solution(vector<string> inputArray) {
int n = inputArray.size();
vector<string> outputString(n);
int maxSize, curPos = 0;
for(auto &i: inputArray)
{
int currentSize = i.size();
if(currentSize > maxSize)
{
maxSize = currentSize;
curPos = 0;
outputString[curPos++] = i;
}else if (currentSize == maxSize)
{
outputString[curPos++] = i;
}
}
cout<<curPos;
outputString.resize(curPos);
return outputString;
}
In the original code without the _cout_ line, the outputString resulted in an empty vector. But upon adding the cout line, the problem gets magically solved. What could be the reason behind this? | `maxSize` is uninitialised so your code has undefined behaviour. UB produces surprising results like printing something changes the behaviour of the program.
By using `reserve` and then adding strings to the vector your code can be a lot simpler:
vector<string> solution(const vector<string>& inputArray) {
size_t n = inputArray.size();
vector<string> outputString;
outputString.reserve(n)
for(auto &i: inputArray)
{
int currentSize = i.size();
if(outputString.empty() || currentSize > outputString.front().size())
{
outputString.clear();
outputString.push_back(i);
}else if (currentSize == outputString.front().size())
{
outputString.push_back(i);
}
}
return outputString;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, vector"
} |
Is using Dev/Test RDS is bad idea for your project over Production RDS?
I am a student. I am using AWS free tier account. I don't have money to pay for the resources. I have developed an application for the society. I don't want my website should face any downtime in production just because of the free service provided by Amazon.SO, can I go for the Dev/Test RDS for my production application? | The basic different between a Dev/Test configuration for Amazon RDS and a Production configuration is that the Production configuration has **Multi-AZ** activated. This means that there is a secondary database provisioned in case of failure of the primary database or the Availability Zone in which the database is running.
Such failures are rare and given that you are cost-conscious and you are not providing a commercial-grade application, using the Dev/Test configuration would be acceptable.
Please note that the intention of the AWS Free Tier is _"to gain free, hands-on experience with the AWS platform, products, and services"_. It is not intended as a way to host applications for free. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "postgresql, amazon web services, amazon rds"
} |
Diagonal maps and product spaces
Problem: For any topological space $X$, $\Delta: X\rightarrow X\times X$ , defined by $\Delta(x)=(x,x)$ is continuous.
My Attempt: Let $U$ be open in $X$. Then $(\pi_1 \circ \Delta)^{-1}(U)=\Delta^{-1}(\pi_1^{-1}(U))$ $=$ $\Delta^{-1}(U\times X)$ $=$ $U$ which is open in X. Hence $\pi_1 \circ \Delta$ is continuous.
I will show that $\pi_2 \circ \Delta$ is continuous. Let $V$ be open in $X$. Then $(\pi_2 \circ \Delta)^{-1}(V)=$ $\Delta^{-1}(\pi_2^{-1}(V))$ $=$ $\Delta^{-1}(X\times V)$ $=$ $V$ , which is open and thus $\pi_2 \circ \Delta$ is continuous. Since $\pi_i \circ \Delta$ is continuous for $i=1,2$, $\Delta$ is continuous.
Note: $x\in \Delta^{-1}(X \times V)$ $\iff$ $x\in X$ and $\Delta(x)\in X\times V$ $\iff$ $(x,x)\in V$ $\iff$ $x\in V$.
Is my attempt correct? | You seem to know and want to apply the theorem
> For any spaces $Y,X$ and any function $f: Y \to X \times X$, $f$ is continuous iff $\pi_1 \circ f$ and $\pi_2 \circ f$ are both continuous (as maps from $Y$ to $X$).
This is a fine idea, but just note that $$\forall x \in X: (\pi_1 \circ \Delta)(x)=\pi_1(\Delta(x)) = \pi(x,x)=x \text{ so } \pi_1 \circ \Delta = 1_X$$
where $1_X: X \to X$ is the identity map on $X$ and similarly $\pi_2 \circ \Delta= 1_X$ as well and the identity maps are always continuous. Done.
Don't reprove that identity maps are continuous, just use it.
As an alternative: let $U \times V$ (so $U,V$ open in $X$) be a basic open set of $X \times X$, and note that
$$\Delta^{-1}[U \times V]=\\{x \in X: (x,x) \in U \times V\\}=U \cap V$$ which is open as a finite intersection of open sets, so the inverse images of basic open subsets are open in $X$ and this implies (standard theorem) that $\Delta$ is continuous. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "general topology, solution verification, products, geometric topology"
} |
Replacing numbers in the last column of data
Quick question, should be rather simple for people who know the syntax, the question is what the title says. if i have this as an example:
Something1 hi bye 12
Cars32 hello bye 23
Cars32 hello bye 65
Cars32 hello bye 34
word hello bye 42
Cars32 hello bye 32
Cars32 hello bye 75
Cars32 hello bye 12
Cars32 hello bye 42
And I want to replace all occurrences of 12 in the last column with 3, and all 42's with 5. How would i go about doing this. Thanks. | Here is one way, using `awk`:
#!/bin/sh
awk '\
{
val = $4;
if(val == 12) {
val = 3;
}else if(val == 42){
val = 5;
}
print $1, $2, $3, val;
}'
If you text file is saved as `example.txt`, save this `awk` script as `exampleScript` (and `chmod 777` so that it's executable), then run it as
> cat example.txt | ./exampleScript
Output:
Something1 hi bye 3
Cars32 hello bye 23
Cars32 hello bye 65
Cars32 hello bye 34
word hello bye 5
Cars32 hello bye 32
Cars32 hello bye 75
Cars32 hello bye 3
Cars32 hello bye 5 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "unix"
} |
Neo4j - Match by multiple relationship types
I want to match between entities by multiple relationship types.
Is it possible to say the following query:
match (Yoav:Person{name:"Yoav"})-[:liked & watched & ... ]->(movie:Movie) return movie
I need "and" between all the relation types; Yova liked and watched and .. a movie. | Yes, you can do something like:
match (gal:Person{name:"Yoav"})-[:liked|:watched|:other]->(movie:Movie)
return movie
Take a look in the docs: Match on multiple relationship types
**EDIT:**
From the comments:
> I need "and" between the relation types.. you gave me an "or"
In this case, you can do:
match (Yoav:Person{name:"Yoav"})-[:liked]->(movie:Movie),
(Yoav)-[:watched]->(movie),
(Yoav)-[:other]->(movie)
return movie | stackexchange-stackoverflow | {
"answer_score": 55,
"question_score": 35,
"tags": "neo4j, cypher"
} |
Incorrect back button response
**Reproduction steps** :
1. view feed
2. view inbox
3. click inbox item question link
4. click back button
**Expected results** : I'd expect to go back to my feed.
**Actual results** : I end up on the current question's main site.
If I click an achievement link then the back button takes me back to my feed as I'd expect.
(Using 1.0.1.86) | The inbox behavior should now match that of achievements. This behavior will appear in the next Appstore update, and in the Beta for version 1.0.1.87. | stackexchange-meta | {
"answer_score": 2,
"question_score": 2,
"tags": "bug, status completed, ios app"
} |
I want current week data
I want current week data from mysql but problem is my field is varchar how i get the data
> Error Number: 1064
>
> 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 'YEARWEEK(CURDATE()) IS NULL' at line 3
SELECT `E`.`event_id`
FROM (`tbl_events` as E)
WHERE YEARWEEK(date_format(str_to_date(E.event_end,'%m-%d-%Y'),'%Y-%m-%d')),YEARWEEK(CURDATE()) IS NULL | You just have an extra `)` before the 2nd `yearweek()` call, which should go at the end of the expression. Syntax wise.
However, I think you are overcomplicating this a bit:
SELECT `E`.`event_id`
FROM (`tbl_events` as E)
WHERE YEARWEEK(str_to_date(E.event_end,'%m-%d-%Y'))=yearweek(curdate())
On the left hand side of the expression I get the week of the year from the record. This should equal to the week of the year for the current week, which is on the right hand side of the expression. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "mysql"
} |
Struggling with interval infinities
This is calculus coursera course question :
 $ are in the domain $ \sqrt{2x - x^3} $
But this is incorrect. As the intervals $ [0 , \sqrt2] $ , $ [\sqrt2 , +\infty) $ are positive then they are contained in the domain of the function$ \sqrt{2x - x^3} $ ?
And as $(-\infty , -\sqrt2 ] $ , $ (-\sqrt2 , 0) $ are negative intervals then they are not contained in this domain ? | I suppose you want $\sqrt{2x-x^3}$ to be real and not complex, so what you need is to find out, when $2x-x^3\ge0$. As others mentioned, $2x-x^3=0$ if $x=\pm \sqrt2$ or x = 0, so now you just need to check for the solutions beyond and below the borders. For x = 2 it's: $$2\cdot 2 - 2^3 =-4$$ So the root would be complex (which I assume you don't want). Same goes for x = -2, so everything below $x=-\sqrt2$ and beyond $x=\sqrt2$ is complex.
For x = 1 it's: $$2 \cdot 1 - 1^3 = 1$$ so everything below $\sqrt2$ and beyond 0 is fine.
For x = -1 it's: $$2 \cdot (-1) - (-1)^3 = -1$$ so it would be complex again. We can assume that the interval you're searching for is $$[\, 0;\sqrt{2}\,] $$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "calculus"
} |
Why a string is interned that is created via constructor and with a char[]?
I was sure that this would output false, but actually it outputs true:
string foo = new string("foo".ToCharArray());
Console.WriteLine(string.IsInterned(foo) != null); // true
I thought that creating it already via constructor would prevent string interning. But even using a `char[]` causes it to be interned. What is the reason or what is my error in reasoning? | Literal strings are interned. And you have the literal `foo` in your source code. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, .net, string, string interning"
} |
Disable selected dates in default Magento2 calendar
I have successfully added calender and disable previous Date in my custom form by using below code.
<script>
require([
"jquery",
"mage/calendar"
], function ($) {
$("#My_ID").calendar({
showsTime: false,
hideIfNoPrevNext: true,
buttonText: "<?php echo __('Select Date') ?>",
minDate: new Date(),
dateFormat: 'yy-mm-dd'
});
});
How to disable List of dates which is in my database ? | Hi you can this code for disable dates
var disableddates = ["20-06-2016", "12-06-2016"]; // assign your database dates
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
jQuery("#My_ID").calendar({
beforeShowDay: DisableSpecificDates
}); | stackexchange-magento | {
"answer_score": 2,
"question_score": 2,
"tags": "magento2, calendar"
} |
Can I remove the "not for replication" option from an existing check constraint in T-SQL?
Suppose a check constraint (involving multiple columns) with the "not for replication" option was added to a database table (e.g. "alter table table_name add constraint constraint_name check not for replication (constraint_expression)")
I found syntax for dropping "not for replication" from a column, but not for an existing check constraint as mentioned above.
Is there a way to remove the "not for replication" from the check constraint other than dropping/recreating the check constraint? | I'm almost certain you have to drop and recreate it without the "not for replication" option.
You can alter columns but I don't think you can alter constraints. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "sql, replication, constraints, alter table"
} |
'Inverting' an intensity variation
This is somewhat hard for me to explain, but what I'm looking for is a technique to correct a fixed-pattern intensity variation in an image. The pattern comes from (say) a projection system and is not inherent to the actual image.
I can produce a 90%-average white frame that exposes these variations, which amount to perhaps as much as 10%, so that the range of values will be from about 85% to 95% in different areas. I then need to make an inverted mask / alpha that undoes those variations. So if applied to the original white frame it would result in a pure image with no variations. Once created, the mask will be applied externally, not within a graphics program.
If I've managed to convey that, how would you approach the creating of this transparency / alpha mask, given the original white frame with variations? My tool of choice is PSP 9 (no laughs), but a solution using PS would be fine. | Below your original with the +/- 5% variance, add a second layer that is an even 90% gray (or white, whichever term you prefer!), then:
* Add a layer below that is a flat 90%, no variations.
* Target your top layer. From the main menu, choose `Image > Apply Image > Subtract`. Set `Layer:` to your new flat layer, `Offset:` to 128 and `Scale:` to 2.
* Invert.
* Change the blend mode of your top layer to Linear Light.
* Merge down.
This will give you a layer that inverts the variations from your base 90%, and will give you a more accurate result than varying the luminance by hand. | stackexchange-graphicdesign | {
"answer_score": 1,
"question_score": 1,
"tags": "photoshop effects, mask, corel paint shop pro"
} |
How to pull multiple attributes from one selected element?
Say for example I have
<select>
<option id="4" data-name="tomato" data-length="six">Tomato</option>
<option id="5" data-name="onion" data-length="five">Onion</option>
</select>
I'm trying to call some javascript code later that will take those data-names and length for different variables:
var str = "name=" + jQuery("#data-name").val() + "&length=" + jQuery("#data-length").val();
How would I do this for multiple attributes from the same element? | You could access jQuery `data`-attributes with `data()` function:
var $opt = $("select option:selected");
var str = "name=" + $opt.data("name") + "&length=" + $data("length");
Or simply treating them as attributes:
var $opt = $("select option:selected");
var str = "name=" + $opt.attr("data-name") + "&length=" + $opt.attr("data-length");
This question may help you to understand the differences between these two approaches: jQuery Data vs Attr?. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript, jquery, html"
} |
Parsing HTML source code to get url's of images without errors. (Python preferred)
I made a wordpress plugin which sends the blogposts as post data so that I can save the webpage. I get the data from the blog using the following query:
select * from $wpdb->posts
The above line is not important, but just mentioned it to tell you how I am getting the blog data.
The data contains HTML markup. I need to parse the HTML to get the URLs of images . Once I get the URL, I know how to download the images from the URL. I want to know a good way of parsing HTML markup to get the URLs of images without any error.
python is the preferred language. | There are several python modules that will do this for you:
* BeautifulSoup
* lxml.html
* html5lib
For example,
import BeautifulSoup
html = """
<html><body>
<h1>My html!</h1>
<img src="yourimage1.jpg" />
<img src="yourimage1.jpg" />
</body></html>
"""
bs = BeautifulSoup.BeautifulSoup(html)
urls = [img["src"] for img in bs.findAll("img")]
results in `urls == ['yourimage1.jpg', 'yourimage2.jpg']` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -7,
"tags": "python, html, html parsing"
} |
Why won't my files import into garageband?
I'm attempting to import an mp3 into garageband for some basic editing.
I used the media browser to locate the file and then I 'dragged and dropped' main area ('drag apple loops here!')- a quick message appears to say it's importing. However, when the message disappears there is a new track but no music.
I checked the whole track to make sure it wasn't sitting at either end and I couldn't see it but alas that shed no light as to where the 'imported' track had vanished to.
I've attached an image - although I'm not really sure how much use it's going to be.
Facts: Running Mac OS X 10.7.2, Garageband '11 v 6.0
!enter image description here | Usually, we can easily import MP3 files to GarageBand (especially GarageBand 11)
However, sometimes the import process will encounter difficulty in importing an MP3 into GarageBand in two situations:
**Situation 1** : GarageBand only imports MP3 files which have the extension in lower case: ".mp3". If you try to import MP3 files (like MP3 recorded from the Olympus LS-10) with the extension in upper case: ".MP3", GarageBand will refuse to import those kinds of MP3 audio.
In this case, change the MP3 file extension to lower case in order to import MP3 to GarageBand.
**Situation 2** : GarageBand only supports those MP3 audio files which have a sample rate of 44.1 kilohertz (kHz) and a bit depth of 16 bits.
In this case, it will be necessary to convert the MP3 file(s) to GarageBand's more compatible AIFF file format.
The following link provides instructions for two methods to convert an MP3 file to a AIFF file at: How to Convert and Import MP3 to GarageBand? | stackexchange-apple | {
"answer_score": 5,
"question_score": 3,
"tags": "macos, music, mp3, garageband"
} |
sql server parsing char to int
I have two SQL server databases which use the same code.
I am getting below error:
Error when executing tsp_parse_str_int at line 26. Error message: Conversion failed when converting the nvarchar value '1000 ' to data type int.
If you notice there is a leading space, however in my code I am removing the space before the conversion!
SET @temp = (select replace(@temp, ' ', ''))
SET @projid = cast(@temp as int)
Thanks, Bruce | I found out it was actually not a space, either a carriage return tab or new line, I got rid of by:
REPLACE(REPLACE(REPLACE(MyField, CHAR(10), ''), CHAR(13), ''), CHAR(9), '') | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server"
} |
What errors that can't be detected by testing techniques but rather by guessing?
Error guessing is known to be one way of knowing the error from previous experiences. however, it's a technique that usually testers perform if all other formal techniques (like Whitebox testing or other blackbox testing) failed to identify the error.
Scenario: Assuming that I have automatic bus door that opens once the bus arrives at the station for people with disabilities.
My question is as follows: What kind of errors can take place (in the scenario above) and can be detected only by guessing not any other formal techniques?
Thanks.. | There are no errors that cannot be found with formal techniques, at least in theory. It is just difficult to generate all relevant test cases and achieve 100% test coverage. The point of error guessing is to use experience and heuristics to find a few test cases that are likely to fail while still ignoring many other test cases which are not. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "testing, automation, black box testing"
} |
Пшеница и пшено
И снова я о похожих словах.
Есть злак пшеница. Зерно пшеницы, соответственно, тоже пшеница. А есть другой злак - просо. Но его зерна почему-то называются пшено.
А почему так? Какая связь между пшеницей и зернами проса? | "Пшеница" происходит от "пшено" (см. в сл. Фасмера), а "пшено" (что сделано?) — это страдательное причастие прошлого времени от "пихать", буквально — "толчённый (злак)". Вероятно, потом произошло сужение смысла слова "пшено", и оно стало обозначать зерно конкретного злака (проса). | stackexchange-rus | {
"answer_score": 2,
"question_score": 2,
"tags": "однокоренные слова"
} |
Delete suddenly taking a long time
We have a feed process which runs every day of the year. As part of that we delete every row from a table (approx 1 million rows) every day, repopulate it using 5 different stored procedures and then commit the transaction. This is the only commit statement that we call. All of a sudden the delete has started takign about 2 hours to complete. The delete is also very simple (delete from T_PROFILE_WORK) This has worked perfectly well for the past year, but in the past week I have noticed this issue.
Any help on this is greatly appreciated | please review the answers of this SO Question: "oracle delete query taking too much time":
> 1. You could be blocked by another session (most likely). Before you delete you should make sure noone else is locking the rows, eg: issue SELECT NULL FROM tablename WHERE colname=:value FOR UPDATE NOWAIT,
> 2. There could be a ON DELETE TRIGGER that does additional work,
> 3. Check for UNINDEXED REFERENCE CONSTRAINTS pointing to this table (there is a script from AskTom that will help you determine if such unindexed foreign keys exist).
>
I would check #2 and #3 first, they are the easiest to diagnose. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "oracle, performance"
} |
Query inner join with Oracle
I have 2 tables
Table 1
> tblpaket : jenis
Table 2
> produk : kd_jenis, nm_jenis
How to display all data in `tblpaket` and one field `in nm_jenis` with `tblpaket.jenis` same as `kd_jenis`
Because I have many fields I am only displaying 3 fields. So I want to display the `nm_produk` field from the `tblpaket` table where the `jenis` record in the `tblpaket` table is the same as the `kd_type` in table product record. With
select * from tblpaket
because I want display all field in `tblpaket` and one field `nm_produk` in table `produk` where table `jenis` field same as table `tblproduk` field `kd_jenis` | Apparently you need to join `TBLPAKET` to `PRODUK`. You've asked for different things, so I'm not sure I understand your requirements exactly, but based on your last comment it appears you want to do something like
SELECT t.*, p.NM_PRODUK
FROM TBLPAKET t
INNER JOIN PRODUK p
ON p.KD_JENIS = t.JENIS
If this isn't quite what you had in mind, feel free to adjust it as needed.
Best of luck. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, oracle, syntax"
} |
Why doesn't the command Python not do anything in Command Prompt?
The Command Prompt does not do anything when I use the Python command to execute a module. It does not even do anything when I use it at all; it just pretends that I did not do anything, and goes back to the current working directory. Attached is a screen shot for clarity.
{
$this.a=$a
$this.b=$b
}
}
$obj = [test]::new(4, 5)
$obj -eq [test]::new(4, 5)
# False
$pt = [System.Drawing.Point]::new(4, 5)
$pt -eq [System.Drawing.Point]::new(4, 5)
# True | Per the documentation:
> To create comparable classes, you need to implement `System.IEquatable<T>` in your class.
class MyFileInfoSet : System.IEquatable[Object] {
[String]$File
[Int64]$Size
[bool] Equals([Object] $obj) {
return ($this.File -eq $obj.File) -and ($this.Size -eq $obj.Size)
}
}
$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$a -eq $b | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": ".net, powershell"
} |
Return a map from a list of values in Clojure
How would you put values from a list or vector into a map?
I do it the following way but it does not seem simple:
user=> (into {} (map #(into [] %) (partition 2 [1 2 3 4 5 6])))
{1 2, 3 4, 5 6}
user=>
Or if I wanted to also deal with an odd number of values (although possibly not worthwhile, but perhaps to preserve keys):
user=> (into {} (map #(if (even? (count %))
#_=> (into [] %)
#_=> [(first %) nil])
#_=> (partition-all 2 [1 2 3 4 5])))
{1 2, 3 4, 5 nil}
user=>
Is there a simpler way to do this? | The below function should take care of both cases (assuming a Vector is passed as an argument to to-map):
(defn to-map [v]
(apply hash-map
(if (odd? (count v))
(conj v nil)
v))) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "clojure"
} |
How to exclude properties from bean to json at runtime
I want to exclude properties from bean to json using json-lib at runtime.
How can i do it?
I have tried using propertyFilter of jsonconfig, I am not sure if its at runtime. | Here's a code-snippet based on the sample code at Filtering Properties in JSON Advanced Features that might be useful.
PropertyFilter pf = new PropertyFilter(){
public boolean apply( Object source, String name, Object value ) {
if( value != null && Number.class.isAssignableFrom( value.getClass() ) ){
return true;
}
return false;
}
};
PrimitiveBean bean = new PrimitiveBean();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(pf);
JSONObject json = JSONObject.fromObject( bean, jsonConfig );
You could set a different function to the JSON Config before you serialize the bean into a JSON object... in case that's what you meant by run time. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, json lib"
} |
Can I use a Clob as a table key (from Java)?
Following a suggestion made to another question to store large amounts of text: can one use a CLOB as primary key field (i.e., from Java's DataNucleus implementation of JDO)?
I know it is probably a very bad idea to use a CLOB as a key, but I do need to use large text as a key on a one-shot operation. | The simple version would be to generate a hash from the CLOB and use this as a key. This key will fit into the allowed key width for your engine (900 SQL Server, 767 InnoDB, 1000 MyISAM etc).
The hash can be generated by the engine as a computed column, trigger, or by some ETL process, or by the application
There is a faint chance of collision (birthday problem) but this would only matter for many records _and_ poor choice of hashing algorithm | stackexchange-dba | {
"answer_score": 4,
"question_score": 2,
"tags": "primary key, datatypes, java"
} |
Java Command Line Trouble with Reading a Class from a Jar Archive
I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance | Here's a concrete example of what _does_ work, so you can compare your own situation.
Take this code and put it anywhere, in a file called `MainClass.java`. (I've assumed a directory called `src` later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package? | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "java, command line"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.