qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
60,631,229 | i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
```
:loading="isLoading[index]"
```
here the vue :
```
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" @click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
```
here the data :
```
data () {
return {
products : [],
isLoading: false,
}
},
```
here my add to cart method where i change the state of isLoading :
```
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
``` | 2020/03/11 | [
"https://Stackoverflow.com/questions/60631229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528834/"
] | you can use:
```
words = input_str.split()
s = set()
result = set()
for w in words:
r = w[::-1]
if r in s:
result.add(r)
else:
s.add(w)
list(result)
```
output:
```
['am', 'eat']
```
this is O(n) time complexity solution, so you have to get first the words and iterate through them, each time you have a new word you are adding him to a set, if the reverse is already in the set you are adding the reverse to the result | just change the indent of line "return reverse" :
```
input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2):
# If both the strings differ in length
if len(s1) != len(s2):
return False
l = len(s1)
for i in range(l):
# In case of any character mismatch
if s1[i] != s2[l-i-1]:
return False
return True
def getWord(str, n):
reverse=[]
# Check every string
for i in range(n-1):
# Pair with every other string
# appearing after the current string
for j in range(i+1, n):
# If first string is equal to the
# reverse of the second string
if (isReverseEqual(str[i], str[j])):
reverse.append(str[i])
if reverse:
return reverse
else: # No such string exists
return "-1"
print(getWord(word, len(word)))
``` |
60,631,229 | i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
```
:loading="isLoading[index]"
```
here the vue :
```
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" @click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
```
here the data :
```
data () {
return {
products : [],
isLoading: false,
}
},
```
here my add to cart method where i change the state of isLoading :
```
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
``` | 2020/03/11 | [
"https://Stackoverflow.com/questions/60631229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528834/"
] | you can use:
```
words = input_str.split()
s = set()
result = set()
for w in words:
r = w[::-1]
if r in s:
result.add(r)
else:
s.add(w)
list(result)
```
output:
```
['am', 'eat']
```
this is O(n) time complexity solution, so you have to get first the words and iterate through them, each time you have a new word you are adding him to a set, if the reverse is already in the set you are adding the reverse to the result | Your solution is overcomplicated. For example, function `isReverseEqual` can be written in one line:
```
def isReverseEqual(s1, s2):
return s1==s2[::-1]
```
Let's simplify it. First, treat your sentence as a set, not a list, because set lookups are more efficient:
```
words = set(input_str.split())
```
Next, select the words from the set/list if their reversed copy is also in the set/list *and* they are alphabetically smaller than the reversed copy (to avoid duplicates):
```
[w for w in words if w[::-1] in words and w < w[::-1]]
#['am', 'eat']
```
This solution works for lists, too. |
60,631,229 | i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
```
:loading="isLoading[index]"
```
here the vue :
```
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" @click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
```
here the data :
```
data () {
return {
products : [],
isLoading: false,
}
},
```
here my add to cart method where i change the state of isLoading :
```
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
``` | 2020/03/11 | [
"https://Stackoverflow.com/questions/60631229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528834/"
] | just change the indent of line "return reverse" :
```
input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2):
# If both the strings differ in length
if len(s1) != len(s2):
return False
l = len(s1)
for i in range(l):
# In case of any character mismatch
if s1[i] != s2[l-i-1]:
return False
return True
def getWord(str, n):
reverse=[]
# Check every string
for i in range(n-1):
# Pair with every other string
# appearing after the current string
for j in range(i+1, n):
# If first string is equal to the
# reverse of the second string
if (isReverseEqual(str[i], str[j])):
reverse.append(str[i])
if reverse:
return reverse
else: # No such string exists
return "-1"
print(getWord(word, len(word)))
``` | ```
input_str= 'i am going to eat ma and tae will also go'
words_list = input_str.split()
new_words_list = [word[::-1] for word in words_list]
data = []
for i in words_list:
if len(i) > 1 and i in new_words_list:
data.append(i)
```
**Output:**
```
['am', 'eat', 'ma', 'tae']
``` |
60,631,229 | i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
```
:loading="isLoading[index]"
```
here the vue :
```
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" @click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
```
here the data :
```
data () {
return {
products : [],
isLoading: false,
}
},
```
here my add to cart method where i change the state of isLoading :
```
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
``` | 2020/03/11 | [
"https://Stackoverflow.com/questions/60631229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528834/"
] | just change the indent of line "return reverse" :
```
input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2):
# If both the strings differ in length
if len(s1) != len(s2):
return False
l = len(s1)
for i in range(l):
# In case of any character mismatch
if s1[i] != s2[l-i-1]:
return False
return True
def getWord(str, n):
reverse=[]
# Check every string
for i in range(n-1):
# Pair with every other string
# appearing after the current string
for j in range(i+1, n):
# If first string is equal to the
# reverse of the second string
if (isReverseEqual(str[i], str[j])):
reverse.append(str[i])
if reverse:
return reverse
else: # No such string exists
return "-1"
print(getWord(word, len(word)))
``` | Your solution is overcomplicated. For example, function `isReverseEqual` can be written in one line:
```
def isReverseEqual(s1, s2):
return s1==s2[::-1]
```
Let's simplify it. First, treat your sentence as a set, not a list, because set lookups are more efficient:
```
words = set(input_str.split())
```
Next, select the words from the set/list if their reversed copy is also in the set/list *and* they are alphabetically smaller than the reversed copy (to avoid duplicates):
```
[w for w in words if w[::-1] in words and w < w[::-1]]
#['am', 'eat']
```
This solution works for lists, too. |
41,048,884 | So, I'm using [dotConnect for Oracle](https://www.devart.com/dotconnect/oracle/). I used the template and wizard to create a model of the database (Database first approach). We have multiple databases that a single application needs to reference and unfortunately the schema naming which contain the tables are not uniform across the other databases.
In the auto generated class in the `Designer.cs` file I get:
```
[Table(Name = @"FMC_TP.EQUIPMENT")]
```
But considering which database connection the schema could be:
```
[Table(Name = @"FMC_DEV.EQUIPMENT"]
```
Is there a way to change the schema for the mapping at runtime? | 2016/12/08 | [
"https://Stackoverflow.com/questions/41048884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351039/"
] | In Oracle you can call `alter session set current_schema = SCHEMA_NAME` statement which set contex of your session. Then you can go without prefixing tables with schema name but this may help only if you're using same session for all statements. | In case anyone has a similar issue I will expand on Kacper's answer:
In the model file `MyModel.lqml` I removed the schema specifications from the table names:
```
<Table Name="SCHEMA.TABLE" Member="ModelTableName">
```
to
```
<Table Name="TABLE" Member="ModelTableName">
```
Basiscally where applicable.
In code:
```
MyModelDataContext mycontext = new MyModelDataContext();
mycontext.ExecuteCommand($"ALTER SESSION SET CURRENT_SCHEMA = {Schema}", new object[1]);
```
Then perform my query.
```
var rows = from x in mycontext.ModelTableName
where x.COLUMN == id
select x;
``` |
41,048,884 | So, I'm using [dotConnect for Oracle](https://www.devart.com/dotconnect/oracle/). I used the template and wizard to create a model of the database (Database first approach). We have multiple databases that a single application needs to reference and unfortunately the schema naming which contain the tables are not uniform across the other databases.
In the auto generated class in the `Designer.cs` file I get:
```
[Table(Name = @"FMC_TP.EQUIPMENT")]
```
But considering which database connection the schema could be:
```
[Table(Name = @"FMC_DEV.EQUIPMENT"]
```
Is there a way to change the schema for the mapping at runtime? | 2016/12/08 | [
"https://Stackoverflow.com/questions/41048884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351039/"
] | In Oracle you can call `alter session set current_schema = SCHEMA_NAME` statement which set contex of your session. Then you can go without prefixing tables with schema name but this may help only if you're using same session for all statements. | There is an additional way to execute a command immediately after establishing a connection: set command (or several commands) via Run Once Command (or Initialization Command) connection string parameter. For more information, refer to <https://www.devart.com/dotconnect/oracle/docs/?Devart.Data.Oracle~Devart.Data.Oracle.OracleConnection~ConnectionString.html>. |
41,048,884 | So, I'm using [dotConnect for Oracle](https://www.devart.com/dotconnect/oracle/). I used the template and wizard to create a model of the database (Database first approach). We have multiple databases that a single application needs to reference and unfortunately the schema naming which contain the tables are not uniform across the other databases.
In the auto generated class in the `Designer.cs` file I get:
```
[Table(Name = @"FMC_TP.EQUIPMENT")]
```
But considering which database connection the schema could be:
```
[Table(Name = @"FMC_DEV.EQUIPMENT"]
```
Is there a way to change the schema for the mapping at runtime? | 2016/12/08 | [
"https://Stackoverflow.com/questions/41048884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351039/"
] | In case anyone has a similar issue I will expand on Kacper's answer:
In the model file `MyModel.lqml` I removed the schema specifications from the table names:
```
<Table Name="SCHEMA.TABLE" Member="ModelTableName">
```
to
```
<Table Name="TABLE" Member="ModelTableName">
```
Basiscally where applicable.
In code:
```
MyModelDataContext mycontext = new MyModelDataContext();
mycontext.ExecuteCommand($"ALTER SESSION SET CURRENT_SCHEMA = {Schema}", new object[1]);
```
Then perform my query.
```
var rows = from x in mycontext.ModelTableName
where x.COLUMN == id
select x;
``` | There is an additional way to execute a command immediately after establishing a connection: set command (or several commands) via Run Once Command (or Initialization Command) connection string parameter. For more information, refer to <https://www.devart.com/dotconnect/oracle/docs/?Devart.Data.Oracle~Devart.Data.Oracle.OracleConnection~ConnectionString.html>. |
38,383,867 | I currently have an iOS App that is already set up to receive push notifications. What I'm trying to do is, after a user presses the 'Join' button, I want to send them a "Welcome" push notification. Any clue on how to do this? | 2016/07/14 | [
"https://Stackoverflow.com/questions/38383867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6031898/"
] | It's pretty easy.
`AppDelegate`:
```
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil))
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("Local notification received (tapped, or while app in foreground): \(notification)")
}
```
Then in your action:
```
@IBAction func welcomeMe(sender: AnyObject) {
let notification = UILocalNotification()
notification.alertBody = "Welcome to the app!" // text that will be displayed in the notification
notification.fireDate = NSDate(timeIntervalSinceNow: 2)
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["title": "Title", "UUID": "12345"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
```
Now if the app is in the background, you see an Push notification. If it's in the foreground then your `didReceiveLocalNotification` fires instead. Tapping on the notification launches your app to the foreground and fires `didReceiveLocalNotification` also. | On YouTube, Jared Davidson offers some great iOS tutorials.
He has two on notifications:
This one is just what you need:
<https://www.youtube.com/watch?v=tqJFJzUPpcI>
...and there's one for remote notifications (not with a button)
<https://www.youtube.com/watch?v=LBw5tuTvKd4> |
27,637,270 | In my application I have written to find IP Address of user.
```
HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");
HttpServletRequest.getLocalAddr();
```
And getting the server ips can be done so:
```
Inet4Address.getLocalHost().getHostAddress();
```
So, If the user already logged in from one ip address, how to restrict his login from another ip address? | 2014/12/24 | [
"https://Stackoverflow.com/questions/27637270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4247609/"
] | Try Following code:
```
Inet4Address address=(Inet4Address) Inet4Address.getLocalHost();
System.out.println(address.getHostAddress());
```
`Inet4Address` comes from `java.net.Inet4Address;` | Best way to find host address in LAN can be done as follows:
```
System.out.println(InetAddress.getByName("anyhostname").getHostAddress());
``` |
27,637,270 | In my application I have written to find IP Address of user.
```
HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");
HttpServletRequest.getLocalAddr();
```
And getting the server ips can be done so:
```
Inet4Address.getLocalHost().getHostAddress();
```
So, If the user already logged in from one ip address, how to restrict his login from another ip address? | 2014/12/24 | [
"https://Stackoverflow.com/questions/27637270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4247609/"
] | Try Following code:
```
Inet4Address address=(Inet4Address) Inet4Address.getLocalHost();
System.out.println(address.getHostAddress());
```
`Inet4Address` comes from `java.net.Inet4Address;` | Try this, it will enumerate all the interface's address of your local machine.
```
try {
Enumeration<NetworkInterface> interfaceEnumeration =
NetworkInterface.getNetworkInterfaces();
while (interfaceEnumeration.hasMoreElements()) {
Enumeration<InetAddress> inetAddressEnumeration =
interfaceEnumeration.nextElement().getInetAddresses();
while (inetAddressEnumeration.hasMoreElements()) {
System.out.println(inetAddressEnumeration.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
```
But the following method is not reliable, in my testing environment, it always return the loop back interface address.
```
try {
InetAddress inetAddress[] = InetAddress.getAllByName("localhost");
for (InetAddress address : inetAddress) {
System.out.println(address.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
``` |
5,493,468 | I have this simple sample on VS2010:
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AbsClass absClass = new ConClass();
// I have tried this also and the error is different:
// ConClass absClass = new ConClass();
absClass.Id = "first";
Console.WriteLine(absClass.Id);
MyMethod(ref absClass); // <<- ERROR.
Console.WriteLine(absClass.Id);
Console.ReadKey();
}
public void MyMethod(ref AbsClass a)
{
a.Id = "new";
}
}
public abstract class AbsClass
{
public string Id { get; set; }
}
public class ConClass : AbsClass { }
}
```
I would like to know why this cannot build right. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5493468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357618/"
] | You need to make your `MyMethod` static:
```
public static void MyMethod(ref AbsClass a)
{
a.Id = "new";
}
```
The problem isn't the abstract class, the "problem" is the static `Main` method. Static methods don't have an instance, and as such, can't call instance methods.
[msdn on static classes and static members](http://msdn.microsoft.com/en-us/library/79b3xss3%28v=VS.100%29.aspx). | You either need to make your `MyMethod` method static:
```
public static MyMethod(ref AbsClass a)
{
a.Id = "new";
}
```
Or preferrably, create an instance of the `Program` class, and call `MyMethod` from that instance:
```
Program p = new Program();
p.MyMethod(ref abs);
```
The reason why the first method works is because the `Main` method is marked static, and isn't tied to an instance of the `Program` class. The .NET Framework CLR searches through your assembly for a static method named `Main` that takes an array of `String`, and makes that function the entry point. You'll notice that a lot of tutorials and even MSDN code samples mark the `Program` class with the static keyword, which is considered best practice when all of the methods in a class contain only static methods.
The reason why the second method works, and why this method is preferred, is because you defined `MyMethod` to be an **instance method**. Basically, you need an instance of an object in order to execute an instance method; the `new` keyword creates an instance of a specified type. Static methods can be called without an instance of an object, but also cannot access any non-static instance members (properties, private/public variables, etc). Generally, you want to avoid static methods and classes unless you must implement a utility class, utilize extension methods, or provide helper methods. |
34,776,816 | I have a template:
```
var playersList = Vue.extend({
props: ['players'],
template: '#players-template'
});
Vue.component('players', playersList);
new Vue({
el: 'body',
methods: {
someMethod: function() {
//JSON data from request comes here
//Want to render template of players component with that data
}
}
});
```
I'm new with Vue.js and don't know how could I make it possible. How can I render the template with data from AJAX request? Someone posted a solution with `v-view` but documentation for it is gone at official website. | 2016/01/13 | [
"https://Stackoverflow.com/questions/34776816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5073678/"
] | You have to specify the data in your Vue instance where the response is going to be stored
```
var playersList = Vue.extend({
template: '#players-template',
props: ['players']
}
});
Vue.component('players', playersList);
new Vue({
el: 'body',
data: {
players: ''
},
methods: {
someMethod: function() {
//JSON data from request comes here
//Want to render template of players component with that data
this.$set('players', data);
}
}
});
in your html
<body>
<ul>
<li v-for="player in players">
<players :players="players"></players>
</li>
</ul>
<template id="players-template">
<p>{{player.name}}</p>
</template>
</body>
``` | Once you create the Vue app on the `body` element, you can use its component anywhere within that element. Since you named the component players, you'd render it like this:
```
<body>
<players :players="players"></players>
</body>
```
Then in your Vue
```
new Vue({
el: 'body',
data: function(){
return { players:[] }
},
methods: {
someMethod: function() {
//var result = ajax result
this.players = result;
}
}
});
```
Since `players` is a prop on your list component, you pass it in with `:players="players"`. Then if `players` updates on the parent app, the list component would automatically update according to the new list. |
36,384 | On my 2002 BMW E46 330Ci, I've been getting error codes `202 Lambda regulating limit Bank1` and `203 Lambda regulating limit Bank2`. Here's the angry sensor readings from the INPA software:
[](https://i.stack.imgur.com/XjFFT.png)
I understand a number of things could be going wrong here, but tonight's discovery has been that the actual readings on the post-cat lambda probes are sitting unchanged at 0.42 whilst the engine runs and I rev the engine. Conversely, the probes pre-cat are varying substantially:
[](https://i.stack.imgur.com/w7INX.png)
These were taken whilst the car's engine was warm, but not right after or during a substantial drive.
If necessary, I can post a video of the readings, but that's the gist of it - pre-cat O2 sensors are fluctuating substantially whilst post-cat sensors aren't at all. It's interesting that they're both sitting dead at 0.42.
Does that mean my post-cat sensors have failed and need replacing? Or is this some incredibly accurate tuning by the geniuses at BMW!
**Hot idle readings**
I just took my car for a quick drive to get the engine temperature up to the operating level, and have the following readings via INPA software:
[](https://i.stack.imgur.com/wQxVY.png)
*Did not clear errors prior to drive/readings*
[](https://i.stack.imgur.com/TsN9P.png)
[](https://i.stack.imgur.com/Fi2fC.png)
[](https://i.stack.imgur.com/x1Ls7.png)
[](https://i.stack.imgur.com/AemvP.png)
Interestingly, the lambdaintegrator readings are now within the expected ranges with flat zeroes.
I've taken screenshots of the rest (digital, throttle, VANOS, roughness etc) but I don't think they'll be helpful so haven't included them so far. If the above readings are also still too much, please advise, though I think they should all be useful. | 2016/09/15 | [
"https://mechanics.stackexchange.com/questions/36384",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/2221/"
] | Here's how to decipher INPA
---------------------------

* **lambdaintegrator**
Short-term fuel trim. Both banks have a short-term correction of 28%.
This should settle down to 0% fairly quickly, so the fact that it stays red indicates that it is attempting to apply the maximum possible correction for a lean condition (and failing to bring it within spec).
* **adaption value additiv**
This is an aspect of long-term fuel trim correction that becomes dominant at low loads.
Unless the fuel trims were reset prior to taking the screenshot, there is something preventing LTFT corrections from being applied.
* **adaption value multiplicativ**
This is the second half of LTFT correction that becomes dominant at high loads. It acts as the chief injector pulse width multiplier.
Same comment as above; it is not being updated for some reason.
---
Based on the update (26-09-2016)
--------------------------------
### MAF, Idle Air Control
[](https://i.stack.imgur.com/TsN9P.png)
[](https://i.stack.imgur.com/Fi2fC.png)
* Mass air flow looks good; my 5.0 L S62 reads about 19-20 kg/hr at idle, so a 3.0 L engine should display about 60% of that value, which it does.
* I don't see anything funky going on with idle air control. Hard to say anything about the knock sensors from a still image.
---
### Fuel Trims
[](https://i.stack.imgur.com/AemvP.png)
* This output makes a lot more sense than before. Perhaps you had reset the fuel trims prior to posting the original screenshot?
* There is a minor positive fuel trim correction on both banks; the fuel trims are normal and healthy - not hitting any limits
---
### Error codes
[](https://i.stack.imgur.com/wQxVY.png)
* This is interesting. The errors are sporadic, so it looks like the conditions that triggered the error occurred 9 times and 7 times for Banks 1 and 2 respectively. At least one of those conditions on either bank was when the car was still warming up (coolant temp at 74˚C).
* I'm concerned that the heater circuits for the front O2 sensors are still active, despite the car being at hot idle. This should not be the case.
* Also, the resistances for the upstream O2 sensors (pre-cat) are unusually high; they should be [closer to 5 Ω](https://mechanics.stackexchange.com/a/15388/675). I think your upstream sensors are shot. Were they ever replaced under your custodianship? If not, I think it's time to invest in a pair.
--
Recommendation
--------------
* **Replace the front O2 sensors**. You can use [this answer](https://mechanics.stackexchange.com/a/15388/675) to test their present condition. It may be worth your while to check the condition of the rear O2 sensors as well while you're at it. | It may depend on how you are gathering that data. Perhaps a "Live Data" OBD Parameter ID or "PID"?
You may need a more specific scan tool or smarter software.
*Some* (especially higher end) vehicles use wide-band O2 sensors, and on my scan tool read out in milliamps, not in volts.
In other words, your scan tool may be looking at the data the wrong way, or in the wrong place.
Also, keep in mind that the cat (and downflow sensor) need to be really hot to give any meaningful data. If your scan tool setup is portable, I'd suggest some observations while driving. |
36,384 | On my 2002 BMW E46 330Ci, I've been getting error codes `202 Lambda regulating limit Bank1` and `203 Lambda regulating limit Bank2`. Here's the angry sensor readings from the INPA software:
[](https://i.stack.imgur.com/XjFFT.png)
I understand a number of things could be going wrong here, but tonight's discovery has been that the actual readings on the post-cat lambda probes are sitting unchanged at 0.42 whilst the engine runs and I rev the engine. Conversely, the probes pre-cat are varying substantially:
[](https://i.stack.imgur.com/w7INX.png)
These were taken whilst the car's engine was warm, but not right after or during a substantial drive.
If necessary, I can post a video of the readings, but that's the gist of it - pre-cat O2 sensors are fluctuating substantially whilst post-cat sensors aren't at all. It's interesting that they're both sitting dead at 0.42.
Does that mean my post-cat sensors have failed and need replacing? Or is this some incredibly accurate tuning by the geniuses at BMW!
**Hot idle readings**
I just took my car for a quick drive to get the engine temperature up to the operating level, and have the following readings via INPA software:
[](https://i.stack.imgur.com/wQxVY.png)
*Did not clear errors prior to drive/readings*
[](https://i.stack.imgur.com/TsN9P.png)
[](https://i.stack.imgur.com/Fi2fC.png)
[](https://i.stack.imgur.com/x1Ls7.png)
[](https://i.stack.imgur.com/AemvP.png)
Interestingly, the lambdaintegrator readings are now within the expected ranges with flat zeroes.
I've taken screenshots of the rest (digital, throttle, VANOS, roughness etc) but I don't think they'll be helpful so haven't included them so far. If the above readings are also still too much, please advise, though I think they should all be useful. | 2016/09/15 | [
"https://mechanics.stackexchange.com/questions/36384",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/2221/"
] | It may depend on how you are gathering that data. Perhaps a "Live Data" OBD Parameter ID or "PID"?
You may need a more specific scan tool or smarter software.
*Some* (especially higher end) vehicles use wide-band O2 sensors, and on my scan tool read out in milliamps, not in volts.
In other words, your scan tool may be looking at the data the wrong way, or in the wrong place.
Also, keep in mind that the cat (and downflow sensor) need to be really hot to give any meaningful data. If your scan tool setup is portable, I'd suggest some observations while driving. | I had the same trouble code from O2 sensors like above. It's not the sensors that have problem. It's just telling you, it's trying to compensate for F/T mixture but it was unable to due to the fact it had reached it's LIMIT for compensation.
I tried a lot of other testing, finally it is the air leak that caused that problem. Mine was when I replaced the Cover Valve Gasket and it was not sitting correctly therefore I had huge vacuum leak. I did a smoke test and found out the problem was the cover valve gasket was NOT sitting properly, fixed that and smoke test again and no smoke. Clear the code, started engine, and no more problem. Don't replace O2 sensors for this problem. I've been running for 2 days without any problem, and INPA showing Petrol Adaptation is back to normal 1-2, instead of 28 like before and the engine is smooth now. |
36,384 | On my 2002 BMW E46 330Ci, I've been getting error codes `202 Lambda regulating limit Bank1` and `203 Lambda regulating limit Bank2`. Here's the angry sensor readings from the INPA software:
[](https://i.stack.imgur.com/XjFFT.png)
I understand a number of things could be going wrong here, but tonight's discovery has been that the actual readings on the post-cat lambda probes are sitting unchanged at 0.42 whilst the engine runs and I rev the engine. Conversely, the probes pre-cat are varying substantially:
[](https://i.stack.imgur.com/w7INX.png)
These were taken whilst the car's engine was warm, but not right after or during a substantial drive.
If necessary, I can post a video of the readings, but that's the gist of it - pre-cat O2 sensors are fluctuating substantially whilst post-cat sensors aren't at all. It's interesting that they're both sitting dead at 0.42.
Does that mean my post-cat sensors have failed and need replacing? Or is this some incredibly accurate tuning by the geniuses at BMW!
**Hot idle readings**
I just took my car for a quick drive to get the engine temperature up to the operating level, and have the following readings via INPA software:
[](https://i.stack.imgur.com/wQxVY.png)
*Did not clear errors prior to drive/readings*
[](https://i.stack.imgur.com/TsN9P.png)
[](https://i.stack.imgur.com/Fi2fC.png)
[](https://i.stack.imgur.com/x1Ls7.png)
[](https://i.stack.imgur.com/AemvP.png)
Interestingly, the lambdaintegrator readings are now within the expected ranges with flat zeroes.
I've taken screenshots of the rest (digital, throttle, VANOS, roughness etc) but I don't think they'll be helpful so haven't included them so far. If the above readings are also still too much, please advise, though I think they should all be useful. | 2016/09/15 | [
"https://mechanics.stackexchange.com/questions/36384",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/2221/"
] | Here's how to decipher INPA
---------------------------

* **lambdaintegrator**
Short-term fuel trim. Both banks have a short-term correction of 28%.
This should settle down to 0% fairly quickly, so the fact that it stays red indicates that it is attempting to apply the maximum possible correction for a lean condition (and failing to bring it within spec).
* **adaption value additiv**
This is an aspect of long-term fuel trim correction that becomes dominant at low loads.
Unless the fuel trims were reset prior to taking the screenshot, there is something preventing LTFT corrections from being applied.
* **adaption value multiplicativ**
This is the second half of LTFT correction that becomes dominant at high loads. It acts as the chief injector pulse width multiplier.
Same comment as above; it is not being updated for some reason.
---
Based on the update (26-09-2016)
--------------------------------
### MAF, Idle Air Control
[](https://i.stack.imgur.com/TsN9P.png)
[](https://i.stack.imgur.com/Fi2fC.png)
* Mass air flow looks good; my 5.0 L S62 reads about 19-20 kg/hr at idle, so a 3.0 L engine should display about 60% of that value, which it does.
* I don't see anything funky going on with idle air control. Hard to say anything about the knock sensors from a still image.
---
### Fuel Trims
[](https://i.stack.imgur.com/AemvP.png)
* This output makes a lot more sense than before. Perhaps you had reset the fuel trims prior to posting the original screenshot?
* There is a minor positive fuel trim correction on both banks; the fuel trims are normal and healthy - not hitting any limits
---
### Error codes
[](https://i.stack.imgur.com/wQxVY.png)
* This is interesting. The errors are sporadic, so it looks like the conditions that triggered the error occurred 9 times and 7 times for Banks 1 and 2 respectively. At least one of those conditions on either bank was when the car was still warming up (coolant temp at 74˚C).
* I'm concerned that the heater circuits for the front O2 sensors are still active, despite the car being at hot idle. This should not be the case.
* Also, the resistances for the upstream O2 sensors (pre-cat) are unusually high; they should be [closer to 5 Ω](https://mechanics.stackexchange.com/a/15388/675). I think your upstream sensors are shot. Were they ever replaced under your custodianship? If not, I think it's time to invest in a pair.
--
Recommendation
--------------
* **Replace the front O2 sensors**. You can use [this answer](https://mechanics.stackexchange.com/a/15388/675) to test their present condition. It may be worth your while to check the condition of the rear O2 sensors as well while you're at it. | I had the same trouble code from O2 sensors like above. It's not the sensors that have problem. It's just telling you, it's trying to compensate for F/T mixture but it was unable to due to the fact it had reached it's LIMIT for compensation.
I tried a lot of other testing, finally it is the air leak that caused that problem. Mine was when I replaced the Cover Valve Gasket and it was not sitting correctly therefore I had huge vacuum leak. I did a smoke test and found out the problem was the cover valve gasket was NOT sitting properly, fixed that and smoke test again and no smoke. Clear the code, started engine, and no more problem. Don't replace O2 sensors for this problem. I've been running for 2 days without any problem, and INPA showing Petrol Adaptation is back to normal 1-2, instead of 28 like before and the engine is smooth now. |
59,433 | So I am sure there are better ways to set this up, but I wanted to see how something like this would work in Objective-C, so I went ahead and built a prototype of a Tradeable Card Game. I've never loaded information from a plist before, so this was the perfect opportunity for me to try that.
The idea here is that the plist will contain all the relevant statistical information for all of the cards in the game in a bunch of dictionaries, each one of them representing a card. Each of those dictionaries may or may not have certain properties attached to predetermined keys. Note, it may not have the key and value at all if that specific card does not need those properties.
When the Game is created, it builds a CardList object using this plist which simply holds an array of these card dictionaries in the order that it finds them in the plist. Then when asked, the CardList object can spit out a Card object that is either random, or determined by its cardId, which would also be its index in the CardList array. I don't know if this is a completely sane way to set this up, but it is working.
One concern is that once the game was "released", the order inside the plist could not be changed easily. However this might be mitigated by using a CardCollection object to hold the permanent storage of cards for a given player from which they can construct their decks. Once a Card is created out of the CardList, only its properties matter and not how it got them. The Game is only building the decks manually in this way for initial testing.
I'll put the plist first so you can see what kind of data the Card objects need to have.
**CardListPlist.plist**
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Cards</key>
<array>
<dict>
<key>cardId</key>
<string>0001</string>
<key>cardName</key>
<string>TestCard01</string>
<key>cardType</key>
<string>0</string>
<key>unitStrength</key>
<string>3</string>
<key>unitHealth</key>
<string>4</string>
<key>abilitySlots</key>
<string>2</string>
</dict>
<dict>
<key>cardId</key>
<string>0002</string>
<key>cardName</key>
<string>TestCard02</string>
<key>cardType</key>
<string>0</string>
<key>unitStrength</key>
<string>6</string>
<key>unitHealth</key>
<string>6</string>
<key>abilitySlots</key>
<string>0</string>
</dict>
<dict>
<key>cardId</key>
<string>0003</string>
<key>cardName</key>
<string>TestCard03</string>
<key>cardType</key>
<string>1</string>
<key>abilitySlots</key>
<string>2</string>
</dict>
</array>
</dict>
</plist>
```
**CardList.h**
```
#import <Foundation/Foundation.h>
#import "CRGCard.h"
@interface CRGCardList : NSObject
@property (strong, nonatomic) NSArray *listOfAllCards;
-(void) buildCardList;
-(void) logCards;
-(CRGCard *) randomCardFromCardList;
-(CRGCard *) cardWithId:(int)cardId;
@end
```
**CardList.m**
```
#import "CRGCardList.h"
NSString* const kCardStrength = @"unitStrength";
NSString* const kCardHealth = @"unitHealth";
NSString* const kCardType = @"cardType";
NSString* const kCardAbilitySlots = @"abilitySlots";
NSString* const kCardName = @"cardName";
NSString* const kCardId = @"cardId";
@implementation CRGCardList
#pragma mark - Initialization
-(id) init {
self = [super init];
if (self) {
_listOfAllCards = [[NSArray alloc]init];
}
return self;
}
-(void) buildCardList {
NSString *plistCatPath = [[NSBundle mainBundle] pathForResource:@"CRGCardListPlist" ofType:@"plist"];
NSDictionary *cardDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistCatPath];
self.listOfAllCards = cardDictionary[@"Cards"];
}
#pragma mark - Card building
-(CRGCard *) randomCardFromCardList {
int randomNumber = arc4random_uniform(_listOfAllCards.count);
NSDictionary *cardDict = [_listOfAllCards objectAtIndex:randomNumber];
CRGCard *card = [[CRGCard alloc]initWithId:[self convertStringToInt:[cardDict objectForKey:kCardId]]
name:[cardDict objectForKey:kCardName]
type:[self convertStringToInt:[cardDict objectForKey:kCardType]]
unitStrength:[self convertStringToInt:[cardDict objectForKey:kCardStrength]]
unitHealth:[self convertStringToInt:[cardDict objectForKey:kCardHealth]]
abilitySlots:[self convertStringToInt:[cardDict objectForKey:kCardAbilitySlots]]];
return card;
}
-(CRGCard *) cardWithId:(int)cardId {
NSDictionary *cardDict = [_listOfAllCards objectAtIndex:cardId];
CRGCard *card = [[CRGCard alloc]initWithId:[self convertStringToInt:[cardDict objectForKey:kCardId]]
name:[cardDict objectForKey:kCardName]
type:[self convertStringToInt:[cardDict objectForKey:kCardType]]];
return card;
}
-(int) convertStringToInt:(NSString *)string {
return [string intValue];
}
#pragma mark - Diagnostic Methods
-(void) logCards {
for (NSDictionary *dict in self.listOfAllCards) {
for (id key in dict) {
NSString *string = [dict objectForKey:key];
NSLog(@"%@", string);
}
}
}
@end
```
**Card.h**
```
#import <Foundation/Foundation.h>
#import "CRGCardType.h"
@interface CRGCard : NSObject
//not all cards will have all the values, so there could be different factory methods, here there is one for units and a default one
-(instancetype) initWithId:(int)cardId name:(NSString *)name type:(CardType)type unitStrength:(int)unitStrength unitHealth:(int)unitHealth abilitySlots:(int)abilitySlots;
-(instancetype) initWithId:(int)cardId name:(NSString *)name type:(CardType)type;
@property int cardId;
@property NSString* name;
@property CardType type;
@property int unitStrength;
@property int unitHealth;
@property int abilitySlots;
@end
```
**Card.m**
```
#import "CRGCard.h"
@implementation CRGCard
-(instancetype) initWithId:(int)cardId name:(NSString *)name type:(CardType)type unitStrength:(int)unitStrength unitHealth:(int)unitHealth abilitySlots:(int)abilitySlots {
self = [super init];
if (self) {
_cardId = cardId;
_name = name;
_type = type;
_unitStrength = unitStrength;
_unitHealth = unitHealth;
_abilitySlots = abilitySlots;
}
return self;
}
-(instancetype) initWithId:(int)cardId name:(NSString *)name type:(CardType)type {
self = [super init];
if (self) {
_cardId = cardId;
_name = name;
_type = type;
}
return self;
}
@end
```
**Game.h**
```
#import <Foundation/Foundation.h>
@interface CRGGame : NSObject
-(void) startGame;
@property NSMutableArray *players;
@end
```
**Game.m**
```
#import "CRGGame.h"
#import "CRGCardList.h"
#import "CRGPlayer.h"
static const int kDeckSize = 30;
@implementation CRGGame {
CRGCardList *_allCardsList;
}
-(id) init {
self = [super init];
if (self) {
_players = [[NSMutableArray alloc]init];
_allCardsList = [[CRGCardList alloc]init];
}
return self;
}
-(void) startGame {
[_allCardsList buildCardList];
[_allCardsList logCards];
[self createPlayers];
[self createDecks];
[self drawStaringHands];
}
-(void) createPlayers {
int numPlayers = 2;
for (int i = 0; i < numPlayers; i++) {
[_players addObject:[[CRGPlayer alloc]init]];
}
}
#pragma mark - Build Decks
-(void) createDecks {
for (CRGPlayer *player in self.players) {
[self fillDeckWithRandomCards:player.deck];
}
}
-(void) fillDeckWithRandomCards:(NSMutableArray *)deck {
for (int i = 0; i < kDeckSize; i++) {
[deck addObject:[_allCardsList randomCardFromCardList]];
}
}
#pragma mark - Draw Hands
-(void) drawStaringHands {
for (CRGPlayer *player in self.players) {
[player drawStartingHand];
}
}
@end
```
**Player.h**
```
#import <Foundation/Foundation.h>
@interface CRGPlayer : NSObject
@property NSMutableArray *deck;
@property NSMutableArray *hand;
-(void) drawStartingHand;
@end
```
**Player.m**
```
#import "CRGPlayer.h"
static const int kStartingHandSize = 3;
@implementation CRGPlayer
-(instancetype) init {
self = [super init];
if (self) {
_deck = [[NSMutableArray alloc]init];
_hand = [[NSMutableArray alloc]init];
}
return self;
}
-(void) drawStartingHand {
for (int i = 0; i < kStartingHandSize; i++) {
[self drawCardFromDeck];
}
}
-(void) drawCardFromDeck {
[_hand addObject:[_deck lastObject]];
[_deck removeLastObject];
}
@end
```
I realize this is a lot of code, but I felt like it was necessary to see all of it together in order to really understand what I am trying to do. What I am most interested in hearing about is the way that I have the plists set up, and whether this is a good approach or not. Also, is the approach properly OOP? | 2014/08/07 | [
"https://codereview.stackexchange.com/questions/59433",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/14608/"
] | Logic
-----
Never omit the optional braces like that. Think of yourself as a contributing factor to a future [coding accident](https://www.imperialviolet.org/2014/02/22/applebug.html). If you really want to omit braces, then put the statement on the same line, so that there is no possibility of misinterpretation.
The function does not check for [overlong encodings](http://en.wikipedia.org/wiki/UTF-8#Overlong_encodings), [invalid byte sequences](http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences), or [invalid code points](http://en.wikipedia.org/wiki/UTF-8#Invalid_code_points). Those caveats should be declared in JavaDoc.
I would eliminate the `length > 6` check, as 6 is a magic number. You don't need that special case anyway.
I would also incorporate the `length == 1` special case into the regular logic.
In general, text is more likely to contain shorter UTF-8 sequences than longer ones, so you might as well handle the shorter cases first to save a few CPU cycles.
Rather than setting `n` to be the number of trailing bytes, set it to be the expected length of the array. I'd rename `n` → `expectedLen` to be more descriptive. That makes the code more readable (and saves one pointless subtraction).
Eliminate the bit-shifting. Just AND with the bitmask to specify which bits you are interested in inspecting.
```
public static boolean validate(byte[] bytes) {
int expectedLen;
if (bytes.length == 0) return false;
else if ((bytes[0] & 0b10000000) == 0b00000000) expectedLen = 1;
else if ((bytes[0] & 0b11100000) == 0b11000000) expectedLen = 2;
else if ((bytes[0] & 0b11110000) == 0b11100000) expectedLen = 3;
else if ((bytes[0] & 0b11111000) == 0b11110000) expectedLen = 4;
else if ((bytes[0] & 0b11111100) == 0b11111000) expectedLen = 5;
else if ((bytes[0] & 0b11111110) == 0b11111100) expectedLen = 6;
else return false;
if (expectedLen != bytes.length) return false;
for (int i = 1; i < bytes.length; i++) {
if ((bytes[i] & 0b11000000) != 0b10000000) {
return false;
}
}
return true;
}
```
Interface design
----------------
It's rarely useful to validate a single character: usually, you'll want to validate a whole string. You should name your function to avoid giving the impression that it checks for multi-character strings.
In Java, functions that perform a test and return a boolean are conventionally named `isSomething()` or `hasSomething()`. A function named `validate()` suggests that it performs an action as a side-effect, perhaps throwing an exception on failure.
Therefore, I'd rename your function to `isValidChar(byte[] bytes)`.
So, what if I need to validate a string? I'd have to somehow chunk it up into right-sized byte arrays first. That's not really possible without examining the string using similar logic to what is in the function itself. Even then, it would be wasteful to construct a byte array just for the function call. Therefore, I think that it would be more useful to provide a function that validates a string. To go further, you could make such a function return something more informative than just a boolean.
```
/**
* Returns the number of UTF-8 characters, or -1 if the array
* does not contain a valid UTF-8 string. Overlong encodings,
* null characters, invalid Unicode values, and surrogates are
* accepted.
*/
public static int charLength(byte[] bytes) {
int charCount = 0, expectedLen;
for (int i = 0; i < bytes.length; i++) {
charCount++;
// Lead byte analysis
if ((bytes[i] & 0b10000000) == 0b00000000) continue;
else if ((bytes[i] & 0b11100000) == 0b11000000) expectedLen = 2;
else if ((bytes[i] & 0b11110000) == 0b11100000) expectedLen = 3;
else if ((bytes[i] & 0b11111000) == 0b11110000) expectedLen = 4;
else if ((bytes[i] & 0b11111100) == 0b11111000) expectedLen = 5;
else if ((bytes[i] & 0b11111110) == 0b11111100) expectedLen = 6;
else return -1;
// Count trailing bytes
while (--expectedLen > 0) {
if (++i >= bytes.length) {
return -1;
}
if ((bytes[i] & 0b11000000) != 0b10000000) {
return -1;
}
}
}
return charCount;
}
```
That's a more versatile function, for about the same amount of code. | this is in addition to 200\_success's answer,
**Better Test Cases**
>
>
> ```
> byte[] bytes1 = {(byte) 0b11001111, (byte) 0b10111111};
> System.out.println(validate(bytes1)); // true
>
> byte[] bytes2 = {(byte) 0b11101111, (byte) 0b10101010, (byte) 0b10111111};
> System.out.println(validate(bytes2)); // true
>
> ```
>
>
You are using simple print statements for testing, instead you can use mature Unit Testing Framework such as JUnit. JUnit can simplify the the process of unit testing greatly. And also instead of simply commenting the expected results you can test against them.
>
> Writing unit test code is labor-intensive, hence it is often not done
> as an integral part of programming. However, unit testing is a
> practical approach to increasing the correctness and quality of
> software; for example, the Extreme Programming approach relies on
> frequent unit testing [1].
>
>
>
Additionally I sense that you are repeating yourself in the test cases. Therefore making it harder for you to add new unit tests later [2].
>
> In software engineering, don't repeat yourself (DRY) is a principle of
> software development, aimed at reducing repetition of information of
> all kinds [3].
>
>
>
You can also consider adding string based unit tests as well.
```
private static final String[] stringTests = {
"A",
"Z",
"Because I'm Batman"
};
```
You can use an array to store all your strings and then loop through it.
```
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
```
using a constant `UTF8_CHARSET` (thanks Vogel612).
```
private static final byte[][] byteTests = {
{(byte) 0b11001111, (byte) 0b10111111},
{(byte) 0b11101111, (byte) 0b10101010, (byte) 0b10111111},
{(byte) 0b10001111, (byte) 0b10111111},
{(byte) 0b11101111, (byte) 0b10101010, (byte) 0b00111111}
};
private static final boolean[] byteTestsExpectedResults = {
true,
true,
false,
false
};
```
You can store the expected results and byte arrays in arrays, which you can easily loop and access the values.
Eventually I created this **unit test**
```
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.junit.Assert;
import org.junit.Test;
/**
* Test ValidateUtf8
*/
public class ValidateUtf8Test {
//for byte based tests
private static final byte[][] byteTests = {
{(byte) 0b11001111, (byte) 0b10111111},
{(byte) 0b11101111, (byte) 0b10101010, (byte) 0b10111111},
{(byte) 0b10001111, (byte) 0b10111111},
{(byte) 0b11101111, (byte) 0b10101010, (byte) 0b00111111}
};
private static final boolean[] byteTestsExpectedResults = {
true,
true,
false,
false
};
//for string based tests
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final String[] stringTests = {
"A",
"Z",
"Because I'm Batman"
};
@Test
public void testValidate() {
for (int i = 0; i < byteTests.length; i++) {
Assert.assertEquals(String.format("validate(byteTests[%d])", i),
ValidateUtf8.validate(byteTests[i]),
byteTestsExpectedResults[i]);
}
}
@Test
public void testValidateFromString() throws UnsupportedEncodingException {
for (String toTest : stringTests) {
Assert.assertTrue(String.format("validate('%s')", toTest),
ValidateUtf8.validate(
toTest.getBytes(UTF8_CHARSET)));
}
}
@Test
public void testCharLengthFromString() throws UnsupportedEncodingException {
for (String toTest : stringTests) {
Assert.assertEquals(String.format("charLength('%s')", toTest),
ValidateUtf8.charLength(toTest.getBytes(UTF8_CHARSET)),
toTest.length());
}
}
}
```
I decided to write a `validate()` method based on the `charLength()` method by 200\_success.
```
public static boolean validate(byte[] bytes) {
return (charLength(bytes) != -1);
}
```
and finally **ValidateUtf8** class
```
public class ValidateUtf8 {
/**
* Returns the number of UTF-8 characters, or -1 if the array does not
* contain a valid UTF-8 string. Overlong encodings, null characters,
* invalid Unicode values, and surrogates are accepted.
*
* @param bytes byte array to check length
* @return length
*/
public static int charLength(byte[] bytes) {
int charCount = 0, expectedLen;
for (int i = 0; i < bytes.length; i++) {
charCount++;
// Lead byte analysis
if ((bytes[i] & 0b10000000) == 0b00000000) {
continue;
} else if ((bytes[i] & 0b11100000) == 0b11000000) {
expectedLen = 2;
} else if ((bytes[i] & 0b11110000) == 0b11100000) {
expectedLen = 3;
} else if ((bytes[i] & 0b11111000) == 0b11110000) {
expectedLen = 4;
} else if ((bytes[i] & 0b11111100) == 0b11111000) {
expectedLen = 5;
} else if ((bytes[i] & 0b11111110) == 0b11111100) {
expectedLen = 6;
} else {
return -1;
}
// Count trailing bytes
while (--expectedLen > 0) {
if (++i >= bytes.length) {
return -1;
}
if ((bytes[i] & 0b11000000) != 0b10000000) {
return -1;
}
}
}
return charCount;
}
/**
* Validate a UTF-8 byte array
*
* @param bytes byte array to validate
* @return true if UTF-8
*/
public static boolean validate(byte[] bytes) {
return (charLength(bytes) != -1);
}
}
```
After running test cases

All the test cases will pass
---
[1]Y. Cheon and G. Leavens, “A Simple and Practical Approach to Unit Testing: The JML and JUnit Way,” in ECOOP 2002 — Object-Oriented Programming, vol. 2374, B. Magnusson, Ed. Springer Berlin Heidelberg, 2002, pp. 231–255.
[2]“Match Simple Sentence or Partial Sentence.” [Online]. Available: [Match Simple Sentence or Partial Sentence](https://codereview.stackexchange.com/questions/60247/match-simple-sentence-or-partial-sentence). [Accessed: 27-Aug-2014].
[3]“Don’t repeat yourself,” Wikipedia, the free encyclopedia. 24-Aug-2014. |
2,655 | I was recently challenged to translate the following sentence from English into Chinese:
*You should stay away from that bar. A friend of mine went there before, and he ended up in the hospital after one drink. We think they put fertilizer in the margarita mix to save costs.*
I provided two translations:
1. 你不要去那个酒吧啊!我朋友以前去过一次,才喝一杯酒就被送到医院去了。我们认为酒保为了省钱就把肥料放进玛格丽特混合物里!
2. 你最好别去那个酒吧!我的朋友去过一次,喝了一杯酒就必须住院。我们想酒保因为要省钱的,所以就把肥料放进玛格丽特里。
**Question (Request):** I'm wondering if a native Chinese speaker could do the following: (a) correct grammatical errors in each of the above translations; (b) make the translations sound more natural; (c) provide your own translation of the challenge sentence.
If you could explain your thinking behind the corrections (i.e., what was the grammatical error; what sounded unnatural; why did you choose to translate as you did) that would be even better. Feel free to write this explanation in Chinese or English; I can read Chinese far more easily than I can write it.
Also, please do not hold back with your criticisms/corrections. | 2013/01/01 | [
"https://chinese.stackexchange.com/questions/2655",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/-1/"
] | Overall both translations are fine and fluent, with some small issues below:
**Grammatical/Syntactic issues:**
I think there is only one issue, in (2) 我们想酒保因为要**省钱的**. Either use 要省钱 as verb (i.e. remove 的), or use 要省钱的 as adjective (i.e. add 是 before 要).
**Semantic issues:**
In (1), margarita mix is translated into 玛格丽特混合物. In Chinese, people don't refer food/drink mix as 混合物. You can either just say 玛格丽特, or use the uncommon but well-understood word 混饮.
In (2), "ended up in the hospital" is translated into 住院. 住院 means hospitalization (overnight), while "ended up in the hospital" might be just seeing the doctor. It's fine if 住院 is deduced from contexts not shown in the question.
In both sentences, 酒保**因为**要省钱,**所以**... sounds a little weird, because 因为..所以 not only states causality, but also has a weak implication that the reason is valid, as if "if the bartender is poor, it is right for him to adulterate the drink." Using **为了** is much more idiomatic, e.g. 奸商为了赚钱,良心都不要了。
Also "they" in the last sentence is referring to the bar as a whole, not just the bartender, so 酒吧 would be more accurate than 酒保.
**Idiomatic/Naturalness issues:**
In both translations, 我们**认为**酒保.../我们**想**酒保... 认为 sounds too formal; 想 sounds unnatural since 我们想 usually means "we want to...". 我们觉得 or 我们猜 are better options.
**My version:**
你最好别去那个酒吧。我朋友以前去过一次,喝了一杯酒就去医院了。我们觉得酒吧为了赚钱,在酒里掺了化肥。
Notes on word choices:
* 最好 is optional. With it the tone is softer and more suggestive.
* 别 vs 不要: people tend to use 别 in Northern China and 不要 in Southern China. Both are correct and natural.
* 省钱 vs 节约成本 vs 降低成本 vs 赚钱: 省钱 is fine but a bit strange (what money is being saved and why, the ultimate goal is actually 赚钱 not 省钱); 节约成本 is a commendatory word so inappropriate (not a problem if you say it automatically in colloquial language); 降低成本 is clear but too neutral to condemn the misbehavior; 赚钱 is the best fit and indeed the most common word to describe a profiteer's motivation.
* 酒 vs 玛格丽特/玛格丽特酒: 玛格丽特 seems redundant because it is irrelevant to the point. The line sounds more fluent without it.
* 把A放进B vs 在B里掺了A: former seems to imply intentional poisoning; latter is a common phrase to describe adulterated product especially food/drink.
* 肥料 vs 化肥: they are essentially the same, but when put side by side, 肥料 focuses on nutrition value while 化肥 focuses on chemical ingredients, hence 化肥 sounds more inedible and toxic. | My translation:
你可别去那个酒吧。我一朋友去过一次,喝了一杯酒就进医院了。我们觉得他们为了省钱,在酒里掺了化肥。
Notes:
1. 你可别去那个酒吧 sounds stronger than 你最好别去那个酒吧.
2. 我一朋友 is more colloquial than 我的一个朋友.
3. 进医院了 means "end up in the hospital (because of sickness)." 去医院 just means "go to hospital," and it may not necessarily infer "to see a doctor." |
2,655 | I was recently challenged to translate the following sentence from English into Chinese:
*You should stay away from that bar. A friend of mine went there before, and he ended up in the hospital after one drink. We think they put fertilizer in the margarita mix to save costs.*
I provided two translations:
1. 你不要去那个酒吧啊!我朋友以前去过一次,才喝一杯酒就被送到医院去了。我们认为酒保为了省钱就把肥料放进玛格丽特混合物里!
2. 你最好别去那个酒吧!我的朋友去过一次,喝了一杯酒就必须住院。我们想酒保因为要省钱的,所以就把肥料放进玛格丽特里。
**Question (Request):** I'm wondering if a native Chinese speaker could do the following: (a) correct grammatical errors in each of the above translations; (b) make the translations sound more natural; (c) provide your own translation of the challenge sentence.
If you could explain your thinking behind the corrections (i.e., what was the grammatical error; what sounded unnatural; why did you choose to translate as you did) that would be even better. Feel free to write this explanation in Chinese or English; I can read Chinese far more easily than I can write it.
Also, please do not hold back with your criticisms/corrections. | 2013/01/01 | [
"https://chinese.stackexchange.com/questions/2655",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/-1/"
] | Overall both translations are fine and fluent, with some small issues below:
**Grammatical/Syntactic issues:**
I think there is only one issue, in (2) 我们想酒保因为要**省钱的**. Either use 要省钱 as verb (i.e. remove 的), or use 要省钱的 as adjective (i.e. add 是 before 要).
**Semantic issues:**
In (1), margarita mix is translated into 玛格丽特混合物. In Chinese, people don't refer food/drink mix as 混合物. You can either just say 玛格丽特, or use the uncommon but well-understood word 混饮.
In (2), "ended up in the hospital" is translated into 住院. 住院 means hospitalization (overnight), while "ended up in the hospital" might be just seeing the doctor. It's fine if 住院 is deduced from contexts not shown in the question.
In both sentences, 酒保**因为**要省钱,**所以**... sounds a little weird, because 因为..所以 not only states causality, but also has a weak implication that the reason is valid, as if "if the bartender is poor, it is right for him to adulterate the drink." Using **为了** is much more idiomatic, e.g. 奸商为了赚钱,良心都不要了。
Also "they" in the last sentence is referring to the bar as a whole, not just the bartender, so 酒吧 would be more accurate than 酒保.
**Idiomatic/Naturalness issues:**
In both translations, 我们**认为**酒保.../我们**想**酒保... 认为 sounds too formal; 想 sounds unnatural since 我们想 usually means "we want to...". 我们觉得 or 我们猜 are better options.
**My version:**
你最好别去那个酒吧。我朋友以前去过一次,喝了一杯酒就去医院了。我们觉得酒吧为了赚钱,在酒里掺了化肥。
Notes on word choices:
* 最好 is optional. With it the tone is softer and more suggestive.
* 别 vs 不要: people tend to use 别 in Northern China and 不要 in Southern China. Both are correct and natural.
* 省钱 vs 节约成本 vs 降低成本 vs 赚钱: 省钱 is fine but a bit strange (what money is being saved and why, the ultimate goal is actually 赚钱 not 省钱); 节约成本 is a commendatory word so inappropriate (not a problem if you say it automatically in colloquial language); 降低成本 is clear but too neutral to condemn the misbehavior; 赚钱 is the best fit and indeed the most common word to describe a profiteer's motivation.
* 酒 vs 玛格丽特/玛格丽特酒: 玛格丽特 seems redundant because it is irrelevant to the point. The line sounds more fluent without it.
* 把A放进B vs 在B里掺了A: former seems to imply intentional poisoning; latter is a common phrase to describe adulterated product especially food/drink.
* 肥料 vs 化肥: they are essentially the same, but when put side by side, 肥料 focuses on nutrition value while 化肥 focuses on chemical ingredients, hence 化肥 sounds more inedible and toxic. | I like the original translator's 被送到医院去了: 被 tends to be for nasty things, with an element of what I call "sitting duck" ("can't-do-anything-about-it"-ness) about it. 被送到医院去了, to me, almost conjures up an image of the drinker being carted off to the hospital, which is appropriate here, I feel.
I also like 孤影萍踪's 你可别 (over 你最好别) as it's stronger, which is appropriate here too, given the circumstances. |
2,655 | I was recently challenged to translate the following sentence from English into Chinese:
*You should stay away from that bar. A friend of mine went there before, and he ended up in the hospital after one drink. We think they put fertilizer in the margarita mix to save costs.*
I provided two translations:
1. 你不要去那个酒吧啊!我朋友以前去过一次,才喝一杯酒就被送到医院去了。我们认为酒保为了省钱就把肥料放进玛格丽特混合物里!
2. 你最好别去那个酒吧!我的朋友去过一次,喝了一杯酒就必须住院。我们想酒保因为要省钱的,所以就把肥料放进玛格丽特里。
**Question (Request):** I'm wondering if a native Chinese speaker could do the following: (a) correct grammatical errors in each of the above translations; (b) make the translations sound more natural; (c) provide your own translation of the challenge sentence.
If you could explain your thinking behind the corrections (i.e., what was the grammatical error; what sounded unnatural; why did you choose to translate as you did) that would be even better. Feel free to write this explanation in Chinese or English; I can read Chinese far more easily than I can write it.
Also, please do not hold back with your criticisms/corrections. | 2013/01/01 | [
"https://chinese.stackexchange.com/questions/2655",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/-1/"
] | My translation:
你可别去那个酒吧。我一朋友去过一次,喝了一杯酒就进医院了。我们觉得他们为了省钱,在酒里掺了化肥。
Notes:
1. 你可别去那个酒吧 sounds stronger than 你最好别去那个酒吧.
2. 我一朋友 is more colloquial than 我的一个朋友.
3. 进医院了 means "end up in the hospital (because of sickness)." 去医院 just means "go to hospital," and it may not necessarily infer "to see a doctor." | I like the original translator's 被送到医院去了: 被 tends to be for nasty things, with an element of what I call "sitting duck" ("can't-do-anything-about-it"-ness) about it. 被送到医院去了, to me, almost conjures up an image of the drinker being carted off to the hospital, which is appropriate here, I feel.
I also like 孤影萍踪's 你可别 (over 你最好别) as it's stronger, which is appropriate here too, given the circumstances. |
59,761,799 | I have a list of coordinates and another list of height values. How can I append height values to coordinate list in sequential order?
```
coor = [[[83.75, 18.70], [57.50, 18.70], [57.5, 2.87], [83.75, 4.18]],
[[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59]],
[[104.86, 19.59], [83.75, 19.59], [83.75, 4.18], [100.0, 5.0]],
[[-5.0, 33.0], [18.12, 33.40],[18.12, 16.70],[-2.53, 16.70]],
[[18.12, 16.70],[-2.53, 16.70], [0.0, 0.0],[18.12, 0.90]]]
height = [5,4,5,6,6]
```
expected result:
```
result = [[[83.75, 18.70], [57.50, 18.70], [57.5, 2.87], [83.75, 4.18],5],
[[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59],4],
[[104.86, 19.59], [83.75, 19.59], [83.75, 4.18], [100.0, 5.0],5],
[[-5.0, 33.0], [18.12, 33.40],[18.12, 16.70],[-2.53, 16.70],6],
[[18.12, 16.70],[-2.53, 16.70], [0.0, 0.0],[18.12, 0.90],6]]
``` | 2020/01/16 | [
"https://Stackoverflow.com/questions/59761799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12237852/"
] | If you don't mind tuples, you can just use `zip`
```
> list(zip(coor, height))
[([[83.75, 18.7], [57.5, 18.7], [57.5, 2.87], [83.75, 4.18]], 5),
([[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59]], 4),
...
```
If it must be a list use `zip` in a comprehension.
```
> [list(pair) for pair in zip(coor, height)]
[[[83.75, 18.7], [57.5, 18.7], [57.5, 2.87], [83.75, 4.18]], 5],
[[[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59]], 4],
...
``` | tldr: One line solution, **zip** the iterables ([Python docs](https://docs.python.org/3.3/library/functions.html#zip)) and list for desired output explanation below:
```
[list(item) for item in list(zip(coor,height))]
```
explanation:
```
list1 = [
[['a','a'],['aa','aa']],
[['b','b'],['bb','bb']]]
list2 = [1,2]
for item in list(zip(list1,list2)):
print('zip output', item)
print('desired output', list(item))
```
Output:
```
zip output ([['a', 'a'], ['aa', 'aa']], 1)
desired output [[['a', 'a'], ['aa', 'aa']], 1]
zip output ([['b', 'b'], ['bb', 'bb']], 2)
desired output [[['b', 'b'], ['bb', 'bb']], 2]
```
as one line list comprehension :
```
[list(item) for item in list(zip(list1,list2))]
```
Output:
```
[[[['a', 'a'], ['aa', 'aa']], 1], [[['b', 'b'], ['bb', 'bb']], 2]]
``` |
23,525,398 | i'm trying to capture pictures in a app using by Sencha Touch 2.3.1 and Cordova 3.4.1-0.1.0.
Reading the docs (<http://docs.sencha.com/touch/2.3.1/#!/api/Ext.device.Camera-method-capture>) it looks very easy and simple, but i'm having a very weird experience.
First i create a Sencha Touch app and initialize Cordova on in it
```
sencha app generate MyApp ./MyApp
cd ./MyApp
sencha cordova init
```
At this point, when i try to build, it works fine on a real device, android emulator or even on browser.
Then, i changed Main.js to add the capture feature.
```
Ext.define('CameraTest.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.device.*'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'Welcome',
iconCls: 'home',
styleHtmlContent: true,
scrollable: true,
items: {
docked: 'top',
xtype: 'titlebar',
title: 'Welcome to Sencha Touch 2'
},
html: [
"You've just generated a new Sencha Touch 2 project. What you're looking at right now is the ",
"contents of <a target='_blank' href=\"app/view/Main.js\">app/view/Main.js</a> - edit that file ",
"and refresh to change what's rendered here."
].join("")
},
{
title: 'Camera',
iconCls: 'action',
layout: {
type:"vbox",
pack:"center",
align:"center"
},
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'CameraTest'
},
{
xtype: 'panel',
html: '<img style="height: 200px; width: 200px;" src="http://placehold.it/200x200" />'
},
{
xtype: "button",
text: "Photo",
handler: function() {
function success(image_uri) {
var img = Ext.ComponentQuery.query("image")[0];
img.setSrc(image_uri);
}
function fail(message) {
Ext.Msg.alert("Failed: " + message);
}
Ext.device.Camera.capture({
sucess: success,
failure: fail,
quality: 50,
destination: 'data',
source: 'camera'
});
}
}
]
}
]
}
});
```
Done, the app stops loading. It stucks in the appLoadingIndicator and doesn't reach the tab panel component.
However, if i open it in a browser it works just fine.
I don't know even how to debug this.
[This is the screen that the app gets stuck](http://i.stack.imgur.com/Z337u.png) | 2014/05/07 | [
"https://Stackoverflow.com/questions/23525398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541615/"
] | JavaScript is single-threaded which means all the work needs to be done on the same thread including queuing events (from setTimeout/rAF, keys etc.), rendering to canvas and so forth.
If the loop is very tight (time-budget-wise) there will simply not be any room for the browser to do other tasks such as GC - for Chrome this task seem to be secondary versus Firefox which gives this higher priority (likely to get more performance out of its engine). Basically the running code will block the browser from doing other things than executing the code itself.
A good indicator of this is when you lower the FPS leaving more space for event queue, clean-up etc. When the profiler is running *it* get more priority in order to catch all sort of things so for some reason GC gets to "sneak" in earlier when profiler is running (in lack of better term). But this is very browser specific and I do not know every underlying details here.
If the browser cannot purge events in the event queue it will eventually stack up and in worst case block/freeze/crash the browser.
In any case, it's hard to debug this (for pin-pointing reasons) as you won't, programmatically, have access to memory or CPU usage etc.
The closest thing is to use a high-resolution timer at the beginning and end of the code inside the loop to see if it comes close to the frame rate time.
For example:
```
function loop() {
var startTime = performance.now();
... other code ...
var innerLoopTime = performance.now() - startTime;
requestAnimationFrame(loop);
}
```
If your frame rate is 60 FPS then the time per frame would be 1000/60, or about 16.667ms.
If your `innerLoopTime` is very close to this time you will know that you need to optimize the code executed inside the loop, or lower the frame rate.
You could use the debugger to get time-cost per step inside the function but the debugger itself will add an overhead to the total. So do measuring the time, but the cost is lower.. it will be a matter of compromise no matter how one twist and turn this one. | I've found that a huge source of memory leaking in javascript code is usually [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures).
If you're accessing a variable inside your setInterval that was declared outside, then you're most likely leaking some memory. As to whether or not this is the actual root cause of the issue is another question.
If you want to understand closures more and how they affect the performance of your js in action, look at [this article](http://www.ibm.com/developerworks/library/wa-memleak/#N100A2) by IBM on the topic. It gives good examples and ways to avoid memory leaks using them, as well as a few other possible sources of memory leaks. |
23,525,398 | i'm trying to capture pictures in a app using by Sencha Touch 2.3.1 and Cordova 3.4.1-0.1.0.
Reading the docs (<http://docs.sencha.com/touch/2.3.1/#!/api/Ext.device.Camera-method-capture>) it looks very easy and simple, but i'm having a very weird experience.
First i create a Sencha Touch app and initialize Cordova on in it
```
sencha app generate MyApp ./MyApp
cd ./MyApp
sencha cordova init
```
At this point, when i try to build, it works fine on a real device, android emulator or even on browser.
Then, i changed Main.js to add the capture feature.
```
Ext.define('CameraTest.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.device.*'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'Welcome',
iconCls: 'home',
styleHtmlContent: true,
scrollable: true,
items: {
docked: 'top',
xtype: 'titlebar',
title: 'Welcome to Sencha Touch 2'
},
html: [
"You've just generated a new Sencha Touch 2 project. What you're looking at right now is the ",
"contents of <a target='_blank' href=\"app/view/Main.js\">app/view/Main.js</a> - edit that file ",
"and refresh to change what's rendered here."
].join("")
},
{
title: 'Camera',
iconCls: 'action',
layout: {
type:"vbox",
pack:"center",
align:"center"
},
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'CameraTest'
},
{
xtype: 'panel',
html: '<img style="height: 200px; width: 200px;" src="http://placehold.it/200x200" />'
},
{
xtype: "button",
text: "Photo",
handler: function() {
function success(image_uri) {
var img = Ext.ComponentQuery.query("image")[0];
img.setSrc(image_uri);
}
function fail(message) {
Ext.Msg.alert("Failed: " + message);
}
Ext.device.Camera.capture({
sucess: success,
failure: fail,
quality: 50,
destination: 'data',
source: 'camera'
});
}
}
]
}
]
}
});
```
Done, the app stops loading. It stucks in the appLoadingIndicator and doesn't reach the tab panel component.
However, if i open it in a browser it works just fine.
I don't know even how to debug this.
[This is the screen that the app gets stuck](http://i.stack.imgur.com/Z337u.png) | 2014/05/07 | [
"https://Stackoverflow.com/questions/23525398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541615/"
] | JavaScript is single-threaded which means all the work needs to be done on the same thread including queuing events (from setTimeout/rAF, keys etc.), rendering to canvas and so forth.
If the loop is very tight (time-budget-wise) there will simply not be any room for the browser to do other tasks such as GC - for Chrome this task seem to be secondary versus Firefox which gives this higher priority (likely to get more performance out of its engine). Basically the running code will block the browser from doing other things than executing the code itself.
A good indicator of this is when you lower the FPS leaving more space for event queue, clean-up etc. When the profiler is running *it* get more priority in order to catch all sort of things so for some reason GC gets to "sneak" in earlier when profiler is running (in lack of better term). But this is very browser specific and I do not know every underlying details here.
If the browser cannot purge events in the event queue it will eventually stack up and in worst case block/freeze/crash the browser.
In any case, it's hard to debug this (for pin-pointing reasons) as you won't, programmatically, have access to memory or CPU usage etc.
The closest thing is to use a high-resolution timer at the beginning and end of the code inside the loop to see if it comes close to the frame rate time.
For example:
```
function loop() {
var startTime = performance.now();
... other code ...
var innerLoopTime = performance.now() - startTime;
requestAnimationFrame(loop);
}
```
If your frame rate is 60 FPS then the time per frame would be 1000/60, or about 16.667ms.
If your `innerLoopTime` is very close to this time you will know that you need to optimize the code executed inside the loop, or lower the frame rate.
You could use the debugger to get time-cost per step inside the function but the debugger itself will add an overhead to the total. So do measuring the time, but the cost is lower.. it will be a matter of compromise no matter how one twist and turn this one. | We've noticed chrome + canvas is not as performant as firefox + canvas. As to GC occurring when you open chrome dev tools, well I'd guess you may have some code that nudges chrome in just the right way to do a GC. Do you have some sort of window resize handler? There might be something else that is doing something similar.
When in doubt bisect the code till it doesn't happen anymore. |
23,525,398 | i'm trying to capture pictures in a app using by Sencha Touch 2.3.1 and Cordova 3.4.1-0.1.0.
Reading the docs (<http://docs.sencha.com/touch/2.3.1/#!/api/Ext.device.Camera-method-capture>) it looks very easy and simple, but i'm having a very weird experience.
First i create a Sencha Touch app and initialize Cordova on in it
```
sencha app generate MyApp ./MyApp
cd ./MyApp
sencha cordova init
```
At this point, when i try to build, it works fine on a real device, android emulator or even on browser.
Then, i changed Main.js to add the capture feature.
```
Ext.define('CameraTest.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.device.*'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'Welcome',
iconCls: 'home',
styleHtmlContent: true,
scrollable: true,
items: {
docked: 'top',
xtype: 'titlebar',
title: 'Welcome to Sencha Touch 2'
},
html: [
"You've just generated a new Sencha Touch 2 project. What you're looking at right now is the ",
"contents of <a target='_blank' href=\"app/view/Main.js\">app/view/Main.js</a> - edit that file ",
"and refresh to change what's rendered here."
].join("")
},
{
title: 'Camera',
iconCls: 'action',
layout: {
type:"vbox",
pack:"center",
align:"center"
},
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'CameraTest'
},
{
xtype: 'panel',
html: '<img style="height: 200px; width: 200px;" src="http://placehold.it/200x200" />'
},
{
xtype: "button",
text: "Photo",
handler: function() {
function success(image_uri) {
var img = Ext.ComponentQuery.query("image")[0];
img.setSrc(image_uri);
}
function fail(message) {
Ext.Msg.alert("Failed: " + message);
}
Ext.device.Camera.capture({
sucess: success,
failure: fail,
quality: 50,
destination: 'data',
source: 'camera'
});
}
}
]
}
]
}
});
```
Done, the app stops loading. It stucks in the appLoadingIndicator and doesn't reach the tab panel component.
However, if i open it in a browser it works just fine.
I don't know even how to debug this.
[This is the screen that the app gets stuck](http://i.stack.imgur.com/Z337u.png) | 2014/05/07 | [
"https://Stackoverflow.com/questions/23525398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541615/"
] | I've found that a huge source of memory leaking in javascript code is usually [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures).
If you're accessing a variable inside your setInterval that was declared outside, then you're most likely leaking some memory. As to whether or not this is the actual root cause of the issue is another question.
If you want to understand closures more and how they affect the performance of your js in action, look at [this article](http://www.ibm.com/developerworks/library/wa-memleak/#N100A2) by IBM on the topic. It gives good examples and ways to avoid memory leaks using them, as well as a few other possible sources of memory leaks. | We've noticed chrome + canvas is not as performant as firefox + canvas. As to GC occurring when you open chrome dev tools, well I'd guess you may have some code that nudges chrome in just the right way to do a GC. Do you have some sort of window resize handler? There might be something else that is doing something similar.
When in doubt bisect the code till it doesn't happen anymore. |
139,912 | >
> **Natural things** ought to be respected as “natural” beings , which
> means that we should try our best to avoid interfering with their
> natural existence and when it is necessary, to restore them into their
> natural state.(self-made)
>
>
>
Obviously, here I use "nutural things" to mean things like trees,flowers, animals,fish. But "thing" has such a broad range of meaning, that "natural things" may cover human body and human imagination, human emotion. So does anyone have any better alternative? Maybe "natural object" suits to my purpose? But it seems too technical a term? | 2013/12/01 | [
"https://english.stackexchange.com/questions/139912",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/51369/"
] | To remove the ambiguity of "natural things", you could possible use "Our natural environment" as a collective noun to set the initial scope of your sentence, which would then focus the meaning of "things" later on to the broadest sense of nature, rather than natural yoghurt, make-up, etc:
>
> Our natural environment ought to be respected, which means that we
> should try our best to avoid interfering with the natural existence of
> things, and when it is necessary, to restore them into their natural
> state.
>
>
> | You could try *All natural phenomena* or *All life, both animal and vegetable* or, more fancifully, *The whole of creation*. |
139,912 | >
> **Natural things** ought to be respected as “natural” beings , which
> means that we should try our best to avoid interfering with their
> natural existence and when it is necessary, to restore them into their
> natural state.(self-made)
>
>
>
Obviously, here I use "nutural things" to mean things like trees,flowers, animals,fish. But "thing" has such a broad range of meaning, that "natural things" may cover human body and human imagination, human emotion. So does anyone have any better alternative? Maybe "natural object" suits to my purpose? But it seems too technical a term? | 2013/12/01 | [
"https://english.stackexchange.com/questions/139912",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/51369/"
] | To remove the ambiguity of "natural things", you could possible use "Our natural environment" as a collective noun to set the initial scope of your sentence, which would then focus the meaning of "things" later on to the broadest sense of nature, rather than natural yoghurt, make-up, etc:
>
> Our natural environment ought to be respected, which means that we
> should try our best to avoid interfering with the natural existence of
> things, and when it is necessary, to restore them into their natural
> state.
>
>
> | Depending on what you intend to include in those "natural things", the following words could convey fine shades of meaning:
**All living creatures** (usually excludes trees and plants)
**All life** (as suggested by Barrie England, also *all of life*)
**Everything** (will also include water, rocks, etc.) |
139,912 | >
> **Natural things** ought to be respected as “natural” beings , which
> means that we should try our best to avoid interfering with their
> natural existence and when it is necessary, to restore them into their
> natural state.(self-made)
>
>
>
Obviously, here I use "nutural things" to mean things like trees,flowers, animals,fish. But "thing" has such a broad range of meaning, that "natural things" may cover human body and human imagination, human emotion. So does anyone have any better alternative? Maybe "natural object" suits to my purpose? But it seems too technical a term? | 2013/12/01 | [
"https://english.stackexchange.com/questions/139912",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/51369/"
] | To remove the ambiguity of "natural things", you could possible use "Our natural environment" as a collective noun to set the initial scope of your sentence, which would then focus the meaning of "things" later on to the broadest sense of nature, rather than natural yoghurt, make-up, etc:
>
> Our natural environment ought to be respected, which means that we
> should try our best to avoid interfering with the natural existence of
> things, and when it is necessary, to restore them into their natural
> state.
>
>
> | It's a bit long-winded, but "All things that are part of the natural world" is what I would choose, for the sake of clarity. Unfortunately, even this long-winded form is open to misinterpretation, because some people may think that it includes humans. |
35,564,808 | may i declare an array with a global element in C?
Can i declare with a const type?
It runs on Xcode, however I fear it isn't correct, because glob is not a const type (same thought on static type).
```
#include <stdio.h>
#include <stdilib.h>
int glob;
void main (){
int const con;
static int stat;
int arr[glob];
int arr2[con];
int arr3[stat];
}
```
In addition, I'm in need of practicing finding mistakes in C code and correcting them for a test (CS student) and could not find a resource for it.
thank you in advance. | 2016/02/22 | [
"https://Stackoverflow.com/questions/35564808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5965371/"
] | The variable `post` is defined inside the `createPost()` function, which means that it is out of scope when you try to append it - it only exists within the `createPost()` function. Define `post` outside of the `createPost()` function, and it will become globally accessible, and it should work.
e.g.
```
var testimg = 'images/1.png'
var post;
function createPost(){
post = document.createElement('div');
post.className += 'col-md-3';
post.className += 'col-sm-6';
post.className += 'col-xs-12';
post.className += 'post';
}
function addElements(){
var img = document.createElement('img');
img.src = testimg;
img.alt = 'post';
img.className += 'img-responsive';
$(post).append(img);
}
createPost();
addElements();
$('#posts-div').append(post);
``` | Since you're using jQuery your code could be :
```
var testimg = 'images/1.png'
var post = '<div class="col-md-3 col-sm-6 col-xs-12 post"></div>';
var img = '<img src="'+testimg+'" alt="post" class="img-responsive" '/>;
$(post).append(img);
$('#posts-div').append(post);
```
Hope this helps. |
35,564,808 | may i declare an array with a global element in C?
Can i declare with a const type?
It runs on Xcode, however I fear it isn't correct, because glob is not a const type (same thought on static type).
```
#include <stdio.h>
#include <stdilib.h>
int glob;
void main (){
int const con;
static int stat;
int arr[glob];
int arr2[con];
int arr3[stat];
}
```
In addition, I'm in need of practicing finding mistakes in C code and correcting them for a test (CS student) and could not find a resource for it.
thank you in advance. | 2016/02/22 | [
"https://Stackoverflow.com/questions/35564808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5965371/"
] | Here's another version which I believe is a better way.
```
var testimg = 'images/1.png';
var post;
var img;
function createPost(){
post = $('<div/>',{ class:"col-md-3 col-sm-6 col-xs-12 post" }).appendTo("#posts-div");
}
function addElements(){
img = $('<img/>',{ src:testimg , alt:'post',class:'img-responsive' }).appendTo(post);
}
createPost();
addElements();
```
Example : <https://jsfiddle.net/DinoMyte/b8tetvhh/1/> | The variable `post` is defined inside the `createPost()` function, which means that it is out of scope when you try to append it - it only exists within the `createPost()` function. Define `post` outside of the `createPost()` function, and it will become globally accessible, and it should work.
e.g.
```
var testimg = 'images/1.png'
var post;
function createPost(){
post = document.createElement('div');
post.className += 'col-md-3';
post.className += 'col-sm-6';
post.className += 'col-xs-12';
post.className += 'post';
}
function addElements(){
var img = document.createElement('img');
img.src = testimg;
img.alt = 'post';
img.className += 'img-responsive';
$(post).append(img);
}
createPost();
addElements();
$('#posts-div').append(post);
``` |
35,564,808 | may i declare an array with a global element in C?
Can i declare with a const type?
It runs on Xcode, however I fear it isn't correct, because glob is not a const type (same thought on static type).
```
#include <stdio.h>
#include <stdilib.h>
int glob;
void main (){
int const con;
static int stat;
int arr[glob];
int arr2[con];
int arr3[stat];
}
```
In addition, I'm in need of practicing finding mistakes in C code and correcting them for a test (CS student) and could not find a resource for it.
thank you in advance. | 2016/02/22 | [
"https://Stackoverflow.com/questions/35564808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5965371/"
] | Here's another version which I believe is a better way.
```
var testimg = 'images/1.png';
var post;
var img;
function createPost(){
post = $('<div/>',{ class:"col-md-3 col-sm-6 col-xs-12 post" }).appendTo("#posts-div");
}
function addElements(){
img = $('<img/>',{ src:testimg , alt:'post',class:'img-responsive' }).appendTo(post);
}
createPost();
addElements();
```
Example : <https://jsfiddle.net/DinoMyte/b8tetvhh/1/> | Since you're using jQuery your code could be :
```
var testimg = 'images/1.png'
var post = '<div class="col-md-3 col-sm-6 col-xs-12 post"></div>';
var img = '<img src="'+testimg+'" alt="post" class="img-responsive" '/>;
$(post).append(img);
$('#posts-div').append(post);
```
Hope this helps. |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | The `pri` is short priority and [determines the order in which multiple swap partitions are used](http://www.brighthub.com/computing/linux/articles/37236.aspx). Partitions with a higher value for `pri` are used first. | assume you have 2 swap-partitions, with 'pri' you can tell the os, which swap partion to use first:
>
> pri=n Specifies the swap space priority. The n variable can
> be 0, 1, 2, 3, 4, with 0 being lowest priority, and 4
> being highest priority.
>
>
> |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | Not on any linux distro, I believe ubuntu does not set any swap priority by default, some others might.
You may call **man swapon** to the rescue ... here is an excerpt:
>
> -p priority
>
>
> Specify the priority of the swap device. This option is only available if swapon was compiled and is used under a 1.3.2 or later kernel. priority is a value between 0 and 32767. Higher numbers indicate higher priority. See swapon(2) for a full description of swap priorities. Add pri=value to the option field of /etc/fstab for use with swapon -a.
>
>
>
As a side note, you might wonder why set swap default priority to *42*, I believe it to be just another reference to the [Great Answer](http://en.wikipedia.org/wiki/Answer_to_life,_universe_and_everything#Answer_to_Life.2C_the_Universe.2C_and_Everything_.2842.29). | The `pri` is short priority and [determines the order in which multiple swap partitions are used](http://www.brighthub.com/computing/linux/articles/37236.aspx). Partitions with a higher value for `pri` are used first. |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | The `pri` is short priority and [determines the order in which multiple swap partitions are used](http://www.brighthub.com/computing/linux/articles/37236.aspx). Partitions with a higher value for `pri` are used first. | I was on the same boat, and in fairness @avelldiroll answer is already perfect.
But, if you are alone on a terminal with no internet, this is the trail to follow:
1. First you start with `man fstab`, and here the relevant portion:
>
> **The fourth field (fs\_mntops).**
>
>
> This field describes the mount options associated with the
> filesystem.
>
>
> It is formatted as a comma-separated list of options. It contains
> at least the type of mount (ro or rw), plus any additional
> options appropriate to the filesystem type (including
> performance-tuning options). For details, see mount(8) or
> swapon(8).
>
>
>
Which is suggesting to use `man mount` and `man swapon`.
2. Then you inspect the first of the two, `man mount`, and ... you find nothing ... thus *pri* is not valid for all the file systems
3. Then you inspect the last of the two, `man swapon`, and (either by scrolling either by searching *fstab*) you'll find this relevant portion:
>
> **-p, --priority** *priority*
>
>
> Specify the priority of the swap device. priority is a value between 0 and 32767. Higher numbers indicate
> higher priority. See swapon(2) for a full description of swap
> priorities. Add pri=value to the option field of /etc/fstab for use
> with swapon -a.
>
>
>
I was wondering how I could remember that parameter purely relying on the documentation, turn out is a bit convolute but possible.
By the way, you can have as many swap partitions as you want, the priority is used to prefer a swap partition over another, e.g. this could be the relevant portion on */etc/fstab*
```
...output omitted...
UUID=... swap swap pri=10 0 0
UUID=... swap swap pri=20 0 0
```
(And yes, `pri=42` is definitely a reference to *the answer to life, the universe, and everything* ) |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | The `pri` is short priority and [determines the order in which multiple swap partitions are used](http://www.brighthub.com/computing/linux/articles/37236.aspx). Partitions with a higher value for `pri` are used first. | One observation.
I have a listing where priority is -2 which I assume is less then 5.
```
swapon -s
Filename Type Size Used Priority
/dev/sda3 partition 2047996 0 -2
/dev/zram0 partition 1455164 0 5
/dev/zram1 partition 1455164 0 5
```
Linux Mint 20.
This is outside the range 0 to 32767 so that is a conflict with previous Info. |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | Not on any linux distro, I believe ubuntu does not set any swap priority by default, some others might.
You may call **man swapon** to the rescue ... here is an excerpt:
>
> -p priority
>
>
> Specify the priority of the swap device. This option is only available if swapon was compiled and is used under a 1.3.2 or later kernel. priority is a value between 0 and 32767. Higher numbers indicate higher priority. See swapon(2) for a full description of swap priorities. Add pri=value to the option field of /etc/fstab for use with swapon -a.
>
>
>
As a side note, you might wonder why set swap default priority to *42*, I believe it to be just another reference to the [Great Answer](http://en.wikipedia.org/wiki/Answer_to_life,_universe_and_everything#Answer_to_Life.2C_the_Universe.2C_and_Everything_.2842.29). | assume you have 2 swap-partitions, with 'pri' you can tell the os, which swap partion to use first:
>
> pri=n Specifies the swap space priority. The n variable can
> be 0, 1, 2, 3, 4, with 0 being lowest priority, and 4
> being highest priority.
>
>
> |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | Not on any linux distro, I believe ubuntu does not set any swap priority by default, some others might.
You may call **man swapon** to the rescue ... here is an excerpt:
>
> -p priority
>
>
> Specify the priority of the swap device. This option is only available if swapon was compiled and is used under a 1.3.2 or later kernel. priority is a value between 0 and 32767. Higher numbers indicate higher priority. See swapon(2) for a full description of swap priorities. Add pri=value to the option field of /etc/fstab for use with swapon -a.
>
>
>
As a side note, you might wonder why set swap default priority to *42*, I believe it to be just another reference to the [Great Answer](http://en.wikipedia.org/wiki/Answer_to_life,_universe_and_everything#Answer_to_Life.2C_the_Universe.2C_and_Everything_.2842.29). | I was on the same boat, and in fairness @avelldiroll answer is already perfect.
But, if you are alone on a terminal with no internet, this is the trail to follow:
1. First you start with `man fstab`, and here the relevant portion:
>
> **The fourth field (fs\_mntops).**
>
>
> This field describes the mount options associated with the
> filesystem.
>
>
> It is formatted as a comma-separated list of options. It contains
> at least the type of mount (ro or rw), plus any additional
> options appropriate to the filesystem type (including
> performance-tuning options). For details, see mount(8) or
> swapon(8).
>
>
>
Which is suggesting to use `man mount` and `man swapon`.
2. Then you inspect the first of the two, `man mount`, and ... you find nothing ... thus *pri* is not valid for all the file systems
3. Then you inspect the last of the two, `man swapon`, and (either by scrolling either by searching *fstab*) you'll find this relevant portion:
>
> **-p, --priority** *priority*
>
>
> Specify the priority of the swap device. priority is a value between 0 and 32767. Higher numbers indicate
> higher priority. See swapon(2) for a full description of swap
> priorities. Add pri=value to the option field of /etc/fstab for use
> with swapon -a.
>
>
>
I was wondering how I could remember that parameter purely relying on the documentation, turn out is a bit convolute but possible.
By the way, you can have as many swap partitions as you want, the priority is used to prefer a swap partition over another, e.g. this could be the relevant portion on */etc/fstab*
```
...output omitted...
UUID=... swap swap pri=10 0 0
UUID=... swap swap pri=20 0 0
```
(And yes, `pri=42` is definitely a reference to *the answer to life, the universe, and everything* ) |
54,228 | When mounting a swap partition on Linux, what does the mount option pri=42 mean?
fstab:
```
/dev/hda1 swap swap pri=42 0 0
``` | 2009/10/12 | [
"https://superuser.com/questions/54228",
"https://superuser.com",
"https://superuser.com/users/13882/"
] | Not on any linux distro, I believe ubuntu does not set any swap priority by default, some others might.
You may call **man swapon** to the rescue ... here is an excerpt:
>
> -p priority
>
>
> Specify the priority of the swap device. This option is only available if swapon was compiled and is used under a 1.3.2 or later kernel. priority is a value between 0 and 32767. Higher numbers indicate higher priority. See swapon(2) for a full description of swap priorities. Add pri=value to the option field of /etc/fstab for use with swapon -a.
>
>
>
As a side note, you might wonder why set swap default priority to *42*, I believe it to be just another reference to the [Great Answer](http://en.wikipedia.org/wiki/Answer_to_life,_universe_and_everything#Answer_to_Life.2C_the_Universe.2C_and_Everything_.2842.29). | One observation.
I have a listing where priority is -2 which I assume is less then 5.
```
swapon -s
Filename Type Size Used Priority
/dev/sda3 partition 2047996 0 -2
/dev/zram0 partition 1455164 0 5
/dev/zram1 partition 1455164 0 5
```
Linux Mint 20.
This is outside the range 0 to 32767 so that is a conflict with previous Info. |
11,646,563 | I implemented several buttons in my webpage as i am doing a booking system. I managed to restrict the user click on buttons in my webpage but my problem here is that user now cannot even select a button as when they try to click on the first button, my alert message will pop up asking them to only select one button. How do i allow users to select only one button and when they try to select another one, my alert message will come into usage. I suspect that is my count that is causing the problem.
here is my .cs code:
```
protected void Button1_Click(object sender, EventArgs e)
{
int counter = 0;
if (counter > 1)
{
Button1.Text = "Selected";
Button1.BackColor = System.Drawing.Color.DarkGreen;
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "9AM";
endingTime.Text = "11AM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "10AM";
endingTime.Text = "12PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "11AM";
endingTime.Text = "1PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
``` | 2012/07/25 | [
"https://Stackoverflow.com/questions/11646563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508546/"
] | This will always evaluate to `false`, so you always get into the `else` block:
```
int counter = 0;
if (counter > 1)
```
You should change `counter` **after** your code executed, also it should be a field of your class (otherwise any changes to it get lost as currently `counter` is gone once the method exits).
You could also use [`Button.Enabled`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.enabled.aspx) to enable/disable buttons. | Declare `int counter = 0` as global variable. |
11,646,563 | I implemented several buttons in my webpage as i am doing a booking system. I managed to restrict the user click on buttons in my webpage but my problem here is that user now cannot even select a button as when they try to click on the first button, my alert message will pop up asking them to only select one button. How do i allow users to select only one button and when they try to select another one, my alert message will come into usage. I suspect that is my count that is causing the problem.
here is my .cs code:
```
protected void Button1_Click(object sender, EventArgs e)
{
int counter = 0;
if (counter > 1)
{
Button1.Text = "Selected";
Button1.BackColor = System.Drawing.Color.DarkGreen;
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "9AM";
endingTime.Text = "11AM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "10AM";
endingTime.Text = "12PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "11AM";
endingTime.Text = "1PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
``` | 2012/07/25 | [
"https://Stackoverflow.com/questions/11646563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508546/"
] | This will always evaluate to `false`, so you always get into the `else` block:
```
int counter = 0;
if (counter > 1)
```
You should change `counter` **after** your code executed, also it should be a field of your class (otherwise any changes to it get lost as currently `counter` is gone once the method exits).
You could also use [`Button.Enabled`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.enabled.aspx) to enable/disable buttons. | you must try with this example for Button1
```
//Save your counter in Viewstate or InputHidden in order to persist
public int Counter
{
get
{
int s = (int)ViewState["Counter"];
return (s == null) ? 0 : s;
}
set
{
ViewState["Counter"] = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Counter = Counter + 1;
if (Counter > 1)
{
Button1.Text = "Selected";
Button1.BackColor = System.Drawing.Color.DarkGreen;
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "9AM";
endingTime.Text = "11AM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
``` |
11,646,563 | I implemented several buttons in my webpage as i am doing a booking system. I managed to restrict the user click on buttons in my webpage but my problem here is that user now cannot even select a button as when they try to click on the first button, my alert message will pop up asking them to only select one button. How do i allow users to select only one button and when they try to select another one, my alert message will come into usage. I suspect that is my count that is causing the problem.
here is my .cs code:
```
protected void Button1_Click(object sender, EventArgs e)
{
int counter = 0;
if (counter > 1)
{
Button1.Text = "Selected";
Button1.BackColor = System.Drawing.Color.DarkGreen;
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "9AM";
endingTime.Text = "11AM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "10AM";
endingTime.Text = "12PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
int counter = 1;
if (counter > 0)
{
Button3.Text = "Selected";
Button3.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "11AM";
endingTime.Text = "1PM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
``` | 2012/07/25 | [
"https://Stackoverflow.com/questions/11646563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508546/"
] | Declare `int counter = 0` as global variable. | you must try with this example for Button1
```
//Save your counter in Viewstate or InputHidden in order to persist
public int Counter
{
get
{
int s = (int)ViewState["Counter"];
return (s == null) ? 0 : s;
}
set
{
ViewState["Counter"] = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Counter = Counter + 1;
if (Counter > 1)
{
Button1.Text = "Selected";
Button1.BackColor = System.Drawing.Color.DarkGreen;
Button2.Text = "Selected";
Button2.BackColor = System.Drawing.Color.DarkGreen;
startingTime.Text = "9AM";
endingTime.Text = "11AM";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
}
}
``` |
28,385,262 | I'm using native javascript ajax but when I look at what's posted it simply says `[object Object]` and so trying to capture `$_REQUEST['stringSent']` in the php file does nothing
Here's what I'm trying, called using `dataPost('test')`
```
function dataPost(dataToSend) {
var params = { "stringSent": dataToSend };
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
if (typeof success === "function") {
alert(xmlhttp.responseText);
success(xmlhttp.responseText);
}
}else if(typeof error === "function" && (xmlhttp.status > 299 || xmlhttp.status < 200)){
error();
}
}
xmlhttp.open("POST", 'dataCapture.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//xmlhttp.send(JSON.stringify(data)); // not needed as I'm sending JSON anyway
xmlhttp.send(params);
}
```
Is there a better way to do this? | 2015/02/07 | [
"https://Stackoverflow.com/questions/28385262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/973552/"
] | Comment this line :
```
// xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
```
or Change it to :
```
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('stringSent=' + dataToSend);
``` | Use Jquery Ajax.
```
$.ajax({
url: 'dataCapture.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: params ,
success: function( data, textStatus, jQxhr ){ $('#response pre').html( data ); },
error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); }
});
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Use the `Any()` operator:
```
dictionary.Keys.Where(key => key.Contains("a")).Any();
```
Or
```
dictionary.Keys.Any(key => key.Contains("a"));
``` | Use `Any` **instead of** `Where`:
```
dictionary.Keys.Any( key => key.Contains("a"));
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Use the `Any()` operator:
```
dictionary.Keys.Where(key => key.Contains("a")).Any();
```
Or
```
dictionary.Keys.Any(key => key.Contains("a"));
``` | If you're asking if you can determine whether or not any key in the dictionary contains `"a"`, then you can do:
```
dictionary.Keys.Any(key => key.Contains("a"))
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Use the `Any()` operator:
```
dictionary.Keys.Where(key => key.Contains("a")).Any();
```
Or
```
dictionary.Keys.Any(key => key.Contains("a"));
``` | You can use the .Any() keyword:
```
bool exists = dictionary.Keys.Any(key => key.Contains("a"));
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Use `Any` **instead of** `Where`:
```
dictionary.Keys.Any( key => key.Contains("a"));
``` | If you're asking if you can determine whether or not any key in the dictionary contains `"a"`, then you can do:
```
dictionary.Keys.Any(key => key.Contains("a"))
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Use `Any` **instead of** `Where`:
```
dictionary.Keys.Any( key => key.Contains("a"));
``` | You can use the .Any() keyword:
```
bool exists = dictionary.Keys.Any(key => key.Contains("a"));
``` |
7,247,235 | we can search dictionary like
```
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
```
but it return list. i want that linq should return true or false. so what would be the right code that search dictionary with linq. please guide. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7247235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | You can use the .Any() keyword:
```
bool exists = dictionary.Keys.Any(key => key.Contains("a"));
``` | If you're asking if you can determine whether or not any key in the dictionary contains `"a"`, then you can do:
```
dictionary.Keys.Any(key => key.Contains("a"))
``` |
129,080 | Let consider an object which has a field called edit\_counting. We knew that for every record, we have a button called EDIT to update the record. First time I edited and save the record. Now the value of Edit\_counting is should be 1. Like this How many times I edit the record, that many times the field value needs to get updated automatically. Please can anyone help me in this?
Note: Field may be any data type.
Thanks in advance
Kumaran | 2016/06/28 | [
"https://salesforce.stackexchange.com/questions/129080",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/-1/"
] | You can create a custom number field and set the default value to zero. Then create a WFR. Your formula would look something like this
```
OR(
ISCHANGED(Field1__c),
ISCHANGED(Field2__c),
ISCHANGED(Field3__c),
ISCHANGED(Field4__c),
ISCHANGED(Field5__c),
ISCHANGED(Field6__c),
ISCHANGED(Field7__c),
ISCHANGED(Field8__c),
ISCHANGED(Field9__c),
ISCHANGED(Field10__c)
)
```
Then you create an immediate action of a field update. And your formula for the field update would be
```
Your_Custom_Number_Field__c + 1
```
This increases your number field by 1 each time your custom field is changed to a non null value.
You can add other fields in the criteria using OR condition | To track the changes made in field create workflow as follows :
* Create a Number field for Edit\_counting
* Create a workflow that fires whenever there is a edit made by using this formula `ISCHANGED(tracking_field)`
* Do a field update on number field as `<Edit_counting> + 1 .` |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | This is a working solution for JPA, Hibernate (with annotations).
This is the beginning of the entity class (for the table that has Interval column):
```
@Entity
@Table(name="table_with_interval_col")
@TypeDef(name="interval", typeClass = Interval.class)
public class TableWithIntervalCol implements Serializable {
```
This is the interval column:
```
@Column(name = "interval_col", nullable = false)
@Type(type = "interval")
private Integer intervalCol;
```
And this is the Interval class:
```
package foo.bar.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.postgresql.util.PGInterval;
/**
* Postgres Interval type
*
* @author bpgergo
*
*/
public class Interval implements UserType {
private static final int[] SQL_TYPES = { Types.OTHER };
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@SuppressWarnings("rawtypes")
@Override
public Class returnedClass() {
return Integer.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String interval = rs.getString(names[0]);
if (rs.wasNull() || interval == null) {
return null;
}
PGInterval pgInterval = new PGInterval(interval);
Date epoch = new Date(0l);
pgInterval.add(epoch);
return Integer.valueOf((int)epoch.getTime() / 1000);
}
public static String getInterval(int value){
return new PGInterval(0, 0, 0, 0, 0, value).getValue();
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
//this http://postgresql.1045698.n5.nabble.com/Inserting-Information-in-PostgreSQL-interval-td2175203.html#a2175205
st.setObject(index, getInterval(((Integer) value).intValue()), Types.OTHER);
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
}
``` | According to the link you should have a day followed by hours:minutes:seconds. So changing the code to something like the following assuming you never need to have more then 23 hours 59 minutes in the interval.
```
statement.setString(index, "'0 "+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
```
I am not able to test this code since I don't have PostGreSql installed. For another discussion on this same issue see the following link, although you would have to modify the code provided to handle seconds. That shouldn't be much of a problem though.
<https://forum.hibernate.org/viewtopic.php?p=2348558&sid=95488ce561e7efec8a2950f76ae4741c> |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | PostgreSQL has a date\_part / extract function which you can use to return different fields, epoch being one of them. When extracting the epoch from an interval, you receive the number of seconds contained in the interval, and from there you can convert however you wish. I lost my experience with Hibernate, but you can do it this way:
```
SELECT
average_interval_between_airings
, date_part('epoch', average_interval_between_airings) / 60 as minutes
, date_part('epoch', average_interval_between_airings) as seconds
FROM shows;
``` | According to the link you should have a day followed by hours:minutes:seconds. So changing the code to something like the following assuming you never need to have more then 23 hours 59 minutes in the interval.
```
statement.setString(index, "'0 "+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
```
I am not able to test this code since I don't have PostGreSql installed. For another discussion on this same issue see the following link, although you would have to modify the code provided to handle seconds. That shouldn't be much of a problem though.
<https://forum.hibernate.org/viewtopic.php?p=2348558&sid=95488ce561e7efec8a2950f76ae4741c> |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | Why not just turn it into a numeric and map to a Long?
```
SELECT EXTRACT(epoch FROM my_interval)
``` | According to the link you should have a day followed by hours:minutes:seconds. So changing the code to something like the following assuming you never need to have more then 23 hours 59 minutes in the interval.
```
statement.setString(index, "'0 "+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
```
I am not able to test this code since I don't have PostGreSql installed. For another discussion on this same issue see the following link, although you would have to modify the code provided to handle seconds. That shouldn't be much of a problem though.
<https://forum.hibernate.org/viewtopic.php?p=2348558&sid=95488ce561e7efec8a2950f76ae4741c> |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | You don't have to write your own Hibernate custom type to map the PostgreSQL `interval` column to a Java `Duration` object. All you need to do is use the [Hibernate Ttypes](https://github.com/vladmihalcea/hibernate-types) project.
So, after adding the proper Hibernate dependency:
```
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.6.0</version>
</dependency>
```
You just have to use the `@TypeDef` annotation to register the [`PostgreSQLIntervalType`](https://vladmihalcea.com/map-postgresql-interval-java-duration-hibernate/):
```
@Entity(name = "Book")
@Table(name = "book")
@TypeDef(
typeClass = PostgreSQLIntervalType.class,
defaultForType = Duration.class
)
@TypeDef(
typeClass = YearMonthDateType.class,
defaultForType = YearMonth.class
)
public class Book {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String isbn;
private String title;
@Column(
name = "published_on",
columnDefinition = "date"
)
private YearMonth publishedOn;
@Column(
name = "presale_period",
columnDefinition = "interval"
)
private Duration presalePeriod;
public Long getId() {
return id;
}
public Book setId(Long id) {
this.id = id;
return this;
}
public String getIsbn() {
return isbn;
}
public Book setIsbn(String isbn) {
this.isbn = isbn;
return this;
}
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public YearMonth getPublishedOn() {
return publishedOn;
}
public Book setPublishedOn(YearMonth publishedOn) {
this.publishedOn = publishedOn;
return this;
}
public Duration getPresalePeriod() {
return presalePeriod;
}
public Book setPresalePeriod(Duration presalePeriod) {
this.presalePeriod = presalePeriod;
return this;
}
}
```
Now, when persisting the `Book` entity:
```
entityManager.persist(
new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setPublishedOn(YearMonth.of(2016, 10))
.setPresalePeriod(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
)
)
);
```
Hibernate will execute the proper SQL INSERT statement:
```
INSERT INTO book (
isbn,
presale_period,
published_on,
title,
id
)
VALUES (
'978-9730228236',
'0 years 0 mons 297 days 0 hours 0 mins 0.00 secs',
'2016-10-01',
'High-Performance Java Persistence',
1
)
```
When fetching the `Book` entity, we can see that the `Duration` attribute is properly fetched from the database:
```
Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load("978-9730228236");
assertEquals(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
),
book.getPresalePeriod()
);
``` | According to the link you should have a day followed by hours:minutes:seconds. So changing the code to something like the following assuming you never need to have more then 23 hours 59 minutes in the interval.
```
statement.setString(index, "'0 "+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
```
I am not able to test this code since I don't have PostGreSql installed. For another discussion on this same issue see the following link, although you would have to modify the code provided to handle seconds. That shouldn't be much of a problem though.
<https://forum.hibernate.org/viewtopic.php?p=2348558&sid=95488ce561e7efec8a2950f76ae4741c> |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | This is a working solution for JPA, Hibernate (with annotations).
This is the beginning of the entity class (for the table that has Interval column):
```
@Entity
@Table(name="table_with_interval_col")
@TypeDef(name="interval", typeClass = Interval.class)
public class TableWithIntervalCol implements Serializable {
```
This is the interval column:
```
@Column(name = "interval_col", nullable = false)
@Type(type = "interval")
private Integer intervalCol;
```
And this is the Interval class:
```
package foo.bar.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.postgresql.util.PGInterval;
/**
* Postgres Interval type
*
* @author bpgergo
*
*/
public class Interval implements UserType {
private static final int[] SQL_TYPES = { Types.OTHER };
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@SuppressWarnings("rawtypes")
@Override
public Class returnedClass() {
return Integer.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String interval = rs.getString(names[0]);
if (rs.wasNull() || interval == null) {
return null;
}
PGInterval pgInterval = new PGInterval(interval);
Date epoch = new Date(0l);
pgInterval.add(epoch);
return Integer.valueOf((int)epoch.getTime() / 1000);
}
public static String getInterval(int value){
return new PGInterval(0, 0, 0, 0, 0, value).getValue();
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
//this http://postgresql.1045698.n5.nabble.com/Inserting-Information-in-PostgreSQL-interval-td2175203.html#a2175205
st.setObject(index, getInterval(((Integer) value).intValue()), Types.OTHER);
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
}
``` | PostgreSQL has a date\_part / extract function which you can use to return different fields, epoch being one of them. When extracting the epoch from an interval, you receive the number of seconds contained in the interval, and from there you can convert however you wish. I lost my experience with Hibernate, but you can do it this way:
```
SELECT
average_interval_between_airings
, date_part('epoch', average_interval_between_airings) / 60 as minutes
, date_part('epoch', average_interval_between_airings) as seconds
FROM shows;
``` |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | This is a working solution for JPA, Hibernate (with annotations).
This is the beginning of the entity class (for the table that has Interval column):
```
@Entity
@Table(name="table_with_interval_col")
@TypeDef(name="interval", typeClass = Interval.class)
public class TableWithIntervalCol implements Serializable {
```
This is the interval column:
```
@Column(name = "interval_col", nullable = false)
@Type(type = "interval")
private Integer intervalCol;
```
And this is the Interval class:
```
package foo.bar.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.postgresql.util.PGInterval;
/**
* Postgres Interval type
*
* @author bpgergo
*
*/
public class Interval implements UserType {
private static final int[] SQL_TYPES = { Types.OTHER };
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@SuppressWarnings("rawtypes")
@Override
public Class returnedClass() {
return Integer.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String interval = rs.getString(names[0]);
if (rs.wasNull() || interval == null) {
return null;
}
PGInterval pgInterval = new PGInterval(interval);
Date epoch = new Date(0l);
pgInterval.add(epoch);
return Integer.valueOf((int)epoch.getTime() / 1000);
}
public static String getInterval(int value){
return new PGInterval(0, 0, 0, 0, 0, value).getValue();
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
//this http://postgresql.1045698.n5.nabble.com/Inserting-Information-in-PostgreSQL-interval-td2175203.html#a2175205
st.setObject(index, getInterval(((Integer) value).intValue()), Types.OTHER);
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
}
``` | Why not just turn it into a numeric and map to a Long?
```
SELECT EXTRACT(epoch FROM my_interval)
``` |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | Why not just turn it into a numeric and map to a Long?
```
SELECT EXTRACT(epoch FROM my_interval)
``` | PostgreSQL has a date\_part / extract function which you can use to return different fields, epoch being one of them. When extracting the epoch from an interval, you receive the number of seconds contained in the interval, and from there you can convert however you wish. I lost my experience with Hibernate, but you can do it this way:
```
SELECT
average_interval_between_airings
, date_part('epoch', average_interval_between_airings) / 60 as minutes
, date_part('epoch', average_interval_between_airings) as seconds
FROM shows;
``` |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | You don't have to write your own Hibernate custom type to map the PostgreSQL `interval` column to a Java `Duration` object. All you need to do is use the [Hibernate Ttypes](https://github.com/vladmihalcea/hibernate-types) project.
So, after adding the proper Hibernate dependency:
```
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.6.0</version>
</dependency>
```
You just have to use the `@TypeDef` annotation to register the [`PostgreSQLIntervalType`](https://vladmihalcea.com/map-postgresql-interval-java-duration-hibernate/):
```
@Entity(name = "Book")
@Table(name = "book")
@TypeDef(
typeClass = PostgreSQLIntervalType.class,
defaultForType = Duration.class
)
@TypeDef(
typeClass = YearMonthDateType.class,
defaultForType = YearMonth.class
)
public class Book {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String isbn;
private String title;
@Column(
name = "published_on",
columnDefinition = "date"
)
private YearMonth publishedOn;
@Column(
name = "presale_period",
columnDefinition = "interval"
)
private Duration presalePeriod;
public Long getId() {
return id;
}
public Book setId(Long id) {
this.id = id;
return this;
}
public String getIsbn() {
return isbn;
}
public Book setIsbn(String isbn) {
this.isbn = isbn;
return this;
}
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public YearMonth getPublishedOn() {
return publishedOn;
}
public Book setPublishedOn(YearMonth publishedOn) {
this.publishedOn = publishedOn;
return this;
}
public Duration getPresalePeriod() {
return presalePeriod;
}
public Book setPresalePeriod(Duration presalePeriod) {
this.presalePeriod = presalePeriod;
return this;
}
}
```
Now, when persisting the `Book` entity:
```
entityManager.persist(
new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setPublishedOn(YearMonth.of(2016, 10))
.setPresalePeriod(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
)
)
);
```
Hibernate will execute the proper SQL INSERT statement:
```
INSERT INTO book (
isbn,
presale_period,
published_on,
title,
id
)
VALUES (
'978-9730228236',
'0 years 0 mons 297 days 0 hours 0 mins 0.00 secs',
'2016-10-01',
'High-Performance Java Persistence',
1
)
```
When fetching the `Book` entity, we can see that the `Duration` attribute is properly fetched from the database:
```
Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load("978-9730228236");
assertEquals(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
),
book.getPresalePeriod()
);
``` | PostgreSQL has a date\_part / extract function which you can use to return different fields, epoch being one of them. When extracting the epoch from an interval, you receive the number of seconds contained in the interval, and from there you can convert however you wish. I lost my experience with Hibernate, but you can do it this way:
```
SELECT
average_interval_between_airings
, date_part('epoch', average_interval_between_airings) / 60 as minutes
, date_part('epoch', average_interval_between_airings) as seconds
FROM shows;
``` |
1,945,615 | Under PostgreSQL, I'm using `PersistentDuration` for the mapping between the sql type interval & duration but it doesn't work.
Another user found the same issue & come with his own class:
```
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.OTHER);
} else {
Long interval = ((Long) value).longValue();
Long hours = interval / 3600;
Long minutes = (interval - (hours * 3600)) / 60;
Long secondes = interval - (hours * 3600) - minutes * 60;
statement.setString(index, "'"+ hours +":"
+ intervalFormat.format(minutes) + ":"
+ intervalFormat.format(secondes)+"'");
}
}
```
But it doesn't work with the real format because it suppose the interval pattern is only
"hh:mm:ss". That is not the case: see
Here some few real examples i need to parse from the database:
```
1 day 00:29:42
00:29:42
1 week 00:29:42
1 week 2 days 00:29:42
1 month 1 week 2 days 00:29:42
1 year 00:29:42
1 decade 00:29:42
```
<http://www.postgresql.org/docs/current/interactive/datatype-datetime.html>
Have you a clean solution? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1945615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236772/"
] | You don't have to write your own Hibernate custom type to map the PostgreSQL `interval` column to a Java `Duration` object. All you need to do is use the [Hibernate Ttypes](https://github.com/vladmihalcea/hibernate-types) project.
So, after adding the proper Hibernate dependency:
```
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.6.0</version>
</dependency>
```
You just have to use the `@TypeDef` annotation to register the [`PostgreSQLIntervalType`](https://vladmihalcea.com/map-postgresql-interval-java-duration-hibernate/):
```
@Entity(name = "Book")
@Table(name = "book")
@TypeDef(
typeClass = PostgreSQLIntervalType.class,
defaultForType = Duration.class
)
@TypeDef(
typeClass = YearMonthDateType.class,
defaultForType = YearMonth.class
)
public class Book {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String isbn;
private String title;
@Column(
name = "published_on",
columnDefinition = "date"
)
private YearMonth publishedOn;
@Column(
name = "presale_period",
columnDefinition = "interval"
)
private Duration presalePeriod;
public Long getId() {
return id;
}
public Book setId(Long id) {
this.id = id;
return this;
}
public String getIsbn() {
return isbn;
}
public Book setIsbn(String isbn) {
this.isbn = isbn;
return this;
}
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public YearMonth getPublishedOn() {
return publishedOn;
}
public Book setPublishedOn(YearMonth publishedOn) {
this.publishedOn = publishedOn;
return this;
}
public Duration getPresalePeriod() {
return presalePeriod;
}
public Book setPresalePeriod(Duration presalePeriod) {
this.presalePeriod = presalePeriod;
return this;
}
}
```
Now, when persisting the `Book` entity:
```
entityManager.persist(
new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setPublishedOn(YearMonth.of(2016, 10))
.setPresalePeriod(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
)
)
);
```
Hibernate will execute the proper SQL INSERT statement:
```
INSERT INTO book (
isbn,
presale_period,
published_on,
title,
id
)
VALUES (
'978-9730228236',
'0 years 0 mons 297 days 0 hours 0 mins 0.00 secs',
'2016-10-01',
'High-Performance Java Persistence',
1
)
```
When fetching the `Book` entity, we can see that the `Duration` attribute is properly fetched from the database:
```
Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load("978-9730228236");
assertEquals(
Duration.between(
LocalDate
.of(2015, Month.NOVEMBER, 2)
.atStartOfDay(),
LocalDate
.of(2016, Month.AUGUST, 25)
.atStartOfDay()
),
book.getPresalePeriod()
);
``` | Why not just turn it into a numeric and map to a Long?
```
SELECT EXTRACT(epoch FROM my_interval)
``` |
71,787,507 | I am trying to make an simple login form using javascript,also don't able to find any error,please help me to succesfully implement it.Here is code
```
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "user")
{
alert("login successfully");
return false;
}
else
{
alert("login failed");
}
}
``` | 2022/04/07 | [
"https://Stackoverflow.com/questions/71787507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17930921/"
] | You can use this code:
```html
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ? true : !isNaN(Number(event.key)) && event.code!=='Space'" />
```
This will avoids all characters that are not numbers!
This part make's input accept only numbers:
```
!isNaN(Number(event.key))
```
This part make's accept the arrow and delete keys:
```
['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code)
```
This part make's Firefox disallow spaces in numbers:
```
event.code!=='Space'
``` | (For react Applications)
If someone has text input and wants to accept only whole numbers. You can use the following code.
```js
const numberInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const eventCode = event.code.toLowerCase();
if (!(event.code !== null
&& (eventCode.includes("digit")
|| eventCode.includes("arrow")
|| eventCode.includes("home")
|| eventCode.includes("end")
|| eventCode.includes("backspace")
|| (eventCode.includes("numpad") && eventCode.length === 7)))
) {
event.preventDefault();
}
};
```
I have compared the length of eventCode to 7 when it includes numpad because its actual value is like numpad0, numpad1 ... numpad9
This function can be specified in onKeyDown such as
```js
<input
id="myNumberInput"
type="text"
placeholder="numeric input"
onKeyDown={numberInputKeyDown}
/>
```
To extent field to accept decimals or negative numbers you can console.log the `eventCode` in `numberInputKeyDown` to check your required key code and add it in if statement. |
58,854,260 | I'm writing my first Azure function (based on .NET Core 2.x), and I'm struggling to extend the app settings with my custom mapping table.
I have a file `local.settings.json`, and I have tried to extend it with a "custom" config section that contains a few "key/value" pairs - something like this:
```
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
... (standard config settings) ...
},
... (more default sections, like "Host" and "ConnectionStrings")
"MappingTable" : {
"01" : "Value1",
"02" : "Value2",
"03" : "Value3",
"else" : "Value4"
}
}
```
I get the `IConfiguration` injected into my worker class via constructor injection, and it works just fine for the "basic" default values stored in the "Values" section:
```
public MyWorker(IConfiguration config)
{
_config = config;
string runtime = _config["FUNCTIONS_WORKER_RUNTIME"]; // works just fine
// this also works fine - the "customSection" object is filled
var customSection = _config.GetSection("MappingTable");
// but now this doesn't return any values
var children = customSection.GetChildren();
// and trying to access like this also only returns "null"
var mapping = customSection["01"];
}
```
I'm stuck here - all the blog post and articles I find seem to indicate to do just this - but in my case, this just doesn't seem to work. What am I missing here? I'm quite familiar with the full .NET framework config system - but this here is new to me and doesn't really make a whole lot of sense just yet......
I have also tried to move the entire `MappingTable` section to `appSettings.json` - but that didn't change anything, I'm still getting back only `null` when trying to access my custom config section's values....
Thanks!
**Update:** all the suggested ways of doing this work just fine with a standard ASP.NET Core 2.1 web app - but in the Azure function, it's not working. Seems like code in an **Azure Function** is **treating configuration differently** than a regular .NET Core code base ... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58854260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13302/"
] | I did something similar using .net core 3.0
local.settings.json
```
{
"AppSettings":{
"MappingTable" : {
"01" : "Value1"
}
}
}
```
Reading appsettings:
```
private void AppSettings()
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var 01 = config["AppSettings:MappingTable:01"];
}
```
In the Azure portal, you need to add this as an application setting.
In your Function App -> *Configuration -Application Settings -> New Application setting*
[](https://i.stack.imgur.com/pmiR5.png)
```
Name:AppSettings:MappingTable:01
Value:Value1
``` | ***A R G H ! ! !***
I knew it - such a stupid little mistake - but with rather massive consequences.....
In my startup class, I had this code (plus some more):
```
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
var config = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
.....
}
}
```
but what was missing is this one line of code after the call to `.Build()` above:
```
builder.Services.AddSingleton<IConfiguration>(config);
```
Somehow, the settings in the `Values` section of `local.settings.json` were present and accessible, but any custom config sections weren't.
Adding this one line has solved my problem - now I can easily read the `MappingTable` from my `local.settings.json` (or `appsettings.json`) file and use it in my code. |
27,199,816 | suppose this is right:
```
std::function< void() > callback = std::bind( &Test::blah, test );
```
can I just do
```
auto callback = std::bind(&Test::blah, test)
```
?
thanks | 2014/11/29 | [
"https://Stackoverflow.com/questions/27199816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2495795/"
] | The return value of `std::bind` is *unspecified* (§20.8.9.1.2), so you're basically forced to use `auto` with it. However, it returns a function object which can be stored in `std::function`, which allows the first line to work. | Yes, in fact all *three* of these could be used:
```
std::function< void() > callback1 = std::bind( &Test::blah, test );
auto callback2 = std::bind(&Test::blah, test);
auto callback3 = [=]() mutable {test.blah();};
```
My choice would be the lambda. |
27,199,816 | suppose this is right:
```
std::function< void() > callback = std::bind( &Test::blah, test );
```
can I just do
```
auto callback = std::bind(&Test::blah, test)
```
?
thanks | 2014/11/29 | [
"https://Stackoverflow.com/questions/27199816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2495795/"
] | The return value of `std::bind` is *unspecified* (§20.8.9.1.2), so you're basically forced to use `auto` with it. However, it returns a function object which can be stored in `std::function`, which allows the first line to work. | Try this:
```
struct f {
virtual void func(auto a) = 0;
};
struct g {
virtual void func(std::function<void()> a) = 0;
};
```
They are two totally different things, and sometimes you can use `auto` but often not. Only function-local variables can be reasonably declared as `auto` (and maybe polylambdas in C++14).
But for function-locals, `auto` is the superior choice. It's becoming an increasing trend for experts to eschew the use of explicitly typed local variables altogether in most circumstances. |
47,253,027 | *Context*: to achieve full "infrastructure as code", I want to codify the process of requesting a SSL certificate using `certbot`, validating a domain using DNS `TXT` records, uploading the certificate to Amazon Certificate Manager (ACM), and finally attaching the certificate ACM ARN to my Cloudfront distribution. This should all be done through the Serverless framework.
I saw 2 potential options to make this work.
*Option 1: use of asynchronous javascript file variables*
I.e. in `serverless.yml` I would define entries like:
```
custom:
domains:
prod: tommedema.tk
ssl:
prod:
dnsTxtRoot: ${{file(scripts/request-cert.js):cert.dnsTxtRoot}}
dnsTxtWww: ${{file(scripts/request-cert.js):cert.dnsTxtWww}}
certArn: ${{file(scripts/request-cert.js):cert.certArn}}
```
Where resources would then use these variables like so:
```
- Type: TXT
Name: _acme-challenge.www.${{self:custom.domains.${{self:provider.stage}}, ''}}
TTL: '86400'
ResourceRecords:
- ${{self:custom.ssl.${{self:provider.stage}}.dnsTxtWww}}
```
Where `scripts/request-cert.js` would look like:
```
module.exports.cert = () => {
console.log('running async logic')
// TODO: run certbot, get DNS records, upload to ACM
return Promise.resolve({
dnsTxtRoot: '"LnaKMkgqlIkXXXXXXXX-7PkKvqb_wqwVnC4q0"',
dnsTxtWww: '"c43VS-XXXXXXXXXWVBRPCXXcA"',
certArn: 'arn:aws:acm:us-east-1:XXXX95:certificate/XXXXXX'
})
}
```
The problem here is that it appears to be impossible to send parameters to `request-cert.js`, or for this script to be aware of the `serverless` or `options` plugin parameters (as it is not a plugin, but a simple script without context). This means that the script cannot be aware of the stage and domain etc. that the deployment is for, and therefore it is missing necessary variables in order to request the certificate.
So, option 1 seems out of the question.
*Option 2: create a plugin*
Of course I can create a plugin, which will have all required variables because it can access the `serverless` and `options` objects. The problem now is that I would have to access the *output* of the plugin inside `serverless.yml`, and so far I have not seen how this can be done. I.e. I would like to be able to do something like this:
```
custom:
domains:
prod: tommedema.tk
ssl:
prod:
dnsTxtRoot: ${{myPlugin:cert.dnsTxtRoot}}
dnsTxtWww: ${{myPlugin:cert.dnsTxtWww}}
certArn: ${{myPlugin:cert.certArn}}
```
But this does not seem possible. Is that right?
If this is also not possible, how can I achieve my purpose to programatically (i.e. following infrastructure as code principles) deploy my services with custom SSL certificates, without any manual steps? I.e.
1. request certificate from certbot
2. receive DNS txt records for validation from certbot
3. attach DNS txt records to route53 recordsets
4. deploy the DNS records and validate the certificate
5. download the certificate from certbot and upload it to ACM
6. receive the certificate ARN from ACM
7. reference to the certificate ARN from within the cloudfront distribution inside the cloudformation template
8. redeploy with the certificate ARN attached | 2017/11/12 | [
"https://Stackoverflow.com/questions/47253027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45974/"
] | You *could* do it at deploy time, but certificates expire so it's best to make this a recurring thing.
When I was faced with this problem, I created a Lambda to upsert the SSL certificate and install it. (it needs a long timeout, but that's fine - it doesn't need to run often). The key it needs can be given as secure environment variables.
Then I use `serverless-warmup-plugin` to set up a daily trigger to check whether the certificate is due to be refreshed. The plugin is configurable to warm up relevant lambdas on deployment too, which allows me to check for expired or missing SSL certs on each deploy.
Maybe you could do something similar. | Using [Step Functions](https://aws.amazon.com/step-functions/) would be the best choice for this particular use case. Since you have 3 distinct steps, they would be three seperate Lambda functions that Step Functions can pass inputs/outputs between as well as including wait times and retries. |
21,972,860 | How to call this function in Javascript?
As it takes *n* as its outer function's parameter and it also needs another parameter *i* in its function inside, but how to call it?
```
function foo(n) {
return function (i) {
return n += i } }
``` | 2014/02/23 | [
"https://Stackoverflow.com/questions/21972860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841121/"
] | Call the returned value of the function:
```
foo(1)(2);
``` | This is a function that returns a function. Often you would want a reference to that function, Like this
```
foofn = foo(7);
result = foofn(7);
```
You could also just call the function right away
```
result = (foo(7))(7);
```
What the function does? Well that wasn't really your question... |
21,972,860 | How to call this function in Javascript?
As it takes *n* as its outer function's parameter and it also needs another parameter *i* in its function inside, but how to call it?
```
function foo(n) {
return function (i) {
return n += i } }
``` | 2014/02/23 | [
"https://Stackoverflow.com/questions/21972860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841121/"
] | Call the returned value of the function:
```
foo(1)(2);
``` | This is the way we usually use JavaScript closures, first function creates a scope to keep the `n` variable safe to be used in the inner function:
```
var n = 11;
var myfunc = foo(n);
```
now you can call your `myfunc` function, with a simple `i` argument, whereas it uses `n` without you needing to pass it directly to your function:
```
myfunc(10);
```
so if you want to just call it, once it is created, you can do: `foo(11)(10);`
But in these cases we don't usually call them like this, they are usually supposed to be used as a callback or something like it. |
21,972,860 | How to call this function in Javascript?
As it takes *n* as its outer function's parameter and it also needs another parameter *i* in its function inside, but how to call it?
```
function foo(n) {
return function (i) {
return n += i } }
``` | 2014/02/23 | [
"https://Stackoverflow.com/questions/21972860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841121/"
] | It a classic [closure](https://stackoverflow.com/q/111102/1048572) example: it does return a function which has access to the `n` variable.
```
var counter = foo(0);
counter(1); // 1
counter(2); // 3
counter(5); // 8
``` | This is a function that returns a function. Often you would want a reference to that function, Like this
```
foofn = foo(7);
result = foofn(7);
```
You could also just call the function right away
```
result = (foo(7))(7);
```
What the function does? Well that wasn't really your question... |
21,972,860 | How to call this function in Javascript?
As it takes *n* as its outer function's parameter and it also needs another parameter *i* in its function inside, but how to call it?
```
function foo(n) {
return function (i) {
return n += i } }
``` | 2014/02/23 | [
"https://Stackoverflow.com/questions/21972860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841121/"
] | It a classic [closure](https://stackoverflow.com/q/111102/1048572) example: it does return a function which has access to the `n` variable.
```
var counter = foo(0);
counter(1); // 1
counter(2); // 3
counter(5); // 8
``` | This is the way we usually use JavaScript closures, first function creates a scope to keep the `n` variable safe to be used in the inner function:
```
var n = 11;
var myfunc = foo(n);
```
now you can call your `myfunc` function, with a simple `i` argument, whereas it uses `n` without you needing to pass it directly to your function:
```
myfunc(10);
```
so if you want to just call it, once it is created, you can do: `foo(11)(10);`
But in these cases we don't usually call them like this, they are usually supposed to be used as a callback or something like it. |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | Try this code:
```
public int findSong(String title) {
int index = -1;
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) index = songs.indexOf(song);
}
// If you didn't know here we have if / else
// if index == -1 print song not found else print the index
System.out.println(index == -1 ? "Song not found: " + title : "Sound found at index " + index);
// If song isn't found index is -1
return index;
}
```
**EDIT:** Max Zoom said in comments
>
> How about the case where there is more then one song with given title?
>
>
>
Code:
```
public int[] findSong(String title) {
List<Integer> indexesList = new ArrayList<>();
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) indexesList.add(songs.indexOf(song));
}
// If we have no songs return empty array
if (indexesList.size() == 0) return new int[0];
// Convert list to int array
int[] indexes = new int[indexesList.size()];
for (int i = 0; i < indexes.length; i++) {
Integer integer = indexesList.get(i);
if (integer != null) indexes[i] = integer.intValue();
else indexes[i] = -1;
}
return indexes;
}
``` | You could to override equal function for your `Song` class to return `true` if two songs names are equal:
```
public class Song{
//Your other fields and functions ....
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Song))
return false;
if (obj == this)
return true;
Song s= (Song) obj;
return s.getTitle().equals(this.title);
}
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | ```
public int findSong(String title, List<Song> songs) {
for (Song song : songs) {
if (song == null || song.getTitle() == null) {
continue;
}
if (song.getTitle().equals(title)) {
int index = songs.indexOf(song);
System.out.println(index);
return index;
}
}
return -1;
}
``` | You could to override equal function for your `Song` class to return `true` if two songs names are equal:
```
public class Song{
//Your other fields and functions ....
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Song))
return false;
if (obj == this)
return true;
Song s= (Song) obj;
return s.getTitle().equals(this.title);
}
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | Try this code:
```
public int findSong(String title) {
int index = -1;
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) index = songs.indexOf(song);
}
// If you didn't know here we have if / else
// if index == -1 print song not found else print the index
System.out.println(index == -1 ? "Song not found: " + title : "Sound found at index " + index);
// If song isn't found index is -1
return index;
}
```
**EDIT:** Max Zoom said in comments
>
> How about the case where there is more then one song with given title?
>
>
>
Code:
```
public int[] findSong(String title) {
List<Integer> indexesList = new ArrayList<>();
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) indexesList.add(songs.indexOf(song));
}
// If we have no songs return empty array
if (indexesList.size() == 0) return new int[0];
// Convert list to int array
int[] indexes = new int[indexesList.size()];
for (int i = 0; i < indexes.length; i++) {
Integer integer = indexesList.get(i);
if (integer != null) indexes[i] = integer.intValue();
else indexes[i] = -1;
}
return indexes;
}
``` | ```
public int findSong(String searchtitle) {
String str;
int index = 0;
for(Song s : songs){
if(s.title.equalsIgnoreCase(searchtitle))
return index;
index++;
}
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | Try this code:
```
public int findSong(String title) {
int index = -1;
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) index = songs.indexOf(song);
}
// If you didn't know here we have if / else
// if index == -1 print song not found else print the index
System.out.println(index == -1 ? "Song not found: " + title : "Sound found at index " + index);
// If song isn't found index is -1
return index;
}
```
**EDIT:** Max Zoom said in comments
>
> How about the case where there is more then one song with given title?
>
>
>
Code:
```
public int[] findSong(String title) {
List<Integer> indexesList = new ArrayList<>();
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) indexesList.add(songs.indexOf(song));
}
// If we have no songs return empty array
if (indexesList.size() == 0) return new int[0];
// Convert list to int array
int[] indexes = new int[indexesList.size()];
for (int i = 0; i < indexes.length; i++) {
Integer integer = indexesList.get(i);
if (integer != null) indexes[i] = integer.intValue();
else indexes[i] = -1;
}
return indexes;
}
``` | ```
public int findSong(String title, List<Song> songs) {
for (Song song : songs) {
if (song == null || song.getTitle() == null) {
continue;
}
if (song.getTitle().equals(title)) {
int index = songs.indexOf(song);
System.out.println(index);
return index;
}
}
return -1;
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | Try this code:
```
public int findSong(String title) {
int index = -1;
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) index = songs.indexOf(song);
}
// If you didn't know here we have if / else
// if index == -1 print song not found else print the index
System.out.println(index == -1 ? "Song not found: " + title : "Sound found at index " + index);
// If song isn't found index is -1
return index;
}
```
**EDIT:** Max Zoom said in comments
>
> How about the case where there is more then one song with given title?
>
>
>
Code:
```
public int[] findSong(String title) {
List<Integer> indexesList = new ArrayList<>();
// Iterate over the elements of the list
for (Song song : songs) {
if (song.getTitle().equals(title)) indexesList.add(songs.indexOf(song));
}
// If we have no songs return empty array
if (indexesList.size() == 0) return new int[0];
// Convert list to int array
int[] indexes = new int[indexesList.size()];
for (int i = 0; i < indexes.length; i++) {
Integer integer = indexesList.get(i);
if (integer != null) indexes[i] = integer.intValue();
else indexes[i] = -1;
}
return indexes;
}
``` | ```
import java.util.ArrayList;
import java.util.List;
public class SongDriver
{
public static void main(String[] args)
{
Song song1 = new Song();
Song song2 = new Song();
Song song3 = new Song();
song1.setTitle("song1");
song2.setTitle("help");
song3.setTitle("song3");
List<Song> songs = new ArrayList<Song>();
songs.add(song1);
songs.add(song2);
songs.add(song3);
for (int i = 0; i < songs.size(); i++)
{
Song song = songs.get(i);
if (song.getTitle().equals("help"))
{
System.out.println("Help is found at index " + i);
}
}
}
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | ```
public int findSong(String title, List<Song> songs) {
for (Song song : songs) {
if (song == null || song.getTitle() == null) {
continue;
}
if (song.getTitle().equals(title)) {
int index = songs.indexOf(song);
System.out.println(index);
return index;
}
}
return -1;
}
``` | ```
public int findSong(String searchtitle) {
String str;
int index = 0;
for(Song s : songs){
if(s.title.equalsIgnoreCase(searchtitle))
return index;
index++;
}
}
``` |
30,491,617 | I am working on a project and currently working on one of the views which is a page of different categories. Everything is rendering correctly however it's also putting the db info in the page.
Here is the code of my view
```
<div class="categories">
<div class="container blurbs">
<div class="cards row">
<%= @categories.each do |c| %>
<div class="card col-xs-4" %>
<%= image_tag c.image, :class => "cat" %>
<h4 class="title"><%= c.title %></h4>
</div>
<% end %>
</div>
</div>
</div>
```
Here is a link to a
[screenshot of rendered page](https://sjconfections.tinytake.com/sf/MTcwOTAzXzEwODEzOTk) | 2015/05/27 | [
"https://Stackoverflow.com/questions/30491617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946228/"
] | ```
public int findSong(String title, List<Song> songs) {
for (Song song : songs) {
if (song == null || song.getTitle() == null) {
continue;
}
if (song.getTitle().equals(title)) {
int index = songs.indexOf(song);
System.out.println(index);
return index;
}
}
return -1;
}
``` | ```
import java.util.ArrayList;
import java.util.List;
public class SongDriver
{
public static void main(String[] args)
{
Song song1 = new Song();
Song song2 = new Song();
Song song3 = new Song();
song1.setTitle("song1");
song2.setTitle("help");
song3.setTitle("song3");
List<Song> songs = new ArrayList<Song>();
songs.add(song1);
songs.add(song2);
songs.add(song3);
for (int i = 0; i < songs.size(); i++)
{
Song song = songs.get(i);
if (song.getTitle().equals("help"))
{
System.out.println("Help is found at index " + i);
}
}
}
}
``` |
18,762,658 | I have created a "People you may know" script in php. I have 2 tables, **users(user\_id, name, surname, email, profile)** and table **friends(friends\_id, user\_one, user\_two)**. I use the following script in order to select people that are friends of my friends:
```
<?php
$friends_of_friends = mysql_query(" SELECT u.*
FROM (SELECT DISTINCT user_one as user_id
FROM friends
WHERE user_two IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
UNION DISTINCT
SELECT DISTINCT user_two
FROM friends
WHERE user_one IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
) f
JOIN users u
ON u.user_id = f.user_id ORDER BY `surname` ASC ");
while ($run_friends= mysql_fetch_assoc($friends_of_friends)) {
$friend_friend_id = $run_friends['user_id'];
// friends of my friends that are not my friends
$check_friend_query = mysql_query(" SELECT friends_id from friends WHERE (user_one='$session_user_id' AND user_two='$friend_friend_id') OR (user_one='$friend_friend_id' AND user_two='$session_user_id') ");
if(mysql_num_rows($check_friend_query) != 1){
$not_friends = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE (`user_id`='$friend_friend_id' and `user_id`!='$session_user_id') ");
while ($run_not_friends= mysql_fetch_assoc($not_friends)) {
$not_friend_id = $run_not_friends['user_id'];
}
}//end if
}//end while
?>
```
My code works succesfully. The only problem is that after I get all the people that I want using this script, I cannot count their number. I have used:
```
$num_of_people=mysql_num_rows($not_friends);
echo"$num_of_people";
```
I am always getting 1. Any idea how can I count this amount of people(friends of my friends that are not my friends). | 2013/09/12 | [
"https://Stackoverflow.com/questions/18762658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2491321/"
] | Make use of a **`counter variable`** here like this
```
$i=0; // I have added here
while ($run_friends= mysql_fetch_assoc($friends_of_friends)) {
$friend_friend_id = $run_friends['user_id'];
$i++;// Increment the var
}//end while
echo $i;//Total number of users
?>
``` | $num\_of\_people=mysql\_num\_rows($not\_friends);
echo"$num\_of\_people";
You are printing it wrong, that's a string not the variable.
* Try this way.
echo $num\_of\_people; |
18,762,658 | I have created a "People you may know" script in php. I have 2 tables, **users(user\_id, name, surname, email, profile)** and table **friends(friends\_id, user\_one, user\_two)**. I use the following script in order to select people that are friends of my friends:
```
<?php
$friends_of_friends = mysql_query(" SELECT u.*
FROM (SELECT DISTINCT user_one as user_id
FROM friends
WHERE user_two IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
UNION DISTINCT
SELECT DISTINCT user_two
FROM friends
WHERE user_one IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
) f
JOIN users u
ON u.user_id = f.user_id ORDER BY `surname` ASC ");
while ($run_friends= mysql_fetch_assoc($friends_of_friends)) {
$friend_friend_id = $run_friends['user_id'];
// friends of my friends that are not my friends
$check_friend_query = mysql_query(" SELECT friends_id from friends WHERE (user_one='$session_user_id' AND user_two='$friend_friend_id') OR (user_one='$friend_friend_id' AND user_two='$session_user_id') ");
if(mysql_num_rows($check_friend_query) != 1){
$not_friends = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE (`user_id`='$friend_friend_id' and `user_id`!='$session_user_id') ");
while ($run_not_friends= mysql_fetch_assoc($not_friends)) {
$not_friend_id = $run_not_friends['user_id'];
}
}//end if
}//end while
?>
```
My code works succesfully. The only problem is that after I get all the people that I want using this script, I cannot count their number. I have used:
```
$num_of_people=mysql_num_rows($not_friends);
echo"$num_of_people";
```
I am always getting 1. Any idea how can I count this amount of people(friends of my friends that are not my friends). | 2013/09/12 | [
"https://Stackoverflow.com/questions/18762658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2491321/"
] | Shankar Damodaran is right use this
```
$i=0;
while ($run_friends= mysql_fetch_assoc($friends_of_friends)) {
$friend_friend_id = $run_friends['user_id'];
// friends of my friends that are not my friends
$check_friend_query = mysql_query(" SELECT friends_id from friends WHERE (user_one='$session_user_id' AND user_two='$friend_friend_id') OR (user_one='$friend_friend_id' AND user_two='$session_user_id') ");
if(mysql_num_rows($check_friend_query) != 1){
$not_friends = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE (`user_id`='$friend_friend_id' and `user_id`!='$session_user_id') ");
if(mysql_num_rows($not_friends)) i++;
}//end if
}//end while
echo $i;
``` | $num\_of\_people=mysql\_num\_rows($not\_friends);
echo"$num\_of\_people";
You are printing it wrong, that's a string not the variable.
* Try this way.
echo $num\_of\_people; |
263,782 | I couldn't find any information on what's the minimum Salesforce license to grant a support person permissions to do Subscriber Support in the LMA.
Can someone please point me to such information? | 2019/05/27 | [
"https://salesforce.stackexchange.com/questions/263782",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/256/"
] | Try clicking on your scratch org name( you have greyed it out) in the bottom bar and then selecting it as default. Or you can run `sfdx force:config:set defaultusername=Org_Alias` command from CLI or any script you are using. I face this issue everytime i create a new scratch org(4-5 times per day) and I always have to do this step. I believe it's an issue with VS code/SF cli which is unable to recognize the org as default. | For me it was because the Salesforce org I was logged in did not have the DevHub features enabled (under Setup/Development/Dev Hub) and also because I was (wrongly) using a DevHub which has a namespace assigned - so impossible to create Scratch Orgs.
You need to create a separate org for that - follow [this link](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_reg_namespace.htm) for a description. |
263,782 | I couldn't find any information on what's the minimum Salesforce license to grant a support person permissions to do Subscriber Support in the LMA.
Can someone please point me to such information? | 2019/05/27 | [
"https://salesforce.stackexchange.com/questions/263782",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/256/"
] | For me it was because the Salesforce org I was logged in did not have the DevHub features enabled (under Setup/Development/Dev Hub) and also because I was (wrongly) using a DevHub which has a namespace assigned - so impossible to create Scratch Orgs.
You need to create a separate org for that - follow [this link](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_reg_namespace.htm) for a description. | Reauthorizing my DevHub helped in my case. |
263,782 | I couldn't find any information on what's the minimum Salesforce license to grant a support person permissions to do Subscriber Support in the LMA.
Can someone please point me to such information? | 2019/05/27 | [
"https://salesforce.stackexchange.com/questions/263782",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/256/"
] | Try clicking on your scratch org name( you have greyed it out) in the bottom bar and then selecting it as default. Or you can run `sfdx force:config:set defaultusername=Org_Alias` command from CLI or any script you are using. I face this issue everytime i create a new scratch org(4-5 times per day) and I always have to do this step. I believe it's an issue with VS code/SF cli which is unable to recognize the org as default. | Reauthorizing my DevHub helped in my case. |
35,526,773 | I am using Butter Knife in my project along with the Material Design Libraries for the UI.
When attempting to create buttons using the Material Design Library i get a 'Class Cast Exception' because of the usage of Butter Knife.
Is there a way to fix this?
MainActivity.Java
```
@Bind(R.id.switch1) Switch switch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ButterKnife.bind(this);
}
```
XML Switch Layout
```
<com.gc.materialdesign.views.Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/switch1"
android:layout_centerHorizontal="true" />
```
Errors
```
Caused by: java.lang.RuntimeException: Unable to bind views for com.example.MainActivty
Caused by: java.lang.ClassCastException:com.gc.materialdesign.views.Switch cannot be cast to android.widget.Switch
``` | 2016/02/20 | [
"https://Stackoverflow.com/questions/35526773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5401668/"
] | You are importing the wrong `Switch` - instead of importing `android.widget.Switch`, you need to import `com.gc.materialdesign.views.Switch` and use that class when defining your `switch` variable. | Remove the line
```
import android.widget.Switch;
```
and replace it with
```
import com.gc.materialdesign.views.Switch;
```
You've simply chosen to import the wrong `Switch` class. |
58,509,682 | When running spring-boot 2.2.0 in debug mode in both Eclipse 2019-06 and IntelliJ 2019.2, attempts to terminate the process via the IDE look like they kill the process (per the IDE), however, the java process is still running (verified by ps -ef | grep java).
When running non debug mode in Eclipse, the process can be terminated but Eclipse displays a message stating "terminate failed".
I've tried all sorts of older post options including:
-Dspring-boot:run.fork=false
-Dfork=false
Running spring at cmd line using mvn spring-boot:run terminates normally with ctrl-c.
I'm not using any spring plugins in Eclipse. I'm using open jdk 11.0.3+7.
Everything worked normally in spring-boot 2.1.7, 2.1.8 and 2.1.9
Is this possibly a bug in spring-boot 2.2.0? | 2019/10/22 | [
"https://Stackoverflow.com/questions/58509682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12258871/"
] | With Spring Boot v2.2.0.RELEASE, JVM process forking is enabled by default when starting from the maven plugin:
<https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.2-Release-Notes#fork-enabled-by-default-in-maven-plugin>
At this time, Intellij's maven plugin in 2019.2 and earlier versions don't appear to associate the child process to the debugging session and the IDE is even unable to shutdown the process once started.
None of the solutions in the references below worked for me. The only way I found to disable forking was to set the flag directly in the spring-boot-maven-plugin in the pom.xml like so:
```
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- disable process forking that is enabled by default in spring-boot 2.2.0.RELEASE and higher -->
<fork>false</fork>
</configuration>
</plugin>
```
Afterward, I can now right-click on spring-boot:run, select debug, and the debugger connects to the right child process.
Additional references:
<https://github.com/spring-projects/spring-boot/issues/18638>
<https://github.com/spring-projects/spring-boot/issues/18706> | I had the same problem when I moved to 2.2.0 (+ JDK 11).
As @guidadic said : since 2.2.0, the JVM is forked by default.
Unfortunately for me, if I disable forking, I lose some features, like colour in the console, which worked before with no fork. In addition, forking allows to use DevTools, with live reloading, which is pretty interesting.
After a long and hazardous search on Internet, I found out a solution on a non related Stackoverflow answer somewhere (I lost the link).
In your main method, get your application context from the run method, and then open a console scanner.
When you will press the red square to kill your app in Eclipse, the scanner throws an exception : the Eclipse managed (visible) thread is the one linked to the console, so the scanner doesn't like that you dare to stop it.
You just need to catch it to exit from the application :
```
log.info("Press 'Enter' to terminate");
try (Scanner scanner = new Scanner(System.in)) {
scanner.nextLine();
}
finally {
log.info("Exiting");
System.exit(SpringApplication.exit(context));
}
```
Additionally, if you press 'enter' in your Eclipse console, it will exit your application and terminate all the application JVMs. |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Now $$\tan\frac{\pi}{3}=\frac{\sin\frac{\pi}{3}}{\cos\frac{\pi}{3}}=\frac{\cos\frac{\pi}{6}}{\sin \frac{\pi}{6}}=\frac{\cos \frac{\pi}{6}}{\sqrt{1-\cos^2\frac{\pi}{6}}}=\frac{\frac{\sqrt{3}}{2}}{\sqrt{1-\frac{3}{4}}}=\frac{\sqrt{3}}{2}\cdot \frac{1}{\sqrt{\frac{1}{4}}}=\sqrt{3}$$ | \begin{align}
&\color{red}{\tan\left(\frac\pi3\right)}=\frac{\sin\left(\frac\pi3\right)}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\cos^2\left(\frac\pi3\right)}}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\left(2\color{blue}{\cos\left(\frac\pi6\right)}^2-1\right)^2}}{2\color{blue}{\cos\left(\frac\pi6\right)}^2-1}\\
&=\frac{\sqrt{1-\left(2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1\right)^2}}{2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1}=\frac{\sqrt{1-\left(2\frac34-1\right)^2}}{2\frac34-1}=\frac{\sqrt{1-\left(\frac12\right)^2}}{\frac12}\\
&=\frac{\sqrt{\frac34}}{\frac12}=\frac{\frac12\sqrt3}{\frac12}=\color{red}{\sqrt 3}
\end{align}
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
> |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Upto the sign, you can calculate the tan-value as $$\tan(x)=\frac{\sqrt{1-\cos^2(x)}}{\cos(x)}$$
Also note $$\cos(2x)=2\cos^2(x)-1$$ which allows you to calculate $\cos(\frac{\pi}{3})$ from $\cos(\frac{\pi}{6})$ | \begin{align}
&\color{red}{\tan\left(\frac\pi3\right)}=\frac{\sin\left(\frac\pi3\right)}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\cos^2\left(\frac\pi3\right)}}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\left(2\color{blue}{\cos\left(\frac\pi6\right)}^2-1\right)^2}}{2\color{blue}{\cos\left(\frac\pi6\right)}^2-1}\\
&=\frac{\sqrt{1-\left(2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1\right)^2}}{2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1}=\frac{\sqrt{1-\left(2\frac34-1\right)^2}}{2\frac34-1}=\frac{\sqrt{1-\left(\frac12\right)^2}}{\frac12}\\
&=\frac{\sqrt{\frac34}}{\frac12}=\frac{\frac12\sqrt3}{\frac12}=\color{red}{\sqrt 3}
\end{align}
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
> |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Now $$\tan\frac{\pi}{3}=\frac{\sin\frac{\pi}{3}}{\cos\frac{\pi}{3}}=\frac{\cos\frac{\pi}{6}}{\sin \frac{\pi}{6}}=\frac{\cos \frac{\pi}{6}}{\sqrt{1-\cos^2\frac{\pi}{6}}}=\frac{\frac{\sqrt{3}}{2}}{\sqrt{1-\frac{3}{4}}}=\frac{\sqrt{3}}{2}\cdot \frac{1}{\sqrt{\frac{1}{4}}}=\sqrt{3}$$ | $\sin(\pi/3) = \sqrt 3/2,$ and $\cos(\pi/3) = 1/2$.
Therefore, $$\tan(\pi/3) = \dfrac{\sin\left(\frac \pi 3\right)}{\cos\left(\frac \pi 3\right)} = \dfrac {\dfrac{\sqrt 3}2}{\dfrac 12}=\sqrt 3$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Just to use another elementary way, which shows all the passages:
$$\cos(60) = \cos(30+30) = \cos(30)\cos(30) - \sin(30)\sin(30)$$
The value of $\cos(30)$ you know it.
The value of $\sin(30)$ is derived from $\cos^2 + \sin^2 = 1$.
Again, once you found $\cos(60)$ you get the value of $\sin(60)$ for free.
Now you can find $\tan(60)$. | Assume $x = \frac\pi6$, thus $\frac\pi3 = 2x$
$$\tan\left(2x\right) = \frac{\sin\left(2x\right)}{\cos\left(2x\right)} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1}$$
Since, $\cos\left(x\right)=\cos\left(\frac\pi6\right)=\frac{\sqrt 3}2$, substituting that on above equation, you'd get:
$$\tan\left(2x\right) = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\frac 34\right)}\left(\frac{\sqrt{3}}2\right)}{2\times \frac 34-1} = \sqrt{3}$$
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
>
Trigonometric Identities used are:
$$\sin\left(2x\right) = 2\sin\left(x\right)\cos\left(x\right)$$
$$\cos\left(2x\right) = 2\cos^2\left(x\right)-1$$
$$\cos^2\left(x\right)+\sin^2\left(x\right)=1$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Upto the sign, you can calculate the tan-value as $$\tan(x)=\frac{\sqrt{1-\cos^2(x)}}{\cos(x)}$$
Also note $$\cos(2x)=2\cos^2(x)-1$$ which allows you to calculate $\cos(\frac{\pi}{3})$ from $\cos(\frac{\pi}{6})$ | $\sin(\pi/3) = \sqrt 3/2,$ and $\cos(\pi/3) = 1/2$.
Therefore, $$\tan(\pi/3) = \dfrac{\sin\left(\frac \pi 3\right)}{\cos\left(\frac \pi 3\right)} = \dfrac {\dfrac{\sqrt 3}2}{\dfrac 12}=\sqrt 3$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | \begin{align}
&\color{red}{\tan\left(\frac\pi3\right)}=\frac{\sin\left(\frac\pi3\right)}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\cos^2\left(\frac\pi3\right)}}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\left(2\color{blue}{\cos\left(\frac\pi6\right)}^2-1\right)^2}}{2\color{blue}{\cos\left(\frac\pi6\right)}^2-1}\\
&=\frac{\sqrt{1-\left(2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1\right)^2}}{2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1}=\frac{\sqrt{1-\left(2\frac34-1\right)^2}}{2\frac34-1}=\frac{\sqrt{1-\left(\frac12\right)^2}}{\frac12}\\
&=\frac{\sqrt{\frac34}}{\frac12}=\frac{\frac12\sqrt3}{\frac12}=\color{red}{\sqrt 3}
\end{align}
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
> | $\sin(\pi/3) = \sqrt 3/2,$ and $\cos(\pi/3) = 1/2$.
Therefore, $$\tan(\pi/3) = \dfrac{\sin\left(\frac \pi 3\right)}{\cos\left(\frac \pi 3\right)} = \dfrac {\dfrac{\sqrt 3}2}{\dfrac 12}=\sqrt 3$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Now $$\tan\frac{\pi}{3}=\frac{\sin\frac{\pi}{3}}{\cos\frac{\pi}{3}}=\frac{\cos\frac{\pi}{6}}{\sin \frac{\pi}{6}}=\frac{\cos \frac{\pi}{6}}{\sqrt{1-\cos^2\frac{\pi}{6}}}=\frac{\frac{\sqrt{3}}{2}}{\sqrt{1-\frac{3}{4}}}=\frac{\sqrt{3}}{2}\cdot \frac{1}{\sqrt{\frac{1}{4}}}=\sqrt{3}$$ | Just to use another elementary way, which shows all the passages:
$$\cos(60) = \cos(30+30) = \cos(30)\cos(30) - \sin(30)\sin(30)$$
The value of $\cos(30)$ you know it.
The value of $\sin(30)$ is derived from $\cos^2 + \sin^2 = 1$.
Again, once you found $\cos(60)$ you get the value of $\sin(60)$ for free.
Now you can find $\tan(60)$. |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Just to use another elementary way, which shows all the passages:
$$\cos(60) = \cos(30+30) = \cos(30)\cos(30) - \sin(30)\sin(30)$$
The value of $\cos(30)$ you know it.
The value of $\sin(30)$ is derived from $\cos^2 + \sin^2 = 1$.
Again, once you found $\cos(60)$ you get the value of $\sin(60)$ for free.
Now you can find $\tan(60)$. | $\sin(\pi/3) = \sqrt 3/2,$ and $\cos(\pi/3) = 1/2$.
Therefore, $$\tan(\pi/3) = \dfrac{\sin\left(\frac \pi 3\right)}{\cos\left(\frac \pi 3\right)} = \dfrac {\dfrac{\sqrt 3}2}{\dfrac 12}=\sqrt 3$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | Now $$\tan\frac{\pi}{3}=\frac{\sin\frac{\pi}{3}}{\cos\frac{\pi}{3}}=\frac{\cos\frac{\pi}{6}}{\sin \frac{\pi}{6}}=\frac{\cos \frac{\pi}{6}}{\sqrt{1-\cos^2\frac{\pi}{6}}}=\frac{\frac{\sqrt{3}}{2}}{\sqrt{1-\frac{3}{4}}}=\frac{\sqrt{3}}{2}\cdot \frac{1}{\sqrt{\frac{1}{4}}}=\sqrt{3}$$ | Assume $x = \frac\pi6$, thus $\frac\pi3 = 2x$
$$\tan\left(2x\right) = \frac{\sin\left(2x\right)}{\cos\left(2x\right)} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1}$$
Since, $\cos\left(x\right)=\cos\left(\frac\pi6\right)=\frac{\sqrt 3}2$, substituting that on above equation, you'd get:
$$\tan\left(2x\right) = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\frac 34\right)}\left(\frac{\sqrt{3}}2\right)}{2\times \frac 34-1} = \sqrt{3}$$
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
>
Trigonometric Identities used are:
$$\sin\left(2x\right) = 2\sin\left(x\right)\cos\left(x\right)$$
$$\cos\left(2x\right) = 2\cos^2\left(x\right)-1$$
$$\cos^2\left(x\right)+\sin^2\left(x\right)=1$$ |
3,079,899 | Given $\cos30 = \frac{\sqrt3}{2}$ use trigonometric identities to find the exact value of $\tan\frac{\pi}{3}$
I understand that $\cos30 = \frac{\sqrt3}{2}$ from the standard trig values chart and I know that $\frac{\pi}{3}$ is 60 degrees and I know the value of it from the same chart. I'm not understanding how to use identities to find the value. | 2019/01/19 | [
"https://math.stackexchange.com/questions/3079899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/110755/"
] | \begin{align}
&\color{red}{\tan\left(\frac\pi3\right)}=\frac{\sin\left(\frac\pi3\right)}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\cos^2\left(\frac\pi3\right)}}{\cos\left(\frac\pi3\right)}=\frac{\sqrt{1-\left(2\color{blue}{\cos\left(\frac\pi6\right)}^2-1\right)^2}}{2\color{blue}{\cos\left(\frac\pi6\right)}^2-1}\\
&=\frac{\sqrt{1-\left(2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1\right)^2}}{2\left(\color{blue}{\frac{\sqrt 3}2}\right)^2-1}=\frac{\sqrt{1-\left(2\frac34-1\right)^2}}{2\frac34-1}=\frac{\sqrt{1-\left(\frac12\right)^2}}{\frac12}\\
&=\frac{\sqrt{\frac34}}{\frac12}=\frac{\frac12\sqrt3}{\frac12}=\color{red}{\sqrt 3}
\end{align}
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
> | Assume $x = \frac\pi6$, thus $\frac\pi3 = 2x$
$$\tan\left(2x\right) = \frac{\sin\left(2x\right)}{\cos\left(2x\right)} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sin\left(x\right)\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1}$$
Since, $\cos\left(x\right)=\cos\left(\frac\pi6\right)=\frac{\sqrt 3}2$, substituting that on above equation, you'd get:
$$\tan\left(2x\right) = \frac{2\sqrt{\left(1-\cos^2\left(x\right)\right)}\cos\left(x\right)}{2\cos^2\left(x\right)-1} = \frac{2\sqrt{\left(1-\frac 34\right)}\left(\frac{\sqrt{3}}2\right)}{2\times \frac 34-1} = \sqrt{3}$$
>
> $$\therefore~\tan\left(\frac\pi3\right)=\sqrt3$$
>
>
>
Trigonometric Identities used are:
$$\sin\left(2x\right) = 2\sin\left(x\right)\cos\left(x\right)$$
$$\cos\left(2x\right) = 2\cos^2\left(x\right)-1$$
$$\cos^2\left(x\right)+\sin^2\left(x\right)=1$$ |
15,461,908 | I wrote a small log-in java program that works with servlets, and JSPs using the MVC pattern that allows me to register and log-in accounts(if we can call them that) to my local mySQL DataBase. I am using sessions to pass values between the servlet and the JSP, and I have a list of if statements on the servlet that work as validation for invalid inputs. Right now when my application is executed this happens:
* Sign\_Up.jsp opens up and displays UserName and Password fields with a submit button below it. Also it shows a link on the top left corner to the Log\_In.jsp. If you enter an username and password that follows requirements, an account is created on the database, and you are redirected to the Welcome.JSP which only shows a few lines of text. (I am not checking weather the password and username entered are unique atm, so there are duplication entries in the user table on the DB)
* If you click on the link at the top of the Sign\_UP.jsp, then you are redirected to the Log\_In.jsp. Here you are required to enter your credentials, if they exist on the database you are redirected to the Welcome.jsp , otherwise you are told that they are invalid and that you need to enter them again.
-----------------------------------THIS IS WHAT I WOULD LIKE TO DO NOW--------------------------------------
Once an account is validated and redirected to the Welcome.jsp I would like that page to show a button that says "Choose File", which when clicked will allow you to browse your computer for files. From there I should be able to select a .csv file that I can parse and enter into the database. Maybe the .csv will contain something as simple as:
```
Username , Password
UserTest1, 123
UserTest2, 234
UserTest3, 567
UserTest4, 890
```
So these are my questions regarding this whole procedure:
* Is it possible to use JS inside a JSP to accomplish my task?
* Is it a good idea to use JS inside a JSP to do it?
* If I were to built a more complex website is it recommended to build it using html,css and jQuery code inside the JSP?
The whole idea is to build a a website that allows the admin ONLY to enter a .csv file containing a list of prices for items, that will be grabbed by the website and uploaded into the database, which in return will show a new stock of items for a certain product. I know that I am far from done, but this is just a start. :) | 2013/03/17 | [
"https://Stackoverflow.com/questions/15461908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565919/"
] | 1. You don't need JavaScript to upload a file
2. I don't see how it would help. Just use a input of type file
3. You can of course use JavaScript, whatever you use at server-side to generate the HTML pages. Embedding JavaScript code inside HTML pages is a bad practice though. You should try to externalize the JS code to .js files as much as possible.
Just a few notes regarding the title and body of your question:
* reading a CSV file is the job of the controller, not the job of the view
* using the session to pass objects from a servlet controller to a view is not what you should do. You should use the request to do that. | You can't read files with JS because it doesn't have permission to access the filesystem.
You will have to upload the file into the server and get the parsing done from there.
There are tons of examples for JSP file uploading in the net.
Most complex websites employ the technologies/libraries you have listed so the answer is yes use them and it will increase usability and look and feel. |
193,115 | Can I provide two plots made using two different softwares in a scientific paper? For example, one is plotted using Origin and another is plotted using Python? | 2023/02/02 | [
"https://academia.stackexchange.com/questions/193115",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/165354/"
] | It is not unusual to have plots created with different software if they are used to display different kind of data. But I would not plot the same kind of data in the same paper once with one software and once with another (unless there is a very convincing reason to do so, in case the reason should also be provided). | **Q:** Can I provide two plots made using two different softwares in a scientific paper?
**A:** Unless a publisher (and their review process) tells you otherwise, you can do whatever you want for figures.
Ideally, the plots in your paper will be consistent formatting with each other (e.g., same tick styles, label fonts).
Personally, I have seen papers where plots come from different programs, and I could tell because the figures mismatched each other with style.
As long as the formatting of the plots does not distract from the science you are presenting, I would not be worried about the format.
*Thus, I think consistent and readable formatting is more important that the program used for your plots.
I would encourage you to focus on your plotting skills rather than the program used to create your plots.* |
193,115 | Can I provide two plots made using two different softwares in a scientific paper? For example, one is plotted using Origin and another is plotted using Python? | 2023/02/02 | [
"https://academia.stackexchange.com/questions/193115",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/165354/"
] | It is not unusual to have plots created with different software if they are used to display different kind of data. But I would not plot the same kind of data in the same paper once with one software and once with another (unless there is a very convincing reason to do so, in case the reason should also be provided). | Using different applications for different plots is not uncommon, especially when there are collaborations among different groups which are accustomed to different applications.
For instance, I have a number of papers published with various groups across the world. I'm used to plotting graphs by using the workflow Matlab->matlab2tikz, whereas other coauthors of mine are more confident with Origin. For diagrams, I usually work with Inkscape, but other groups may have other preferences.
Most of the time, we didn't have any issue, but there have been rare occasions in which a reviewer (you know, that reviewer #2, the nitpicking one) asked us to make the diagrams more uniform across a paper. This request was typically not referred to plots but to circuit diagrams, and it was more related to the symbols used rather than the software used, but indeed it's easier to guarantee uniformity when the same software is used (in cases like this one, when I'm the first author, I usually volunteer to redraw everything in a uniform way with the same software). |
193,115 | Can I provide two plots made using two different softwares in a scientific paper? For example, one is plotted using Origin and another is plotted using Python? | 2023/02/02 | [
"https://academia.stackexchange.com/questions/193115",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/165354/"
] | It is not unusual to have plots created with different software if they are used to display different kind of data. But I would not plot the same kind of data in the same paper once with one software and once with another (unless there is a very convincing reason to do so, in case the reason should also be provided). | It will depend on how the journal operates. Many journals will be able to accept images you create. Others will want the data for a graph to typeset it themselves. Others will accept images sometimes for some types of figures, and want to plot the data themselves for others. For images, there will be image file formats they can accept, and others they cannot. They will also have opinions on what format and resolution looks best.
Also, these things may change over time. A journal that acquires new publishing software may find that new sets of restrictions exist.
Contact the journal to find out what they can deal with, and what restrictions there are. They probably have a standard response for such questions, because they probably get it frequently. |
193,115 | Can I provide two plots made using two different softwares in a scientific paper? For example, one is plotted using Origin and another is plotted using Python? | 2023/02/02 | [
"https://academia.stackexchange.com/questions/193115",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/165354/"
] | Using different applications for different plots is not uncommon, especially when there are collaborations among different groups which are accustomed to different applications.
For instance, I have a number of papers published with various groups across the world. I'm used to plotting graphs by using the workflow Matlab->matlab2tikz, whereas other coauthors of mine are more confident with Origin. For diagrams, I usually work with Inkscape, but other groups may have other preferences.
Most of the time, we didn't have any issue, but there have been rare occasions in which a reviewer (you know, that reviewer #2, the nitpicking one) asked us to make the diagrams more uniform across a paper. This request was typically not referred to plots but to circuit diagrams, and it was more related to the symbols used rather than the software used, but indeed it's easier to guarantee uniformity when the same software is used (in cases like this one, when I'm the first author, I usually volunteer to redraw everything in a uniform way with the same software). | **Q:** Can I provide two plots made using two different softwares in a scientific paper?
**A:** Unless a publisher (and their review process) tells you otherwise, you can do whatever you want for figures.
Ideally, the plots in your paper will be consistent formatting with each other (e.g., same tick styles, label fonts).
Personally, I have seen papers where plots come from different programs, and I could tell because the figures mismatched each other with style.
As long as the formatting of the plots does not distract from the science you are presenting, I would not be worried about the format.
*Thus, I think consistent and readable formatting is more important that the program used for your plots.
I would encourage you to focus on your plotting skills rather than the program used to create your plots.* |
193,115 | Can I provide two plots made using two different softwares in a scientific paper? For example, one is plotted using Origin and another is plotted using Python? | 2023/02/02 | [
"https://academia.stackexchange.com/questions/193115",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/165354/"
] | Using different applications for different plots is not uncommon, especially when there are collaborations among different groups which are accustomed to different applications.
For instance, I have a number of papers published with various groups across the world. I'm used to plotting graphs by using the workflow Matlab->matlab2tikz, whereas other coauthors of mine are more confident with Origin. For diagrams, I usually work with Inkscape, but other groups may have other preferences.
Most of the time, we didn't have any issue, but there have been rare occasions in which a reviewer (you know, that reviewer #2, the nitpicking one) asked us to make the diagrams more uniform across a paper. This request was typically not referred to plots but to circuit diagrams, and it was more related to the symbols used rather than the software used, but indeed it's easier to guarantee uniformity when the same software is used (in cases like this one, when I'm the first author, I usually volunteer to redraw everything in a uniform way with the same software). | It will depend on how the journal operates. Many journals will be able to accept images you create. Others will want the data for a graph to typeset it themselves. Others will accept images sometimes for some types of figures, and want to plot the data themselves for others. For images, there will be image file formats they can accept, and others they cannot. They will also have opinions on what format and resolution looks best.
Also, these things may change over time. A journal that acquires new publishing software may find that new sets of restrictions exist.
Contact the journal to find out what they can deal with, and what restrictions there are. They probably have a standard response for such questions, because they probably get it frequently. |
25,261,647 | Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from `C#`, which is encrypted with the `System.Security.Cryptography` reference.
**UPDATE**
I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't.
I've also can't install because it latest version is `3.3` while my version is `3.4`. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25261647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902480/"
] | The available Cryptographic Services available in the Standard Library are [those](https://docs.python.org/3.4/library/crypto.html). As you can see `AES` is not listed, but is suggest to use [`pycrypto`](https://pypi.python.org/pypi/pycrypto) which is an *extra module*.
You just have to install it using *pip*, or *easy\_install* and then as showed in *pycrypto*'s page:
```
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
print obj.encrypt(message)
```
The only other way without using an extra module would be to code the function yourself, but what's the difference of downloading an extra module and use that instead?
If you want a pure Python implementation of AES that you can download and import check [pyaes](https://pypi.python.org/pypi/pyaes). | Python 3.6 with cryptography module
```
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"my deep dark secret")
print(token)
f.decrypt(token)
``` |
25,261,647 | Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from `C#`, which is encrypted with the `System.Security.Cryptography` reference.
**UPDATE**
I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't.
I've also can't install because it latest version is `3.3` while my version is `3.4`. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25261647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902480/"
] | I'm using [Cryptography](https://cryptography.io/en/latest/#) library.
>
> Cryptography is an actively developed library that provides
> cryptographic recipes and primitives. It supports Python 2.6-2.7,
> Python 3.3+ and PyPy.
>
>
>
[Here is an example](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/?highlight=aes) of how to use that library:
```
>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'
``` | [Here is a self-contained implementation of AES compatible with Python 3](http://uthcode.googlecode.com/svn-history/r678/trunk/python/py3AES.py).
Example usage:
```
aesmodal = AESModeOfOperation()
key = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]
size = aesmodal.aes.keySize["SIZE_128"]
mode,orig_len,ciphertext = aesmodal.encrypt("Hello, world!", aesmodal.modeOfOperation["OFB"], key, size, iv)
print(ciphertext)
plaintext = aesmodal.decrypt(ciphertext, orig_len, mode, key, size, iv)
print(plaintext)
``` |
25,261,647 | Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from `C#`, which is encrypted with the `System.Security.Cryptography` reference.
**UPDATE**
I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't.
I've also can't install because it latest version is `3.3` while my version is `3.4`. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25261647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902480/"
] | The available Cryptographic Services available in the Standard Library are [those](https://docs.python.org/3.4/library/crypto.html). As you can see `AES` is not listed, but is suggest to use [`pycrypto`](https://pypi.python.org/pypi/pycrypto) which is an *extra module*.
You just have to install it using *pip*, or *easy\_install* and then as showed in *pycrypto*'s page:
```
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
print obj.encrypt(message)
```
The only other way without using an extra module would be to code the function yourself, but what's the difference of downloading an extra module and use that instead?
If you want a pure Python implementation of AES that you can download and import check [pyaes](https://pypi.python.org/pypi/pyaes). | [Here is a self-contained implementation of AES compatible with Python 3](http://uthcode.googlecode.com/svn-history/r678/trunk/python/py3AES.py).
Example usage:
```
aesmodal = AESModeOfOperation()
key = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]
size = aesmodal.aes.keySize["SIZE_128"]
mode,orig_len,ciphertext = aesmodal.encrypt("Hello, world!", aesmodal.modeOfOperation["OFB"], key, size, iv)
print(ciphertext)
plaintext = aesmodal.decrypt(ciphertext, orig_len, mode, key, size, iv)
print(plaintext)
``` |
25,261,647 | Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from `C#`, which is encrypted with the `System.Security.Cryptography` reference.
**UPDATE**
I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't.
I've also can't install because it latest version is `3.3` while my version is `3.4`. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25261647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902480/"
] | I'm using [Cryptography](https://cryptography.io/en/latest/#) library.
>
> Cryptography is an actively developed library that provides
> cryptographic recipes and primitives. It supports Python 2.6-2.7,
> Python 3.3+ and PyPy.
>
>
>
[Here is an example](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/?highlight=aes) of how to use that library:
```
>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'
``` | Python 3.6 with cryptography module
```
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"my deep dark secret")
print(token)
f.decrypt(token)
``` |
25,261,647 | Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from `C#`, which is encrypted with the `System.Security.Cryptography` reference.
**UPDATE**
I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't.
I've also can't install because it latest version is `3.3` while my version is `3.4`. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25261647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902480/"
] | PYAES should work with any version of Python3.x. No need to modify the library.
Here is a complete working example for pyaes CTR mode for Python3.x
(<https://github.com/ricmoo/pyaes>)
```
import pyaes
# A 256 bit (32 byte) key
key = "This_key_for_demo_purposes_only!"
plaintext = "Text may be any length you wish, no padding is required"
# key must be bytes, so we convert it
key = key.encode('utf-8')
aes = pyaes.AESModeOfOperationCTR(key)
ciphertext = aes.encrypt(plaintext)
# show the encrypted data
print (ciphertext)
# DECRYPTION
# CRT mode decryption requires a new instance be created
aes = pyaes.AESModeOfOperationCTR(key)
# decrypted data is always binary, need to decode to plaintext
decrypted = aes.decrypt(ciphertext).decode('utf-8')
# True
print (decrypted == plaintext)
```
Let me know if you get any errors | The available Cryptographic Services available in the Standard Library are [those](https://docs.python.org/3.4/library/crypto.html). As you can see `AES` is not listed, but is suggest to use [`pycrypto`](https://pypi.python.org/pypi/pycrypto) which is an *extra module*.
You just have to install it using *pip*, or *easy\_install* and then as showed in *pycrypto*'s page:
```
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
print obj.encrypt(message)
```
The only other way without using an extra module would be to code the function yourself, but what's the difference of downloading an extra module and use that instead?
If you want a pure Python implementation of AES that you can download and import check [pyaes](https://pypi.python.org/pypi/pyaes). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.