qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
21,020,187 |
From [this Spring documentation](http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-autowire) I know that when I use @Bean, the default is already equivalent to:
@Bean(autowire = Autowire.NO)
>
> (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
>
>
>
I am just trying to understand what this means for me. If my system is 100% Java Config **and has no XML configuration**, then from what I can tell, when I use @Bean, the 'Autowire.no' has no impact whatsoever.
**EDIT**
By "no impact" I mean that other @Autowired references to this bean ARE autowired (in other Java Config classes). I suspect that is because with Java Config there is no explicit 'ref element' defined, so this (default) setting has no effect.
Example:
First Config:
```
package a.b.c;
@Configuration
public class AlphaConfig {
@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}
```
Then in second config:
```
package d.e.f;
import a.b.c.AlphaBeanType;
@Configuration
public class AnotherConfig {
@Autowire
private AlphaBeanType alphaBeanType;
@Bean
. . .
}
```
What I see is that 'alphaBeanType' is always autowired in the second config class - which seems to be in conflict with the documentation - hence my question.
**end edit**
Of course, I can't quite tell from the documentation! Does anyone know for sure?
|
2014/01/09
|
['https://Stackoverflow.com/questions/21020187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538856/']
|
Setting `Autowire.NO` does not mean that the bean cannot be injected in other beans via `@Autowire`. `@Autowire` works by default by type, and can also work by name using `@Qualifier`.
So if your bean has the right type or name, it will get inject in other beans, that's normal.
`Autowire.NO` means something like:
>
> Don't inject the properties of **THIS** bean being declared with `@Bean` neither by type or by name. If the bean properties are not set in the `@Bean` method code, leave them unfilled.
>
>
>
This a code example of how this works, let's define two beans:
```
public class MyBeanTwo {
public MyBeanTwo() {
System.out.println(">>> MY Bean 2 created!");
}
}
public class MyBean {
private MyBeanTwo myBeanTwo;
public MyBean() {
System.out.println(">>>MyBean created !!");
}
public void setMyBeanTwo(MyBeanTwo myBeanTwo) {
System.out.println(">>> Injecting MyBeanTwo INTO MyBeanOne !!!");
this.myBeanTwo = myBeanTwo;
}
}
```
And some configuration:
```
@Configuration
public class SimpleConfigOne {
@Bean
public MyBean createMyBean() {
return new MyBean();
}
@Bean
public MyBeanTwo createMyBeanTwo() {
return new MyBeanTwo();
}
}
```
With this configuration, the startup of this application gives this log:
```
>>>MyBean created !!
>>> MY Bean 2 created!
```
Meaning one instance of each bean was created, but `MyBean` did NOT get injected with `MyBeanTwo`, even tough a bean with the correct type existed.
By declaring `MyBean` like this:
```
@Bean(autowire = Autowire.BY_TYPE)
public MyBean createMyBean() {
return new MyBean();
}
```
`MyBeanOne` is now eligible to have it's properties set via autowiring by type.
The startup log becomes:
```
>>>MyBean created !!
>>> MY Bean 2 created!
>>> Injecting MyBeanTwo INTO MyBeanOne !!!
```
This shows that `MyBean` had `MyBeanTwo` injected by type via a by type injection.
**Reason why Autowire.NO is the default:**
Usually we don't want to autowire the properties of beans created with `@Bean`. What we usually do is set the properties explicitly via code for readability, as a form of documentation and to make sure the property is set with the correct value.
|
The `autowire` element of the `@Bean` annotation (as well as the `autowire` attribute of the `bean` element in xml-based config) determines the autowiring status of the **bean's own properties** and has no relation to how a bean which is marked with the `@Bean` annotation will be injected into other beans.
On the other hand the `@Autowired` annotation explicitly
>
> marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
>
>
>
So in your case the `@Bean` annotation declared on the `alphaBean` method with the default `Autowire.NO` mode disables automatic (that is implicit) injection of the properties (if any) of the `AlphaBeanType` bean. While the `@Autowired` annotation indicates that an `AlphaBeanType` bean should be injected into `AnotherConfig` configuration object.
|
21,020,187 |
From [this Spring documentation](http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-autowire) I know that when I use @Bean, the default is already equivalent to:
@Bean(autowire = Autowire.NO)
>
> (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
>
>
>
I am just trying to understand what this means for me. If my system is 100% Java Config **and has no XML configuration**, then from what I can tell, when I use @Bean, the 'Autowire.no' has no impact whatsoever.
**EDIT**
By "no impact" I mean that other @Autowired references to this bean ARE autowired (in other Java Config classes). I suspect that is because with Java Config there is no explicit 'ref element' defined, so this (default) setting has no effect.
Example:
First Config:
```
package a.b.c;
@Configuration
public class AlphaConfig {
@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}
```
Then in second config:
```
package d.e.f;
import a.b.c.AlphaBeanType;
@Configuration
public class AnotherConfig {
@Autowire
private AlphaBeanType alphaBeanType;
@Bean
. . .
}
```
What I see is that 'alphaBeanType' is always autowired in the second config class - which seems to be in conflict with the documentation - hence my question.
**end edit**
Of course, I can't quite tell from the documentation! Does anyone know for sure?
|
2014/01/09
|
['https://Stackoverflow.com/questions/21020187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538856/']
|
The `autowire` element of the `@Bean` annotation (as well as the `autowire` attribute of the `bean` element in xml-based config) determines the autowiring status of the **bean's own properties** and has no relation to how a bean which is marked with the `@Bean` annotation will be injected into other beans.
On the other hand the `@Autowired` annotation explicitly
>
> marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
>
>
>
So in your case the `@Bean` annotation declared on the `alphaBean` method with the default `Autowire.NO` mode disables automatic (that is implicit) injection of the properties (if any) of the `AlphaBeanType` bean. While the `@Autowired` annotation indicates that an `AlphaBeanType` bean should be injected into `AnotherConfig` configuration object.
|
`no` The traditional Spring default.
No automagical wiring. Bean references must be defined in the XML file via the `<ref/>` element (or `ref` attribute).
We recommend this in most cases as it makes documentation more explicit.
Note that this default mode also allows for annotation-driven autowiring, if activated.
`no` refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses
|
21,020,187 |
From [this Spring documentation](http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-autowire) I know that when I use @Bean, the default is already equivalent to:
@Bean(autowire = Autowire.NO)
>
> (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
>
>
>
I am just trying to understand what this means for me. If my system is 100% Java Config **and has no XML configuration**, then from what I can tell, when I use @Bean, the 'Autowire.no' has no impact whatsoever.
**EDIT**
By "no impact" I mean that other @Autowired references to this bean ARE autowired (in other Java Config classes). I suspect that is because with Java Config there is no explicit 'ref element' defined, so this (default) setting has no effect.
Example:
First Config:
```
package a.b.c;
@Configuration
public class AlphaConfig {
@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}
```
Then in second config:
```
package d.e.f;
import a.b.c.AlphaBeanType;
@Configuration
public class AnotherConfig {
@Autowire
private AlphaBeanType alphaBeanType;
@Bean
. . .
}
```
What I see is that 'alphaBeanType' is always autowired in the second config class - which seems to be in conflict with the documentation - hence my question.
**end edit**
Of course, I can't quite tell from the documentation! Does anyone know for sure?
|
2014/01/09
|
['https://Stackoverflow.com/questions/21020187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538856/']
|
Setting `Autowire.NO` does not mean that the bean cannot be injected in other beans via `@Autowire`. `@Autowire` works by default by type, and can also work by name using `@Qualifier`.
So if your bean has the right type or name, it will get inject in other beans, that's normal.
`Autowire.NO` means something like:
>
> Don't inject the properties of **THIS** bean being declared with `@Bean` neither by type or by name. If the bean properties are not set in the `@Bean` method code, leave them unfilled.
>
>
>
This a code example of how this works, let's define two beans:
```
public class MyBeanTwo {
public MyBeanTwo() {
System.out.println(">>> MY Bean 2 created!");
}
}
public class MyBean {
private MyBeanTwo myBeanTwo;
public MyBean() {
System.out.println(">>>MyBean created !!");
}
public void setMyBeanTwo(MyBeanTwo myBeanTwo) {
System.out.println(">>> Injecting MyBeanTwo INTO MyBeanOne !!!");
this.myBeanTwo = myBeanTwo;
}
}
```
And some configuration:
```
@Configuration
public class SimpleConfigOne {
@Bean
public MyBean createMyBean() {
return new MyBean();
}
@Bean
public MyBeanTwo createMyBeanTwo() {
return new MyBeanTwo();
}
}
```
With this configuration, the startup of this application gives this log:
```
>>>MyBean created !!
>>> MY Bean 2 created!
```
Meaning one instance of each bean was created, but `MyBean` did NOT get injected with `MyBeanTwo`, even tough a bean with the correct type existed.
By declaring `MyBean` like this:
```
@Bean(autowire = Autowire.BY_TYPE)
public MyBean createMyBean() {
return new MyBean();
}
```
`MyBeanOne` is now eligible to have it's properties set via autowiring by type.
The startup log becomes:
```
>>>MyBean created !!
>>> MY Bean 2 created!
>>> Injecting MyBeanTwo INTO MyBeanOne !!!
```
This shows that `MyBean` had `MyBeanTwo` injected by type via a by type injection.
**Reason why Autowire.NO is the default:**
Usually we don't want to autowire the properties of beans created with `@Bean`. What we usually do is set the properties explicitly via code for readability, as a form of documentation and to make sure the property is set with the correct value.
|
`no` The traditional Spring default.
No automagical wiring. Bean references must be defined in the XML file via the `<ref/>` element (or `ref` attribute).
We recommend this in most cases as it makes documentation more explicit.
Note that this default mode also allows for annotation-driven autowiring, if activated.
`no` refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses
|
54,141,802 |
i am using a viewbag to show a drop down in view .. now when my post method is complete it returns back to view which then throws exception for dropdown because my view bag has nothing after that .
```
[HttpGet]
public ActionResult Add(string id)
{
List<req> objlist = new List<req>();
objlist = Getlist(Id);
ViewBag.List = objlist;
TempData["tempList"] = ViewBag.List;
return View();
}
```
Above is my Get method and for POST method can i do this
```
[HttpPost]
public ActionResult Add()
{
ViewBag.List = TempData["tempList"];
return View();
}
```
All this because i dont want Run the SQL Call again .
|
2019/01/11
|
['https://Stackoverflow.com/questions/54141802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10250043/']
|
Here is an example combining transform and some gradient:
```css
.CD {
width: 200px;
height: 200px;
margin: auto;
background:
linear-gradient(to bottom, #000 0,
#000 calc(50% - 20px), transparent calc(50% - 20px),
transparent calc(50% + 20px), #000 calc(50% + 20px))
center/3px 100%,
linear-gradient(to right, #000 0,
#000 calc(50% - 20px), transparent calc(50% - 20px),
transparent calc(50% + 20px), #000 calc(50% + 20px))
center/100% 3px,
radial-gradient(circle at center, transparent 20px, #000 21px, #000 23px, grey 24px);
background-repeat: no-repeat;
border: 2px solid;
border-radius: 100%;
position: relative;
transform: perspective(350px) rotateX(65deg);
}
.CD::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: inherit;
background-size: 3px 100%, 100% 3px, 0 0;
border-radius: inherit;
transform: rotate(45deg);
}
.bar {
width: 20px;
height: 74px;
margin: 25px auto -112px;
z-index: 1;
position: relative;
border-radius: 4px 4px 8px 8px;
background: #000;
}
.middle {
height: 110px;
width: 212px;
background:
linear-gradient(#000,#000) calc(100% - 18px) 10px/3px 50%,
linear-gradient(#000,#000) 18px 10px/3px 50%,
linear-gradient(#000,#000) center/4px 50%,
linear-gradient(#000,#000) top right/3px 50%,
linear-gradient(#000,#000) top left/3px 50%,
radial-gradient(85% 100% at top center,
red 75%,#000 76%,
#000 calc(76% + 3px) ,transparent calc(76% + 4px));
background-repeat:no-repeat;
margin: -90px auto 0;
}
.bottom {
height: 110px;
width: 212px;
background:
linear-gradient(#000,#000) top right/3px 50%,
linear-gradient(#000,#000) top left/3px 50%,
radial-gradient(85% 100% at top center,
green 75%,#000 76%,
#000 calc(76% + 3px) ,transparent calc(76% + 4px));
background-repeat:no-repeat;
margin: -70px auto;
position: relative;
z-index: -1;
}
```
```html
<div class="bar"></div>
<div class="CD"></div>
<div class="middle"></div>
<div class="bottom"></div>
```
And here is with tabs:
```css
.CD {
width: 200px;
height: 200px;
margin: auto;
background:
linear-gradient(to bottom, #000 0,
#000 calc(50% - 20px), transparent calc(50% - 20px),
transparent calc(50% + 20px), #000 calc(50% + 20px))
center/3px 100%,
linear-gradient(to right, #000 0,
#000 calc(50% - 20px), transparent calc(50% - 20px),
transparent calc(50% + 20px), #000 calc(50% + 20px))
center/100% 3px,
radial-gradient(circle at center, transparent 20px, #000 21px, #000 23px, grey 24px);
background-repeat: no-repeat;
border: 2px solid;
border-radius: 100%;
position: relative;
transform: perspective(350px) rotateX(65deg);
z-index:1;
}
.CD::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: inherit;
background-size: 3px 100%, 100% 3px, 0 0;
border-radius: inherit;
transform: rotate(45deg);
}
.bar {
width: 20px;
height: 74px;
margin: 25px auto -112px;
z-index: 2;
position: relative;
border-radius: 4px 4px 8px 8px;
background: #000;
}
.middle {
height: 110px;
width: 212px;
background:
linear-gradient(#000,#000) calc(100% - 18px) 10px/3px 50%,
linear-gradient(#000,#000) 18px 10px/3px 50%,
linear-gradient(#000,#000) center/4px 50%,
linear-gradient(#000,#000) top right/3px 50%,
linear-gradient(#000,#000) top left/3px 50%,
radial-gradient(85% 100% at top center,
red 75%,#000 76%,
#000 calc(76% + 3px) ,transparent calc(76% + 4px));
background-repeat:no-repeat;
margin: -90px auto 0;
display:flex;
}
.bottom {
height: 110px;
width: 212px;
background:
linear-gradient(#000,#000) top right/3px 50%,
linear-gradient(#000,#000) top left/3px 50%,
radial-gradient(85% 100% at top center,
green 75%,#000 76%,
#000 calc(76% + 3px) ,transparent calc(76% + 4px));
background-repeat:no-repeat;
margin: -70px auto;
position: relative;
z-index: -1;
}
.middle > span:first-child,
.middle > span:last-child{
height: 63px;
width: 15px;
margin:0 3px;
}
.middle > span:nth-child(2),
.middle > span:nth-child(3){
flex-grow:1;
height:83px;
}
.middle > span:first-child {
border-radius: 0 0 0 24px;
background: pink;
}
.middle > span:last-child {
border-radius: 0 0 24px 0;
background: orange;
}
.middle > span:nth-child(2) {
margin-right: 2px;
border-radius: 0 0 0 86px/0 0 0 24px;
background:blue;
}
.middle > span:nth-child(3) {
margin-left: 2px;
border-radius: 0 0 86px 0/0 0 24px 0;
background:purple;
}
.middle > span {
cursor:pointer;
}
.middle > span:hover {
filter:brightness(50%);
}
```
```html
<div class="bar"></div>
<div class="CD"></div>
<div class="middle">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div class="bottom"></div>
```
|
You could create a vectorized image in Illustrator and then transform it to SVG code for HTML.
Examples with SVG: <https://www.w3schools.com/graphics/svg_examples.asp>
A practical guide here: <https://svgontheweb.com/>
Inspiration: <https://www.awwwards.com/websites/svg/>
|
102,032 |
Next month I am traveling to country **X**, where I would need **Y** minutes of calls, **Z** text messages and most importantly **Q** megabytes of data. How can I find the cheapest/most reliable SIM card for my needs?
|
2017/09/13
|
['https://travel.stackexchange.com/questions/102032', 'https://travel.stackexchange.com', 'https://travel.stackexchange.com/users/9009/']
|
Your best bet is to check the massively useful website called "[Prepaid Data SIM Card Wiki](https://prepaid-data-sim-card.fandom.com/wiki/Prepaid_SIM_with_data)". They have an article on pretty much every country in the world and it's kept relatively up to date thanks to their volunteer editors.
There is also a new website called [eSimDB](https://esimdb.com/mexico) that provides comparisons between eSIM cards by various virtual operators. The advantage of those is that you can configure everything before leaving. Disclaimer: I am not affiliated with this website in any way.
After you visit country **X** and check out their prepaid offers, make sure to go back to the Data SIM Wiki and update the respective article if something is missing or outdated, so that future readers can use your experience as well.
|
For your usecase I would consider getting a phone which supports eSIM. This will at least in some countries ([see list](https://support.apple.com/en-us/HT209096) on Apple's website) put your in a position to sign up with a GSM operator purely over the Internet (which also means: prior to arrival) and have your plan activated when you arrive. This can be handy if you arrive in places or at times when shops are not open or hard to find.
Yet in some countries GSM operators require a proof of identity in order to sign you up, like Germany or Switzerland for example. In that case, the eSIM enabled operators will usually also allow you to do some kind of remote identification, so you can still prepare prior to arriving.
|
29,227,143 |
I have a simple WPF MVVM application that consist of a `MainWindow` and two UserControl (`Login`, `Register`) and Database Table `Users`. I want to bind the user control to main window like, if in my sql table data already exist then `Login` user control will be displayed else `Register` user control.
|
2015/03/24
|
['https://Stackoverflow.com/questions/29227143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4701699/']
|
If you look at my answer to the [WPF MVVM navigate views](https://stackoverflow.com/questions/19654295/wpf-mvvm-navigate-views/19654812#19654812) question, you'll find a way to display different views in a single place. The answer to your question is for you to implement a similar setup in which you can display either your `Login` view or your `Register` view:
```
public BaseViewModel ViewModel { get; set; }
```
...
```
<DataTemplate DataType="{x:Type ViewModels:LoginViewModel}">
<Views:LoginView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:RegisterViewModel}">
<Views:RegisterView />
</DataTemplate>
```
When your main view model loads, you simply need to check whether you have any data in the database for the current user and then choose to display the relevant view... perhaps something like this:
```
ViewModel = IsUsernameRegistered(username) ? new LoginView() : new RegisterView();
```
|
I got my answer as
Write the below method in **App.xaml.cs** and delete **StartupUri=""** from **App.xaml**
```
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var con = new SqlConnection
{
ConnectionString = "Data Source=localhost;Initial Catalog=demo;User ID=sa;Password=mypassword;"
};
con.Open();
const string chkadmin = "select COUNT(*) from dbo.Registrations";
var command = new SqlCommand(chkadmin, con);
int count = Convert.ToInt32(command.ExecuteScalar());
if (count == 0)
{
var reg = new AdminUser(); //this is the Registration window class
this.MainWindow = reg;
reg.Show();
}
else
{
var win = new Home(); //this is the Home window class
this.MainWindow = win;
win.Show();
}
}
```
|
193,306 |
I'm a chrome user and an enthusiast but few days ago I made Ubuntu get some updates using `Update Manager`, then I turned off my notebook and when I restarted it, I tried to start Chrome which after a few seconds turned the screen completely black, and some errors appeared for few seconds and then I got logged off, and had to re-login,
and when I opened Chrome again the same thing happened!
I've uninstalled it with Synaptic and did complete cleanings before re-installing Chrome but nothing succeeded. Now I can't use either Chromium and Chrome, but Firefox works. It's a very strange thing, never happened to me before and I don't know what to do because I had all my bookmarks syncronized in Chrome!
Please help if you can :)
|
2012/09/26
|
['https://askubuntu.com/questions/193306', 'https://askubuntu.com', 'https://askubuntu.com/users/92902/']
|
If your bookmarks are the only thing you are worried about, you can recover them from
the terminal by running `cp ~/.config/google-chrome/Default/Bookmarks* ~/.` This will copy your Chrome bookmarks to your home folder directory.
You should sync Chrome through Google, it is one of the major selling points of chrome. <http://www.guidingtech.com/3125/chrome-bookmarks-sync/>
I also recommend you do the following: open the terminal and run
Chrome. It will crash but give you an output of what may have happened.
You can use the command
```
tail -f /var/log/syslog
```
to see what may have gone wrong.
My advice for you though is to make a new profile: Briefly, after backing up your data, open nautilus (home folder), press `Ctrl``H` to display hidden files, navigate to `.config/` and delete both `chromium` and `google-chrome` folders and start Chrome over. A totally clean profile will be recreated automatically. Let us know what happened, so I can improve my answer.
The official version on creating a new profile in Chrome is here: [Create a new browser user profile](http://support.google.com/chrome/bin/answer.py?hl=en&answer=142059).
|
Same thing happened to me, and I found the following user who was able to resolve the issue:
<http://productforums.google.com/forum/#!msg/chrome/xcKqyLSij5A/OGSpv2FaLZoJ>
Could it be that in your case, as in mine and the above user's, you tried updating your NVIDIA drivers and something went wrong? If so a reinstall of the same driver might help.
|
13,672,727 |
I am writing a webapp that utilizes localstorage. I have it setup now to save to the local storage with the following format:
Key: Four digit number
Value: My data
I need to take all the separate data from the localStorage, and output it to a single file with the following format:
XXXX <- Four digit key
Data
-linebreak-
How would I go about doing this? Also, is it possible to somehow take all this information, and send it via email. Or some way to get it out of localstorage and to clipboard so the user can copy it into their email.
Thanks ahead.
|
2012/12/02
|
['https://Stackoverflow.com/questions/13672727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1341539/']
|
```
var output = "";
for(var key in localStorage) {
output += key+"\n";
output += localStorage[key]+"\n";
output += "\n";
}
// output contains combined string
```
As for the email part you could try using a `mailto:` like this,
```
<a href='mailto:user@domain?subject=[subject here]&body=[email body here]'></a>
```
This could be combined into a function like this:
```
function sendLocalStorageByEmail(recipient) {
// create localstorage string
var output = "";
for(var key in localStorage) {
output += key+"\n";
output += localStorage[key]+"\n";
output += "\n";
}
// create temporary anchor to emulate mailto click in new tab
var anchor = document.createElement("a");
anchor.href = "mailto:"+recipient+"?subject=Local+Storage+Data&body="+encodeURIComponent(output);
anchor.style.display = "none";
anchor.setAttribute("target","_blank");
anchor.appendChild(document.createTextNode(""));
document.body.appendChild(anchor);
if (anchor.click) {
return anchor.click();
}
// some browsers (chromium/linux) have trouble with anchor.click
var clickEv = document.createEvent("HTMLEvents");
clickEv.initEvent("click", true, true);
anchor.dispatchEvent(clickEv)
}
```
Usage:
```
<a href='javascript:sendLocalStorageByEmail(prompt("Please enter your e-mail address"))'>
Send Email
</a>
```
|
It is possible to integrate directly mail adress in the code, before mailto:
```
anchor.href = "mailto:*[email protected]*"+recipient+"?
subject=Local+Storage+Data&body="+encodeURIComponent(output);
```
|
3,956,004 |
I would like to deactivate the right click in my app that offers the option to install the app on the desktop. How do I do such thing?
|
2010/10/18
|
['https://Stackoverflow.com/questions/3956004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375814/']
|
Right click on the project in Visual Studio and select properties. There is a check-box "enable running out of browser" option there.
|
Here's a hackish way to do it for older versions of SilverLight from [a silverlight forum](http://forums.silverlight.net/forums/p/37820/350972.aspx):
```
<div id="silverlightObjDiv">
<!-- silverlight object here -->
</div>
<script>
document.getElementById('silverlightObjDiv').oncontextmenu = disableRightClick;
function disableRightClick(e) {
if (!e) e = window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
</script>
```
If you are using a recent version, you can disable this behavior from the properties of your project.
|
4,249,795 |
I've been working with Java for a long time but never have come across something like this.
I would like to know what it does and why it is not an error.
```
public class Foo{
private int someVariable;
{
doSomething();
}
public Foo(){
}
private void doSomething(){
// Something is done here
}
}
```
I would like to know what the purpose of the individual block is which contains a call to "doSomething()".
Its just a skeleton code. The actual code that I came across is at <http://www.peterfranza.com/2010/07/15/gwt-scrollpanel-for-touch-screens/>
|
2010/11/22
|
['https://Stackoverflow.com/questions/4249795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297376/']
|
It's a (non-static) initializer block. It is documented in the official tutorial [here](http://download.oracle.com/javase/tutorial/java/javaOO/initial.html):
>
> **Initializing Instance Members**
>
>
> Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
> Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
>
>
>
> ```
> {
> // whatever code is needed for initialization goes here
> }
>
> ```
>
> The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
>
>
>
---
Here is a simple demo:
```
public class Test {
{
System.out.println("Initializer block");
}
Test() {
System.out.println("Constructor 1");
}
Test(int i) {
System.out.println("Constructor 2");
}
public static void main(String[] args) {
new Test();
System.out.println("---");
new Test(1);
}
}
```
**Output**:
```
Initializer block
Constructor 1
---
Initializer block
Constructor 2
```
---
You may find this useful when for instance adding a `JLabel` to panel:
```
panel.add(new JLabel() {{ setBackground(Color.GREEN); setText("Hello"); }});
```
---
**Under the hood:**
The bytecode of the initializer block is literally copied into each constructor. (At least by Suns javac and the eclipse compiler:
```
Test();
Code:
0: aload_0
1: invokespecial
4: getstatic #2;
7: ldc #3; //String "Initializer block"
9: invokevirtual #4; //Method PrintStream.println:(String;)V
12: getstatic #2;
15: ldc #5;
17: invokevirtual #4;
20: return
Test(int);
Code:
0: aload_0
1: invokespecial #1;
4: getstatic #2;
7: ldc #3; //String "Initializer block"
9: invokevirtual #4; //Method PrintStream.println:(String;)V
12: getstatic #2;
15: ldc #6;
17: invokevirtual #4;
20: return
```
|
That's an initializer block, which is copied into all constructors for the class.
|
59,512,508 |
I had been trying to do it like when I add a new line to a normal statement but it doesn't work if I do it like that.
```
cars = ["audi", "bmw", "toyota"]
print(\ncars)
```
It shows this error:
```
SyntaxError: unexpected character after line continuation character
```
How does one add a new line to a printed list? Btw I am a beginner to python and programming in general.
|
2019/12/28
|
['https://Stackoverflow.com/questions/59512508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11820914/']
|
try this:
```
print("\n",cars)
```
write backslash n, instead of slash n
|
Try
```
print("\n"+cars)
```
That's the correct way to do it.
You need to write backslash n, not forward slash n
|
59,512,508 |
I had been trying to do it like when I add a new line to a normal statement but it doesn't work if I do it like that.
```
cars = ["audi", "bmw", "toyota"]
print(\ncars)
```
It shows this error:
```
SyntaxError: unexpected character after line continuation character
```
How does one add a new line to a printed list? Btw I am a beginner to python and programming in general.
|
2019/12/28
|
['https://Stackoverflow.com/questions/59512508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11820914/']
|
`print("\n".join(cars))`
This was answered already here:
[Printing list elements on separated lines in Python](https://stackoverflow.com/questions/6167731/printing-list-elements-on-separated-lines-in-python)
|
Try
```
print("\n"+cars)
```
That's the correct way to do it.
You need to write backslash n, not forward slash n
|
59,512,508 |
I had been trying to do it like when I add a new line to a normal statement but it doesn't work if I do it like that.
```
cars = ["audi", "bmw", "toyota"]
print(\ncars)
```
It shows this error:
```
SyntaxError: unexpected character after line continuation character
```
How does one add a new line to a printed list? Btw I am a beginner to python and programming in general.
|
2019/12/28
|
['https://Stackoverflow.com/questions/59512508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11820914/']
|
try this:
```
print("\n",cars)
```
write backslash n, instead of slash n
|
`print("\n".join(cars))`
This was answered already here:
[Printing list elements on separated lines in Python](https://stackoverflow.com/questions/6167731/printing-list-elements-on-separated-lines-in-python)
|
25,071,854 |
I've been stuck on this problem for quite some time to the point that I've moved on and finished experimenting with coding other quiz styles ala-Buzzfeed. Now, the logic goes, "Once a radio button in all of the radio button sets are clicked, show the div"
I've "somewhat" solved this problem by cheating my way to it, a.k.a by making a button which listens when a radio button in all sets are clicked. But, that's not what I want to happen.
Help?
```
//PART OF THE CODE GOES...
//RESULTS ALGORITHM
$('#submit').click(function() {
var choice1 = 0;
var choice2 = 0;
var choice3 = 0;
var choice4 = 0;
var choice5 = 0;
var choice6 = 0;
$('input[type=radio]').prop('disabled', true);
//REQUIRES ANSWERS TO ALL QUESTIONS
if (($("input[name='qa4']:checked").length == "0") ||
($("input[name='qa5']:checked").length == "0")){
alert("Please answer all questions.");
}
else{
//TABULATE THE RESULTS OF ANSWERS
switch(parseInt($("input[name='qa1']:checked").val())){
case 1: choice1++; break;
case 2: choice2++; break;
case 3: choice3++; break;
case 4: choice4++; break;
case 5: choice5++; break;
case 6: choice6++; break;
}
```
Full Code Fiddle: <http://jsfiddle.net/djleonardo/m4Jcb/>
|
2014/08/01
|
['https://Stackoverflow.com/questions/25071854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3804291/']
|
```
$("input[name^=qa]").on('change', function() {
if(!$("input[name^=qa]:not(:checked)").length) {
//all input box that name begin with "qa" checked
$('div#id').show();
} else {
// do some stuff here while it's not all checked.
}
});
```
|
I solved it by enclosing your `.click()` inside a function `giveResults()` that will be called from a `.click()` event on the `.a-choice` once every input is `:checked` ;)
[Fixed JsFiddle](http://jsfiddle.net/m4Jcb/1/)
|
35,005,158 |
What is the difference between the `@ComponentScan` and `@EnableAutoConfiguration` annotations in Spring Boot? Is it necessary to add these? My application works very well without these annotations. I just want to understand why we have to add them.
|
2016/01/26
|
['https://Stackoverflow.com/questions/35005158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5258516/']
|
>
> What is the difference between the @ComponentScan and
> @EnableAutoConfiguration annotations in Spring Boot?
>
>
>
[`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) annotation tells Spring Boot to "guess" how you will want to configure Spring, based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring will auto-configure an in-memory database.
[`@ComponentScan`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html) tells Spring to look for other components, configurations, and services in the specified package. Spring is able to auto scan, detect and register your beans or components from pre-defined project package. If no package is specified current class package is taken as the root package.
>
> Is it necessary to add these?
>
>
>
If you need Spring boot to Auto configure every thing for you [`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) is required. You don't need to add it manually, spring will add it internally for you based on the annotation you provide.
Actually the [`@SpringBootApplication`](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html) annotation is equivalent to using [`@Configuration`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html), [`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) and [`@ComponentScan`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html) with their default attributes.
**See also:**
* [Using the @SpringBootApplication annotation](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html)
* [Auto-configuration](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html)
|
One of the main advantages of Spring Boot is its annotation driven versus traditional xml based configurations, **@EnableAutoConfiguration** automatically configures the Spring application based on its included jar files, it sets up defaults or helper based on dependencies in pom.xml.
Auto-configuration is usually applied based on the classpath and the defined beans. Therefore, we donot need to define any of the DataSource, EntityManagerFactory, TransactionManager etc and magically based on the classpath, Spring Boot automatically creates proper beans and registers them for us. For example when there is a tomcat-embedded.jar on your classpath you likely need a TomcatEmbeddedServletContainerFactory (unless you have defined your own EmbeddedServletContainerFactory bean). @EnableAutoConfiguration has a exclude attribute to disable an auto-configuration explicitly otherwise we can simply exclude it from the pom.xml, for example if we donot want Spring to configure the tomcat then exclude spring-bootstarter-tomcat from spring-boot-starter-web.
**@ComponentScan** provides scope for spring component scan, it simply goes though *the provided base package* and picks up dependencies required by @Bean or @Autowired etc, In a typical Spring application, @ComponentScan is used in a configuration classes, the ones annotated with @Configuration. Configuration classes contains methods annotated with @Bean. These @Bean annotated methods generate beans managed by Spring container. Those beans will be auto-detected by @ComponentScan annotation. There are some annotations which make beans auto-detectable like @Repository , @Service, @Controller, @Configuration, @Component.
In below code Spring starts scanning from the package including BeanA class.
```
@Configuration
@ComponentScan(basePackageClasses = BeanA.class)
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Config {
@Bean
public BeanA beanA(){
return new BeanA();
}
@Bean
public BeanB beanB{
return new BeanB();
}
}
```
|
35,005,158 |
What is the difference between the `@ComponentScan` and `@EnableAutoConfiguration` annotations in Spring Boot? Is it necessary to add these? My application works very well without these annotations. I just want to understand why we have to add them.
|
2016/01/26
|
['https://Stackoverflow.com/questions/35005158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5258516/']
|
>
> What is the difference between the @ComponentScan and
> @EnableAutoConfiguration annotations in Spring Boot?
>
>
>
[`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) annotation tells Spring Boot to "guess" how you will want to configure Spring, based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring will auto-configure an in-memory database.
[`@ComponentScan`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html) tells Spring to look for other components, configurations, and services in the specified package. Spring is able to auto scan, detect and register your beans or components from pre-defined project package. If no package is specified current class package is taken as the root package.
>
> Is it necessary to add these?
>
>
>
If you need Spring boot to Auto configure every thing for you [`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) is required. You don't need to add it manually, spring will add it internally for you based on the annotation you provide.
Actually the [`@SpringBootApplication`](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html) annotation is equivalent to using [`@Configuration`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html), [`@EnableAutoConfiguration`](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html) and [`@ComponentScan`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html) with their default attributes.
**See also:**
* [Using the @SpringBootApplication annotation](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html)
* [Auto-configuration](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html)
|
**`@EnableAutoConfiguration`** in spring boot tells how you want to configure spring, based on the jars that you have added in your classpath.
For example, if you add `spring-boot-starter-web` dependency in your classpath, it automatically configures Tomcat and Spring MVC.
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
You can use `@EnableAutoConfiguration` annotation along with `@Configuration` annotation.
It has two optional elements,
* exclude : if you want to exclude the auto-configuration of a class.
* excludeName : if you want to exclude the auto-configuration of a class using fully qualified name of class.
Examples:
```
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
@EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
`@SpringBootApplication` is a newer version of `@EnableAutoConfiguration` which was introduced in Spring Boot 1.2.
`@SpringBootApplication` is a combination of three annotations,
* `@Configuration` - for java based configuration classes.
* `@ComponentScan` - to enable component scanning, all the packages and
subpackages will be auto-scanned which are under the root package on
which @SpringBootApplication is applied.
* `@EnableAutoConfiguration` - to enable auto-configuration of the
classes bases on the jars added in classpath.
**`@ComponentScan`** enables component scanning so that web controller classes and other components that you create will be automatically
discovered and registered as beans in spring's application context.
You can specify the base packages that will be scanned for auto-discovering and registering of beans.
One of the optional element is,
* basePackages - can be used to state specific packages to scan.
Example,
```
@ComponentScan(basePackages = {"com.example.test"})
@Configuration
public class SpringConfiguration { }
```
|
35,005,158 |
What is the difference between the `@ComponentScan` and `@EnableAutoConfiguration` annotations in Spring Boot? Is it necessary to add these? My application works very well without these annotations. I just want to understand why we have to add them.
|
2016/01/26
|
['https://Stackoverflow.com/questions/35005158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5258516/']
|
One of the main advantages of Spring Boot is its annotation driven versus traditional xml based configurations, **@EnableAutoConfiguration** automatically configures the Spring application based on its included jar files, it sets up defaults or helper based on dependencies in pom.xml.
Auto-configuration is usually applied based on the classpath and the defined beans. Therefore, we donot need to define any of the DataSource, EntityManagerFactory, TransactionManager etc and magically based on the classpath, Spring Boot automatically creates proper beans and registers them for us. For example when there is a tomcat-embedded.jar on your classpath you likely need a TomcatEmbeddedServletContainerFactory (unless you have defined your own EmbeddedServletContainerFactory bean). @EnableAutoConfiguration has a exclude attribute to disable an auto-configuration explicitly otherwise we can simply exclude it from the pom.xml, for example if we donot want Spring to configure the tomcat then exclude spring-bootstarter-tomcat from spring-boot-starter-web.
**@ComponentScan** provides scope for spring component scan, it simply goes though *the provided base package* and picks up dependencies required by @Bean or @Autowired etc, In a typical Spring application, @ComponentScan is used in a configuration classes, the ones annotated with @Configuration. Configuration classes contains methods annotated with @Bean. These @Bean annotated methods generate beans managed by Spring container. Those beans will be auto-detected by @ComponentScan annotation. There are some annotations which make beans auto-detectable like @Repository , @Service, @Controller, @Configuration, @Component.
In below code Spring starts scanning from the package including BeanA class.
```
@Configuration
@ComponentScan(basePackageClasses = BeanA.class)
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Config {
@Bean
public BeanA beanA(){
return new BeanA();
}
@Bean
public BeanB beanB{
return new BeanB();
}
}
```
|
**`@EnableAutoConfiguration`** in spring boot tells how you want to configure spring, based on the jars that you have added in your classpath.
For example, if you add `spring-boot-starter-web` dependency in your classpath, it automatically configures Tomcat and Spring MVC.
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
You can use `@EnableAutoConfiguration` annotation along with `@Configuration` annotation.
It has two optional elements,
* exclude : if you want to exclude the auto-configuration of a class.
* excludeName : if you want to exclude the auto-configuration of a class using fully qualified name of class.
Examples:
```
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
@EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
`@SpringBootApplication` is a newer version of `@EnableAutoConfiguration` which was introduced in Spring Boot 1.2.
`@SpringBootApplication` is a combination of three annotations,
* `@Configuration` - for java based configuration classes.
* `@ComponentScan` - to enable component scanning, all the packages and
subpackages will be auto-scanned which are under the root package on
which @SpringBootApplication is applied.
* `@EnableAutoConfiguration` - to enable auto-configuration of the
classes bases on the jars added in classpath.
**`@ComponentScan`** enables component scanning so that web controller classes and other components that you create will be automatically
discovered and registered as beans in spring's application context.
You can specify the base packages that will be scanned for auto-discovering and registering of beans.
One of the optional element is,
* basePackages - can be used to state specific packages to scan.
Example,
```
@ComponentScan(basePackages = {"com.example.test"})
@Configuration
public class SpringConfiguration { }
```
|
26,691,252 |
I've been trying to recreate a list like the one below (the checkbox and the x are just png images) but I can't seem to figure it out.

I have tried using two texted cols but I can't for the life of me figure out how to get the alignment and the text breaks correct.
Any help would be very much appreciated.
Right now, my code looks like this:
```
<div class="row">
<div class="col-md-6 col-md-6-offset-2">
<h4 style="text-align: center;">THEY LOVE</h4>
<div class="row ">
<div class="col-xs-1">
<img src="http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png">
</div>
<div class="col-xs-11">
<p style="padding-top: 8px;">Stuff</p>
</div>
</div>
</div>
<div class="col-md-6" style="text-align: center;"><h4>THEY DON'T LOVE</h4></div>
<div class="row ">
<div class="col-xs-1">
<img src="http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png">
</div>
<div class="col-xs-10">
<p style="padding-top: 8px;">Stuff</p>
</div>
</div>
</div>
```
|
2014/11/01
|
['https://Stackoverflow.com/questions/26691252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1816357/']
|
DEMO: <http://jsbin.com/faboze/1/>
----------------------------------
*<http://jsbin.com/faboze/1/edit?html,css,output>*

*Look carefully at the html and the css so you can understand how to adjust the spacing and how a hanging indent is done with an un-ordered list. Also look at the grid classes used.*
```
<div class="container">
<div class="row">
<div class="col-sm-offset-2 col-sm-4">
<h4 class="text-center">THEY LOVE</h4>
<ul class="list-unstyled love">
<li>Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.</li>
<li>Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.</li>
<li>Phasellus ultrices nulla quis nibh. Quisque a lectus. Donec consectetuer ligula vulputate sem tristique cursus. Nam nulla quam, gravida non, commodo a, sodales sit amet, nisi.</li>
<li>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</li>
</ul>
</div>
<div class="col-sm-4">
<h4 class="text-center">THEY DON’T LOVE</h4>
<ul class="list-unstyled no-love">
<li>Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.</li>
<li>Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.</li>
<li>Phasellus ultrices nulla quis nibh. Quisque a lectus. Donec consectetuer ligula vulputate sem tristique cursus. Nam nulla quam, gravida non, commodo a, sodales sit amet, nisi.</li>
<li>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</li>
</ul>
</div>
</div>
</div>
```
**CSS**
```
.list-unstyled.love li,
.list-unstyled.no-love li {
background: url('http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png') no-repeat;
padding:0 0 5% 45px;
}
/* ======= change the no-love image ========== */
.list-unstyled.no-love li {
background: url('http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png') no-repeat;
}
```
|
You didnt close your tags properly. Check below code.
You can use text-center class from bootstrap for centering the stuff.
```html
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row text-center">
<div class="col-md-6 col-md-6-offset-2">
<h4>THEY LOVE</h4>
<div class="row ">
<div class="col-xs-1">
<img src="http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png"/>
</div>
<div class="col-xs-11">
<p style="padding-top: 8px;">Stuff</p>
</div>
</div>
</div>
<div class="col-md-6"><h4>THEY DON'T LOVE</h4>
<div class="row ">
<div class="col-xs-1">
<img src="http://d26mw3lpqa99qj.cloudfront.net/prod-fool/sell/yes-15d4ba569f9f4beb7d8cfd8adc8ed886.png"/>
</div>
<div class="col-xs-11">
<p style="padding-top: 8px;">Stuff</p>
</div>
</div>
</div>
```
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.
It'd be wonderful if you could do something like `div[div.a]` or `div:containing[div.a]` as you said, but this isn't possible.
You may want to consider looking at [jQuery](http://jquery.com). Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.
If you use jQuery, something along the lines of this would may work (untested but the theory is there):
```
$('div:has(div.a)').css('border', '1px solid red');
```
or
```
$('div:has(div.a)').addClass('redBorder');
```
combined with a CSS class:
```
.redBorder
{
border: 1px solid red;
}
```
Here's the documentation for the [jQuery "has" selector](http://api.jquery.com/has-selector/).
|
Basically, no. The following *would* be what you were after in theory:
```
div.a < div { border: solid 3px red; }
```
Unfortunately it doesn't exist.
There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:
<http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors>
Update. Many years later, :has has arrived, browser support is increasing.
<https://developer.mozilla.org/en-US/docs/Web/CSS/:has>
12 years is a long time.
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.
It'd be wonderful if you could do something like `div[div.a]` or `div:containing[div.a]` as you said, but this isn't possible.
You may want to consider looking at [jQuery](http://jquery.com). Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.
If you use jQuery, something along the lines of this would may work (untested but the theory is there):
```
$('div:has(div.a)').css('border', '1px solid red');
```
or
```
$('div:has(div.a)').addClass('redBorder');
```
combined with a CSS class:
```
.redBorder
{
border: 1px solid red;
}
```
Here's the documentation for the [jQuery "has" selector](http://api.jquery.com/has-selector/).
|
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the *decisions* in the logic and not based on a CSS state.
**tl;dr;** apply the `a` and `b` styles to the parent `<div>`, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
```
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
```
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.
It'd be wonderful if you could do something like `div[div.a]` or `div:containing[div.a]` as you said, but this isn't possible.
You may want to consider looking at [jQuery](http://jquery.com). Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.
If you use jQuery, something along the lines of this would may work (untested but the theory is there):
```
$('div:has(div.a)').css('border', '1px solid red');
```
or
```
$('div:has(div.a)').addClass('redBorder');
```
combined with a CSS class:
```
.redBorder
{
border: 1px solid red;
}
```
Here's the documentation for the [jQuery "has" selector](http://api.jquery.com/has-selector/).
|
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
```
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
After implementing the following line code within the [initComplete](https://datatables.net/reference/option/initComplete) function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
```
$('tbody td:has(input.a)').css('padding', '0px');
```
Now, you can see that the correct styles are being applied to the parent element:
```
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
Basically, no. The following *would* be what you were after in theory:
```
div.a < div { border: solid 3px red; }
```
Unfortunately it doesn't exist.
There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:
<http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors>
Update. Many years later, :has has arrived, browser support is increasing.
<https://developer.mozilla.org/en-US/docs/Web/CSS/:has>
12 years is a long time.
|
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the *decisions* in the logic and not based on a CSS state.
**tl;dr;** apply the `a` and `b` styles to the parent `<div>`, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
```
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
```
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
Basically, no. The following *would* be what you were after in theory:
```
div.a < div { border: solid 3px red; }
```
Unfortunately it doesn't exist.
There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:
<http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors>
Update. Many years later, :has has arrived, browser support is increasing.
<https://developer.mozilla.org/en-US/docs/Web/CSS/:has>
12 years is a long time.
|
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
```
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
After implementing the following line code within the [initComplete](https://datatables.net/reference/option/initComplete) function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
```
$('tbody td:has(input.a)').css('padding', '0px');
```
Now, you can see that the correct styles are being applied to the parent element:
```
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
|
2,326,499 |
Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?
I think this is best explained using an example.
**Note**: I'm trying to **style the parent element**, depending on what child elements it contains.
```
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
```
**Note 2**: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.
|
2010/02/24
|
['https://Stackoverflow.com/questions/2326499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19635/']
|
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the *decisions* in the logic and not based on a CSS state.
**tl;dr;** apply the `a` and `b` styles to the parent `<div>`, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
```
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
```
|
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
```
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
After implementing the following line code within the [initComplete](https://datatables.net/reference/option/initComplete) function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
```
$('tbody td:has(input.a)').css('padding', '0px');
```
Now, you can see that the correct styles are being applied to the parent element:
```
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
```
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
|
9,923,265 |
I'm trying to utilise TFS Team Build to deploy web applications from a solution as part of the build process, however I'm having a problem with the IIS website name when using package .zip and cmd files.
In the web application project settings "Package/Publish Web" tab I can set the IIS website name (eg "mobile") and when the project is built using the MSBuild action from the workflow the resulting .zip and .xml files are created correctly. However, upon opening the SetParamters.xml file, the IIS Web Application Name parameter has an old value, something like "Default website/mobile\_deploy".
If I build a package directly from within Visual Studio 2010 the SetParameters.xml has the IIS Web Application Name I set in the project file settings.
The build template is set to clear the workspace on each build and I've confirmed this by watching the binaries folder being cleared on the build agent during the build so I'm certain its not the value hasn't been overwritten.
Any suggestions to get the project's IIS Web Application Name pulled through properly?
|
2012/03/29
|
['https://Stackoverflow.com/questions/9923265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329666/']
|
Maybe, when you build your project through `MSBuild` you don't set the same `Configuration` in which you have changed the `IIS Web Site/application name` through `Package/Publish Web` settings on Visual Studio 2010.
|
The deploy path can be different for each Project Configuration. Perhaps you set the Debug value while TFS is using Release?
|
33,631 |
I need help dimensioning a screw-beam system of a press. I built one prototype but the beam is bending too much.
Below is a sketch of my press. In the middle it has a fixing screw which presses downwards on a beam (3D printed plastic) that presses down my Device Under Test (DUT). The problem is that the beam bends too much so it doesn’t apply pressure evenly downwards on the DUT.
(I used plastic instead of a harder material because I have access to a 3D printer but no access to a workshop)
[](https://i.stack.imgur.com/Pltvh.jpg)
I did some research and found in the book “Mechanics of Materials” of Gere and Timoshenko following formulae for displacement $\delta$:
$$
\delta = \frac{F\cdot L^3}{48 \cdot E \cdot I}
$$
F = Force downward
L = Length of beam
E = Young's Modulus
I = Moment of inertia
And for the moment of inertia:
$$
I = \frac{b \cdot h^3}{12}
$$
So that I have
$$
\delta = \frac{F\cdot L^3}{4 \cdot E \cdot b \cdot h^3}
$$
I believe I can specify a maximum displacement $\delta$ of let’s say 0.1 mm and the compute the necessary beam height $h$ or choose another material with a higher Young’s modulus E
* My first question is: How do I compute the force F that the screw is foing downwards? I tried looking in Shigley’s “Mechanical engineering Design” Chapter about screws but couldn’t find anything.
* My second question is: Is my dimensioning approach (to specify a maximum bending) correct?
Thanks in advance!
|
2020/03/13
|
['https://engineering.stackexchange.com/questions/33631', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/21516/']
|
You are on track with your beam calculations, but I doubt you will be happy with the results, just because a 3-D printed part is unlikely to act the way a cast or milled solid plastic part would. You would be well served to just buy aluminum bar stock and cut it with a hack saw.
As to the screw force produced, I doubt you will be happy with that either. Much of the torque will go to thread friction instead of down into the beam. Without friction, a screw is modeled as an simple inclined plane, so force exerted would be given by dividing the force produced by the sine of the thread angle (not the angle of the threads, but of the pitch, in metric threads the arctan of pitch/diameter). The force would be the torque divided by the radius, to the mid-point of the threads. Greased threads would be appropriate, and you could use a scale to calculate your friction losses.
I recommend using something like a beam that you can place weights on to give you a force driving downward onto your testing beam. It can then act directly without worry of friction. Loosely anchor the beam on one side of your press, have a connector going down to your testing device, and extend the beam over the other side. Known weights will then produce a known force, and you could also change the lever by placing weights on different notches along the beam.
|
Force F is related to torque and the pitch of the screw:
let's call the radius of your screw r and the tread pitch N and torque t.
$ F= \frac{\tau/r}{(2\pi r/N )} $
And the answer to the 2nd part is the numbers are ok, but these are for very small angles of deformation, things around a few degrees, and L should bee the distance between the supports as Jko said.
|
15,467,646 |
Im implementing HeapSort for an assignment in my algorithms class, and Im finally done, but for some reason, the sort is skipping over the first element in my array.
Original array:
```
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
```
Output after HeapSort()
```
5 99 32 15 13 12 8 4 1
```
Iv gone through all the functions and cant figure out why its skipping the first element. Can anyone help me out? Iv included all the HeapSort functions below. I know its alot to look at, but im sooooo close.
```
int main()
{
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
HeapSort(heapArray);
return 0;
}
```
.........................................................................................
```
void HeapSort(int heapArray[])
{
int heap_size = SIZE;
int n = SIZE;
int temp;
Build_Max_Heap(heapArray);
for(int i = n-1; i >= 2; i--)
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);
}
return;
}
```
...........................................................................................
```
void Build_Max_Heap(int heapArray[])
{
double n = SIZE;
for(double i = floor((n-1)/2); i >= 1; i--)
{
Max_Heapify(heapArray,i);
}
return;
}
```
...........................................................................................
```
void Max_Heapify(int heapArray[],int i)
{
int n = SIZE;
int largest = 0;
int l = Left(i);
int r = Right(i);
if(( l <= n) && (heapArray[l] > heapArray[i]))
{
largest = l;
}
else
{
largest = i;
}
if( (r <= n) && ( heapArray[r] > heapArray[largest]))
{
largest = r;
}
int temp;
if(largest != i)
{
temp = heapArray[i];
heapArray[i] = heapArray[largest];
heapArray[largest] = temp;
Max_Heapify(heapArray,largest);
}
return;
}
```
...........................................................................................
```
int Parent(int i)
{
return (i/2);
}
int Left(int i)
{
return (2*i);
}
int Right(int i)
{
return ((2*i)+1);
}
```
|
2013/03/17
|
['https://Stackoverflow.com/questions/15467646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1286945/']
|
You have several issues in your code:
Firstly: array indices start from 0 not 1, therefore, there are many places with index errors listed as follows:
In HeapSort function:
```
for(int i = n-1; i >= 2; i--) {
//should be 1 not 2
temp = heapArray[1]; //should be 0 not 1 in those 2 statements
heapArray[1] = heapArray[i];
heapArray[i] = temp;
}
Max_Heapify(heapArray,1);
//should start from 0 not 1
```
Besides:
```
for(double i = floor((n-1)/2); i >= 1; i--)
{ //should start from 0 not 1
Max_Heapify(heapArray,i);
}
```
You Parent, Left and Right have similar errors, you can see the above two posts.
Meanwhile, You have logical errors in you HeapSort and Max\_Heapfiy function.
You define heap\_size and update it, but you never really used it. You have to pass it into the Max\_Heapify function. Since each time when you put the current largest element to the end of the array, you only need to heapify the remaining elements not the whole heap anymore. This also means that your heapify function has errors since you never really used heap\_size. The correct HeapSort and Max\_Heapify as well as Build\_Max\_Heap function should be:
HeapSort:
```
void HeapSort(int heapArray[])
{
//do what you did before this sentence
Build_Max_Heap(heapArray,heap_size);
//need to pass heap_size since Max_Heapify use heap_size
for(int i = n-1; i >= 1; i--)
{
//...same as you did but pay attention to index
heap_size = heap_size-1;
Max_Heapify(heapArray,0,heap_size); //remember to use heap_size
}
//you declared void, no need to return anything
}
```
Build\_Max\_Heap function:
```
void Build_Max_Heap(int heapArray[], int heapSize) //should use heapSize
{
int n = SIZE;
for(int i = floor((n-1)/2); i >= 0; i--) //here should be 0 not 1
{
Max_Heapify(heapArray,i,heapSize); //should use heapSize
}
}
```
Max\_Heapify function:
```
void Max_Heapify(int heapArray[],int i, int heap_size) //should use heap_size
{
//....here similar to what you did
if(( l < heap_size) && (heapArray[l] > heapArray[i]))
{ //^^compare with heap_size not SIZE
//skip identical part
}
if( (r < heaps_ize) && ( heapArray[r] > heapArray[largest]))
{
//same error as above
}
//skip identical part again
Max_Heapify(heapArray,largest, heap_size); //have to use heap_size
}
}
```
You may need to get a better understanding of the HeapSort algorithm from the pseudocode.
|
here
```
Build_Max_Heap(heapArray);
for(int i = n-1; i >= 2; i--)
{ ^^^^^
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);
}
return;
}
```
you stop looping on i=2, decrease it to 1, don't take first element of heapArray which is indexed by **0**
|
15,467,646 |
Im implementing HeapSort for an assignment in my algorithms class, and Im finally done, but for some reason, the sort is skipping over the first element in my array.
Original array:
```
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
```
Output after HeapSort()
```
5 99 32 15 13 12 8 4 1
```
Iv gone through all the functions and cant figure out why its skipping the first element. Can anyone help me out? Iv included all the HeapSort functions below. I know its alot to look at, but im sooooo close.
```
int main()
{
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
HeapSort(heapArray);
return 0;
}
```
.........................................................................................
```
void HeapSort(int heapArray[])
{
int heap_size = SIZE;
int n = SIZE;
int temp;
Build_Max_Heap(heapArray);
for(int i = n-1; i >= 2; i--)
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);
}
return;
}
```
...........................................................................................
```
void Build_Max_Heap(int heapArray[])
{
double n = SIZE;
for(double i = floor((n-1)/2); i >= 1; i--)
{
Max_Heapify(heapArray,i);
}
return;
}
```
...........................................................................................
```
void Max_Heapify(int heapArray[],int i)
{
int n = SIZE;
int largest = 0;
int l = Left(i);
int r = Right(i);
if(( l <= n) && (heapArray[l] > heapArray[i]))
{
largest = l;
}
else
{
largest = i;
}
if( (r <= n) && ( heapArray[r] > heapArray[largest]))
{
largest = r;
}
int temp;
if(largest != i)
{
temp = heapArray[i];
heapArray[i] = heapArray[largest];
heapArray[largest] = temp;
Max_Heapify(heapArray,largest);
}
return;
}
```
...........................................................................................
```
int Parent(int i)
{
return (i/2);
}
int Left(int i)
{
return (2*i);
}
int Right(int i)
{
return ((2*i)+1);
}
```
|
2013/03/17
|
['https://Stackoverflow.com/questions/15467646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1286945/']
|
You have several issues in your code:
Firstly: array indices start from 0 not 1, therefore, there are many places with index errors listed as follows:
In HeapSort function:
```
for(int i = n-1; i >= 2; i--) {
//should be 1 not 2
temp = heapArray[1]; //should be 0 not 1 in those 2 statements
heapArray[1] = heapArray[i];
heapArray[i] = temp;
}
Max_Heapify(heapArray,1);
//should start from 0 not 1
```
Besides:
```
for(double i = floor((n-1)/2); i >= 1; i--)
{ //should start from 0 not 1
Max_Heapify(heapArray,i);
}
```
You Parent, Left and Right have similar errors, you can see the above two posts.
Meanwhile, You have logical errors in you HeapSort and Max\_Heapfiy function.
You define heap\_size and update it, but you never really used it. You have to pass it into the Max\_Heapify function. Since each time when you put the current largest element to the end of the array, you only need to heapify the remaining elements not the whole heap anymore. This also means that your heapify function has errors since you never really used heap\_size. The correct HeapSort and Max\_Heapify as well as Build\_Max\_Heap function should be:
HeapSort:
```
void HeapSort(int heapArray[])
{
//do what you did before this sentence
Build_Max_Heap(heapArray,heap_size);
//need to pass heap_size since Max_Heapify use heap_size
for(int i = n-1; i >= 1; i--)
{
//...same as you did but pay attention to index
heap_size = heap_size-1;
Max_Heapify(heapArray,0,heap_size); //remember to use heap_size
}
//you declared void, no need to return anything
}
```
Build\_Max\_Heap function:
```
void Build_Max_Heap(int heapArray[], int heapSize) //should use heapSize
{
int n = SIZE;
for(int i = floor((n-1)/2); i >= 0; i--) //here should be 0 not 1
{
Max_Heapify(heapArray,i,heapSize); //should use heapSize
}
}
```
Max\_Heapify function:
```
void Max_Heapify(int heapArray[],int i, int heap_size) //should use heap_size
{
//....here similar to what you did
if(( l < heap_size) && (heapArray[l] > heapArray[i]))
{ //^^compare with heap_size not SIZE
//skip identical part
}
if( (r < heaps_ize) && ( heapArray[r] > heapArray[largest]))
{
//same error as above
}
//skip identical part again
Max_Heapify(heapArray,largest, heap_size); //have to use heap_size
}
}
```
You may need to get a better understanding of the HeapSort algorithm from the pseudocode.
|
The `Parent`, `Left` and `Right` functions are fit for 1-based arrays. For 0-based you need to use:
```
int Parent(int i)
{
return (i - 1) / 2;
}
int Left(int i)
{
return (2 * i) + 1;
}
int Right(int i)
{
return 2 * (i + 1);
}
```
As you can check on example heap:
```
0
/ \
1 2
/ \ / \
3 4 5 6
```
|
683,529 |
A brief summary of my problem is that we have started a DNS server upgrade here at my facility.
We currently have 2 internal dns servers and 2 external dns servers. We are upgrading to new equipment and merging our servers so we have 1 master and 1 slave that will take care of both internal and external dns. Both servers have two NIC's that have been IP'd with one address in the public external network and one in the internal network. On my master I have setup an Internal view that is only accessible from our internal network ranges and an external view that is allowed to be queried by anyone. I have everything setup and DNS resolution works fine. The problem I am getting though is that that when I configured the slave and set it up, the slave will only inherit updates for zones listed in the Internal view. All external view zones give an error of
```
;<<>> DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.2 <<>> IN AXFR 43.96.32.in-addr.arpa @129.yy.yy.10
;; global options: +cmd
; Transfer failed.
```
I have been googling like crazy and cannot find a solution hopefully someone on here might have an idea of why this is occuring.
Below I will give the samples of my master / slave named.conf files. My system is currently running RHEL 6.6 and Bind DNS 9.8.2.
**Master - Named.conf**
```
acl internal_hosts { 10.101.0.0/16; 172.21.0.0/16;
10.2.0.0/16; 169.254.0.0/16;
172.23.0.0/16; 32.0.0.0/8;
12.109.164.0/24; 12.109.165.0/24;
63.79.18.0/24; 63.88.0.0/16;
129.42.0.0/16; 4.30.26.0/24;
4.28.188.0/24; 172.21.131.248/29;};
acl internal_slave { 10.xx.xx.2; };
acl external_slave { 129.yy.yy.11; };
acl internal_master { 10.xx.xx.1; };
acl external_master { 129.yy.yy.10; };
options {
directory "/etc";
pid-file "/var/run/named/named.pid";
dnssec-enable no;
query-source port 53;
forward only;
notify yes;
allow-query { any; };
listen-on {
10.xx.xx.1;
127.0.0.1;
129.yy.yy.10;
};
forwarders {
129.34.20.80;
198.4.83.35;
4.2.2.2;
8.8.8.8;
};
allow-transfer {127.0.0.1; };
};
server 10.xx.xx.2 {
transfer-format many-answers;
transfers 10000;
};
server 129.yy.yy.11 {
transfer-format many-answers;
transfers 10000;
};
view "Internal" {
match-clients { internal_hosts; !external_slave; internal_slave; };
also-notify { 10.xx.xx.2; };
allow-transfer { internal_slave; };
recursion yes;
allow-recursion { internal_hosts; };
transfer-source 10.xx.xx.1;
zone "64.2.10.in-addr.arpa" {
type master;
also-notify { 10.xx.xx.2; };
notify yes;
allow-transfer { internal_slave; };
file "/var/named/10.2.64.rev";
};
view "External" {
match-clients { !internal_slave; external_slave; any; };
recursion no;
allow-transfer { external_slave; };
also-notify { 129.yy.yy.11; };
transfer-source 129.yy.yy.10;
zone "50.146.204.in-addr.arpa" {
type master;
notify yes;
also-notify {129.yy.yy.11;};
allow-transfer {external_slave;};
file "/var/named/204.146.50.rev";
};
```
**Slave - Named.conf**
```
acl internal_hosts { 10.101.0.0/16; 172.21.0.0/16;
10.2.0.0/16; 169.254.0.0/16;
172.23.0.0/16; 32.0.0.0/8;
12.109.164.0/24; 12.109.165.0/24;
63.79.18.0/24; 63.88.0.0/16;
129.42.0.0/16; 4.30.26.0/24;
4.28.188.0/24; 172.21.131.248/29;
};
acl internal_slave { 10.xx.xx.2; };
acl external_slave { 129.yy.yy.11; };
acl internal_master { 10.xx.xx.1; };
acl external_master { 129.yy.yy.10; };
options {
directory "/etc";
pid-file "/var/run/named/named.pid";
dnssec-enable no;
query-source port 53;
forward only;
allow-query { any; };
listen-on port 53 {
127.0.0.1;
10.xx.xx.2;
129.yy.yy.11;
};
forwarders {
129.34.20.80;
198.4.83.35;
4.2.2.2;
8.8.8.8;
};
allow-transfer {127.0.0.1; };
};
server 10.xx.xx.1 {
transfer-format many-answers;
transfers 10000;
};
server 129.yy.yy.10 {
transfer-format many-answers;
transfers 10000;
};
view "Internal" {
match-clients { internal_hosts; !external_master; internal_master; };
recursion yes;
allow-recursion {internal_hosts;};
allow-transfer { internal_master; };
transfer-source 10.xx.xx.2;
allow-notify {10.xx.xx.1;};
zone "64.2.10.in-addr.arpa" {
type slave;
masters {10.xx.xx.1;};
allow-transfer {internal_master;};
allow-update {internal_master;};
file "/var/named/slaves/10.2.64.Internal.rev";
};
view "External" {
allow-transfer {external_master;};
allow-notify {129.yy.yy.10;};
transfer-source 129.yy.yy.11;
match-clients {!internal_master; external_master; internal_hosts; any;};
recursion no;
zone "50.146.204.in-addr.arpa" {
type slave;
masters {129.yy.yy.10;};
allow-transfer {external_master;};
allow-update {external_master;};
file "/var/named/slaves/204.146.50.External.rev";
};
```
Here is an output from my /var/log/messages requested about the DIG to my Master. The DIG for brsbld.ihost.com is the one in the External view that failed, whereas the DIG for bldbcrs.net is in the Internal view and goes through fine.
```
Apr 17 09:32:31 bbridns01 named[1717]: client 10.101.8.2#55756: view Internal: transfer of 'bldbcrs.net/IN': AXFR started
Apr 17 09:32:31 bbridns01 named[1717]: client 10.101.8.2#55756: view Internal: transfer of 'bldbcrs.net/IN': AXFR started
Apr 17 09:32:31 bbridns01 named[1717]: client 10.101.8.2#55756: view Internal: transfer of 'bldbcrs.net/IN': AXFR ended
Apr 17 09:32:31 bbridns01 named[1717]: client 10.101.8.2#55756: view Internal: transfer of 'bldbcrs.net/IN': AXFR ended
Apr 17 09:32:56 bbridns01 named[1717]: client 129.42.206.11#41783: view Internal: bad zone transfer request: 'brsbld.ihost.com/IN': non-authoritative zone (NOTAUTH)
Apr 17 09:32:56 bbridns01 named[1717]: client 129.42.206.11#41783: view Internal: bad zone transfer request: 'brsbld.ihost.com/IN': non-authoritative zone (NOTAUTH)
```
|
2015/04/17
|
['https://serverfault.com/questions/683529', 'https://serverfault.com', 'https://serverfault.com/users/282253/']
|
He guys just wanted to update this to let you know what I found out for the solution. Under my Internal view the match-clients argument was messing me up.
```
match-clients { internal_hosts; !external_slave; internal_slave; };
```
The internal\_hosts acl includes the range 129.42.0.0/16. This was listed before the !external\_slave; argument so it was picking that up first because the slave server is 129.42.206.11 and putting it into the internal view. I rearranged it so that it excludes the external\_slave first then it was properly being picked up by the external view.
```
match-clients { !external_slave; internal_hosts; internal_slave; };
```
|
My guess this line in your master config options is preventing the others from getting the zones:
```
allow-transfer {127.0.0.1; };
```
I'd try removing that line or updating it to include your external\_master.
Perhaps it's because you have multiple views in your config, the default view is getting that limited allow-transfer directive from options.
<http://docs.freebsd.org/doc/8.3-RELEASE/usr/share/doc/bind9/arm/Bv9ARM.ch06.html>
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
Try:
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[ 0 ][ 1 ]
```
However I worry that you are planning to parse xml with regular expressions. If this cdata is part of a larger valid xml document, better to use an xml parser
|
The code below shows the substring extraction using regex in groovy:
```
class StringHelper {
@NonCPS
static String stripSshPrefix(String gitUrl){
def match = (gitUrl =~ /ssh:\/\/(.+)/)
if (match.find()) {
return match.group(1)
}
return gitUrl
}
static void main(String... args) {
def gitUrl = "ssh://[email protected]:jiahut/boot.git"
def gitUrl2 = "[email protected]:jiahut/boot.git"
println(stripSshPrefix(gitUrl))
println(stripSshPrefix(gitUrl2))
}
}
```
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
Try:
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[ 0 ][ 1 ]
```
However I worry that you are planning to parse xml with regular expressions. If this cdata is part of a larger valid xml document, better to use an xml parser
|
A little bit late to the party but try using backslash when defining your pattern, example:
```
def articleContent = "real groovy"
def matches = (articleContent =~ /gr\w{4}/) //grabs 'gr' and its following 4 chars
def firstmatch = matches[0] //firstmatch would be 'groovy'
```
you were on the right track, it was just the pattern definition that needed to be altered.
References:
<https://www.regular-expressions.info/groovy.html>
<http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html>
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
Try:
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[ 0 ][ 1 ]
```
However I worry that you are planning to parse xml with regular expressions. If this cdata is part of a larger valid xml document, better to use an xml parser
|
One more sinle-line solution additional to tim\_yates's one
```
def result = articleContent.replaceAll(/<!\[CDATA\[(.+)]]>/,/$1/)
```
Please, take into account that in case of regexp doesn't match then result will be equal to the source. Unlikely in case of
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[0][1]
```
it will raise an exception.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
Try:
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[ 0 ][ 1 ]
```
However I worry that you are planning to parse xml with regular expressions. If this cdata is part of a larger valid xml document, better to use an xml parser
|
In my case, the actual string was multi-line like below
```
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
```
I wanted to extract the `Start Date` value from this string so here is how my script looks like
```
def matches = (originalData =~ /(?<=Actual Start Date :).*/)
def extractedData = matches[0]
```
This regex extracts the string content from each line which has a prefix matching `Start Date :`
In my case, the result is is `2020-11-25 00:00:00`
**Note :** If your `originalData` is a multi-line string then in groovy you can include it as follows
```
def originalData =
"""
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
"""
```
---
This script looks simple but took me some good time to figure out few things so I'm posting this here.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
The code below shows the substring extraction using regex in groovy:
```
class StringHelper {
@NonCPS
static String stripSshPrefix(String gitUrl){
def match = (gitUrl =~ /ssh:\/\/(.+)/)
if (match.find()) {
return match.group(1)
}
return gitUrl
}
static void main(String... args) {
def gitUrl = "ssh://[email protected]:jiahut/boot.git"
def gitUrl2 = "[email protected]:jiahut/boot.git"
println(stripSshPrefix(gitUrl))
println(stripSshPrefix(gitUrl2))
}
}
```
|
A little bit late to the party but try using backslash when defining your pattern, example:
```
def articleContent = "real groovy"
def matches = (articleContent =~ /gr\w{4}/) //grabs 'gr' and its following 4 chars
def firstmatch = matches[0] //firstmatch would be 'groovy'
```
you were on the right track, it was just the pattern definition that needed to be altered.
References:
<https://www.regular-expressions.info/groovy.html>
<http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html>
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
The code below shows the substring extraction using regex in groovy:
```
class StringHelper {
@NonCPS
static String stripSshPrefix(String gitUrl){
def match = (gitUrl =~ /ssh:\/\/(.+)/)
if (match.find()) {
return match.group(1)
}
return gitUrl
}
static void main(String... args) {
def gitUrl = "ssh://[email protected]:jiahut/boot.git"
def gitUrl2 = "[email protected]:jiahut/boot.git"
println(stripSshPrefix(gitUrl))
println(stripSshPrefix(gitUrl2))
}
}
```
|
One more sinle-line solution additional to tim\_yates's one
```
def result = articleContent.replaceAll(/<!\[CDATA\[(.+)]]>/,/$1/)
```
Please, take into account that in case of regexp doesn't match then result will be equal to the source. Unlikely in case of
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[0][1]
```
it will raise an exception.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
The code below shows the substring extraction using regex in groovy:
```
class StringHelper {
@NonCPS
static String stripSshPrefix(String gitUrl){
def match = (gitUrl =~ /ssh:\/\/(.+)/)
if (match.find()) {
return match.group(1)
}
return gitUrl
}
static void main(String... args) {
def gitUrl = "ssh://[email protected]:jiahut/boot.git"
def gitUrl2 = "[email protected]:jiahut/boot.git"
println(stripSshPrefix(gitUrl))
println(stripSshPrefix(gitUrl2))
}
}
```
|
In my case, the actual string was multi-line like below
```
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
```
I wanted to extract the `Start Date` value from this string so here is how my script looks like
```
def matches = (originalData =~ /(?<=Actual Start Date :).*/)
def extractedData = matches[0]
```
This regex extracts the string content from each line which has a prefix matching `Start Date :`
In my case, the result is is `2020-11-25 00:00:00`
**Note :** If your `originalData` is a multi-line string then in groovy you can include it as follows
```
def originalData =
"""
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
"""
```
---
This script looks simple but took me some good time to figure out few things so I'm posting this here.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
A little bit late to the party but try using backslash when defining your pattern, example:
```
def articleContent = "real groovy"
def matches = (articleContent =~ /gr\w{4}/) //grabs 'gr' and its following 4 chars
def firstmatch = matches[0] //firstmatch would be 'groovy'
```
you were on the right track, it was just the pattern definition that needed to be altered.
References:
<https://www.regular-expressions.info/groovy.html>
<http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html>
|
One more sinle-line solution additional to tim\_yates's one
```
def result = articleContent.replaceAll(/<!\[CDATA\[(.+)]]>/,/$1/)
```
Please, take into account that in case of regexp doesn't match then result will be equal to the source. Unlikely in case of
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[0][1]
```
it will raise an exception.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
A little bit late to the party but try using backslash when defining your pattern, example:
```
def articleContent = "real groovy"
def matches = (articleContent =~ /gr\w{4}/) //grabs 'gr' and its following 4 chars
def firstmatch = matches[0] //firstmatch would be 'groovy'
```
you were on the right track, it was just the pattern definition that needed to be altered.
References:
<https://www.regular-expressions.info/groovy.html>
<http://mrhaki.blogspot.com/2009/09/groovy-goodness-matchers-for-regular.html>
|
In my case, the actual string was multi-line like below
```
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
```
I wanted to extract the `Start Date` value from this string so here is how my script looks like
```
def matches = (originalData =~ /(?<=Actual Start Date :).*/)
def extractedData = matches[0]
```
This regex extracts the string content from each line which has a prefix matching `Start Date :`
In my case, the result is is `2020-11-25 00:00:00`
**Note :** If your `originalData` is a multi-line string then in groovy you can include it as follows
```
def originalData =
"""
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
"""
```
---
This script looks simple but took me some good time to figure out few things so I'm posting this here.
|
17,536,926 |
I have data that looks like this
```
{
"status": "success",
"data": {
"data1": {
"serialNumber": "abc123",
"version": "1.6"
},
"data2": {
"irrelvent": [
"irrelvent",
"irrelvent"
]
},
"data3": {
"irrelevantLibs": {
"irrelevantFiles": [
"irrelevant.jar",
"irrelevant.jar",
"irrelevant.jar"
]
}
},
"data4": {
"configuration": "auth"
}
}
}
```
I am using the Jackson JSON Processor. What I need to do under the `data` object is to extract each `data(x)` into it's own data.
Hard to explain but I will try to be detailed. My intent is to make the JSON data more readable for our customers. So I'm trying to make the JSON data more friendly by splitting each `data(x)` object into blocks/tables on a website. So `data1` will be displayed independently. Then `data2` will be displayed independently and so on. So in this case I have four `data(x)` objects and I want to store those four objects into four different `Strings` and display them however I want. My problem is how do I get the Jackson Processor to do this?
Not sure if this is helpful but my current JSON function to process the JSON data is this:
```
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
```
I'm positive that I can manipulate the processor to get those data separated but I don't know where to start.
EDIT: Hmm, since Jackson seems to be a pretty difficult parser to work with, would it be easier if I used the Javascript JSON parser to extract only the `data` objects? Since I already have Jackson convert the JSON data into a String, using Javascript would work?
|
2013/07/08
|
['https://Stackoverflow.com/questions/17536926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227566/']
|
One more sinle-line solution additional to tim\_yates's one
```
def result = articleContent.replaceAll(/<!\[CDATA\[(.+)]]>/,/$1/)
```
Please, take into account that in case of regexp doesn't match then result will be equal to the source. Unlikely in case of
```
def result = (articleContent =~ /<!\[CDATA\[(.+)]]>/)[0][1]
```
it will raise an exception.
|
In my case, the actual string was multi-line like below
```
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
```
I wanted to extract the `Start Date` value from this string so here is how my script looks like
```
def matches = (originalData =~ /(?<=Actual Start Date :).*/)
def extractedData = matches[0]
```
This regex extracts the string content from each line which has a prefix matching `Start Date :`
In my case, the result is is `2020-11-25 00:00:00`
**Note :** If your `originalData` is a multi-line string then in groovy you can include it as follows
```
def originalData =
"""
ID : AB-223
Product : Standard Profile
Start Date : 2020-11-19 00:00:00
Subscription : Annual
Volume : 11
Page URL : null
Commitment : 1200.00
Start Date : 2020-11-25 00:00:00
"""
```
---
This script looks simple but took me some good time to figure out few things so I'm posting this here.
|
52,700,186 |
I successfully trained a few models on the Custom Translator portal which I cannot deploy. I tried several times, but each time I start the deployment I get a "Deploymentfailed" status after a while.
Is there anything I should bear in mind or anything I can do about that?
Thanks
|
2018/10/08
|
['https://Stackoverflow.com/questions/52700186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10472409/']
|
Quoting the [official backports documentation](https://backports.debian.org/Instructions/)
>
> For jessie add this line
>
>
>
> ```
> deb http://ftp.debian.org/debian jessie-backports main
>
> ```
>
> to your `sources.list` (or add a new file with the ".list" extension to
> `/etc/apt/sources.list.d/`) You can also find a list of other mirrors at
> <https://www.debian.org/mirror/list>
>
>
> For stretch add this line
>
>
>
> ```
> deb http://ftp.debian.org/debian stretch-backports main
>
> ```
>
> to your `sources.list` (or add a new file with the ".list" extension to
> `/etc/apt/sources.list.d/`) You can also find a list of other mirrors at
> <https://www.debian.org/mirror/list>
>
>
>
Now these instructions seem pretty clear (rather than "pretty vague"), that you should edit a file, rather than run a `deb` command.
(Probably the "your `sources.list` " could be changed to "your `/etc/apt/sources.list`")
|
Ok so I found out how this works and wanted to answer because I felt that the documentation I found was pretty vague so this is how you add Debian 9 stretch-backports to your sources.list:
* Manually, and with admin rights, navigate to /etc/apt/sources.list then create your stretch-backport.list file then enter it with nano, in my case I added this whole line:
```
deb http://ftp.debian.org/debian stretch-backports main
```
to this
```
sudo nano /etc/apt/sources.list.d/stretch-backports.list
```
And it was that simple, I could then use the following line without any errors:
```
sudo apt-get install certbot -t stretch-backports
```
There it is! Hope I was clear.
|
52,700,186 |
I successfully trained a few models on the Custom Translator portal which I cannot deploy. I tried several times, but each time I start the deployment I get a "Deploymentfailed" status after a while.
Is there anything I should bear in mind or anything I can do about that?
Thanks
|
2018/10/08
|
['https://Stackoverflow.com/questions/52700186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10472409/']
|
You can also append the key to sources.list via echo.
```
sudo echo "deb http://deb.debian.org/debian stretch-backports main" | tee -a /etc/apt/sources.list
```
My full install script is (all run as root or sudo)
```
echo "deb http://deb.debian.org/debian stretch-backports main" | tee -a /etc/apt/sources.list
apt-get update
apt-get install certbot python-certbot-apache -t stretch-backports
```
|
Ok so I found out how this works and wanted to answer because I felt that the documentation I found was pretty vague so this is how you add Debian 9 stretch-backports to your sources.list:
* Manually, and with admin rights, navigate to /etc/apt/sources.list then create your stretch-backport.list file then enter it with nano, in my case I added this whole line:
```
deb http://ftp.debian.org/debian stretch-backports main
```
to this
```
sudo nano /etc/apt/sources.list.d/stretch-backports.list
```
And it was that simple, I could then use the following line without any errors:
```
sudo apt-get install certbot -t stretch-backports
```
There it is! Hope I was clear.
|
52,700,186 |
I successfully trained a few models on the Custom Translator portal which I cannot deploy. I tried several times, but each time I start the deployment I get a "Deploymentfailed" status after a while.
Is there anything I should bear in mind or anything I can do about that?
Thanks
|
2018/10/08
|
['https://Stackoverflow.com/questions/52700186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10472409/']
|
Quoting the [official backports documentation](https://backports.debian.org/Instructions/)
>
> For jessie add this line
>
>
>
> ```
> deb http://ftp.debian.org/debian jessie-backports main
>
> ```
>
> to your `sources.list` (or add a new file with the ".list" extension to
> `/etc/apt/sources.list.d/`) You can also find a list of other mirrors at
> <https://www.debian.org/mirror/list>
>
>
> For stretch add this line
>
>
>
> ```
> deb http://ftp.debian.org/debian stretch-backports main
>
> ```
>
> to your `sources.list` (or add a new file with the ".list" extension to
> `/etc/apt/sources.list.d/`) You can also find a list of other mirrors at
> <https://www.debian.org/mirror/list>
>
>
>
Now these instructions seem pretty clear (rather than "pretty vague"), that you should edit a file, rather than run a `deb` command.
(Probably the "your `sources.list` " could be changed to "your `/etc/apt/sources.list`")
|
You can also append the key to sources.list via echo.
```
sudo echo "deb http://deb.debian.org/debian stretch-backports main" | tee -a /etc/apt/sources.list
```
My full install script is (all run as root or sudo)
```
echo "deb http://deb.debian.org/debian stretch-backports main" | tee -a /etc/apt/sources.list
apt-get update
apt-get install certbot python-certbot-apache -t stretch-backports
```
|
42,019,535 |
I have questions about how to properly implement objects in C.
Is the fact that I return objects from methods more prone to memory leaks than, for example, never returning an object and doing it by reference in the argument list like this?
```
extern void quaternion_get_product(Quaternion * this, Quaternion * q, Quaternion * result);
```
This way the `malloc()` call is only done in the constructor, so it is easier to control.
I am new to this kind of encapsulation in C, so I am not sure if this would be the way to solve my problem. I just want my code to be scalable, and I see that if I continue doing this, memory leaks are going to be all around, and it is going to be really hard to debug. How is it usually approached? Am I on the right track with my code?
My question is, if I have this:
```
Quaternion p = *quaternion_create(1, 0, 0, 0);
Quaternion q = *quaternion_create(1, 0, 1, 0);
Quaternion r = *quaternion_create(1, 1, 1, 0);
Quaternion s = *quaternion_create(1, 1, 1, 1);
p = *quaterion_get_product(&p, &q); // Memory leak, old p memory block is not being pointed by anyone
Quaternion t = *quaternion_get_product(&q, quaternion_get_product(&s, &r));
```
Memory leaks are present when nesting function calls, intermediate memory blocks are not pointed by any existing pointer, cannot call quaternion\_destroy
**Header file:**
```
#ifndef __QUATERNIONS_H_
#define __QUATERNIONS_H_
#include <stdlib.h>
typedef struct Quaternion Quaternion;
struct Quaternion {
float w;
float x;
float y;
float z;
};
extern Quaternion *quaternion_create(float nw, float nx, float ny, float nz);
extern void quaternion_destroy(Quaternion *q);
extern Quaternion *quaternion_get_product(Quaternion *this, Quaternion *q);
extern Quaternion *quaternion_get_conjugate(Quaternion *this);
extern float quaternion_get_magnitude(Quaternion *this);
extern void quaternion_normalize(Quaternion *this);
extern Quaternion *quaternion_get_normalized(Quaternion *this);
#endif
```
**Implementation file:**
```
#include "quaternion.h"
#include <math.h>
Quaternion *quaternion_create(float nw, float nx, float ny, float nz) {
Quaternion *q = malloc(sizeof(Quaternion));
q->w = nw;
q->x = nx;
q->y = ny;
q->z = nz;
return q;
}
void quaternion_destroy(Quaternion *q) {
free(q);
}
Quaternion *quaternion_get_product(Quaternion *this, Quaternion *p) {
Quaternion *return_q = quaternion_create(
this->w * p->w - this->x * p->x - this->y * p->y - this->z * p->z, // new w
this->w * p->x + this->x * p->w + this->y * p->z - this->z * p->y, // new x
this->w * p->y - this->x * p->z + this->y * p->w + this->z * p->x, // new y
this->w * p->z + this->x * p->y - this->y * p->x + this->z * p->w
);
return return_q;
}
Quaternion *quaternion_get_conjugate(Quaternion *this)
{
return quaternion_create(this->w, -this->x, -this->y, -this->z);
}
float quaternion_get_magnitude(Quaternion *this) {
return sqrt(this->w * this->w + this->x * this->x + this->y * this->y + this->z * this->z);
}
void quaternion_normalize(Quaternion *this) {
float m = quaternion_get_magnitude(this);
this->w /= m;
this->x /= m;
this->y /= m;
this->z /= m;
}
Quaternion *quaternion_get_normalized(Quaternion *this) {
Quaternion *r = quaternion_create(this->w, this->x, this->y, this->z);
quaternion_normalize(r);
return r;
}
```
|
2017/02/03
|
['https://Stackoverflow.com/questions/42019535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4900440/']
|
Actually, it can get even worse if some function has *both* side effect of updating something and return a newly constructed value. Say, who remembers that `scanf` returns a value?
Looking at [GNU Multi Precision Arithmetic Library](https://gmplib.org/) I'd suggest that the following is one reasonable solution (actually, they go even further by making memory allocation user's headache, not library's):
1. Only a constructor can create a new object. I'd also suggest that all constructors' name follow the same pattern.
2. Only a destructor can destroy an already existing object.
3. Functions take both input arguments (say, two sides of `+`) and output argument(s) (where to put the result, overriding everything that was in the object before), like this:
`mpz_add (a, a, b); /* a=a+b */`
That way you will always clearly see when objects are created/destroyed and can ensure that there are no leaks or double frees. Of course, that prevents you from "chaining" multiple operations together and makes you manually manage temporary variables for intermediate results. However, I believe you'd still have to do that manually in C, because even compiler does not know much about dynamically allocated variable's lifetime.
Actually, if we leave no. 3 and add the "library does not manage memory" clause, we will get even more error-prone solution (from library's point of view), which will require library's user to manage memory however they want. That way you also don't lock user with `malloc`/`free` memory allocation, which is kind of good thing.
|
There is no need to dynamically allocate your quaterions. A quaternion has a fixed size and therefore you can use just plain Quaternions. If you make integer calculations you also use just `int`s without dynamically allocating space for each `int`.
Idea for not using `malloc/free` (untested code)
```
Quaternion quaternion_create(float nw, float nx, float ny, float nz) {
Quaternion q;
q.w = nw;
q.x = nx;
q.y = ny;
q.z = nz;
return q;
}
Quaternion quaternion_get_product(Quaternion *this, Quaternion *p) {
Quaternion return_q = quaternion_create(
this->w * p->w - this->x * p->x - this->y * p->y - this->z * p->z, // new w
this->w * p->x + this->x * p->w + this->y * p->z - this->z * p->y, // new x
this->w * p->y - this->x * p->z + this->y * p->w + this->z * p->x, // new y
this->w * p->z + this->x * p->y - this->y * p->x + this->z * p->w
);
return return_q;
}
```
Usage
```
Quaternion p = quaternion_create(1, 0, 0, 0);
Quaternion q = quaternion_create(1, 0, 1, 0);
Quaternion r = quaternion_create(1, 1, 1, 0);
Quaternion s = quaternion_create(1, 1, 1, 1);
p = quaterion_get_product(&p, &q);
Quaternion t = quaternion_get_product(&q, quaternion_get_product(&s, &r));
```
There are no `malloc`s nor `free`s so there is no possible memory leak and the performance will be better.
|
42,019,535 |
I have questions about how to properly implement objects in C.
Is the fact that I return objects from methods more prone to memory leaks than, for example, never returning an object and doing it by reference in the argument list like this?
```
extern void quaternion_get_product(Quaternion * this, Quaternion * q, Quaternion * result);
```
This way the `malloc()` call is only done in the constructor, so it is easier to control.
I am new to this kind of encapsulation in C, so I am not sure if this would be the way to solve my problem. I just want my code to be scalable, and I see that if I continue doing this, memory leaks are going to be all around, and it is going to be really hard to debug. How is it usually approached? Am I on the right track with my code?
My question is, if I have this:
```
Quaternion p = *quaternion_create(1, 0, 0, 0);
Quaternion q = *quaternion_create(1, 0, 1, 0);
Quaternion r = *quaternion_create(1, 1, 1, 0);
Quaternion s = *quaternion_create(1, 1, 1, 1);
p = *quaterion_get_product(&p, &q); // Memory leak, old p memory block is not being pointed by anyone
Quaternion t = *quaternion_get_product(&q, quaternion_get_product(&s, &r));
```
Memory leaks are present when nesting function calls, intermediate memory blocks are not pointed by any existing pointer, cannot call quaternion\_destroy
**Header file:**
```
#ifndef __QUATERNIONS_H_
#define __QUATERNIONS_H_
#include <stdlib.h>
typedef struct Quaternion Quaternion;
struct Quaternion {
float w;
float x;
float y;
float z;
};
extern Quaternion *quaternion_create(float nw, float nx, float ny, float nz);
extern void quaternion_destroy(Quaternion *q);
extern Quaternion *quaternion_get_product(Quaternion *this, Quaternion *q);
extern Quaternion *quaternion_get_conjugate(Quaternion *this);
extern float quaternion_get_magnitude(Quaternion *this);
extern void quaternion_normalize(Quaternion *this);
extern Quaternion *quaternion_get_normalized(Quaternion *this);
#endif
```
**Implementation file:**
```
#include "quaternion.h"
#include <math.h>
Quaternion *quaternion_create(float nw, float nx, float ny, float nz) {
Quaternion *q = malloc(sizeof(Quaternion));
q->w = nw;
q->x = nx;
q->y = ny;
q->z = nz;
return q;
}
void quaternion_destroy(Quaternion *q) {
free(q);
}
Quaternion *quaternion_get_product(Quaternion *this, Quaternion *p) {
Quaternion *return_q = quaternion_create(
this->w * p->w - this->x * p->x - this->y * p->y - this->z * p->z, // new w
this->w * p->x + this->x * p->w + this->y * p->z - this->z * p->y, // new x
this->w * p->y - this->x * p->z + this->y * p->w + this->z * p->x, // new y
this->w * p->z + this->x * p->y - this->y * p->x + this->z * p->w
);
return return_q;
}
Quaternion *quaternion_get_conjugate(Quaternion *this)
{
return quaternion_create(this->w, -this->x, -this->y, -this->z);
}
float quaternion_get_magnitude(Quaternion *this) {
return sqrt(this->w * this->w + this->x * this->x + this->y * this->y + this->z * this->z);
}
void quaternion_normalize(Quaternion *this) {
float m = quaternion_get_magnitude(this);
this->w /= m;
this->x /= m;
this->y /= m;
this->z /= m;
}
Quaternion *quaternion_get_normalized(Quaternion *this) {
Quaternion *r = quaternion_create(this->w, this->x, this->y, this->z);
quaternion_normalize(r);
return r;
}
```
|
2017/02/03
|
['https://Stackoverflow.com/questions/42019535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4900440/']
|
Actually, it can get even worse if some function has *both* side effect of updating something and return a newly constructed value. Say, who remembers that `scanf` returns a value?
Looking at [GNU Multi Precision Arithmetic Library](https://gmplib.org/) I'd suggest that the following is one reasonable solution (actually, they go even further by making memory allocation user's headache, not library's):
1. Only a constructor can create a new object. I'd also suggest that all constructors' name follow the same pattern.
2. Only a destructor can destroy an already existing object.
3. Functions take both input arguments (say, two sides of `+`) and output argument(s) (where to put the result, overriding everything that was in the object before), like this:
`mpz_add (a, a, b); /* a=a+b */`
That way you will always clearly see when objects are created/destroyed and can ensure that there are no leaks or double frees. Of course, that prevents you from "chaining" multiple operations together and makes you manually manage temporary variables for intermediate results. However, I believe you'd still have to do that manually in C, because even compiler does not know much about dynamically allocated variable's lifetime.
Actually, if we leave no. 3 and add the "library does not manage memory" clause, we will get even more error-prone solution (from library's point of view), which will require library's user to manage memory however they want. That way you also don't lock user with `malloc`/`free` memory allocation, which is kind of good thing.
|
Looks to me like you're calling it wrong.
You also need to check to see if malloc() returns NULL and handle that failure (such as by displaying an out of memory error message and exiting if it fails because that's non-recoverable generally).
**UPDATE:**
Since YOU need to free your intermediate result you have to take more action to retain the pointer.
**UPDATE 2**
@MichaelWalz approach is great. Why deal with all the allocations and pointer management if you don't need to? However, if you *do* use pointers and allocate memory you have to retain pointers and make sure you free things and pass them around/reuse them carefully. I've updated my example to handle the nested call.
**UPDATE 3**
I had to remove the &'s from the function call arguments because you're passing pointers in, which are already the address of what you want to point to. You didn't assign the output of the functions properly. Notice how the pointer assignments are different in the fixed example too.
---
```
Quaternion p = *quaternion_create(1, 0, 0, 0);
Quaternion q = *quaternion_create(1, 0, 1, 0);
Quaternion r = *quaternion_create(1, 1, 1, 0);
Quaternion s = *quaternion_create(1, 1, 1, 1);
p = *quaterion_get_product(&p, &q); // Memory leak, old p memory block is not being pointed by anyone
Quaternion t = *quaternion_get_product(&q, quaternion_get_product(&s, &r));
```
---
```
Quaternion *p = quaternion_create(1, 0, 0, 0);
Quaternion *q = quaternion_create(1, 0, 1, 0);
Quaternion *r = quaternion_create(1, 1, 1, 0);
Quaternion *s = quaternion_create(1, 1, 1, 1);
Quaternian *tmp = quaterion_get_product(p, q);
quaternian_destroy(p);
p = tmp;
tmp = quaternion_get_product(s, r)
Quaternion *t = quaternion_get_product(q, tmp);
quaternian_destroy(tmp);
```
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
What you want is to add a view from your running service instance. This way you can persist the view across all activities - and from anywhere else. See this great example:
<http://www.piwai.info/chatheads-basics/>
|
What you want is an Activity instead of a Service and a Dialog instead View. I suggest you read this document by google: <http://developer.android.com/guide/topics/fundamentals.html>
However to answer your question about both being interactable. This isn't possible. At any given time 1 and only 1 activity is on the top of the activity stack. The user can only interact with that activity. If you want something like a floating window then will have to create it yourself. Although keep in mind that goes against the android design principles.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Services most definitely can have a user interface: Input methods are an obvious example. See <http://developer.android.com/resources/samples/SoftKeyboard/index.html> for an example.
|
Services run in the background and do not have an UI. So you can not show something over a Service.
If you need a Service to notify user about something, then use [`Notification`](http://developer.android.com/guide/topics/ui/notifiers/notifications.html).
Ayou could use a `Toast`, but I advise against it, as it can confuse users since it can pop-out over another app's activity.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
I guess you are misusing the word "Service".
Service is invisible, Activities are visible.
There are no buttons in an Service!
So you have no choice! You should put both views in one Activity, and I would use a RelativeLayout and set the visibility of your chidren to GONE/Visible.
<http://developer.android.com/reference/android/widget/RelativeLayout.html>
Also using a popup and making the layout under it clickable will disturb the user. You are completely changing User experience. I strongly suggest too make your popup appear at the top/bottom of your initial layout
|
Services run in the background and do not have an UI. So you can not show something over a Service.
If you need a Service to notify user about something, then use [`Notification`](http://developer.android.com/guide/topics/ui/notifiers/notifications.html).
Ayou could use a `Toast`, but I advise against it, as it can confuse users since it can pop-out over another app's activity.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Yes it's possible, what you need to do is call the `WindowManager` service and add your view via the same.
```
WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout=(RelativeLayout) inflater.inflate(R.layout.box,null);
```
You need a `WindowManager.LayoutParams` object which should contain the parameters for the layout
```
windowManager.addView(layout,params);
```
Well, adds the view
|
Services most definitely can have a user interface: Input methods are an obvious example. See <http://developer.android.com/resources/samples/SoftKeyboard/index.html> for an example.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Services most definitely can have a user interface: Input methods are an obvious example. See <http://developer.android.com/resources/samples/SoftKeyboard/index.html> for an example.
|
What you want is an Activity instead of a Service and a Dialog instead View. I suggest you read this document by google: <http://developer.android.com/guide/topics/fundamentals.html>
However to answer your question about both being interactable. This isn't possible. At any given time 1 and only 1 activity is on the top of the activity stack. The user can only interact with that activity. If you want something like a floating window then will have to create it yourself. Although keep in mind that goes against the android design principles.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Yes it's possible, what you need to do is call the `WindowManager` service and add your view via the same.
```
WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout=(RelativeLayout) inflater.inflate(R.layout.box,null);
```
You need a `WindowManager.LayoutParams` object which should contain the parameters for the layout
```
windowManager.addView(layout,params);
```
Well, adds the view
|
What you want is to add a view from your running service instance. This way you can persist the view across all activities - and from anywhere else. See this great example:
<http://www.piwai.info/chatheads-basics/>
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Yes it's possible, what you need to do is call the `WindowManager` service and add your view via the same.
```
WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout=(RelativeLayout) inflater.inflate(R.layout.box,null);
```
You need a `WindowManager.LayoutParams` object which should contain the parameters for the layout
```
windowManager.addView(layout,params);
```
Well, adds the view
|
Services run in the background and do not have an UI. So you can not show something over a Service.
If you need a Service to notify user about something, then use [`Notification`](http://developer.android.com/guide/topics/ui/notifiers/notifications.html).
Ayou could use a `Toast`, but I advise against it, as it can confuse users since it can pop-out over another app's activity.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
I guess you are misusing the word "Service".
Service is invisible, Activities are visible.
There are no buttons in an Service!
So you have no choice! You should put both views in one Activity, and I would use a RelativeLayout and set the visibility of your chidren to GONE/Visible.
<http://developer.android.com/reference/android/widget/RelativeLayout.html>
Also using a popup and making the layout under it clickable will disturb the user. You are completely changing User experience. I strongly suggest too make your popup appear at the top/bottom of your initial layout
|
What you want is an Activity instead of a Service and a Dialog instead View. I suggest you read this document by google: <http://developer.android.com/guide/topics/fundamentals.html>
However to answer your question about both being interactable. This isn't possible. At any given time 1 and only 1 activity is on the top of the activity stack. The user can only interact with that activity. If you want something like a floating window then will have to create it yourself. Although keep in mind that goes against the android design principles.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
What you want is to add a view from your running service instance. This way you can persist the view across all activities - and from anywhere else. See this great example:
<http://www.piwai.info/chatheads-basics/>
|
Services run in the background and do not have an UI. So you can not show something over a Service.
If you need a Service to notify user about something, then use [`Notification`](http://developer.android.com/guide/topics/ui/notifiers/notifications.html).
Ayou could use a `Toast`, but I advise against it, as it can confuse users since it can pop-out over another app's activity.
|
7,521,307 |
Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.

Is this in theory possible? If yes, how should I initialize that view?
Thanks!
|
2011/09/22
|
['https://Stackoverflow.com/questions/7521307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651418/']
|
Yes it's possible, what you need to do is call the `WindowManager` service and add your view via the same.
```
WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout=(RelativeLayout) inflater.inflate(R.layout.box,null);
```
You need a `WindowManager.LayoutParams` object which should contain the parameters for the layout
```
windowManager.addView(layout,params);
```
Well, adds the view
|
I guess you are misusing the word "Service".
Service is invisible, Activities are visible.
There are no buttons in an Service!
So you have no choice! You should put both views in one Activity, and I would use a RelativeLayout and set the visibility of your chidren to GONE/Visible.
<http://developer.android.com/reference/android/widget/RelativeLayout.html>
Also using a popup and making the layout under it clickable will disturb the user. You are completely changing User experience. I strongly suggest too make your popup appear at the top/bottom of your initial layout
|
52,647,892 |
Bit of theoretical question. I'd like someone to explain me which colour space provides the best distances among similar looking colours? I am trying to make a humidity detection system using a normal RGB camera in dry fruits like almond and peanuts. I have tried RGB and HSV color space for EDA(please find the attachment). Currently I am unable to find a really big difference between the accepted and rejected model. It would be really a great help if someone can tell me what should I look for and also where.
[](https://i.stack.imgur.com/A95Y2.png)
[](https://i.stack.imgur.com/aLcYV.png)
|
2018/10/04
|
['https://Stackoverflow.com/questions/52647892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7554629/']
|
A `ValueEventListener` always gets a snapshot of the entire location you attach it to.
If you'd like to get a snapshot of the specific child, you should use a `ChildEventListener`.
```
ref.child("chat").child("branches").addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
System.out.println(snapshot.getKey()+" was added after "+previousChildKey);
}
public void onChildChanged(DataSnapshot snapshot) {
System.out.println(snapshot.getKey()+" was changed");
}
...
```
When you first attach this listener, the `onChildAdded` method will be called for each branch. After that, if you make a change to a single branch, the `onChildChanged` method will be called for just that branch.
|
```
ref.on("child_changed", function(snapshot) {
var changedPost = snapshot.val();
console.log("The updated post title is " + changedPost.title);
});
```
For more information you can **[click](https://firebase.google.com/docs/database/admin/retrieve-data#child-changed)** Here
|
60,540,060 |
is there a way to set a css class on a child component inside a Blazor component?
What i have right now is:
```cs
@using Microsoft.AspNetCore.Components;
@inherits ComponentBase
<div class="button-group-wrapper">
@SecondaryButton
<div class="floating-sticky-wrapper">
@PrimaryButton
</div>
</div>
@code {
[Parameter]
public RenderFragment PrimaryButton { get; set; }
[Parameter]
public RenderFragment SecondaryButton { get; set; }
}
```
I then "inject" the RenderFragments via:
```cs
<FloatingStickyButton>
<SecondaryButton>
<button type="button" class="button ...">Secondary</button>
</SecondaryButton>
<PrimaryButton>
<button type="submit" class="button button--primary ...">Primary</button>
</PrimaryButton>
</FloatingStickyButton>
```
What do i want?
---------------
I want to set the css class called "floating-sticky-button" on the primary button. But i would like to set this css class inside the component so that the programmer does not need to care about setting the class outside on the button element.
Something like this (Mind the **@PrimaryButton** here):
```cs
@using Microsoft.AspNetCore.Components;
@inherits ComponentBase
<div class="button-group-wrapper">
@SecondaryButton
<div class="floating-sticky-wrapper">
@PrimaryButton({class: 'floating-sticky-button'})
</div>
</div>
@code {
[Parameter]
public RenderFragment PrimaryButton { get; set; }
[Parameter]
public RenderFragment SecondaryButton { get; set; }
}
```
Unfortunately that doesn't work. Is there any way to do this?
|
2020/03/05
|
['https://Stackoverflow.com/questions/60540060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8018536/']
|
Setting the startingDeadlineSeconds to 180 fixed the problem + removing the spec.template.metadata.labels.
|
I suspended my workload then resumed it after quite a while and saw the same error.
Isn't it a bug because I triggered the suspend action on purpose anytime between suspend and resume should NOT be counted against missing starting.
|
2,377,096 |
I am having trouble with my UITableView in the NavigationController.
When I add data to the table I use another class to download images to display in that table, while all that works great but if in the middle of images being download I swtich back to the previous view in the navigationcontroller app crashed.
Here is my code to explain further
```
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Set appIcon and clear temporary data/image
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
UIImage *appIcon;
if (image.size.width != kAppIconHeight && image.size.height != kAppIconHeight)
{
CGSize itemSize = CGSizeMake(125, 85);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[image drawInRect:imageRect];
appIcon = UIGraphicsGetImageFromCurrentImageContext();
///UIGraphicsEndImageContext();
}
else
{
appIcon = image;
//self.appRecord.appIcon = image;
}
self.activeDownload = nil;
// Release the connection now that it's finished
self.imageConnection = nil;
// call our delegate and tell it that our icon is ready for display
if(delegate != nil)
[delegate appImageDidLoad:self.indexPathInTableView imaged:appIcon ];
[image release];
}
```
The appImageDidLoad is a method that exists in my UITableView view.
Is there a way I can check to see if the UITableView is valid in my imagedownload class so I know not to send the image.
Thanks in advance.
|
2010/03/04
|
['https://Stackoverflow.com/questions/2377096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190892/']
|
If you view all files for the project and then view the file called Reference.svcmap for the appropriate service reference could you please let me know what the following config options are in the xml?
```
<ExcludedTypes />
<ImportXmlTypes>false</ImportXmlTypes>
<GenerateInternalTypes>false</GenerateInternalTypes>
<GenerateSerializableTypes>false</GenerateSerializableTypes>
<Serializer>Auto</Serializer>
```
Sorry about putting it in as an answer but it was horribly unreadable in the comments.
**Edit**
Ok, so what is happening here is following:
1. You are using auto for the serializer.
2. The default is DataContractSerializer
3. When generating the proxy code, there is a check for forbidden xsd elements.
4. If forbidden elements are found, the XmlSerializer is used.
In your case, adding the xsd:any element is causing the serialization mode to change. If you want consistent serialization, you will have to remove the forbidden element or force the proxy generation to use XmlSerialization all the time.
[Here](http://msdn.microsoft.com/en-us/library/ms733112.aspx) is a link about the allowable schema elements for the DataContractSerializer.
Cheers
-Leigh
|
As far as I know, proxy classes are generated by SvcUtil.exe why do not you look at it with reflector...
|
1,635,102 |
I am getting an unexpected value with a simple math calculation in Objective C. I have output the three different parts of the calculation as well as the result of the calculation below.
The following code
```
NSLog(@"self.contentView.bounds.size.width: %f", self.contentView.bounds.size.width);
NSLog(@"SWATCHES_WIDTH: %f", SWATCHES_WIDTH);
NSLog(@"RIGHT_MARGIN: %f", RIGHT_MARGIN);
NSLog(@"(self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN): %f", (self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN));
```
gives the following output:
self.contentView.bounds.size.width: 288.000000
SWATCHES\_WIDTH: 82.000000
RIGHT\_MARGIN: 12.000000
(self.contentView.bounds.size.width - SWATCHES\_WIDTH - RIGHT\_MARGIN): 214.000000
I would expect the result would be 194 instead of 214 (288-82-12=194). Can anyone give any insight as to why this is being calculated the way it is and what I can do to fix it? Thanks!
As far as I know, all three of these values are CGFloats. The two constants are defined as follows:
```
#define SWATCHES_WIDTH SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0
#define RIGHT_MARGIN 12.0
```
|
2009/10/28
|
['https://Stackoverflow.com/questions/1635102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197808/']
|
This:
```
self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN
```
is expanding to this:
```
self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0 - RIGHT_MARGIN
```
What you really want is:
```
self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 - SPACE_BETWEEN * 2.0 - RIGHT_MARGIN
self.contentView.bounds.size.width - (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0) - RIGHT_MARGIN
```
You need to add parentheses around it so it is expanded properly:
```
#define SWATCHES_WIDTH (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0)
```
|
CPP strike again!
Your subtraction, after cpp runs, goes from this:
`(self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN)`
to this:
`(self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0 - 12.0)`
See the problem?
You want SWATCHES\_WIDTH to expand with parens around it, so that you get what you expect, which is
`(self.contentView.bounds.size.width - (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0) - 12.0)`
So you're subtracting rather than adding `SPACE_BETWEEN*2.0` to your result.
|
50,925,793 |
What is the proper way of adding external CSS file in Vue.js Application ?
I found several ways to add CSS file in Vue.js Application.
Some one suggest to use this one. `<link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">`.
Some one suggest this one
```
<style lang="scss">
@import 'src/assets/css/mycss_lib.css';
</style>
```
Some one suggest this one
`require('./assets/layout3/css/layout.min.css')`
Some one suggest to use below code in `webpack.config.js`.
```
{
test: /\.(css|less)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
}
```
Some one suggest to use this one
```
<style src="../node_modules/vue-multiselect/dist/vue-multiselect.min.css"></style>
```
What are the merits and demerits of using all those ways ?
I would like to use in a way so that all CSS files become a single file at the time of deployment. So that my application loads faster.
|
2018/06/19
|
['https://Stackoverflow.com/questions/50925793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5043301/']
|
1. Install sass
```
npm install sass-loader --save-dev
```
2. Create new `css` directory under your `src/assets` directory
3. Create a `styles.scss` file in the new `css` directory
4. Add the following line of code to your `main.js` file
```
import '../src/assets/css/styles.scss';
```
In the `styles.scss` file you can import multiple css files.
```
@import '~bootstrap/scss/bootstrap.min.css';
@import './common.css';
```
You can also write regular CSS properties like this in the same file
```
body {
background: gray;
}
div {
font-weight: bold;
}
```
5. Restart your dev server
```
npm run serve
```
|
The best way for me(!) in Vue.js is to include global page-styles in my main index.html with a link tag. This way they are accessible from everywhere and are loaded when the page is first opened.
Like this:
*index.html:*
```
<link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
```
The style-rules for my components are inlined in .vue-files using: *mycomponent.vue:*
```
<style scoped>
...
</style>
```
EDIT:
If you don't want to use .vue files and work with .js files you can not scope the css inside components. If thats the case I always name them the same as the component and also include it inside index.html in link tag.
|
7,376,423 |
* Would you please examine [this jsFiddle](http://jsfiddle.net/znPGj/)?
* Resize the width of the "result" frame.
* Observe that the layout of the boxes switches between 2 and 3
columns.
This glitch is anoying I want the layout to look like this and stay like this even when I resize the window:
```
_________
| ▄ ▄ ▄ |
| 1 2 3 |
| ▄ ▄ ▄ |
| 4 5 6 |
¯¯¯¯¯¯¯¯¯
```
Could you alter the HTML/CSS to perfect the layout and get rid of the glitch?
Thanks in advance!
|
2011/09/11
|
['https://Stackoverflow.com/questions/7376423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552067/']
|
<http://jsfiddle.net/znPGj/3/> fixes it by setting a height in px on the img boxes
|
check this example <http://jsfiddle.net/sandeep/znPGj/4/> css:
```
a {
float:left;
width: 33%;
margin: 0;
padding: 4px 0;
color: #000;
font: medium sans-serif;
text-align: center;
}
a:nth-child(4){clear:both}
img {
width: 80%;
}
```
|
7,376,423 |
* Would you please examine [this jsFiddle](http://jsfiddle.net/znPGj/)?
* Resize the width of the "result" frame.
* Observe that the layout of the boxes switches between 2 and 3
columns.
This glitch is anoying I want the layout to look like this and stay like this even when I resize the window:
```
_________
| ▄ ▄ ▄ |
| 1 2 3 |
| ▄ ▄ ▄ |
| 4 5 6 |
¯¯¯¯¯¯¯¯¯
```
Could you alter the HTML/CSS to perfect the layout and get rid of the glitch?
Thanks in advance!
|
2011/09/11
|
['https://Stackoverflow.com/questions/7376423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552067/']
|
<http://jsfiddle.net/znPGj/3/> fixes it by setting a height in px on the img boxes
|
You could wrap all the `img` in a `div` and set a specific `width` on the `div`
Example: <http://jsfiddle.net/jasongennaro/znPGj/5/>
|
7,376,423 |
* Would you please examine [this jsFiddle](http://jsfiddle.net/znPGj/)?
* Resize the width of the "result" frame.
* Observe that the layout of the boxes switches between 2 and 3
columns.
This glitch is anoying I want the layout to look like this and stay like this even when I resize the window:
```
_________
| ▄ ▄ ▄ |
| 1 2 3 |
| ▄ ▄ ▄ |
| 4 5 6 |
¯¯¯¯¯¯¯¯¯
```
Could you alter the HTML/CSS to perfect the layout and get rid of the glitch?
Thanks in advance!
|
2011/09/11
|
['https://Stackoverflow.com/questions/7376423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552067/']
|
<http://jsfiddle.net/znPGj/3/> fixes it by setting a height in px on the img boxes
|
Have you tried dropping the width to 32%? Worked for me, but I didn't test on many browsers.
|
58,029,124 |
I would like to modify the date of a pandas Timestamp variable but keeping the time as it is. E.g. having the following timestamp
```
time_stamp_1 = pd.Timestamp('1900-1-1 13:59')
```
I would like to set the date to the 3rd of February 2000. I.e. after the modification the print statement
```
print(time_stamp_1)
```
should return
```
2000-02-03 13:59:00
```
|
2019/09/20
|
['https://Stackoverflow.com/questions/58029124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1833326/']
|
Use [`Timestamp.replace`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.replace.html):
```
print (time_stamp_1.replace(year=2000, month=2, day=3))
2000-02-03 13:59:00
```
Or add to `Timestamp` only times converted to `timedelta` with times extracted by [`Timestamp.strftime`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.strftime.html):
```
print (pd.Timestamp('2000-02-03') + pd.Timedelta(time_stamp_1.strftime('%H:%M:%S')))
#alternative
print (pd.Timestamp('2000-02-03') + pd.to_timedelta(time_stamp_1.strftime('%H:%M:%S')))
2000-02-03 13:59:00
```
|
can also do:
```
new = pd.Timestamp('2000-02-03') + pd.Timedelta(str(time_stamp_1.time()))
```
output:
```
Timestamp('2000-02-03 13:59:00')
```
|
58,029,124 |
I would like to modify the date of a pandas Timestamp variable but keeping the time as it is. E.g. having the following timestamp
```
time_stamp_1 = pd.Timestamp('1900-1-1 13:59')
```
I would like to set the date to the 3rd of February 2000. I.e. after the modification the print statement
```
print(time_stamp_1)
```
should return
```
2000-02-03 13:59:00
```
|
2019/09/20
|
['https://Stackoverflow.com/questions/58029124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1833326/']
|
Use [`Timestamp.replace`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.replace.html):
```
print (time_stamp_1.replace(year=2000, month=2, day=3))
2000-02-03 13:59:00
```
Or add to `Timestamp` only times converted to `timedelta` with times extracted by [`Timestamp.strftime`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.strftime.html):
```
print (pd.Timestamp('2000-02-03') + pd.Timedelta(time_stamp_1.strftime('%H:%M:%S')))
#alternative
print (pd.Timestamp('2000-02-03') + pd.to_timedelta(time_stamp_1.strftime('%H:%M:%S')))
2000-02-03 13:59:00
```
|
You can do subtraction with `normalize`
```
pd.to_datetime('2000-02-03') + (time_stamp_1 - time_stamp_1.normalize())
Timestamp('2000-02-03 13:59:00')
```
---
This scales much better if you have a Series/DataFrame because it avoids `.strftime`, though is slower for a single timestamp.
```
import perfplot
import pandas as pd
perfplot.show(
setup=lambda n: pd.Series([pd.Timestamp('1900-1-1 13:59')]*n),
kernels=[
lambda s: pd.to_datetime('2000-02-03') + (s - s.dt.normalize()),
lambda s: pd.Timestamp('2000-02-03') + pd.to_timedelta(s.dt.strftime('%H:%M:%S')),
],
labels=["normalize", "strftime"],
n_range=[2 ** k for k in range(16)],
equality_check=None, # Because datetime type
xlabel="len(s)"
)
```
[](https://i.stack.imgur.com/L10HT.png)
|
10,509,984 |
I am using Graph API to upload video on facebook. I am able to upload .wmv format video but not .mp4. My code is as below
```
strVidUrl=@"http://myshow.com.au/Videos/mp4s/20111216044530271247467.mp4";
//strVidUrl=@"http://www.myshow.com.au/Videos/BossAlarm.wmv";
NSURL *url = [NSURL URLWithString:strVidUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
data, @"video.mov",
@"video/mp4", @"contentType",
[dicVideoDetails valueForKey:@"fld_display_name"], @"title",
[dicVideoDetails valueForKey:@"fld_video_description"], @"description",
nil];
```
if I use .wmv then code is below and it is running.
```
NSURL *url = [NSURL URLWithString:@"http://www.myshow.com.au/Videos/BossAlarm.wmv"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
data, @"video.mov",
@"video/quicktime", @"contentType",
@"Video Test Title", @"title",
@"Video Test Description", @"description",
nil];
```
Result is comming same in both cases but .mp4 video is not showing on facebook. while .wmv is showing there.
Please help me.
|
2012/05/09
|
['https://Stackoverflow.com/questions/10509984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482058/']
|
That may be due to the missmatch of codecs and compression rates of your source video and fb's recomented video format
|
Check the following Links
* [Upload Video on facebook](http://developers.facebook.com/blog/post/532/)
* [demo](http://developers.facebook.com/attachment/VideoUploadTest.zip)
Regards,
Let me know in case of queries.
|
68,172,043 |
The output i need
>
> enter name: john
>
>
>
>
> name not found in array
>
>
>
Here is my pseudocode
```
//ask for name
System.out.print("enter name")
name = sc.nextLine()
//loop to check if name exists in my array
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{ code to be executed if name is found in arrayofnames }
}
```
I tried putting an else/else if condition after the if but it executes the code arrayofnames.length times. How do I only make it print something like "name not found in array" only once then break?
|
2021/06/29
|
['https://Stackoverflow.com/questions/68172043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16306518/']
|
You can have a flag, which you can test after the loop
```
System.out.print("enter name")
name = sc.nextLine()
boolean found = false;
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{
found = true;
break;
}
}
if (!found) System.out.println ("Not found");
```
|
```
public static void main(String[] args) {
String name = "jhn";
String[] arrayofnames = {"john", "tomer", "roy", "natalie"};
IsName(name, arrayofnames);
}
public static void IsName(String _name, String[] _arrayofnames){
boolean a = false;
for (String name : _arrayofnames) {
if(name == _name){
System.out.println("name is in the array");
a = true;
}
}
if(!a){
System.out.println("name is not in the array");
}
}
```
|
68,172,043 |
The output i need
>
> enter name: john
>
>
>
>
> name not found in array
>
>
>
Here is my pseudocode
```
//ask for name
System.out.print("enter name")
name = sc.nextLine()
//loop to check if name exists in my array
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{ code to be executed if name is found in arrayofnames }
}
```
I tried putting an else/else if condition after the if but it executes the code arrayofnames.length times. How do I only make it print something like "name not found in array" only once then break?
|
2021/06/29
|
['https://Stackoverflow.com/questions/68172043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16306518/']
|
You can have a flag, which you can test after the loop
```
System.out.print("enter name")
name = sc.nextLine()
boolean found = false;
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{
found = true;
break;
}
}
if (!found) System.out.println ("Not found");
```
|
You can solve this problem by putting your `String[] arrayOfNames` into an `ArrayList<>` and simply checking if the `ArrayList<>` contains the name given by the user.
```
String[] arrayOfNames = {"Angelo", "David", "John"};
String name = "Angelo"; //the name given by the user
ArrayList<String> newArray = new ArrayList<>(Arrays.asList(arrayOfNames));
//check too see if the ArrayList contains the name
if (newArray.contains(name))
System.out.println("Name found in array");
else
System.out.println("Name not found in array");
```
|
68,172,043 |
The output i need
>
> enter name: john
>
>
>
>
> name not found in array
>
>
>
Here is my pseudocode
```
//ask for name
System.out.print("enter name")
name = sc.nextLine()
//loop to check if name exists in my array
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{ code to be executed if name is found in arrayofnames }
}
```
I tried putting an else/else if condition after the if but it executes the code arrayofnames.length times. How do I only make it print something like "name not found in array" only once then break?
|
2021/06/29
|
['https://Stackoverflow.com/questions/68172043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16306518/']
|
You can have a flag, which you can test after the loop
```
System.out.print("enter name")
name = sc.nextLine()
boolean found = false;
for (int count = 0; count < arrayofnames.length; count++)
{
if (name.equals(arrayofnames[count]))
{
found = true;
break;
}
}
if (!found) System.out.println ("Not found");
```
|
If you want your code more compact, you can also use Streams to check if any element of the array equals the given String like this:
```java
boolean found = Arrays.stream(arrayofnames).anyMatch(n -> n.equals(name));
if(found) {
//code to be executed if name is found in arrayofnames
}
```
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
When Spring loads your bean definitions, and has been configured to look for `@Transactional` annotations, it will create these **proxy objects** around your actual **bean**. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with `@Transactional`, Spring will create a `TransactionInterceptor`, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the `TransactionInterceptor` (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the `TransactionInterceptor` commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
|
It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.
For example, you have a class that looks like this
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
```
and you have an aspect, that looks like this:
```
@Component
@Aspect
public class CrossCuttingConcern {
@Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
```
When you execute it like this:
```
@Service
public class CoreBusinessKickOff {
@Autowired
CoreBusinessSubordinate subordinate;
// getter/setters
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
```
}
**Results of calling kickOff above given code above.**
```
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
```
but when you change your code to
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
//subordinate.doSomethingSmall(4);
}
```
You see, the method internally calls another method so it won't be intercepted and the output would look like this:
```
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
```
You can by-pass this by doing that
```
public void doSomethingBig() {
System.out.println("I did something small");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
```
Code snippets taken from:
<https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/>
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on [Aspect-Oriented Programming](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-api) and [Transactions](https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction), as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare `@Transactional` on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with `@Transactional`, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the `this` reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in [this forum post](http://forum.springsource.org/showthread.php?t=11656) in which I use a `BeanFactoryPostProcessor` to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called `me`. Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. `me.someMethod()`.) The forum post explains in more detail.
Note that the `BeanFactoryPostProcessor` code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.
|
**The simplest answer is:**
On whichever method you declare `@Transactional` the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then **all commits are with in this transaction boundary**.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an **exception occur**, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be **rollback** with entity3.
**Transaction :**
>
> 1. entity1.save
> 2. entity2.save
> 3. entity3.save
>
>
>
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
When Spring loads your bean definitions, and has been configured to look for `@Transactional` annotations, it will create these **proxy objects** around your actual **bean**. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with `@Transactional`, Spring will create a `TransactionInterceptor`, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the `TransactionInterceptor` (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the `TransactionInterceptor` commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
|
All existing answers are correct, but I feel cannot give just this complex topic.
For a comprehensive, practical explanation you might want to have a look at this [Spring @Transactional In-Depth](https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth) guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: `Client` executes `Proxy.method()`.
1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
2. If a before aspect is defined, the proxy will execute it
3. Then, the actual method (target) is executed
4. After-returning and after-throwing are optional aspects that are
executed after the method returns and/or if the method throws an
exception
5. After that, the proxy executes the after aspect (if defined)
6. Finally the proxy returns to the calling client

(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: <https://www.noelvaes.eu>)
|
It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.
For example, you have a class that looks like this
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
```
and you have an aspect, that looks like this:
```
@Component
@Aspect
public class CrossCuttingConcern {
@Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
```
When you execute it like this:
```
@Service
public class CoreBusinessKickOff {
@Autowired
CoreBusinessSubordinate subordinate;
// getter/setters
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
```
}
**Results of calling kickOff above given code above.**
```
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
```
but when you change your code to
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
//subordinate.doSomethingSmall(4);
}
```
You see, the method internally calls another method so it won't be intercepted and the output would look like this:
```
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
```
You can by-pass this by doing that
```
public void doSomethingBig() {
System.out.println("I did something small");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
```
Code snippets taken from:
<https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/>
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on [Aspect-Oriented Programming](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-api) and [Transactions](https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction), as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare `@Transactional` on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with `@Transactional`, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the `this` reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in [this forum post](http://forum.springsource.org/showthread.php?t=11656) in which I use a `BeanFactoryPostProcessor` to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called `me`. Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. `me.someMethod()`.) The forum post explains in more detail.
Note that the `BeanFactoryPostProcessor` code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.
|
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: `Client` executes `Proxy.method()`.
1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
2. If a before aspect is defined, the proxy will execute it
3. Then, the actual method (target) is executed
4. After-returning and after-throwing are optional aspects that are
executed after the method returns and/or if the method throws an
exception
5. After that, the proxy executes the after aspect (if defined)
6. Finally the proxy returns to the calling client

(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: <https://www.noelvaes.eu>)
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
When Spring loads your bean definitions, and has been configured to look for `@Transactional` annotations, it will create these **proxy objects** around your actual **bean**. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with `@Transactional`, Spring will create a `TransactionInterceptor`, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the `TransactionInterceptor` (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the `TransactionInterceptor` commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
|
**The simplest answer is:**
On whichever method you declare `@Transactional` the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then **all commits are with in this transaction boundary**.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an **exception occur**, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be **rollback** with entity3.
**Transaction :**
>
> 1. entity1.save
> 2. entity2.save
> 3. entity3.save
>
>
>
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
All existing answers are correct, but I feel cannot give just this complex topic.
For a comprehensive, practical explanation you might want to have a look at this [Spring @Transactional In-Depth](https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth) guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.
|
It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.
For example, you have a class that looks like this
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
```
and you have an aspect, that looks like this:
```
@Component
@Aspect
public class CrossCuttingConcern {
@Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
```
When you execute it like this:
```
@Service
public class CoreBusinessKickOff {
@Autowired
CoreBusinessSubordinate subordinate;
// getter/setters
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
```
}
**Results of calling kickOff above given code above.**
```
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
```
but when you change your code to
```
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
//subordinate.doSomethingSmall(4);
}
```
You see, the method internally calls another method so it won't be intercepted and the output would look like this:
```
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
```
You can by-pass this by doing that
```
public void doSomethingBig() {
System.out.println("I did something small");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
```
Code snippets taken from:
<https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/>
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
**The simplest answer is:**
On whichever method you declare `@Transactional` the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then **all commits are with in this transaction boundary**.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an **exception occur**, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be **rollback** with entity3.
**Transaction :**
>
> 1. entity1.save
> 2. entity2.save
> 3. entity3.save
>
>
>
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
|
All existing answers are correct, but I feel cannot give just this complex topic.
For a comprehensive, practical explanation you might want to have a look at this [Spring @Transactional In-Depth](https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth) guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: `Client` executes `Proxy.method()`.
1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
2. If a before aspect is defined, the proxy will execute it
3. Then, the actual method (target) is executed
4. After-returning and after-throwing are optional aspects that are
executed after the method returns and/or if the method throws an
exception
5. After that, the proxy executes the after aspect (if defined)
6. Finally the proxy returns to the calling client

(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: <https://www.noelvaes.eu>)
|
All existing answers are correct, but I feel cannot give just this complex topic.
For a comprehensive, practical explanation you might want to have a look at this [Spring @Transactional In-Depth](https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth) guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.
|
1,099,025 |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
>
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
>
>
>
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?**
|
2009/07/08
|
['https://Stackoverflow.com/questions/1099025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133830/']
|
When Spring loads your bean definitions, and has been configured to look for `@Transactional` annotations, it will create these **proxy objects** around your actual **bean**. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with `@Transactional`, Spring will create a `TransactionInterceptor`, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the `TransactionInterceptor` (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the `TransactionInterceptor` commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
|
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: `Client` executes `Proxy.method()`.
1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
2. If a before aspect is defined, the proxy will execute it
3. Then, the actual method (target) is executed
4. After-returning and after-throwing are optional aspects that are
executed after the method returns and/or if the method throws an
exception
5. After that, the proxy executes the after aspect (if defined)
6. Finally the proxy returns to the calling client

(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: <https://www.noelvaes.eu>)
|
21,715,723 |
Ok, I realize there are similar topics on this, many in fact, but none of them are helping me figure out my issue and it just seems to lead me farther and farther from my goal. I have tried implode, for each, loops, etc., but either I receive "Query was empty" because I am passing empty array or else I get a syntax error.
I am using mysqli prepared statements and here is what I have tried working with with no luck. Very stumped. Basically, I am inserting potentially many ingredient rows passed from an API I have built:
API URL string
```
menu_item.php?ingredient_name[]=bacon&ingredient_price[]=1.00&ingredient_default[]=0&ingredient_name[]=cheese&ingredient_price[]=0&ingredient_default[]=1
```
PHP
```
// set arrays, item_id, foreign key, already set from previous query
$ingredient_name = $_GET['ingredient_name'];
$ingredient_price = $_GET['ingredient_price'];
$ingredient_default = $_GET['ingredient_default'];
// define arrays
$ingredients = array(
'ingredient_name' => $ingredient_name,
'ingredient_price' => $ingredient_price,
'ingredient_default' => $ingredient_default
);
$insertQuery = array();
$insertData = array();
// set array length
$len = count($ingredients);
/**
prepare the array values for mysql
**/
// prepare values to insert recursively
$ingQuery = "INSERT INTO TABLE (column1,column2,column3,column4) VALUES ";
// set placeholders
foreach ($ingredients as $row) {
$insertQuery[] = '(?,?,?,?)';
}
// iterate through all available data
for( $i=0;$i<$len;$i++ ) {
$insertData[] = $ingredients['ingredient_name'][$i];
$insertData[] = $ingredients['ingredient_price'][$i];
$insertData[] = $ingredients['ingredient_default'][$i];
}
// set ingredient value placeholders
$ingQuery .= implode(', ', $insertQuery);
// prepare statement ingredients
$ingStmt = $mysqli->prepare($sql);
// run the query
if( $ingStmt ) {
$ingStmt->execute($insertData);
} else {
// handle error return
echo json_encode(array('error' => $mysqli->error.__LINE__));
echo json_encode($insertData);
}
```
For now ignore all that maybe I need to start over. Any suggestions? Currently I am receiving Query Was Empty error... I need to do this a better, more efficient way, but I am scratching my head on this!
**EDIT (still in progress)**
```
// the query
$ingQuery = "INSERT INTO table (column1,column2,column3,column4) VALUES (?,?,?,?)";
// prepare statement
$ingStmt = $mysqli->prepare($ingQuery);
if( $ingStmt ) {
// iterate through all available data
for( $i=0;$i<count($_GET['ingredient_name']);$i++ ) {
$ingStmt->execute(array($item_id,$_GET['ingredient_name'][$i],$_GET['ingredient_price'][$i],$_GET['ingredient_default'][$i]));
}
} else {
echo json_encode(array('error' => $mysqli->error.__LINE__));
}
$ingStmt->close();
```
|
2014/02/11
|
['https://Stackoverflow.com/questions/21715723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2036030/']
|
What's with the single-dollar on the first command?
```
<tab>$(CC) >>$<< $(CC) ...
```
|
Don't you need blank lines between different sections? James' snippet has the `%.o:` target, followed by a blank line, followed by the `$(EXE):` target, followed by a blank line, followed by the `clean:` target.
Now that I think about it some more, I believe the blank lines aren't optional.
In your snippet, try putting a blank line between the one that starts with `<tab>` and the one that starts with `clean:`.
|
21,715,723 |
Ok, I realize there are similar topics on this, many in fact, but none of them are helping me figure out my issue and it just seems to lead me farther and farther from my goal. I have tried implode, for each, loops, etc., but either I receive "Query was empty" because I am passing empty array or else I get a syntax error.
I am using mysqli prepared statements and here is what I have tried working with with no luck. Very stumped. Basically, I am inserting potentially many ingredient rows passed from an API I have built:
API URL string
```
menu_item.php?ingredient_name[]=bacon&ingredient_price[]=1.00&ingredient_default[]=0&ingredient_name[]=cheese&ingredient_price[]=0&ingredient_default[]=1
```
PHP
```
// set arrays, item_id, foreign key, already set from previous query
$ingredient_name = $_GET['ingredient_name'];
$ingredient_price = $_GET['ingredient_price'];
$ingredient_default = $_GET['ingredient_default'];
// define arrays
$ingredients = array(
'ingredient_name' => $ingredient_name,
'ingredient_price' => $ingredient_price,
'ingredient_default' => $ingredient_default
);
$insertQuery = array();
$insertData = array();
// set array length
$len = count($ingredients);
/**
prepare the array values for mysql
**/
// prepare values to insert recursively
$ingQuery = "INSERT INTO TABLE (column1,column2,column3,column4) VALUES ";
// set placeholders
foreach ($ingredients as $row) {
$insertQuery[] = '(?,?,?,?)';
}
// iterate through all available data
for( $i=0;$i<$len;$i++ ) {
$insertData[] = $ingredients['ingredient_name'][$i];
$insertData[] = $ingredients['ingredient_price'][$i];
$insertData[] = $ingredients['ingredient_default'][$i];
}
// set ingredient value placeholders
$ingQuery .= implode(', ', $insertQuery);
// prepare statement ingredients
$ingStmt = $mysqli->prepare($sql);
// run the query
if( $ingStmt ) {
$ingStmt->execute($insertData);
} else {
// handle error return
echo json_encode(array('error' => $mysqli->error.__LINE__));
echo json_encode($insertData);
}
```
For now ignore all that maybe I need to start over. Any suggestions? Currently I am receiving Query Was Empty error... I need to do this a better, more efficient way, but I am scratching my head on this!
**EDIT (still in progress)**
```
// the query
$ingQuery = "INSERT INTO table (column1,column2,column3,column4) VALUES (?,?,?,?)";
// prepare statement
$ingStmt = $mysqli->prepare($ingQuery);
if( $ingStmt ) {
// iterate through all available data
for( $i=0;$i<count($_GET['ingredient_name']);$i++ ) {
$ingStmt->execute(array($item_id,$_GET['ingredient_name'][$i],$_GET['ingredient_price'][$i],$_GET['ingredient_default'][$i]));
}
} else {
echo json_encode(array('error' => $mysqli->error.__LINE__));
}
$ingStmt->close();
```
|
2014/02/11
|
['https://Stackoverflow.com/questions/21715723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2036030/']
|
The "line 4" is a bit misleading, but that's the line **of the `$(EXE)` rule** that make's parser
got to before deciding it couldn't proceed any further. As @jia103 alluded
to, you have a spurious `$` in your $(EXE) rule. You also have what appears
to be incorrect compiler flag syntax - there shouldn't be any whitespace
between `-` and `o` to form the output arg `-o $@`.
May I suggest the following rules instead of the `$(EXE)` and `clean` rules
that you have?
```
%.o: %.c
<tab>$(CC) $(CFLAGS) -o $@ $<
$(EXE): $(OBJECTS)
<tab>$(CC) $(CFLAGS) -o $@ $(OBJECTS)
clean:
<tab>$(RM) $(EXE) $(OBJECTS)
```
(remembering to change to the actual tab character...)
One final thing - if you're using Solaris and Sun Make, there's a decent chance that your c compiler is actually Solaris Studio. In which case, the `-Wall` flag doesn't work - that's a gcc flag. Utter `cc -flags` to see what options are available with Studio C.
|
Don't you need blank lines between different sections? James' snippet has the `%.o:` target, followed by a blank line, followed by the `$(EXE):` target, followed by a blank line, followed by the `clean:` target.
Now that I think about it some more, I believe the blank lines aren't optional.
In your snippet, try putting a blank line between the one that starts with `<tab>` and the one that starts with `clean:`.
|
21,715,723 |
Ok, I realize there are similar topics on this, many in fact, but none of them are helping me figure out my issue and it just seems to lead me farther and farther from my goal. I have tried implode, for each, loops, etc., but either I receive "Query was empty" because I am passing empty array or else I get a syntax error.
I am using mysqli prepared statements and here is what I have tried working with with no luck. Very stumped. Basically, I am inserting potentially many ingredient rows passed from an API I have built:
API URL string
```
menu_item.php?ingredient_name[]=bacon&ingredient_price[]=1.00&ingredient_default[]=0&ingredient_name[]=cheese&ingredient_price[]=0&ingredient_default[]=1
```
PHP
```
// set arrays, item_id, foreign key, already set from previous query
$ingredient_name = $_GET['ingredient_name'];
$ingredient_price = $_GET['ingredient_price'];
$ingredient_default = $_GET['ingredient_default'];
// define arrays
$ingredients = array(
'ingredient_name' => $ingredient_name,
'ingredient_price' => $ingredient_price,
'ingredient_default' => $ingredient_default
);
$insertQuery = array();
$insertData = array();
// set array length
$len = count($ingredients);
/**
prepare the array values for mysql
**/
// prepare values to insert recursively
$ingQuery = "INSERT INTO TABLE (column1,column2,column3,column4) VALUES ";
// set placeholders
foreach ($ingredients as $row) {
$insertQuery[] = '(?,?,?,?)';
}
// iterate through all available data
for( $i=0;$i<$len;$i++ ) {
$insertData[] = $ingredients['ingredient_name'][$i];
$insertData[] = $ingredients['ingredient_price'][$i];
$insertData[] = $ingredients['ingredient_default'][$i];
}
// set ingredient value placeholders
$ingQuery .= implode(', ', $insertQuery);
// prepare statement ingredients
$ingStmt = $mysqli->prepare($sql);
// run the query
if( $ingStmt ) {
$ingStmt->execute($insertData);
} else {
// handle error return
echo json_encode(array('error' => $mysqli->error.__LINE__));
echo json_encode($insertData);
}
```
For now ignore all that maybe I need to start over. Any suggestions? Currently I am receiving Query Was Empty error... I need to do this a better, more efficient way, but I am scratching my head on this!
**EDIT (still in progress)**
```
// the query
$ingQuery = "INSERT INTO table (column1,column2,column3,column4) VALUES (?,?,?,?)";
// prepare statement
$ingStmt = $mysqli->prepare($ingQuery);
if( $ingStmt ) {
// iterate through all available data
for( $i=0;$i<count($_GET['ingredient_name']);$i++ ) {
$ingStmt->execute(array($item_id,$_GET['ingredient_name'][$i],$_GET['ingredient_price'][$i],$_GET['ingredient_default'][$i]));
}
} else {
echo json_encode(array('error' => $mysqli->error.__LINE__));
}
$ingStmt->close();
```
|
2014/02/11
|
['https://Stackoverflow.com/questions/21715723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2036030/']
|
It is possible you have newline expressions for a different system (eg. Windows newline symbols in a Unix makefile).
You can fix it in Notepad++: edit->EOL conversion->Unix (or Windows or Old Mac) or you can reenter the newline characters manually on the machine on which you're compiling.
|
Don't you need blank lines between different sections? James' snippet has the `%.o:` target, followed by a blank line, followed by the `$(EXE):` target, followed by a blank line, followed by the `clean:` target.
Now that I think about it some more, I believe the blank lines aren't optional.
In your snippet, try putting a blank line between the one that starts with `<tab>` and the one that starts with `clean:`.
|
339,515 |
I'm a developer who builds mainly single page client side web applications where state in maintained on the client-side. Lately some of the applications have become very complex with very rich domain models on the client-side and increasingly complicated UI interactions.
As we've gone along we've implemented some very useful design patterns such as Passive View MVC, Observers, bindings, key-value observers (cocoa). I have recently got a lot of inspiration from the work of SproutCore and Cappuccino which are both JavaScript web frameworks inspired by Cocoa.
Obviously all of the problems that developers are having now in building complex web applications have been solved by desktop developers many moons ago. As few months ago all I knew about Cocoa was that is was some Apple thing, now it has had a big impact in the way I develop my web applications.
I was wondering if anyone who has more experience in building desktop GUI's than I, could point me any other frameworks out there which may also give me inspiration in terms of design patterns and structures to use for my JavaScript web applications?
I really don't care what languages or platform these frameworks reside in, as long as they can teach me something about good application design in general.
|
2008/12/04
|
['https://Stackoverflow.com/questions/339515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37196/']
|
Try something like this:
```
<object>
<param name="wmode" value="transparent" />
<embed src="example.swf" wmode="transparent"></embed>
</object>
```
The main things to note are the `<param />` tag with the transparent attribute, and the `wmode="transparent"` in the embed tag. You'll also need to run the following javascript code to make this work across all browsers:
```
theObjects = document.getElementsByTagName("object");
for (var i = 0; i < theObjects.length; i++) {
theObjects[i].outerHTML = theObjects[i].outerHTML;
}
```
This code should be run when the document is loaded. The site I got this code from claims that it must be run from an external file in order to work (although I haven't tested that).
I got this answer from here, where you can get more detail and a working example:
<http://www.cssplay.co.uk/menus/flyout_flash.html>
|
should be aware that wmode=transparent will kill use of scroll wheel in firefox. this is true even in FP10
|
339,515 |
I'm a developer who builds mainly single page client side web applications where state in maintained on the client-side. Lately some of the applications have become very complex with very rich domain models on the client-side and increasingly complicated UI interactions.
As we've gone along we've implemented some very useful design patterns such as Passive View MVC, Observers, bindings, key-value observers (cocoa). I have recently got a lot of inspiration from the work of SproutCore and Cappuccino which are both JavaScript web frameworks inspired by Cocoa.
Obviously all of the problems that developers are having now in building complex web applications have been solved by desktop developers many moons ago. As few months ago all I knew about Cocoa was that is was some Apple thing, now it has had a big impact in the way I develop my web applications.
I was wondering if anyone who has more experience in building desktop GUI's than I, could point me any other frameworks out there which may also give me inspiration in terms of design patterns and structures to use for my JavaScript web applications?
I really don't care what languages or platform these frameworks reside in, as long as they can teach me something about good application design in general.
|
2008/12/04
|
['https://Stackoverflow.com/questions/339515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37196/']
|
I believe the short answer is: **No**.
Sorry.
However, If you had complete control over how the Flash object is authored - you might be able to expose a public API to the javascript - allowing it to "manually" forward live mouse-coordinate, and mouse-button information into the flash, as you operate the mouse on top of the HTML overlay.
It might be worth checking, if Google's street-view Flash object exposes a public javascript API that might allow you to take some control of the flash - based on mouse-events picked up by your HTML overlay.
Expect the skies to fall, if you try this. :-)
|
should be aware that wmode=transparent will kill use of scroll wheel in firefox. this is true even in FP10
|
73,645,259 |
`ListView` doesn't stop scrolling when I reach the end of content, It keeps scrolling (**not infinite scrolling**).
How do I stop the scroll when there is no more content to scroll to?
Tried replacing `ListView` with `Column` --> didn't work.
Tried adding `SingleChildScrollView` --> didn't work.
Tried adding `physics: NeverScrollableScrollPhysics()` to `ListView` --> didn't work.
**Edit:** Tried removing the `Expanded` widget --> didn't work.
It is as there is extra height at the end, but there shouldn't be anything.
Simplified code:
```
Expanded(
child: ListView(
children: [
Obx(() => Column()),
Obx(() => Text("Example")),
Row()
],
),
)
```
Gif of the problem:
<https://imgur.com/a/MsZBanu>
Also, in there is some gray overlay over the whole screen when the Flutter Inspector is working
```
Expanded(
child: ListView(
shrinkWrap: true,
children: [
Obx(
() => NameAndLocationWidget(
mountainsController: _mountainsController,
locationName: 'Lokacija',
name:
'${_mountainsController.mountain.value != null ? _mountainsController.mountain.value!.name : "-"}',
pathsController: null,
fontSize: AppFontSizes.aboutMountainTitle,
),
),
Obx(
() => Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppPaddings
.aboutMountainMountainNameHorizontalPadding),
child: Text(
'${_mountainsController.mountain.value != null ? _mountainsController.mountain.value!.description : "-"}',
style: const TextStyle(
color: AppColors.aboutMountainDescriptionTextColor,
fontSize: AppFontSizes.aboutMountainDescriptionText,
height:
AppConstants.aboutMountainDescriptionTextHeight,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppPaddings
.aboutMountainMountainNameHorizontalPadding,
vertical: AppPaddings
.aboutMountainMountainNameVerticalPadding),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
DistanceTimeDifficultyWidget(
dTDInfoName: 'distance'.tr,
dTDInfoValue: '6 - 10 km',
),
DistanceTimeDifficultyWidget(
dTDInfoName: 'time'.tr,
dTDInfoValue: '2 - 4 h',
),
DistanceTimeDifficultyWidget(
dTDInfoName: 'difficulty'.tr,
dTDInfoValue: 'Easy',
),
],
),
)
],
),
)
```
**Update:**
The problem is not in the code above, but in the bottomNavigationBar:SlidingUpPanel()
```
SlidingUpPanel(
backdropEnabled: true,
backdropOpacity: 0.25,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(
AppConstants.aboutMountainSolidBottomSheetBorderRadius),
topRight: Radius.circular(
AppConstants.aboutMountainSolidBottomSheetBorderRadius)),
minHeight: MediaQuery.of(context).size.height * 0.1,
maxHeight: MediaQuery.of(context).size.height * 0.75,
controller: _pc,
panel: Column(
children: [
SizedBox(
width: double.maxFinite,
child: ClipRRect(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(AppConstants
.aboutMountainSolidBottomSheetBorderRadius),
topLeft: Radius.circular(AppConstants
.aboutMountainSolidBottomSheetBorderRadius),
),
child: TextButton(
child: Column(
children: [
RotationTransition(
turns: Tween(begin: 0.0, end: 1.0)
.animate(_controller),
child: const Icon(
Icons.expand_less,
color: AppColors
.aboutMountainSolidBottomSheetTextColor,
size: AppFontSizes
.aboutMountainSolidBottomSheetText,
),
),
Text(
"path_list".tr,
style: const TextStyle(
color: AppColors
.mountainsScreenBottomModalButtonColor,
fontSize: AppFontSizes
.mountainsScreenBottomModalButtonText),
)
],
),
onPressed: () {
FocusManager.instance.primaryFocus?.unfocus();
if (_pc.isPanelClosed) {
_controller.forward(from: 0.0);
_pc.open();
} else {
_controller.reverse(from: 0.5);
_pc.close();
}
}),
),
),
Container(
margin: const EdgeInsets.symmetric(
horizontal: AppConstants.bottomModalSheetSearchMarginHor,
vertical: AppConstants.bottomModalSheetSearchMarginVer),
decoration: BoxDecoration(
color: AppColors.searchBoxBackgroundColor,
borderRadius:
BorderRadius.circular(AppConstants.searchBoxRadius),
),
child: SingleChildScrollView(
child: TextField(
onChanged: (value) {
_pathsController.searchPaths(SearchPathDto(
start: 0,
size: 10,
name: value,
mountainId: Get.parameters['id']!));
_pathsController.onClose();
},
decoration: InputDecoration(
hintStyle: const TextStyle(
fontSize: AppFontSizes.searchBoxHintText),
hintText: 'search'.tr,
suffixIcon: const Icon(
Icons.search,
color: AppColors.searchBoxSearchIconColor,
),
border: InputBorder.none,
contentPadding:
const EdgeInsets.all(AppPaddings.searchBoxPadding),
),
),
),
),
Expanded(
child: Obx(
() => ListView.builder(
itemCount: _pathsController.paths.length,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
final item = _pathsController.paths[index];
return PathCardBox(
path: item,
);
},
),
),
),
],
),
)
```
It looks like it takes the whole screen (as you can see by the grey overlay in the Flutter Inspector), but it should only take the small amount when it's collapsed.
**Update(12.9.2022):**
Changed the whole layout, now everything from Scaffold(body:) in inside SlidingUpPanel(body:), but the scroll isn't working as well,
is there some SlidingUpPanel property that can conflict with the scroll?
|
2022/09/08
|
['https://Stackoverflow.com/questions/73645259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19717894/']
|
Use below formula.
```
=TRIM(RIGHT(SUBSTITUTE(A1,"\",REPT(" ",100)),100))
```
If you have most recent release of ***Microsoft-365*** then could try.
```
=TEXTAFTER(A1,"\",-1)
```
[](https://i.stack.imgur.com/deQgt.png)
|
Just select the column.
Data tab - text to column - select "Delimited" - next - choose Other and enter "" in the box - next - Finish
You can keep which part you want and delete others
[](https://i.stack.imgur.com/M5nnB.png)
[](https://i.stack.imgur.com/PyooL.png)
|
526,522 |
For simplicity, let's take the 1D Schrödinger's equation for a single non-relativistic particle:
$$-\frac{\hbar^2}{2m} \frac{\partial^2 \Psi(x,t)}{\partial x^2} + V(x) \Psi(x,t) = i\hbar \frac{\partial\Psi(x,t)}{\partial t}$$
Applying separation of variables, $\Psi(x,t)=\psi (x)\phi (t)$, we get the time dependent solution.
$$-\frac{\hbar^2}{2m} \frac{\psi'' (x)}{\psi (x)} + V(x)= i\hbar \frac{\phi' (t)}{\phi (t)}=C$$
$$\phi (t)=Ae^{-iCt/\hbar }$$
Here, the separation constant $C$ is taken as the energy of the particle, $E$. I see that this is convenient cause the exponent must be dimensionless. However, do we have further arguments for asserting it?
|
2020/01/22
|
['https://physics.stackexchange.com/questions/526522', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/173206/']
|
This is essentially the *definition* of energy in quantum mechanics -- it is $\hbar$ times the rate of change of phase. That's one of the fundamentally new ideas in quantum mechanics, so it can't be derived from anything you already know classically.
If that's not very satisfying, we can say the same thing in more steps. The energy of an energy eigenstate is defined to be the eigenvalue of the Hamiltonian. And we have
$$H \Psi(x, t) = i \hbar \frac{\partial}{\partial t} \Psi(x, t) = i \frac{\partial}{\partial t} (\psi(x) \phi(t)) = i \hbar \left(- \frac{iC}{\hbar}\right) \Psi(x, t)
= C \Psi(x, t).$$
So $C$ is the energy.
Of course, this just reduces the question to "why is the time-dependent Schrodinger equation true", and the answer is, again, that in quantum mechanics energy is $\hbar$ times the rate of change in phase.
|
The reason that we take it to be the energy is that this is closely related to the classical energy, when one follows the standard rules and conventions of "quantizing" the classical quantities.
In a similar manner, you can take any classical quantity $A$, and then from the classical concept of the Hamiltonian (which is the classical energy $E\_K+V$ in standard systems) you know that
$$\dot{A} = \{ A, H \} +\frac{ \partial A }{\partial t}$$
with $\{ a,b\}$ the Poisson brackets. Following quantization rules we replace the Poisson brackets with commutation relations (divided by $i\hbar$), and all quantities in operators, to get
$$\frac{d}{dt} \langle A \rangle = -\frac{i}{\hbar}\langle \left[ A, H \right] \rangle + \frac{ \partial }{\partial t}\langle A \rangle$$
and you can see how $H$ here plays the role of the energy. This is just the Heisenberg picture, which is equivalent to the Schroedinger picture, so we can identify the term as a Hamiltonian, which measures the energy.
Another (closely related) way to see this: start from the fundamental relations of QM $[x,p]=i\hbar$, from which you can derive $[x, f(p)]=i\hbar \partial\_p f$ and $[f(x),p]=i\hbar \partial\_x f$. Then you take Hamilton equations from classical mechanics and quantize them
$$ \frac{d}{dt}\langle x \rangle = \langle \frac{\partial H}{\partial p} \rangle = -\frac{i}{\hbar}\langle \left[x, H\right]\rangle$$
and again you got Heisenberg picture, from which you can derive Schroedinger equation, with the $H$ the energy as it comes from classical mechanics.
|
61,312,693 |
So I have a file that has one line of int : 5551212
I am trying to use InputStream to read this file and then see if I can extract the number written within in it
I did the following steps:
```
import java.io.*;
class Shuffle {
public static void main(String args[]) throws IOException {
FileInputStream newfile = new FileInputStream("file path");
System.out.println(newfile.getChannel());
System.out.println(newfile.getFD());
System.out.println("Number of remaining bytes:"+newfile.available());
int data;
while ((data = newfile.read()) != -1) {
System.out.print(data + " ");
}
newfile.close();
}
}
```
However, the output that I got is: 53, 53, 53, 49, 50, 49, 50
I am not really sure what this is suppose to represent, or simply how do I use InputStream on integers
|
2020/04/19
|
['https://Stackoverflow.com/questions/61312693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11122895/']
|
With Java 11 or above, a file can be read using a single line of code - ***Files.readString***
**Here is a working example for reading a text file:**
```
// File name: ReadFile.java
import java.nio.file.*;
public class ReadFile {
public static void main(String[] args) throws Exception {
String path = "my-file.txt";
// Read file content as a string
System.out.println(Files.readString(Paths.get(path)));
}
}
```
**Output:**
```
> javac ReadFile.java
> java ReadFile
5551212
```
|
The file you're reading is a text file, and thus the bytes you're receiving are representing encoded chars. If you look at ascii table (eg <http://www.asciitable.com/>) at decimal value 53, you'll see it's corresponding to a char "5"
|
61,312,693 |
So I have a file that has one line of int : 5551212
I am trying to use InputStream to read this file and then see if I can extract the number written within in it
I did the following steps:
```
import java.io.*;
class Shuffle {
public static void main(String args[]) throws IOException {
FileInputStream newfile = new FileInputStream("file path");
System.out.println(newfile.getChannel());
System.out.println(newfile.getFD());
System.out.println("Number of remaining bytes:"+newfile.available());
int data;
while ((data = newfile.read()) != -1) {
System.out.print(data + " ");
}
newfile.close();
}
}
```
However, the output that I got is: 53, 53, 53, 49, 50, 49, 50
I am not really sure what this is suppose to represent, or simply how do I use InputStream on integers
|
2020/04/19
|
['https://Stackoverflow.com/questions/61312693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11122895/']
|
With Java 11 or above, a file can be read using a single line of code - ***Files.readString***
**Here is a working example for reading a text file:**
```
// File name: ReadFile.java
import java.nio.file.*;
public class ReadFile {
public static void main(String[] args) throws Exception {
String path = "my-file.txt";
// Read file content as a string
System.out.println(Files.readString(Paths.get(path)));
}
}
```
**Output:**
```
> javac ReadFile.java
> java ReadFile
5551212
```
|
You are reading an int, and the file is text data, not binary. Hence whatever bytes are in the file are interpreted as binary, and you get these numbers.
To read from a text file, you can either use a Scanner, or read as text first and then convert to int.
```
import java.io.*;
class Shuffle {
public static void main(String args[]) throws IOException {
try (InputStream file = new FileInputStream("file.txt");
InputStreamReader in = new InputStreamReader(file);
BufferedReader r = new BufferedReader(in)) {
String line = r.readLine();
while (line != null) {
int number = Integer.parseInt(line);
System.out.println(number);
line = r.readLine();
}
}
}
}
```
This code also uses try-with-resources, which makes sure all readers and files are closed at the end, even if an exception is thrown.
|
17,937,982 |
Im trying to search for three pieces of data from a string and they are:
```
first name, space ,last name (?=[A-Z][a-z]+\s[A-Z][a-z]+)
//AND
first name ,space ,last name ,and suffix (?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)
//AND,
age (?=[0-9]{2})
```
from several tutorials I've seen it seems that these three patterns:
```
(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2})
```
together should be my solution, but its not working.... any suggestions....(its a php script and im using preg\_match\_all)
my script:
```
$content = file_get_contents('http://www.somesite.com');
$pattern = '/(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2}) /';
if(preg_match_all($pattern,$content,$matches))
{
// has the pattern, do something
//$matches has all the matches from preg_match
}
```
|
2013/07/30
|
['https://Stackoverflow.com/questions/17937982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497763/']
|
That multiple-lookahead trick is for times when you know certain components must be present, but you don't know what order they'll appear in. You see it most often in regexes that enforce strong password policies.
Your problem is much simpler; the components always come in the same order, but the last one is optional. That's much easier:
```
'/\b([A-Z][a-z]*)\s+([A-Z][a-z]*)(?:\s+([0-9]{2}))?\b/'
```
The first name is captured in group #1, the last name will be in group #2, and if there's a suffix you'll find it in group #3.
|
You're looking for an OR operator, not an AND:
```
[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+|[0-9]{2}
```
If there can be multiple space characters between words, make sure to quantify the `\s`:
```
[A-Z][a-z]+\s+[A-Z][a-z]+|[A-Z][a-z]+\s+[A-Z][a-z]+\s+[A-Z][a-z]+|[0-9]{2}
```
And don't forget about *anchors* (`^` and `$`) if you're looking for exact matches.
|
17,937,982 |
Im trying to search for three pieces of data from a string and they are:
```
first name, space ,last name (?=[A-Z][a-z]+\s[A-Z][a-z]+)
//AND
first name ,space ,last name ,and suffix (?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)
//AND,
age (?=[0-9]{2})
```
from several tutorials I've seen it seems that these three patterns:
```
(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2})
```
together should be my solution, but its not working.... any suggestions....(its a php script and im using preg\_match\_all)
my script:
```
$content = file_get_contents('http://www.somesite.com');
$pattern = '/(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2}) /';
if(preg_match_all($pattern,$content,$matches))
{
// has the pattern, do something
//$matches has all the matches from preg_match
}
```
|
2013/07/30
|
['https://Stackoverflow.com/questions/17937982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497763/']
|
That multiple-lookahead trick is for times when you know certain components must be present, but you don't know what order they'll appear in. You see it most often in regexes that enforce strong password policies.
Your problem is much simpler; the components always come in the same order, but the last one is optional. That's much easier:
```
'/\b([A-Z][a-z]*)\s+([A-Z][a-z]*)(?:\s+([0-9]{2}))?\b/'
```
The first name is captured in group #1, the last name will be in group #2, and if there's a suffix you'll find it in group #3.
|
You can use non-capturing group `(?:...)` and question marks to make the groups optional:
```
[A-Z][a-z]+\s[A-Z][a-z]+(?:\s[A-Z][a-z]+(?:\s[0-9]{2,3})?)?
```
If you want to extract the data, using named captures is a clean way:
```
$pattern = <<<'LOD'
~
(?<first_name>[A-Z][a-z]+)
\s+
(?<last_name>[A-Z][a-z]+)
(?:
\s+ (?<suffix>[A-Z][a-z]+)
(?: \s+ (?<age> [0-9]{2,3}) )?
)?
~x
LOD;
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo '<br/>' . $match['first_name'] . ', ' . $match['last_name'];
}
```
|
17,937,982 |
Im trying to search for three pieces of data from a string and they are:
```
first name, space ,last name (?=[A-Z][a-z]+\s[A-Z][a-z]+)
//AND
first name ,space ,last name ,and suffix (?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)
//AND,
age (?=[0-9]{2})
```
from several tutorials I've seen it seems that these three patterns:
```
(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2})
```
together should be my solution, but its not working.... any suggestions....(its a php script and im using preg\_match\_all)
my script:
```
$content = file_get_contents('http://www.somesite.com');
$pattern = '/(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2}) /';
if(preg_match_all($pattern,$content,$matches))
{
// has the pattern, do something
//$matches has all the matches from preg_match
}
```
|
2013/07/30
|
['https://Stackoverflow.com/questions/17937982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497763/']
|
That multiple-lookahead trick is for times when you know certain components must be present, but you don't know what order they'll appear in. You see it most often in regexes that enforce strong password policies.
Your problem is much simpler; the components always come in the same order, but the last one is optional. That's much easier:
```
'/\b([A-Z][a-z]*)\s+([A-Z][a-z]*)(?:\s+([0-9]{2}))?\b/'
```
The first name is captured in group #1, the last name will be in group #2, and if there's a suffix you'll find it in group #3.
|
```
([a-zA-Z]+\s+[a-zA-Z]+\s+[a-zA-Z0-9])
```
You can test your RegEx with tools like <http://www.cyber-reality.com/regexy.html>
|
62,160,195 |
I'm setting up a CI pipeline on a BitBucket Repository based around docker. I'm running build commands then up then test, basically. This all works so far, but the issue I'm having is BitBucket **only** commits or lets me edit changes to the *bitbucket-pipelines.yaml* file on the master branch.
I'm not the only developer on the project, and right now our master is our staging/ready for prod branch, and we've all agreed to use other branches for things and let one of us manage master and merges into it.
My question is, can I use another, different branch than master to "manage" my pipelines file on, like our active development branch? For some reason, I can't find a way to add a pipeline to another branch, and pushing up a bitbucket-pipelines.yaml file on the develop branch won't trigger a build.
For reference, my pipeline yaml:
```
image: atlassian/default-image:2
pipelines:
# pull-requests:
# 'feature/*':
# - step:
# services:
# - docker
branches:
develop:
# each step starts a new Docker container with a clone of your repository
- step:
services:
- docker
script:
- (cd app/laravel/ ; npm install)
- (cd app/laravel/ ; npm run production)
- docker build -t myApp -f app/Dockerfile app/
- docker stack up -c docker/docker-compose.yaml myApp
```
|
2020/06/02
|
['https://Stackoverflow.com/questions/62160195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3069555/']
|
You should be able to have a pipeline in any branch you want.
From the [troubleshooting section](https://confluence.atlassian.com/bitbucket/troubleshooting-bitbucket-pipelines-792298903.html#TroubleshootingBitbucketPipelines-Mybranchdoesn%27tbuild):
>
> My branch doesn't build
> -----------------------
>
>
> Make sure that there is a `bitbucket-pipelines.yml` file in the root of your branch.
>
>
> To build a branch, you must specify a `default` or a `branch-specific` pipeline configuration.
>
> For more information, see [Configure bitbucket-pipelines.yml](https://confluence.atlassian.com/bitbucket/configure-bitbucket-pipelines-yml-792298910.html#Configurebitbucket-pipelines.yml-pipelines_branch_definition).
>
>
>
I would test that, following [branch workflow](https://confluence.atlassian.com/bitbucket/branch-workflows-856697482.html), with a simplified yaml first (one which does just an echo for a given branch), for testing.
As the [OP RoboBear](https://stackoverflow.com/users/3069555/robobear) confirms [in the comments](https://stackoverflow.com/questions/62160195/avoid-using-master-branch-for-bitbucket-pipeline/62166436?noredirect=1#comment109951501_62166436), the `bitbucket-pipelines.yml` must use the `.yml` extension, *not* `.yaml`.
|
My problem was that pipelines had not been enabled for the repo and since I added the bitbucket-pipelines.yml file to a branch that was not the main branch, and not using the onboarding tutorial, pipelines had not been enabled for the repository. Go to Repository settings -> Pipelines | Settings -> Enable Pipelines. Then you will have to push another change to the branch with the bitbucket-pipelines.yml and it should run the pipeline.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
It is totally impossible to be able to tell if someone is 'cheating' unless you go to their house and check their phone browser history for any of those word helping websites. Other than that, what's to say they aren't just good with words?
It is also important to note that the complexity of the word or length mean nothing in comparison to playing the game well. Knowing words helps, but dropping those big point letters on the triple letters and dropping those big point words on the triple words is what nets you the big points. I bet you could score 100 point with the word Zoo if you placed it well enough. Words with friends is a lot of strategy not just word knowledge.
A couple tips to beat them at their own game.
1. **Take longshots**: What's the worst that can happen if you try to put in a word that's not real? It's not like someone is looking over your shoulder saying "Haha you loser, you don't even know what a word is.". Try to land those high letters on those triples.
2. **Don't set *them* up:** If you're making a word, be very concious of where *they* will be able to go next round with your word. Did you just open up a path to a double word? A triple word? Make sure you're leaving them with basically nothing awesome.
|
What you can do is play two or three games with them simultaneously. Work out their average time they take to make a move. They could cheat in the first game because they could take any length of time, but after their first go, you should be able to tell if you are both playing at the same time. If they don't play their moves regularly, but always beat you on the first game and not the second, then it might indicate that they cheat. Or if they take unusually longer on their second game, and suddenly get an unusual word, that's also a clue.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
It is totally impossible to be able to tell if someone is 'cheating' unless you go to their house and check their phone browser history for any of those word helping websites. Other than that, what's to say they aren't just good with words?
It is also important to note that the complexity of the word or length mean nothing in comparison to playing the game well. Knowing words helps, but dropping those big point letters on the triple letters and dropping those big point words on the triple words is what nets you the big points. I bet you could score 100 point with the word Zoo if you placed it well enough. Words with friends is a lot of strategy not just word knowledge.
A couple tips to beat them at their own game.
1. **Take longshots**: What's the worst that can happen if you try to put in a word that's not real? It's not like someone is looking over your shoulder saying "Haha you loser, you don't even know what a word is.". Try to land those high letters on those triples.
2. **Don't set *them* up:** If you're making a word, be very concious of where *they* will be able to go next round with your word. Did you just open up a path to a double word? A triple word? Make sure you're leaving them with basically nothing awesome.
|
On their phone check the dictionary of words added - it'll be the letters from their rack(s) when they entered them on the site.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
It is totally impossible to be able to tell if someone is 'cheating' unless you go to their house and check their phone browser history for any of those word helping websites. Other than that, what's to say they aren't just good with words?
It is also important to note that the complexity of the word or length mean nothing in comparison to playing the game well. Knowing words helps, but dropping those big point letters on the triple letters and dropping those big point words on the triple words is what nets you the big points. I bet you could score 100 point with the word Zoo if you placed it well enough. Words with friends is a lot of strategy not just word knowledge.
A couple tips to beat them at their own game.
1. **Take longshots**: What's the worst that can happen if you try to put in a word that's not real? It's not like someone is looking over your shoulder saying "Haha you loser, you don't even know what a word is.". Try to land those high letters on those triples.
2. **Don't set *them* up:** If you're making a word, be very concious of where *they* will be able to go next round with your word. Did you just open up a path to a double word? A triple word? Make sure you're leaving them with basically nothing awesome.
|
It is indeed hard to figure out if your friend is using an online cheat tools or dictionary when playing Words with Friends, since you cannot see them in person. But there are other signs which could help you to figure out whether they are cheating or not such as your friend tend to use difficult or unknown words consistently and they are getting huge points in every move. If you want to know more [How to Catch a Friend Using Words with Friends Cheat](http://gameolosophy.com/games/how-to-catch-a-friend-using-words-with-friends-cheat/) you can read this article for additional information.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
It is totally impossible to be able to tell if someone is 'cheating' unless you go to their house and check their phone browser history for any of those word helping websites. Other than that, what's to say they aren't just good with words?
It is also important to note that the complexity of the word or length mean nothing in comparison to playing the game well. Knowing words helps, but dropping those big point letters on the triple letters and dropping those big point words on the triple words is what nets you the big points. I bet you could score 100 point with the word Zoo if you placed it well enough. Words with friends is a lot of strategy not just word knowledge.
A couple tips to beat them at their own game.
1. **Take longshots**: What's the worst that can happen if you try to put in a word that's not real? It's not like someone is looking over your shoulder saying "Haha you loser, you don't even know what a word is.". Try to land those high letters on those triples.
2. **Don't set *them* up:** If you're making a word, be very concious of where *they* will be able to go next round with your word. Did you just open up a path to a double word? A triple word? Make sure you're leaving them with basically nothing awesome.
|
If it it someone you know, the best thing to do is ask them if they think it's fair to use the cheater apps or sites. My good friend said she thought that was quite legit and I told her I prefer not to play like that. So now we don't.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
It is totally impossible to be able to tell if someone is 'cheating' unless you go to their house and check their phone browser history for any of those word helping websites. Other than that, what's to say they aren't just good with words?
It is also important to note that the complexity of the word or length mean nothing in comparison to playing the game well. Knowing words helps, but dropping those big point letters on the triple letters and dropping those big point words on the triple words is what nets you the big points. I bet you could score 100 point with the word Zoo if you placed it well enough. Words with friends is a lot of strategy not just word knowledge.
A couple tips to beat them at their own game.
1. **Take longshots**: What's the worst that can happen if you try to put in a word that's not real? It's not like someone is looking over your shoulder saying "Haha you loser, you don't even know what a word is.". Try to land those high letters on those triples.
2. **Don't set *them* up:** If you're making a word, be very concious of where *they* will be able to go next round with your word. Did you just open up a path to a double word? A triple word? Make sure you're leaving them with basically nothing awesome.
|
There is ENTIRELY too much cheating in Words with Friends. There is really nothing you can do about it except refuse to play the cheater anymore. One good indicator that your opponent is using a cheat program, however, is that these programs only try to score the maximum points while ignoring strategy. I've seen opponents play a 40 or 50 point word only to leave a 75 or 80 point opportunity for me. Take comfort that karma will prevail!
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
What you can do is play two or three games with them simultaneously. Work out their average time they take to make a move. They could cheat in the first game because they could take any length of time, but after their first go, you should be able to tell if you are both playing at the same time. If they don't play their moves regularly, but always beat you on the first game and not the second, then it might indicate that they cheat. Or if they take unusually longer on their second game, and suddenly get an unusual word, that's also a clue.
|
It is indeed hard to figure out if your friend is using an online cheat tools or dictionary when playing Words with Friends, since you cannot see them in person. But there are other signs which could help you to figure out whether they are cheating or not such as your friend tend to use difficult or unknown words consistently and they are getting huge points in every move. If you want to know more [How to Catch a Friend Using Words with Friends Cheat](http://gameolosophy.com/games/how-to-catch-a-friend-using-words-with-friends-cheat/) you can read this article for additional information.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
On their phone check the dictionary of words added - it'll be the letters from their rack(s) when they entered them on the site.
|
It is indeed hard to figure out if your friend is using an online cheat tools or dictionary when playing Words with Friends, since you cannot see them in person. But there are other signs which could help you to figure out whether they are cheating or not such as your friend tend to use difficult or unknown words consistently and they are getting huge points in every move. If you want to know more [How to Catch a Friend Using Words with Friends Cheat](http://gameolosophy.com/games/how-to-catch-a-friend-using-words-with-friends-cheat/) you can read this article for additional information.
|
54,231 |
I would deem cheating in Words with Friends to use a dictionary or site that generates words in a manner of best score.
I have had opponents play 100 + point words that I didn't even know existed.
Is there anyway without being with them / watching them play to see if my opponent is 'cheating' ?
|
2012/03/08
|
['https://gaming.stackexchange.com/questions/54231', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18818/']
|
If it it someone you know, the best thing to do is ask them if they think it's fair to use the cheater apps or sites. My good friend said she thought that was quite legit and I told her I prefer not to play like that. So now we don't.
|
It is indeed hard to figure out if your friend is using an online cheat tools or dictionary when playing Words with Friends, since you cannot see them in person. But there are other signs which could help you to figure out whether they are cheating or not such as your friend tend to use difficult or unknown words consistently and they are getting huge points in every move. If you want to know more [How to Catch a Friend Using Words with Friends Cheat](http://gameolosophy.com/games/how-to-catch-a-friend-using-words-with-friends-cheat/) you can read this article for additional information.
|
53,179,085 |
I'm writing a code using Java Swing to press the right button when I type a number key.
But I can't find what I want through search.
This is my code and I can't understand why this isn't working.
Please help me..
```
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class class01 {
public static void main(String[] args) {
JFrame f = new JFrame("Key event test");
f.setSize(230, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
JButton button1 = new JButton("Coffe");
button1.setSize(100, 100);
button1.setLocation(0, 0);
JButton button2 = new JButton("Latte");
button2.setSize(100, 100);
button2.setLocation(0, 100);
JButton button3 = new JButton("Espresso");
button3.setSize(100, 100);
button3.setLocation(100, 100);
JButton button4 = new JButton("Vanilla Latte");
button4.setSize(100, 100);
button4.setLocation(100, 0);
f.add(button1);
f.add(button2);
f.add(button3);
f.add(button4);
// Show message when the corresponding button is pressed.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button2.keyPressed(KeyEvent.VK_2);
JOptionPane.showMessageDialog(f.getComponent(0), "Latte selected");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button3.keyPressed(KeyEvent.VK_3);
JOptionPane.showMessageDialog(f.getComponent(0), "Espresso selected");
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button4.keyPressed(KeyEvent.VK_4);
JOptionPane.showMessageDialog(f.getComponent(0), "Vanilla Latte selected");
}
});
}
}
```
|
2018/11/06
|
['https://Stackoverflow.com/questions/53179085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8933767/']
|
The code you are showing does exactly one thing: attach action listeners to your buttons..
Meaning: when you click the button, then the listener will be called.
You need a generic keyboard listener that translates key events into calls to the appropriate button, respectively action listener instead.
|
When you do this:
```
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
```
You are telling `button1` what to do when somebody clicks on the button. The line with `keyPressed` should not be there (it does not compile even).
What you need to do is listen for key presses by adding a `KeyListener` to the frame like this:
```
f.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if( e.getKeyChar() == KeyEvent.VK_1) {
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
}
});
```
I repeated the `showMessageDialog`, but you should extract the actual logic into a method and call that method from within the `KeyListener` on the frame and the `ActionListener` on the button.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.