qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
233,574 | I'm moving a couple of servers to a colo and was wondering what you would recommend for a hardware firewall to sit in front of them? Is it fine to just get the cheapest Cisco/Fortigate/Juniper/whatever firewall? I don't need anything fancy, pretty much just port forwarding. | 2011/02/09 | [
"https://serverfault.com/questions/233574",
"https://serverfault.com",
"https://serverfault.com/users/546/"
] | I would not get the cheapest firewall. You need to look at your requirements such as throughput, active connections, security, vpn requirements and more. If it needs to be cheap I would recommend setting up a separate linux box as the firewall using iptables. If there is budget for a firewall but you need something small consider the cisco asa 5505(smaller than 1U), or if you need something with more requirements consider the 5510 or 5520 which are rack mountable. The cisco firewalls have a gui interface and after initial setup can be relatively easy to manage. | You are probably looking at "wasting" at least 1U of rack space for this firewall.
I would not buy a consumer-grade cheapie firewall.
The Juniper Netscreen SSG5 would probably meet your needs, but it is a paperback size format and doesn't come with rack arms (that I recall). The first "rackable" SSG is the SSG140, but that's not quite so cheap -- definitely overkill for your application here.
If you can figure out a way to mount it neatly, the SSG5 would almost certainly be sufficient. |
233,574 | I'm moving a couple of servers to a colo and was wondering what you would recommend for a hardware firewall to sit in front of them? Is it fine to just get the cheapest Cisco/Fortigate/Juniper/whatever firewall? I don't need anything fancy, pretty much just port forwarding. | 2011/02/09 | [
"https://serverfault.com/questions/233574",
"https://serverfault.com",
"https://serverfault.com/users/546/"
] | I would not get the cheapest firewall. You need to look at your requirements such as throughput, active connections, security, vpn requirements and more. If it needs to be cheap I would recommend setting up a separate linux box as the firewall using iptables. If there is budget for a firewall but you need something small consider the cisco asa 5505(smaller than 1U), or if you need something with more requirements consider the 5510 or 5520 which are rack mountable. The cisco firewalls have a gui interface and after initial setup can be relatively easy to manage. | Alternatively - get a Mikrotik RB1100 and see how far it lasts (50mbit for smallish packets was on the table by someone running game servers).
It is CHEAP and has a TON of features in RouterOS. Uses very little power, too.
Then later you can upgrade to something more powerfull if needed. Again, the RB1100 is CHEAP to start with. |
233,574 | I'm moving a couple of servers to a colo and was wondering what you would recommend for a hardware firewall to sit in front of them? Is it fine to just get the cheapest Cisco/Fortigate/Juniper/whatever firewall? I don't need anything fancy, pretty much just port forwarding. | 2011/02/09 | [
"https://serverfault.com/questions/233574",
"https://serverfault.com",
"https://serverfault.com/users/546/"
] | You are probably looking at "wasting" at least 1U of rack space for this firewall.
I would not buy a consumer-grade cheapie firewall.
The Juniper Netscreen SSG5 would probably meet your needs, but it is a paperback size format and doesn't come with rack arms (that I recall). The first "rackable" SSG is the SSG140, but that's not quite so cheap -- definitely overkill for your application here.
If you can figure out a way to mount it neatly, the SSG5 would almost certainly be sufficient. | Alternatively - get a Mikrotik RB1100 and see how far it lasts (50mbit for smallish packets was on the table by someone running game servers).
It is CHEAP and has a TON of features in RouterOS. Uses very little power, too.
Then later you can upgrade to something more powerfull if needed. Again, the RB1100 is CHEAP to start with. |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | This outputs your version:
```
System.Environment.Version.ToString()
``` | [Environment.Version](http://msdn2.microsoft.com/en-us/library/system.environment.version) |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | This outputs your version:
```
System.Environment.Version.ToString()
``` | ```
<%@ Page language="C#" %>
<% Response.Write(".NET Framework Version: " + Environment.Version.ToString()); %>
``` |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | This outputs your version:
```
System.Environment.Version.ToString()
``` | ### Enable Trace
Enabling Trace is another option view every details of rendered page, including .NET Version
Add **Trace="true"** in page directive
```
<%@ Page Trace="true" %>
```
Scroll down to bottom and you will see rendered .NET Version |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | This outputs your version:
```
System.Environment.Version.ToString()
``` | Actually, you all got the CLR version (but not really either, you actually get a string that is hard-coded in mscorlib.dll).
For the actual ASP.NET version, as you see it on the YSOD error pages, see here (they are NOT the same):
```
using System;
namespace MyElmahReplacement
{
public class MyVersionInfo
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(string strModuleName);
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int GetModuleFileName(IntPtr ptrHmodule, System.Text.StringBuilder strFileName, int szeSize);
private static string GetFileNameFromLoadedModule(string strModuleName)
{
IntPtr hModule = GetModuleHandle(strModuleName);
if (hModule == IntPtr.Zero)
{
return null;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
if (GetModuleFileName(hModule, sb, 256) == 0)
{
return null;
}
string strRetVal = sb.ToString();
if (strRetVal != null && strRetVal.StartsWith("\\\\?\\"))
strRetVal = strRetVal.Substring(4);
sb.Length = 0;
sb = null;
return strRetVal;
}
private static string GetVersionFromFile(string strFilename)
{
string strRetVal = null;
try
{
System.Diagnostics.FileVersionInfo fviVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(strFilename);
strRetVal = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", new object[] {
fviVersion.FileMajorPart,
fviVersion.FileMinorPart,
fviVersion.FileBuildPart,
fviVersion.FilePrivatePart
});
}
catch
{
strRetVal = "";
}
return strRetVal;
}
private static string GetVersionOfLoadedModule(string strModuleName)
{
string strFileNameOfLoadedModule = GetFileNameFromLoadedModule(strModuleName);
if (strFileNameOfLoadedModule == null)
return null;
return GetVersionFromFile(strFileNameOfLoadedModule);
}
public static string SystemWebVersion
{
get
{
return GetVersionFromFile(typeof(System.Web.HttpRuntime).Module.FullyQualifiedName);
}
}
public static bool IsMono
{
get
{
return Type.GetType("Mono.Runtime") != null;
}
}
public static string MonoVersion
{
get
{
string strMonoVersion = "";
Type tMonoRuntime = Type.GetType("Mono.Runtime");
if (tMonoRuntime != null)
{
System.Reflection.MethodInfo displayName = tMonoRuntime.GetMethod("GetDisplayName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (displayName != null)
strMonoVersion = (string)displayName.Invoke(null, null);
}
return strMonoVersion;
}
}
public static string DotNetFrameworkVersion
{
get
{
// values.Add(ExceptionPageTemplate.Template_RuntimeVersionInformationName, RuntimeHelpers.MonoVersion);
if (IsMono)
return MonoVersion;
// Return System.Environment.Version.ToString()
return GetVersionOfLoadedModule("mscorwks.dll");
}
}
public static string AspNetVersion
{
get
{
//values.Add(ExceptionPageTemplate.Template_AspNetVersionInformationName, Environment.Version.ToString());
if (IsMono)
return System.Environment.Version.ToString();
return GetVersionOfLoadedModule("webengine.dll");
}
}
public static bool IsVistaOrHigher
{
get
{
System.OperatingSystem osWindowsVersion = System.Environment.OSVersion;
return osWindowsVersion.Platform == System.PlatformID.Win32NT && osWindowsVersion.Version.Major >= 6;
}
}
public static void Test()
{
string ErrorPageInfo =
string.Format("Version Information: Microsoft .NET Framework Version: {0}; ASP.NET Version: {1}"
,DotNetFrameworkVersion
,AspNetVersion
);
Console.WriteLine(ErrorPageInfo);
}
} // End Class MyVersionInfo
} // End Namespace LegendenTest
``` |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | [Environment.Version](http://msdn2.microsoft.com/en-us/library/system.environment.version) | ### Enable Trace
Enabling Trace is another option view every details of rendered page, including .NET Version
Add **Trace="true"** in page directive
```
<%@ Page Trace="true" %>
```
Scroll down to bottom and you will see rendered .NET Version |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | [Environment.Version](http://msdn2.microsoft.com/en-us/library/system.environment.version) | Actually, you all got the CLR version (but not really either, you actually get a string that is hard-coded in mscorlib.dll).
For the actual ASP.NET version, as you see it on the YSOD error pages, see here (they are NOT the same):
```
using System;
namespace MyElmahReplacement
{
public class MyVersionInfo
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(string strModuleName);
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int GetModuleFileName(IntPtr ptrHmodule, System.Text.StringBuilder strFileName, int szeSize);
private static string GetFileNameFromLoadedModule(string strModuleName)
{
IntPtr hModule = GetModuleHandle(strModuleName);
if (hModule == IntPtr.Zero)
{
return null;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
if (GetModuleFileName(hModule, sb, 256) == 0)
{
return null;
}
string strRetVal = sb.ToString();
if (strRetVal != null && strRetVal.StartsWith("\\\\?\\"))
strRetVal = strRetVal.Substring(4);
sb.Length = 0;
sb = null;
return strRetVal;
}
private static string GetVersionFromFile(string strFilename)
{
string strRetVal = null;
try
{
System.Diagnostics.FileVersionInfo fviVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(strFilename);
strRetVal = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", new object[] {
fviVersion.FileMajorPart,
fviVersion.FileMinorPart,
fviVersion.FileBuildPart,
fviVersion.FilePrivatePart
});
}
catch
{
strRetVal = "";
}
return strRetVal;
}
private static string GetVersionOfLoadedModule(string strModuleName)
{
string strFileNameOfLoadedModule = GetFileNameFromLoadedModule(strModuleName);
if (strFileNameOfLoadedModule == null)
return null;
return GetVersionFromFile(strFileNameOfLoadedModule);
}
public static string SystemWebVersion
{
get
{
return GetVersionFromFile(typeof(System.Web.HttpRuntime).Module.FullyQualifiedName);
}
}
public static bool IsMono
{
get
{
return Type.GetType("Mono.Runtime") != null;
}
}
public static string MonoVersion
{
get
{
string strMonoVersion = "";
Type tMonoRuntime = Type.GetType("Mono.Runtime");
if (tMonoRuntime != null)
{
System.Reflection.MethodInfo displayName = tMonoRuntime.GetMethod("GetDisplayName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (displayName != null)
strMonoVersion = (string)displayName.Invoke(null, null);
}
return strMonoVersion;
}
}
public static string DotNetFrameworkVersion
{
get
{
// values.Add(ExceptionPageTemplate.Template_RuntimeVersionInformationName, RuntimeHelpers.MonoVersion);
if (IsMono)
return MonoVersion;
// Return System.Environment.Version.ToString()
return GetVersionOfLoadedModule("mscorwks.dll");
}
}
public static string AspNetVersion
{
get
{
//values.Add(ExceptionPageTemplate.Template_AspNetVersionInformationName, Environment.Version.ToString());
if (IsMono)
return System.Environment.Version.ToString();
return GetVersionOfLoadedModule("webengine.dll");
}
}
public static bool IsVistaOrHigher
{
get
{
System.OperatingSystem osWindowsVersion = System.Environment.OSVersion;
return osWindowsVersion.Platform == System.PlatformID.Win32NT && osWindowsVersion.Version.Major >= 6;
}
}
public static void Test()
{
string ErrorPageInfo =
string.Format("Version Information: Microsoft .NET Framework Version: {0}; ASP.NET Version: {1}"
,DotNetFrameworkVersion
,AspNetVersion
);
Console.WriteLine(ErrorPageInfo);
}
} // End Class MyVersionInfo
} // End Namespace LegendenTest
``` |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | ```
<%@ Page language="C#" %>
<% Response.Write(".NET Framework Version: " + Environment.Version.ToString()); %>
``` | ### Enable Trace
Enabling Trace is another option view every details of rendered page, including .NET Version
Add **Trace="true"** in page directive
```
<%@ Page Trace="true" %>
```
Scroll down to bottom and you will see rendered .NET Version |
3,308,437 | How can I see the version of .net framework which renders my aspx page on remote server? | 2010/07/22 | [
"https://Stackoverflow.com/questions/3308437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259881/"
] | ```
<%@ Page language="C#" %>
<% Response.Write(".NET Framework Version: " + Environment.Version.ToString()); %>
``` | Actually, you all got the CLR version (but not really either, you actually get a string that is hard-coded in mscorlib.dll).
For the actual ASP.NET version, as you see it on the YSOD error pages, see here (they are NOT the same):
```
using System;
namespace MyElmahReplacement
{
public class MyVersionInfo
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(string strModuleName);
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int GetModuleFileName(IntPtr ptrHmodule, System.Text.StringBuilder strFileName, int szeSize);
private static string GetFileNameFromLoadedModule(string strModuleName)
{
IntPtr hModule = GetModuleHandle(strModuleName);
if (hModule == IntPtr.Zero)
{
return null;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
if (GetModuleFileName(hModule, sb, 256) == 0)
{
return null;
}
string strRetVal = sb.ToString();
if (strRetVal != null && strRetVal.StartsWith("\\\\?\\"))
strRetVal = strRetVal.Substring(4);
sb.Length = 0;
sb = null;
return strRetVal;
}
private static string GetVersionFromFile(string strFilename)
{
string strRetVal = null;
try
{
System.Diagnostics.FileVersionInfo fviVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(strFilename);
strRetVal = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", new object[] {
fviVersion.FileMajorPart,
fviVersion.FileMinorPart,
fviVersion.FileBuildPart,
fviVersion.FilePrivatePart
});
}
catch
{
strRetVal = "";
}
return strRetVal;
}
private static string GetVersionOfLoadedModule(string strModuleName)
{
string strFileNameOfLoadedModule = GetFileNameFromLoadedModule(strModuleName);
if (strFileNameOfLoadedModule == null)
return null;
return GetVersionFromFile(strFileNameOfLoadedModule);
}
public static string SystemWebVersion
{
get
{
return GetVersionFromFile(typeof(System.Web.HttpRuntime).Module.FullyQualifiedName);
}
}
public static bool IsMono
{
get
{
return Type.GetType("Mono.Runtime") != null;
}
}
public static string MonoVersion
{
get
{
string strMonoVersion = "";
Type tMonoRuntime = Type.GetType("Mono.Runtime");
if (tMonoRuntime != null)
{
System.Reflection.MethodInfo displayName = tMonoRuntime.GetMethod("GetDisplayName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (displayName != null)
strMonoVersion = (string)displayName.Invoke(null, null);
}
return strMonoVersion;
}
}
public static string DotNetFrameworkVersion
{
get
{
// values.Add(ExceptionPageTemplate.Template_RuntimeVersionInformationName, RuntimeHelpers.MonoVersion);
if (IsMono)
return MonoVersion;
// Return System.Environment.Version.ToString()
return GetVersionOfLoadedModule("mscorwks.dll");
}
}
public static string AspNetVersion
{
get
{
//values.Add(ExceptionPageTemplate.Template_AspNetVersionInformationName, Environment.Version.ToString());
if (IsMono)
return System.Environment.Version.ToString();
return GetVersionOfLoadedModule("webengine.dll");
}
}
public static bool IsVistaOrHigher
{
get
{
System.OperatingSystem osWindowsVersion = System.Environment.OSVersion;
return osWindowsVersion.Platform == System.PlatformID.Win32NT && osWindowsVersion.Version.Major >= 6;
}
}
public static void Test()
{
string ErrorPageInfo =
string.Format("Version Information: Microsoft .NET Framework Version: {0}; ASP.NET Version: {1}"
,DotNetFrameworkVersion
,AspNetVersion
);
Console.WriteLine(ErrorPageInfo);
}
} // End Class MyVersionInfo
} // End Namespace LegendenTest
``` |
260,924 | Assume a multi-line file (`myInput.txt`) with lines comprising one or more words.
```
echo -e "Foo\nFoo bar\nFoo baz\nFoo bar baz\nBar\nBaz\nBaz qux\nBaz qux quux\nQux quux" > myInput.txt
```
I wish to remove all one-word lines that are identical with the first word of any multi-word lines **using Python**.
```
echo -e "Foo bar\nFoo baz\nFoo bar baz\nBar\nBaz qux\nBaz qux quux\nQux quux" > myGoal.txt
```
The following code satisfies my goal but does not appear overtly Pythonic to me.
```
from itertools import compress
myList = list()
with open("myInput.txt", "r") as myInput:
for line in [l.strip() for l in myInput.readlines()]:
if not line.startswith("#"):
myList.append(line)
# Get all lines with more than one word
more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList]))
# Get all lines with only one word
only_one_word = list(compress(myList, [len(e.strip().split(" "))==1 for e in myList]))
# Keep only unique set of initial words of more_than_one
unique_first_words = list(set([e.split(" ")[0] for e in more_than_one]))
# Remove all union set words from only_one_word
only_one_word_reduced = [e for e in only_one_word if e not in unique_first_words]
# Combine more_than_one and only_one_word_reduced
combined_list = only_one_word_reduced + more_than_one
```
Do you have any suggestions on making the Python code slimmer and more straightforward? | 2021/05/19 | [
"https://codereview.stackexchange.com/questions/260924",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/122794/"
] | ```py
# Get all lines with more than one word
more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList]))
```
* The function `split` splits by whitespaces by default, there is no need to pass the explicit argument
* Lines have been stripped already when reading the file, using `strip` seems unnecessary
* Using list comprehension should be enough, without the function `compress` and `list`
For example:
```py
more_than_one = [line for line in myList if len(line.split()) > 1]
```
Or:
```py
more_than_one = [line for line in myList if ' ' in line]
```
* Same observations for `Get all lines with only one word`
---
```py
# Keep only unique set of initial words of more_than_one
unique_first_words = list(set([e.split(" ")[0] for e in more_than_one]))
```
* Not sure why the `set` is converted to a `list`. Checking for unique words in a set is much faster than in a list
---
* **Functions**: would be better to include all the operations in a function, for easier testing and reuse
* **PEP 8**: function and variable names should be lowercase, with words separated by underscores as necessary to improve readability. `myList` should be `my_list`. [More info](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names).
---
A function that does the same could be the following:
```
def remove_duplicates(lines):
seen = set()
for line in lines:
first_word, *tail = line.split()
if tail:
seen.add(first_word)
return [line for line in lines if line not in seen]
```
An use it like:
```
print(remove_duplicates(['a','a b','b','c','c d','z']))
# Output: ['a b', 'b', 'c d', 'z']
``` | Although you have several useful suggestions already, they don't quite cut to
the heart of the matter. Your example fits into a common type of problem: read
a text file; parse it to extract information; perform some computations on that
information; and report to the user. In my experience one of the best things
you can do to keep this type of code fairly simple and easy to maintain is to
**convert to meaningful information early in the process**. Here's one way to
do that for your use case:
```
# Use fileinput, so we don't have to hard code the file
# path in the script. This is handy for development/debugging.
import fileinput
# Define a meaningful object to hold information about each line.
# You could use a namedtuple, a dataclass, or an attrs class.
from collections import namedtuple
WordLine = namedtuple('WordLine', 'line first rest')
# Convert the raw information (lines) to those meaningful objects.
wlines = []
for line in fileinput.input():
first, *rest = line.split()
wlines.append(WordLine(line, first, rest))
```
From that point forward, the algorithmic computations become so simple that
they don't amount to much. A few examples:
```
more_than_one = [wl for wl in wlines if wl.rest]
only_one_word = [wl for wl in wlines if not wl.rest]
unique_first_words = set(wl.first for wl in wlines)
``` |
260,924 | Assume a multi-line file (`myInput.txt`) with lines comprising one or more words.
```
echo -e "Foo\nFoo bar\nFoo baz\nFoo bar baz\nBar\nBaz\nBaz qux\nBaz qux quux\nQux quux" > myInput.txt
```
I wish to remove all one-word lines that are identical with the first word of any multi-word lines **using Python**.
```
echo -e "Foo bar\nFoo baz\nFoo bar baz\nBar\nBaz qux\nBaz qux quux\nQux quux" > myGoal.txt
```
The following code satisfies my goal but does not appear overtly Pythonic to me.
```
from itertools import compress
myList = list()
with open("myInput.txt", "r") as myInput:
for line in [l.strip() for l in myInput.readlines()]:
if not line.startswith("#"):
myList.append(line)
# Get all lines with more than one word
more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList]))
# Get all lines with only one word
only_one_word = list(compress(myList, [len(e.strip().split(" "))==1 for e in myList]))
# Keep only unique set of initial words of more_than_one
unique_first_words = list(set([e.split(" ")[0] for e in more_than_one]))
# Remove all union set words from only_one_word
only_one_word_reduced = [e for e in only_one_word if e not in unique_first_words]
# Combine more_than_one and only_one_word_reduced
combined_list = only_one_word_reduced + more_than_one
```
Do you have any suggestions on making the Python code slimmer and more straightforward? | 2021/05/19 | [
"https://codereview.stackexchange.com/questions/260924",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/122794/"
] | Based on your code, the lines don't need to be kept in order.
This code reads each line of the file once. If there are multiple words on a line, it is appended to `combined_lines` and the first words is added to a set of first words. Another set is used for single words. At the end, any single words that aren't a first word (using set subtraction) are added to `combined_lines`.
With revisions suggested in the comments:
```
combined_lines = list()
single_words = set()
first_words = set()
with open("myInput.txt", "r") as sourcefile:
for line in sourcefile:
line = line.strip()
if line == '' or line.startswith("#"):
continue
first, rest = line.split(maxsplit=1)
if rest:
combined_lines.append(line)
first_words.add(first)
else:
single_words.add(first)
combined_lines.extend(single_words - first_words)
``` | Although you have several useful suggestions already, they don't quite cut to
the heart of the matter. Your example fits into a common type of problem: read
a text file; parse it to extract information; perform some computations on that
information; and report to the user. In my experience one of the best things
you can do to keep this type of code fairly simple and easy to maintain is to
**convert to meaningful information early in the process**. Here's one way to
do that for your use case:
```
# Use fileinput, so we don't have to hard code the file
# path in the script. This is handy for development/debugging.
import fileinput
# Define a meaningful object to hold information about each line.
# You could use a namedtuple, a dataclass, or an attrs class.
from collections import namedtuple
WordLine = namedtuple('WordLine', 'line first rest')
# Convert the raw information (lines) to those meaningful objects.
wlines = []
for line in fileinput.input():
first, *rest = line.split()
wlines.append(WordLine(line, first, rest))
```
From that point forward, the algorithmic computations become so simple that
they don't amount to much. A few examples:
```
more_than_one = [wl for wl in wlines if wl.rest]
only_one_word = [wl for wl in wlines if not wl.rest]
unique_first_words = set(wl.first for wl in wlines)
``` |
2,582,951 | Also I want to know how to add meta data while indexing so that i can boost some parameters | 2010/04/06 | [
"https://Stackoverflow.com/questions/2582951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150887/"
] | Lucene indexes text not files - you'll need some other process for extracting the text out of the file and running Lucene over that. | see <https://github.com/WolfgangFahl/pdfindexer>
for a java solution that uses PDFBox and Apache Lucene to split the PDF files page by page to text,
index these text-pages and create a resulting html index file that links to the pages in the pdf sources by using a corresponding open parameter. |
2,582,951 | Also I want to know how to add meta data while indexing so that i can boost some parameters | 2010/04/06 | [
"https://Stackoverflow.com/questions/2582951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150887/"
] | There are several frameworks for extracting text suitable for Lucene indexing from rich text files (pdf, ppt etc.)
* One of them is [Apache Tika](http://lucene.apache.org/tika/), a sub-project of Lucene.
* [Apache POI](http://poi.apache.org/) is a more general document handling project inside Apache.
* There are also some commercial alternatives. | see <https://github.com/WolfgangFahl/pdfindexer>
for a java solution that uses PDFBox and Apache Lucene to split the PDF files page by page to text,
index these text-pages and create a resulting html index file that links to the pages in the pdf sources by using a corresponding open parameter. |
2,582,951 | Also I want to know how to add meta data while indexing so that i can boost some parameters | 2010/04/06 | [
"https://Stackoverflow.com/questions/2582951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150887/"
] | You can use Apache [Tika](http://lucene.apache.org/tika/index.html). Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries.
Supported Document Formats
* HyperText Markup Language
* XML and derived formats
* Microsoft Office document formats
* OpenDocument Format
* Portable Document Format
* Electronic Publication Format
* Rich Text Format
* Compression and packaging formats
* Text formats
* Audio formats
* Image formats
* Video formats
* Java class files and archives
* The mbox format
The code will look like this.
Reader reader = new Tika().parse(stream); | see <https://github.com/WolfgangFahl/pdfindexer>
for a java solution that uses PDFBox and Apache Lucene to split the PDF files page by page to text,
index these text-pages and create a resulting html index file that links to the pages in the pdf sources by using a corresponding open parameter. |
2,314,637 | All, I am creating a web application and I need to give users the ability to add/edit/delete records in a grid type control. I can't use 3rd party controls so I am restricted to just whats in the box for asp.net (datagrid or gridview) or creating my own. Any thoughts on the best direction to go in. I'd like to keep the complexity level at a dull roar :)
thanks in advance
daniel | 2010/02/22 | [
"https://Stackoverflow.com/questions/2314637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164257/"
] | Gridviews have different item templates that you can use for editing and inserting data. That'd be an easy way to go about it.
As long as you set your datakeyid property to the primary key in the database, you should be able to make template fields based off of whether or not you're editing or inserting data. The command name of the button you use to fire the event will handle the statements required for updating/inserting data.
[This](http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx) is a good site for some examples. | the out of the box grid is not too bad.
Here are a few links on master detail records in asp.net this should get you started on the CRUD opperations.
<http://www.exforsys.com/tutorials/asp.net-2.0/displaying-master-detail-data-on-the-same-page.html> <http://msdn.microsoft.com/en-us/library/aa581796.aspx>
<http://www.bing.com/search?q=asp.net+master+detail> |
2,314,637 | All, I am creating a web application and I need to give users the ability to add/edit/delete records in a grid type control. I can't use 3rd party controls so I am restricted to just whats in the box for asp.net (datagrid or gridview) or creating my own. Any thoughts on the best direction to go in. I'd like to keep the complexity level at a dull roar :)
thanks in advance
daniel | 2010/02/22 | [
"https://Stackoverflow.com/questions/2314637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164257/"
] | You should definitely use edit and insert templates. All you have to do is give the button/link the command name such as insert/delete/update and you can allow the Grid to do most of all the work.
[Check out this link](http://www.codeproject.com/KB/aspnet/InsertingWithGridView.aspx)
I think you'll learn to love the gridviews because they are pretty powerful. | the out of the box grid is not too bad.
Here are a few links on master detail records in asp.net this should get you started on the CRUD opperations.
<http://www.exforsys.com/tutorials/asp.net-2.0/displaying-master-detail-data-on-the-same-page.html> <http://msdn.microsoft.com/en-us/library/aa581796.aspx>
<http://www.bing.com/search?q=asp.net+master+detail> |
2,314,637 | All, I am creating a web application and I need to give users the ability to add/edit/delete records in a grid type control. I can't use 3rd party controls so I am restricted to just whats in the box for asp.net (datagrid or gridview) or creating my own. Any thoughts on the best direction to go in. I'd like to keep the complexity level at a dull roar :)
thanks in advance
daniel | 2010/02/22 | [
"https://Stackoverflow.com/questions/2314637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164257/"
] | Gridviews have different item templates that you can use for editing and inserting data. That'd be an easy way to go about it.
As long as you set your datakeyid property to the primary key in the database, you should be able to make template fields based off of whether or not you're editing or inserting data. The command name of the button you use to fire the event will handle the statements required for updating/inserting data.
[This](http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx) is a good site for some examples. | this is the best site for what you are after
**www.Asp.Net**
* [**Data Access Tutorials controls**](http://www.asp.net/learn/data-access/)
* [**Master/Detail Using a Selectable
Master GridView with a Details
DetailView**](http://www.asp.net/learn/data-access/tutorial-10-cs.aspx)
* [**Using TemplateFields in the GridView
Control**](http://www.asp.net/learn/data-access/tutorial-12-cs.aspx)
**Others**
* [**Beginners Guide to the GridView
Control**](http://aspnet101.com/tutorials.aspx?id=51)
* [**The GridView Control**](http://www.hotscripts.com/listing/asp-net-2-0-free-tutorials-the-gridview-control/)
* [**IN-DEPTH LOOK AT THE GRIDVIEW CONTROL**](http://www.programminglearn.com/409/in-depth-look-at-the-gridview-control) |
2,314,637 | All, I am creating a web application and I need to give users the ability to add/edit/delete records in a grid type control. I can't use 3rd party controls so I am restricted to just whats in the box for asp.net (datagrid or gridview) or creating my own. Any thoughts on the best direction to go in. I'd like to keep the complexity level at a dull roar :)
thanks in advance
daniel | 2010/02/22 | [
"https://Stackoverflow.com/questions/2314637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164257/"
] | You should definitely use edit and insert templates. All you have to do is give the button/link the command name such as insert/delete/update and you can allow the Grid to do most of all the work.
[Check out this link](http://www.codeproject.com/KB/aspnet/InsertingWithGridView.aspx)
I think you'll learn to love the gridviews because they are pretty powerful. | this is the best site for what you are after
**www.Asp.Net**
* [**Data Access Tutorials controls**](http://www.asp.net/learn/data-access/)
* [**Master/Detail Using a Selectable
Master GridView with a Details
DetailView**](http://www.asp.net/learn/data-access/tutorial-10-cs.aspx)
* [**Using TemplateFields in the GridView
Control**](http://www.asp.net/learn/data-access/tutorial-12-cs.aspx)
**Others**
* [**Beginners Guide to the GridView
Control**](http://aspnet101.com/tutorials.aspx?id=51)
* [**The GridView Control**](http://www.hotscripts.com/listing/asp-net-2-0-free-tutorials-the-gridview-control/)
* [**IN-DEPTH LOOK AT THE GRIDVIEW CONTROL**](http://www.programminglearn.com/409/in-depth-look-at-the-gridview-control) |
2,088,079 | Differentiate $$\:\left(x-1/2\right)^2+\left(y-1/4\right)^2=5/16$$
With respect to $x.$
The above simplifies to
$$x^2-x+y^2-\frac{y}{2} = 0$$
I know that you have to take the implicit derivative, such that
$$\frac{d}{dx}(x^2-x+y^2-\frac{y}{2}) = \frac{d}{dx}(0)$$
Thus
$$2x-1+2y-\frac{1}{2}=0$$
and
$$y=-x+\frac{3}{4}$$
So $$y'=-x+\frac{3}{4}$$
Have I made any errors, and where can I improve on this solution? In particular, I am worried because the last two equations are the same except the difference between $y$ and $y'.$ I mean, both can't be assumed to be true, right?
And I am asked to find the equation of the tangent of the circle that intersects at the point $(1, 0).$ In this case, do I write the equation in the form $y=mx+b$ (but with numbers replacing $m$ and $b$) as well, in which case I would have two $y$ variables in my solution? | 2017/01/07 | [
"https://math.stackexchange.com/questions/2088079",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/293926/"
] | Your error is first forgetting that $y$ depends on $x$ (I assume because implicit derivatives are mentioned and $x(y)$ would be pretty mean) and then getting confused and solving for $y$ and not $y'$.
You are right that you need to take
$$
\frac{d}{dx}(x^2-x+y^2-y/2)=0
$$
But $y$ is a function of $x$ so this should be by the chain rule
$$
2x-1+2yy'-1/2y'=0
$$
Can you solve for $y'$ now?
Now as for the tangent line to the circle described by this curve, you now have the equation for the slope of the tangent line to the curve at any point and a given point. So your $m=y'(1)$ and you can use precalculus methods to find the equation of the line in point slope form. | It should be $2x-1+\left(2y-\frac{1}{2}\right)y'=0$ |
68,883,343 | I'm trying to only call an axios call once per render from an event handler (onClick basically), so I'm using useEffect and inside that useEffect, I'm using useState. Problem is - when onClick is called, I get the following error:
>
> Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
>
>
>
I understand why I'm getting it, I'm using useState in an event handler - but I don't know what else to do. How else can I handle these variables without useState?
HttpRequest.js
```js
import {useEffect, useState} from 'react'
import axios from 'axios'
export function useAxiosGet(path) {
const [request, setRequest] = useState({
loading: false,
data: null,
error: false
});
useEffect(() => {
setRequest({
loading: true,
data: null,
error: false
});
axios.get(path)
.then(response => {
setRequest({
loading: false,
data: response.data,
error: false
})
})
.catch((err) => {
setRequest({
loading: false,
data: null,
error: true
});
if (err.response) {
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
console.log(err.request);
} else {
console.log('Error', err.message);
}
console.log(err.config);
})
}, [path])
return request
}
```
RandomItem.js
```js
import React, {useCallback, useEffect, useState} from 'react';
import Item from "../components/Item";
import Loader from "../../shared/components/UI/Loader";
import {useAxiosGet} from "../../shared/hooks/HttpRequest";
import {useLongPress} from 'use-long-press';
function collectItem(item) {
return useAxiosGet('collection')
}
function RandomItem() {
let content = null;
let item;
item = useAxiosGet('collection');
console.log(item);
const callback = useCallback(event => {
console.log("long pressed!");
}, []);
const longPressEvent = useLongPress(callback, {
onStart: event => console.log('Press started'),
onFinish: event => console.log('Long press finished'),
onCancel: event => collectItem(),
//onMove: event => console.log('Detected mouse or touch movement'),
threshold: 500,
captureEvent: true,
cancelOnMovement: false,
detect: 'both',
});
if (item.error === true) {
content = <p>There was an error retrieving a random item.</p>
}
if (item.loading === true) {
content = <Loader/>
}
if (item.data) {
return (
content =
<div {...longPressEvent}>
<Item name={item.data.name} image={item.data.filename} description={item.data.description}/>
</div>
)
}
return (
<div>
{content}
</div>
);
}
export default RandomItem;
```
[use-long-press](https://github.com/minwork/use-long-press)
It works to load up the first item just fine, but when you try to cancel a long click (Basically the onClick event handler), it spits out the error above. | 2021/08/22 | [
"https://Stackoverflow.com/questions/68883343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200025/"
] | You need to redo your hook so it would not start loading unconditionally but instead return a callback that might be called to initiate loading at some moment:
```
const [loadCollections, { isLoading, data, error }] = useLazyAxiosGet('collections');
....
onCancel: loadCollections
```
I propose to follow [approach that Apollo uses](https://www.apollographql.com/docs/react/api/react/hooks/#usequery) when there is `useQuery` that starts loading instantly and `useLazyQuery` that returns callback to be called later and conditionally. But both share similar API so could be easily replaced without much updates in code.
Just beware that "immediate" and "lazy" version don't just differ by ability to be called conditionally. Say, for "lazy" version you need to decide what will happen on series calls to callback - should next call rely on existing data or reset and send brand new call. For "immediate" version there are no such a dilemma since component will be re-rendered for multiple times per lifetime, so it definitely *should not* send new requests each time. | A user in discord provided this solution: <https://codesandbox.io/s/cool-frog-9vim0?file=/src/App.js>
```js
import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import "./styles.css";
const fetchDataFromApi = () => {
return axios(
`https://jsonplaceholder.typicode.com/todos/${
1 + Math.floor(Math.random() * 10)
}`
).then(({ data }) => data);
};
const MyComponent = () => {
const [data, setData] = useState(undefined);
const [canCall, setCanCall] = useState(true);
const handler = {
onClick: useCallback(() => {
if (canCall) {
setCanCall(false); // This makes it so you can't call more than once per button click
fetchDataFromApi().then((data) => {
setData(data);
setCanCall(true); // Unlock button Click
});
}
}, [canCall]),
onLoad: useCallback(() => {
if (canCall) {
setCanCall(false); // This makes it so you can't call more than once per button click
fetchDataFromApi().then((data) => {
setData(data);
setCanCall(true); // Unlock button Click
});
}
}, [canCall])
};
useEffect(() => {
handler.onLoad(); //initial call
}, []);
return (
<div>
<pre>{JSON.stringify(data, " ", 2)}</pre>
<button disabled={!canCall} onClick={handler.onClick}>
fetch my data!
</button>
</div>
);
};
export default function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}
``` |
5,047 | I would like to draw a land for a motocross game. I've been thinking of Bezier Curves but I am not sure whether this is the best approach. Can you give me some advice? I want to do it in JavaScript, not very good choice but it's personal project so for time being it's OK. | 2010/10/31 | [
"https://gamedev.stackexchange.com/questions/5047",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/2938/"
] | I found a couple of links that might be useful for others:
Example script of Bezier implementation in JS
<http://jsfromhell.com/math/bezier>
It can be used from JavaScript or ActionScript to animate along a bezier path.
<http://code.google.com/p/javascript-beziers/>
Online drawing script/plot, quite useful if you want to make some tests
<http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm>
A bit of theory and an implementation example
<http://13thparallel.com/archive/bezier-curves/> | Instead of beziers, you probably want b-splines or catmull-rom splines.
```
float bspline(float t, float p0, float p1, float p2, float p3)
{
float it = 1.0f - t;
float b0 = it*it*it * (1.0f / 6.0f);
float b1 = (3*t*t*t - 6*t*t +4) * (1.0f / 6.0f);
float b2 = (-3*t*t*t +3*t*t + 3*t + 1) * (1.0f / 6.0f);
float b3 = t*t*t * (1.0f / 6.0f);
return
b0*p0 +
b1*p1 +
b2*p2 +
b3*p3;
}
float catmullrom(float t, float p0, float p1, float p2, float p3)
{
return 0.5f * (
(2 * p1) +
(-p0 + p2) * t +
(2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t +
(-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t
);
}
```
Usage: t ranges from 0 to 1, where the value interpolates the spline between two control points, and the floats p0, p1, p2 and p3 are represent the control points (previous, current, next, and the following). To interpolate n-dimensional curves, just call the functions once per axis.
The practical difference between bsplines and catmull-rom is basically that catmull-rom goes through all control points while bsplines are more smooth. |
9,056 | I want to implement mutual exclusion for $n$ processes. Critical section code:
```
int turn = 0; /* shared control variable */
Pi: /* i is 0 or 1 */
while (turn != i)
; /* busy wait */
CSi;
turn = 1 - i;
```
This solution from [this page](http://phoenix.goucher.edu/~kelliher/cs42/sep27.html) but it is only made for two processes.
I tried to adapt it for $n$ processes like this:
```
turn = 0 // shared control variable
i = turn;
while (turn != i);
// CS
turn = (turn + 1) % n;
```
Does this work? | 2013/01/20 | [
"https://cs.stackexchange.com/questions/9056",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/6488/"
] | From my understanding of the 2-processor, if you want to do the same thing you would delete the statement (I truly dont know why you had it. There could be something interesting behind this statement of yours).
```
i = turn
```
and instead, let each of the $n$ processors have an id from $\{1, \dots, n\}$. Then, you would let the processors go *in sequence* to the critical code. That is, assume a processor $i$ takes the token and left it. Then, it has to wait the other $n- 1$ to take the token if it want to take it again. The problem in this solution is the sequential method of taking the token.
If you want to have something more efficient, then have a look at the Lamport's bakery algorithm. The pseudocode of the algorithm is available in the site you provided, and it is explained in wikipedia. The idea of this algorithm is very simple in fact. There is a *queue* of processors that want to get the token. These processors enter the queue, and the first come is first served.
In regard to the [link](http://phoenix.goucher.edu/~kelliher/cs42/sep27.html) you included in your question, this is done by these lines:
```
number[i] = max(number) + 1; // enter the queue !
...
...
while (number[j] != 0 && (number[j] < number[i] ||
number[j] == number[i] && j < i) )
// wait until your turn comes.
...
Do your critical section ! ...
...
number[i] = 0; // go out of the queue ..
```
Obviously, you can play around with this. But it is a neat way of implementing FIFO requests. | Take a look at Allen B. Downey's ["The Little Book of Semaphores](http://www.greenteapress.com/semaphores/), it discusses synchronization in great depth. In any case, schemes based on just the atomicity of writing to memory are unwieldly and of no practical use (real CPUs have special instructions that simplify implementing this stuff enormously). |
5,914,507 | Hey all. I need to work on all of the skills that come along with working with web services in Android. Most of the apps I've worked on have used static/local data. Obviously, to create something powerful, I need to learn how to work with web services.
To that end, does anyone have any recommendations for an easy API to work with? I don't really have any preference (I'm doing this project just so I can learn), though I'd rather not work with Twitter.
So, I'm looking for one of the popular APIs, but something that's relatively simple so that I don't have to be bogged down in an ultra-complex API. I want to be able to focus more on the Android/Java implementation.
Thanks a lot! | 2011/05/06 | [
"https://Stackoverflow.com/questions/5914507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479180/"
] | You have many API that you can use to leverage your skills. Facebook is one of them but you can also have a look at websites such as Read It Later, Instapaper, Delicious or MeeGo that use simple web API with JSON/XML to transmit data. | My suggestion would be to go with Facebook;
<http://developers.facebook.com/docs/guides/mobile/#android>
While many others might disagree, some maybe saying it isn't a web service at all, personally I liked the idea of having many different kinds of data. And chose to do some experiments on top of Facebook Graph API based on pretty much same rationale you're describing here.
It really doesn't take long while to make your first connection, namely have your application authorized, and after you have an access token, Graph API is rather intuitive to use. And Facebook SDK doesn't make it any harder either.
Anyway, that's my two cents, nothing more, nothing less. |
5,914,507 | Hey all. I need to work on all of the skills that come along with working with web services in Android. Most of the apps I've worked on have used static/local data. Obviously, to create something powerful, I need to learn how to work with web services.
To that end, does anyone have any recommendations for an easy API to work with? I don't really have any preference (I'm doing this project just so I can learn), though I'd rather not work with Twitter.
So, I'm looking for one of the popular APIs, but something that's relatively simple so that I don't have to be bogged down in an ultra-complex API. I want to be able to focus more on the Android/Java implementation.
Thanks a lot! | 2011/05/06 | [
"https://Stackoverflow.com/questions/5914507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479180/"
] | My suggestion would be to go with Facebook;
<http://developers.facebook.com/docs/guides/mobile/#android>
While many others might disagree, some maybe saying it isn't a web service at all, personally I liked the idea of having many different kinds of data. And chose to do some experiments on top of Facebook Graph API based on pretty much same rationale you're describing here.
It really doesn't take long while to make your first connection, namely have your application authorized, and after you have an access token, Graph API is rather intuitive to use. And Facebook SDK doesn't make it any harder either.
Anyway, that's my two cents, nothing more, nothing less. | First web API I used was Flickr. They have great documentation, most (all?) of the data can be returned in JSON format, and it's pretty expansive. I thought it was pretty simple to use, myself. |
5,914,507 | Hey all. I need to work on all of the skills that come along with working with web services in Android. Most of the apps I've worked on have used static/local data. Obviously, to create something powerful, I need to learn how to work with web services.
To that end, does anyone have any recommendations for an easy API to work with? I don't really have any preference (I'm doing this project just so I can learn), though I'd rather not work with Twitter.
So, I'm looking for one of the popular APIs, but something that's relatively simple so that I don't have to be bogged down in an ultra-complex API. I want to be able to focus more on the Android/Java implementation.
Thanks a lot! | 2011/05/06 | [
"https://Stackoverflow.com/questions/5914507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479180/"
] | You have many API that you can use to leverage your skills. Facebook is one of them but you can also have a look at websites such as Read It Later, Instapaper, Delicious or MeeGo that use simple web API with JSON/XML to transmit data. | First web API I used was Flickr. They have great documentation, most (all?) of the data can be returned in JSON format, and it's pretty expansive. I thought it was pretty simple to use, myself. |
16,949,444 | I added a Blog Archive widget to my [Orchard CMS blog](http://logiczone.me/logically-me/archive/2013/6). It displayed the archive dates as intended and clicking the date displays a list of blog posts that fall under the date. The problem I have is with the list of blog posts that are being shown. They do not seem to follow the regular blog post style. Looking at the source the posts are simply rendered as plain tags without any CSS classes. Using the shape tracing tool tells me that they're simply rendered as the List core shape. I've tried modifying the Blog Archive content part to add a CSS part, but that didn't work. I've create several shape alternates using the tracing tool but none of them worked. Can anyone out there point me to the right direction? Much appreciated. | 2013/06/05 | [
"https://Stackoverflow.com/questions/16949444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2457314/"
] | You are right, that list should have a class on it. Please file a bug for it. The fix is simple but requires modification of the blog module. In BlogPostController, after the line saying `var list = Shape.List();`, add this:
```
list.Classes.Add("blog-archive");
``` | Override ListByarchive View from Orchard.Blogs/Views/BlogPost in your Theme
in the view instead of line
```
@Display(Model.ContentItems)
```
which renders the archilves list
replace it with
```
@{
var blogPosts = Model.ContentItems;
var items = blogPosts.Items;
}
///write your own logic here
@foreach (var item in items) {
<div>
@Display(item)
</div>
}
```
you can see live [here](http://bhoopaljanga.azurewebsites.net/blog/archive/2013/8) |
36,386,213 | I am trying to achieve the functionality seen on Google Play where a CardView has an options menu that can be clicked and you can click on the card to view more detail on the card.
I have implemented an OnItemTouch listener on my RecyclerView which works fine and responds when touched, taking me to another activity. However, when I now try and add a click listener to an options icon I have added within the RecyclerView item (which is a CardView), the OnItemTouch listener is called. Can anyone help?
Activity
```
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getApplicationContext(),
TransactionDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("transaction_key", mTransactionList.get(position));
intent.putExtras(bundle);
startActivity(intent);
}
})
); mRecyclerView.setAdapter(mAdapter);
```
Click Listener
```
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildPosition(childView));
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
``` | 2016/04/03 | [
"https://Stackoverflow.com/questions/36386213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1810110/"
] | If you don't want to handle the clicks of CardView children, OnItemTouchListener is the way.
But if you want to handle the cliks of cardview children, you may have to attach OnClickListener (in the Adapter class' DataObjectHolder or onBindViewHolder method) to the CardView or its immediate child (which can be any layout Eg. LinearLayout, RelativeLayout, etc) to handle the card clicks. If done so, the OnClickListener of any view inside the CardView will work.
Following is an example:
**Adapter**
```
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.DataObjectHolder>{
Context context;
ArrayList<String> list;
static String TAG = "ApprovalsRV Adapter";
DeleteListener deleteListener;
public RecyclerViewAdapter(Context context, ArrayList<String> list)
{
this.context = context;
this.list = list;
deleteListener = (DeleteListener) context;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder
{
TextView tName;
RelativeLayout rlName;
CardView cvName;
public DataObjectHolder(View itemView, final Context context)
{
super(itemView);
tName = (TextView) itemView.findViewById(R.id.tName);
rlName = (RelativeLayout) itemView.findViewById(R.id.rlName);
cvName = (CardView) itemView.findViewById(R.id.cvName);
cvName.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
//Handle the card click here
deleteListener.deleteName(position); // if handling from activity (explained below)
}
});
tName.setOnClickListener(new View.OnClickListener()
{ //You can have similar listeners for subsequent children
@Override
public void onClick(View view) {
//Handle the textview click here
}
});
}
}
@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card_view_layout, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view, context);
return dataObjectHolder;
}
@Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
holder.tName.setText(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
}
```
If you want to handle the card click from the activity, you will need to use an interface here.
**DeleteListener.java**
```
public interface DeleteListener {
public void deleteName(int position);
}
```
Now to use this in your activity:
**MyActivity.java**
```
public class MyActivity extends AppCompatActivity implements DeleteListener
{
@Override
public void deleteName(int position) {
//Your job
}
}
```
This will clear your doubt. | Instead of using OnItemTouchListener to handle RecyclerView item click events, use OnClickListener for the itemView which you get in the ViewHolder.
```
public class MyViewHolder extends RecyclerView.ViewHolder implements OnClickListener{
public MyViewHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v){
// handle click event
}
}
```
So, when the options icon is pressed, the whole itemView ClickListener will not be called. |
29,643,473 | So, for my question have a look at my Jmeter setup:

Let me explain what's happening and then move on to my question.
**Explanation**
On the server I have a guava cache (with timeout of 5 seconds) and a DB hooked up to it. Request A sends data (read from csv file) to the server and puts it in cache. It returns a unique ID corresponding with that data. Request B sends a seconds request (with that unique ID) that evicts the item from cache and saves to DB. The third request, C, uses that unique ID again to read from DB and process the data.
Now, to share that unique ID (and some other URL params) between thread groups I put them in a queue in Jmeter (using the jp@gc - Inter-Thread Communication PreProcessor and PostProcessor). All works like it should, both Jmeter and Server.
**Question**
To finish up this setup I need to add one more thing... For each request A only 10% (random) of the unique IDs need to be put in queue A. And again for each request B only 10% (random) of those unique IDs need to be put in queue B.
How can I do this last part if Jmeter does not allow if-controllers to be put as part of an http-request? | 2015/04/15 | [
"https://Stackoverflow.com/questions/29643473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3354890/"
] | If anyone is interested in the answer. I found out that the easiest way to do this is to create a random variable (in variable `rnd`) and a beanshell postprocessor, both under Http request A. The beanshell code is:
```
import kg.apc.jmeter.modifiers.FifoMap;
if (vars.get("rnd").equals("1")) {
FifoMap.getInstance().put("QUEUE_A", "${uniqueId");
}
```
For Request B, analog to the procedure for Request A. Works perfectly. | Did you try to use Inter-Thread Communication PostProcessor outside of http-request - for instanse, inside "Simple Controller" which is placed after http-request? In this case you can use any logic controllers (if, throughput, etc.) |
36,060 | I have read about sakkayaditti
<https://www.wisdomlib.org/definition/sakkayaditti>
Sakkayaditti means something in Buddhism, Pali.
please help me to clarify | 2019/11/22 | [
"https://buddhism.stackexchange.com/questions/36060",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/17327/"
] | This is a key concept in the Early Buddhist Texts:
>
> [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Anusetvevassa sakkΔyadiαΉαΉhΔnusayo.
>
>
> [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Yet the underlying tendency to ***identity view*** still lies within them.
>
>
>
Identity View is the view that "I am". For example, we say, "I am Chinese" or "I am educated" or "I am poor", etc.
These personal perspectives contribute to suffering. If "I am poor", then "I want to be rich". If "I am ugly" then "I want to be beautiful". Through study and practice, we step away from personal perspectives and abandon Identity View as not satisfying, not conducive to happiness. To be an Arahant, to be a Realized One, Identity View is abandoned entirely.
SakkΔyadiαΉαΉhi is the [heresy of individuality](https://suttacentral.net/define/sakk%C4%81yadi%E1%B9%AD%E1%B9%ADhi)
To be clear, that does not mean that Buddhists are all alike. The Buddha in fact insisted that each of us find the truth for ourselves. What it means is that Buddhists are alike in dismissing personal cravings as unskillful and unwholesome. | This is misunderstood by many people today. They say sakkaya ditti means: self view. According to dhamma, when a peraon become 1st entrant (sotΔpanna) he uproots the sakkaya ditti. So if sakkaya ditti means self view, then that person no need to go beyond that point, since there's noone (no self view) to attain nibbana.
So please think wise and don't get to the trap of self view.
Sakkaya diiti means: giving values to the things (in mind). Eg: Ferrari is a very good car, so its valuable (in mind). The food in ABC restaurant is very tasty so its worth going to that restaurant or eating that food. This view is called sakkaya ditti. When someone become 1st entrant; he understand that its a lie. Its not true. So he uproots the sakkaya dittia and become to samma ditti. Which is knowing that nothing is valuable but the Nirvana.
How to understand / realize that things doesn't have a value is a different topic. |
36,060 | I have read about sakkayaditti
<https://www.wisdomlib.org/definition/sakkayaditti>
Sakkayaditti means something in Buddhism, Pali.
please help me to clarify | 2019/11/22 | [
"https://buddhism.stackexchange.com/questions/36060",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/17327/"
] | This is a key concept in the Early Buddhist Texts:
>
> [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Anusetvevassa sakkΔyadiαΉαΉhΔnusayo.
>
>
> [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Yet the underlying tendency to ***identity view*** still lies within them.
>
>
>
Identity View is the view that "I am". For example, we say, "I am Chinese" or "I am educated" or "I am poor", etc.
These personal perspectives contribute to suffering. If "I am poor", then "I want to be rich". If "I am ugly" then "I want to be beautiful". Through study and practice, we step away from personal perspectives and abandon Identity View as not satisfying, not conducive to happiness. To be an Arahant, to be a Realized One, Identity View is abandoned entirely.
SakkΔyadiαΉαΉhi is the [heresy of individuality](https://suttacentral.net/define/sakk%C4%81yadi%E1%B9%AD%E1%B9%ADhi)
To be clear, that does not mean that Buddhists are all alike. The Buddha in fact insisted that each of us find the truth for ourselves. What it means is that Buddhists are alike in dismissing personal cravings as unskillful and unwholesome. | >
> Ime kho, Δvuso visΔkha, paΓ±cupΔdΔnakkhandhΔ **sakkΔyo** vutto
> bhagavatΔ
>
>
> These five clinging-aggregates are the **self-identification**
> described by the Blessed One.
>
>
> The craving that makes for further becoming β accompanied by passion &
> delight, relishing now here & now there β i.e., craving for sensual
> pleasure, craving for becoming, craving for non-becoming: This, friend
> Visakha, is the origination of self-identification described by the
> Blessed One
>
>
> KathaαΉ panΔyye, **sakkΔyadiαΉαΉhi** hotΔ« ti?
>
>
> But, lady, how does **self-identification view** come about?
>
>
> There is the case, friend Visakha, where an uninstructed,
> run-of-the-mill person β who has no regard for noble ones, is not
> well-versed or disciplined in their Dhamma; who has no regard for men
> of integrity, is not well-versed or disciplined in their Dhamma β
> assumes form (the body) to be the self, or the self as possessing
> form, or form as in the self, or the self as in form.
>
>
> He assumes feeling to be the self...
>
>
> He assumes perception to be the self...
>
>
> He assumes (mental) fabrications to be the self...
>
>
> He assumes consciousness to be the self, or the self as possessing
> consciousness, or consciousness as in the self, or the self as in
> consciousness.
>
>
> This is how self-identification view comes about.
>
>
> [MN 44](https://www.accesstoinsight.org/tipitaka/mn/mn.044.than.html)
>
>
> |
36,060 | I have read about sakkayaditti
<https://www.wisdomlib.org/definition/sakkayaditti>
Sakkayaditti means something in Buddhism, Pali.
please help me to clarify | 2019/11/22 | [
"https://buddhism.stackexchange.com/questions/36060",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/17327/"
] | >
> Ime kho, Δvuso visΔkha, paΓ±cupΔdΔnakkhandhΔ **sakkΔyo** vutto
> bhagavatΔ
>
>
> These five clinging-aggregates are the **self-identification**
> described by the Blessed One.
>
>
> The craving that makes for further becoming β accompanied by passion &
> delight, relishing now here & now there β i.e., craving for sensual
> pleasure, craving for becoming, craving for non-becoming: This, friend
> Visakha, is the origination of self-identification described by the
> Blessed One
>
>
> KathaαΉ panΔyye, **sakkΔyadiαΉαΉhi** hotΔ« ti?
>
>
> But, lady, how does **self-identification view** come about?
>
>
> There is the case, friend Visakha, where an uninstructed,
> run-of-the-mill person β who has no regard for noble ones, is not
> well-versed or disciplined in their Dhamma; who has no regard for men
> of integrity, is not well-versed or disciplined in their Dhamma β
> assumes form (the body) to be the self, or the self as possessing
> form, or form as in the self, or the self as in form.
>
>
> He assumes feeling to be the self...
>
>
> He assumes perception to be the self...
>
>
> He assumes (mental) fabrications to be the self...
>
>
> He assumes consciousness to be the self, or the self as possessing
> consciousness, or consciousness as in the self, or the self as in
> consciousness.
>
>
> This is how self-identification view comes about.
>
>
> [MN 44](https://www.accesstoinsight.org/tipitaka/mn/mn.044.than.html)
>
>
> | This is misunderstood by many people today. They say sakkaya ditti means: self view. According to dhamma, when a peraon become 1st entrant (sotΔpanna) he uproots the sakkaya ditti. So if sakkaya ditti means self view, then that person no need to go beyond that point, since there's noone (no self view) to attain nibbana.
So please think wise and don't get to the trap of self view.
Sakkaya diiti means: giving values to the things (in mind). Eg: Ferrari is a very good car, so its valuable (in mind). The food in ABC restaurant is very tasty so its worth going to that restaurant or eating that food. This view is called sakkaya ditti. When someone become 1st entrant; he understand that its a lie. Its not true. So he uproots the sakkaya dittia and become to samma ditti. Which is knowing that nothing is valuable but the Nirvana.
How to understand / realize that things doesn't have a value is a different topic. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | `file` is a stack variable in `ListFiles()` and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid.
If you want to return a string, you should [allocate it on the heap](http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html), return it, use it, then free it once you're done using it. | You're trying to display a string value char file[30] that is allocated on the stack (function stack). The content of this memory is not guaranteed after the method return. You should allocate it dynamically (for ex. malloc) or eventually use global value, or allocate it on the stack of the outer function (in your example main() function) |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this:
```
char* strdup(const char* org)
{
if(org == NULL) return NULL;
char* newstr = malloc(strlen(org)+1);
char* p;
if(newstr == NULL) return NULL;
p = newstr;
while(*org) *p++ = *org++; /* copy the string. */
return newstr;
}
```
And then:
```
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */
/* do something... */
char* ListFiles() {
/* .... */
return strdup(f);
}
```
Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable. | `file` is a stack variable in `ListFiles()` and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid.
If you want to return a string, you should [allocate it on the heap](http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html), return it, use it, then free it once you're done using it. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | What you're doing is returning a pointer to a local variable, which used to be allocated on stack.
Change your return statement to
```
return strdup(file);
``` | You're trying to display a string value char file[30] that is allocated on the stack (function stack). The content of this memory is not guaranteed after the method return. You should allocate it dynamically (for ex. malloc) or eventually use global value, or allocate it on the stack of the outer function (in your example main() function) |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this:
```
char* strdup(const char* org)
{
if(org == NULL) return NULL;
char* newstr = malloc(strlen(org)+1);
char* p;
if(newstr == NULL) return NULL;
p = newstr;
while(*org) *p++ = *org++; /* copy the string. */
return newstr;
}
```
And then:
```
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */
/* do something... */
char* ListFiles() {
/* .... */
return strdup(f);
}
```
Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable. | you shouldn't return data that sits on automatic storage, when you return it goes out of scope. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | What you're doing is returning a pointer to a local variable, which used to be allocated on stack.
Change your return statement to
```
return strdup(file);
``` | You are returning a pointer points to the stack variable. When the function returns, the stack gets popped off. The stack variable no longer exists, the pointer become a dangling pointer.
One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this:
```
char* strdup(const char* org)
{
if(org == NULL) return NULL;
char* newstr = malloc(strlen(org)+1);
char* p;
if(newstr == NULL) return NULL;
p = newstr;
while(*org) *p++ = *org++; /* copy the string. */
return newstr;
}
```
And then:
```
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */
/* do something... */
char* ListFiles() {
/* .... */
return strdup(f);
}
```
Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable. | You're trying to display a string value char file[30] that is allocated on the stack (function stack). The content of this memory is not guaranteed after the method return. You should allocate it dynamically (for ex. malloc) or eventually use global value, or allocate it on the stack of the outer function (in your example main() function) |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | You are returning a pointer points to the stack variable. When the function returns, the stack gets popped off. The stack variable no longer exists, the pointer become a dangling pointer.
One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function. | You're trying to display a string value char file[30] that is allocated on the stack (function stack). The content of this memory is not guaranteed after the method return. You should allocate it dynamically (for ex. malloc) or eventually use global value, or allocate it on the stack of the outer function (in your example main() function) |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this:
```
char* strdup(const char* org)
{
if(org == NULL) return NULL;
char* newstr = malloc(strlen(org)+1);
char* p;
if(newstr == NULL) return NULL;
p = newstr;
while(*org) *p++ = *org++; /* copy the string. */
return newstr;
}
```
And then:
```
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */
/* do something... */
char* ListFiles() {
/* .... */
return strdup(f);
}
```
Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable. | You are returning a pointer points to the stack variable. When the function returns, the stack gets popped off. The stack variable no longer exists, the pointer become a dangling pointer.
One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | What you're doing is returning a pointer to a local variable, which used to be allocated on stack.
Change your return statement to
```
return strdup(file);
``` | `file` is a stack variable in `ListFiles()` and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid.
If you want to return a string, you should [allocate it on the heap](http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html), return it, use it, then free it once you're done using it. |
10,131,464 | I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
```
char* ListFiles(){
FILE *fp;
char file[30];
char *f;
if((fp=fopen("list","r"))==NULL)
{
...
}
while (!feof(fp))
{
fgets(file,50,fp);
}
fclose(fp);
f=file;
printf("%s",f); //get display!!!
return f;
}
int main(){
char *files;
...
...
files=ListFiles();
printf("%s",files); //nothing display!!
sent();
}
```
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113845/"
] | `file` is a stack variable in `ListFiles()` and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid.
If you want to return a string, you should [allocate it on the heap](http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html), return it, use it, then free it once you're done using it. | you shouldn't return data that sits on automatic storage, when you return it goes out of scope. |
47,978,833 | I'm creating my first bootstrap frontend, and I'm experiencing some issues which I'm not able to solve:
[](https://i.stack.imgur.com/az6go.png)
The row expanding to the whole width of the container, the max column width (12 units) will not extend to this width:
[](https://i.stack.imgur.com/3vMXm.png)
Further on, why is within the container writing over the padding:
[](https://i.stack.imgur.com/vx9ne.png)
Any hints appreciated!
I already tried to use container-fluid class, but the row seems not to get the max width.
Whole HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>Snoo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Snoo!</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reddit!</a>
</li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="row">
<div class="col_xl-12">
<div id="content">
<h1>Snoo!</h1>
<hr>
<h3>A chatbot based on a million reddit comments, quiet salty!</h3>
<button class="btn btn-primary btn-lg">Learn more!</button>
</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</html>
```
css:
```
#content {
text-align: center;
padding-top: 25%
}
``` | 2017/12/26 | [
"https://Stackoverflow.com/questions/47978833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7109315/"
] | your class name wrong `col_xl-12` to change class name `col-xl-12`
[](https://i.stack.imgur.com/P6IcL.png)
<https://v4-alpha.getbootstrap.com/layout/grid/> | I'm seeing a typo, try to change:
`col_xl-12` to -> `col-xl-12` |
47,978,833 | I'm creating my first bootstrap frontend, and I'm experiencing some issues which I'm not able to solve:
[](https://i.stack.imgur.com/az6go.png)
The row expanding to the whole width of the container, the max column width (12 units) will not extend to this width:
[](https://i.stack.imgur.com/3vMXm.png)
Further on, why is within the container writing over the padding:
[](https://i.stack.imgur.com/vx9ne.png)
Any hints appreciated!
I already tried to use container-fluid class, but the row seems not to get the max width.
Whole HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>Snoo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Snoo!</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reddit!</a>
</li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="row">
<div class="col_xl-12">
<div id="content">
<h1>Snoo!</h1>
<hr>
<h3>A chatbot based on a million reddit comments, quiet salty!</h3>
<button class="btn btn-primary btn-lg">Learn more!</button>
</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</html>
```
css:
```
#content {
text-align: center;
padding-top: 25%
}
``` | 2017/12/26 | [
"https://Stackoverflow.com/questions/47978833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7109315/"
] | your class name wrong `col_xl-12` to change class name `col-xl-12`
[](https://i.stack.imgur.com/P6IcL.png)
<https://v4-alpha.getbootstrap.com/layout/grid/> | 1. Remove container from your coding. Then the row will have full width
2. your class should be `col-*-*`, but you used `col_xl-12`
The HTML Structure Will be:
```
<div class="row">
<div class="/* Container or Container-fluid or Col-* */">
</div>
</div>
``` |
47,978,833 | I'm creating my first bootstrap frontend, and I'm experiencing some issues which I'm not able to solve:
[](https://i.stack.imgur.com/az6go.png)
The row expanding to the whole width of the container, the max column width (12 units) will not extend to this width:
[](https://i.stack.imgur.com/3vMXm.png)
Further on, why is within the container writing over the padding:
[](https://i.stack.imgur.com/vx9ne.png)
Any hints appreciated!
I already tried to use container-fluid class, but the row seems not to get the max width.
Whole HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>Snoo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Snoo!</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reddit!</a>
</li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="row">
<div class="col_xl-12">
<div id="content">
<h1>Snoo!</h1>
<hr>
<h3>A chatbot based on a million reddit comments, quiet salty!</h3>
<button class="btn btn-primary btn-lg">Learn more!</button>
</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</html>
```
css:
```
#content {
text-align: center;
padding-top: 25%
}
``` | 2017/12/26 | [
"https://Stackoverflow.com/questions/47978833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7109315/"
] | I'm seeing a typo, try to change:
`col_xl-12` to -> `col-xl-12` | 1. Remove container from your coding. Then the row will have full width
2. your class should be `col-*-*`, but you used `col_xl-12`
The HTML Structure Will be:
```
<div class="row">
<div class="/* Container or Container-fluid or Col-* */">
</div>
</div>
``` |
15,385,002 | I am using django-cms to design a site,as of now i had to create a basic home page with a menu bar like `About Us`, `Products`, `Contact Us` etc.,
I had done all the necessary settings of `django` and `django-cms`, activated the admin section and working perfectly.
I have created a `Home Page template` that contains the `About Us`, `Products`, `Contact Us` and created a page called `aboutus` through django-cms `admin` with a slug `about-us`.
Now i had given that slug `about-us` which is nothing but a url in the anchor tag for `About Us` menu , so when i clicked the link its working fine and redirecting me to the page `aboutus` with the url in the browser as `http://localhost:8080/aboutus`.
but the problem is , when i clicked again on the `aboutus` link its generating the url twice that is like `http://localhost:8080/aboutus/aboutus`, i mean for each and every click, the slug `aboutus` is appending to the url.
Below are my codes
**settings.py**
```
TEMPLATE_CONTEXT_PROCESSORS = (
.......
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
)
CMS_TEMPLATES = (
('home.html', gettext('Home')),
('aboutus.html', gettext("About Us")),
('management_team.html',gettext('Management Team')),
)
.....
....
```
**urls.py**
```
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cms.urls')),
)
```
**home.html**
```
{% load cms_tags sekizai_tags %}
{% load staticfiles %}
{% load staticfiles %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{% block head %}{% endblock %}</title>
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
<div class="submenu">
<a href="about-us">About Company Services</a><br />
<a href="management-team">Our Management Team</a>
</div>
<a href="about-us" class="menu aboutus">About Us</a></div>
{% render_block "js" %}
</body>
</html>
```
So above is my overall code,in which `home.html` displays a home page with the menu as below
(by using some css styles)
```
About Us
About Company Services
Our Management Team
```
So when i clicked on the the link `About Us` the url generating is `http://localhost:8000/about-us/` and immediately when we clicked on `About Company Services` the url generating is `http://localhost:8000/about-us/about-us` and `http://localhost:8000/about-us/about-us/our-management-team/` when clicked on `Our Management Team` immediately . So the url is appending to the previous url instead of appending to the `domain name`.
I have created all the pages by using the created templates from django-cms admin as
```
Page Name slug
About Us about-us
About Company Services about-us
Our Management Team our-management-team
```
So whats wrong in the above code, why the urls are appending to the previous urls instead of appending to the domain ?
How to create a `childs(About Company Services,Our Management Team )` from the django-cms admin to the `parent(About Us)`
Actually i want to create two pages`(About Company Services,Our Management Team )` under `About Us` page , how can we achieve this in django-cms admin
Can anyone please let me know the concept of menus in django-cms, i have tried and read the documentation of `django-cms many many many times` but unable to understand the concept of `menus` so approached `SO` | 2013/03/13 | [
"https://Stackoverflow.com/questions/15385002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342109/"
] | If this is your page layout in the admin section (`/admin/cms/page`):
```
- Home (level=0)
- About Us (level=1)
- About Company Services (level=2)
- Foo Bar (level=3)
- Our Management Team (level=2)
- Some Other Section (level=1)
- Some Sub Section (level=2)
- ...
```
When you print `{% show_menu A B C D %}` you are rendering a `ul` menu, where A,B,C & D are numbers which specify the configuration of the menu.
```
A = Start
B = End
C = Inactive
D = Active
```
So `{% show_menu 1 2 0 100 %}`
* `A=1` means start the navigation at level 1, i.e. excluding `Home` which is level 0
* `B=2` means render the navigation down to level 2, i.e. excluding `Foo Bar`
* `C=0` means that for inactive trails, show 0 levels. So if we are currently on the `About Us` page, we wont see any links in the menu below `Some Other Section` (as this is an inactive trail), but we will still see `About Company...` and `Out Management...` (as this is an active trail)
* `D=100` means that for the currently active trail, show down to 100 levels (this is why we see the `About Company...` and `Our Management` mentioned above)
So the result is:
```
- About Us (level=1)
- About Company Services (level=2)
- Our Management Team (level=2)
- Some Other Section (level=1)
``` | use the {% show\_menu %} template tag to render menus. Be sure to read the documentation for that as well. |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | The question is internally inconsistent. I will assume if a line has 3 commas then we want to change the first and last comma to a period. Otherwise the line has 2 commas and we only want to change the last comma to a period:
```
$ sed -E '/(,[^,]+){3}/ { s/^([^,]+),/\1./ }; s/,([^,]+)$/.\1/' P7.csv
30,-4.098511E-02
30.05,-4.098511E-02
66.7,-1.865433
```
I suggest you regenerate the data from the original source in an unambitious format if at all possible. The heuristic you asked us to implement which may introduce (data) errors.
This invocation you mention will modify the file P7.csv and write a blank file P7\_test.csv. This is probably not what you want (where ... is some script):
```
sed -i ... P7.csv > P7_test.csv
``` | You can try this sed:
```bash
cat file
30,-4,098511E-02
66,7,-1,865433
42,35,18,15199
30,05,-4,098511E-02
sed -E 's/^([0-9]*),([0-9])/\1.\2/; s/([0-9]),([0-9E-]*)$/\1.\2/' file
30,-4,098511E-02
66.7,-1.865433
42.35,18.15199
30.05,-4.098511E-02
```
Here `^([0-9]*),([0-9])` matches 2 digits at start separated by a `,` in capture groups 1 and 2. In replacement we place a dot between captured values. |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | Assuming you know there are only 2 columns *and* the second column is always a floating-point number (when there are any), you can use this:
```
awk -F, 'NF == 3 { $0 = $1FS$2"."$3 } NF == 4 { $0 = $1"."$2FS$3"."$4 } 1' infile
``` | You can try this sed:
```bash
cat file
30,-4,098511E-02
66,7,-1,865433
42,35,18,15199
30,05,-4,098511E-02
sed -E 's/^([0-9]*),([0-9])/\1.\2/; s/([0-9]),([0-9E-]*)$/\1.\2/' file
30,-4,098511E-02
66.7,-1.865433
42.35,18.15199
30.05,-4.098511E-02
```
Here `^([0-9]*),([0-9])` matches 2 digits at start separated by a `,` in capture groups 1 and 2. In replacement we place a dot between captured values. |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | You could easily do this tsk in `awk`. Please try following code written and tested in GNU `awk`.
```
awk '
BEGIN{ FS=OFS="," }
NF==3{
match($0,/(^[^,]*),([^,]*),(.*$)/,arr)
print arr[1],arr[2]"."arr[3]
next
}
NF==4{
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr)
print arr[1]"."arr[2],arr[3]"."arr[4]
}
' Input_file
```
***NOTE:*** In case you want to save output into `Input_file` itself then append `> temp && mv temp Input_file` to above code.
***Explanation:*** Adding detailed explanation for above `awk` code.
```
awk ' ##Starting awk program from here.
BEGIN{ FS=OFS="," } ##Setting FS and OFS as comma in BEGIN section of this awk program.
NF==3{ ##Checking if there are 3 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),(.*$)/,arr) ##Using match to match regex (^[^,]*),([^,]*),(.*$) to create 3 capturing group to be saved into arr array.
print arr[1],arr[2]"."arr[3] ##Printing 1st element of arr followed by comma followed by 2nd element followed by DOT followed by 3rd element of arr.
next ##next will skip all further statements from here.
}
NF==4{ ##Checking if there are 4 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr) ##Using match to match regex (^[^,]*),([^,]*),([^,]*),(.*)$ to create 4 capturing group to be saved into arr array.
print arr[1]"."arr[2],arr[3]"."arr[4] ##Printing 1st element of arr followed by dot followed by 2nd element followed by comma followed by 3rd element of arr, followed by DOT followed by 4th element of arr.
}
' Input_file ##Mentioning Input_file name here.
``` | You can try this sed:
```bash
cat file
30,-4,098511E-02
66,7,-1,865433
42,35,18,15199
30,05,-4,098511E-02
sed -E 's/^([0-9]*),([0-9])/\1.\2/; s/([0-9]),([0-9E-]*)$/\1.\2/' file
30,-4,098511E-02
66.7,-1.865433
42.35,18.15199
30.05,-4.098511E-02
```
Here `^([0-9]*),([0-9])` matches 2 digits at start separated by a `,` in capture groups 1 and 2. In replacement we place a dot between captured values. |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | Assuming you know there are only 2 columns *and* the second column is always a floating-point number (when there are any), you can use this:
```
awk -F, 'NF == 3 { $0 = $1FS$2"."$3 } NF == 4 { $0 = $1"."$2FS$3"."$4 } 1' infile
``` | The question is internally inconsistent. I will assume if a line has 3 commas then we want to change the first and last comma to a period. Otherwise the line has 2 commas and we only want to change the last comma to a period:
```
$ sed -E '/(,[^,]+){3}/ { s/^([^,]+),/\1./ }; s/,([^,]+)$/.\1/' P7.csv
30,-4.098511E-02
30.05,-4.098511E-02
66.7,-1.865433
```
I suggest you regenerate the data from the original source in an unambitious format if at all possible. The heuristic you asked us to implement which may introduce (data) errors.
This invocation you mention will modify the file P7.csv and write a blank file P7\_test.csv. This is probably not what you want (where ... is some script):
```
sed -i ... P7.csv > P7_test.csv
``` |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | You could easily do this tsk in `awk`. Please try following code written and tested in GNU `awk`.
```
awk '
BEGIN{ FS=OFS="," }
NF==3{
match($0,/(^[^,]*),([^,]*),(.*$)/,arr)
print arr[1],arr[2]"."arr[3]
next
}
NF==4{
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr)
print arr[1]"."arr[2],arr[3]"."arr[4]
}
' Input_file
```
***NOTE:*** In case you want to save output into `Input_file` itself then append `> temp && mv temp Input_file` to above code.
***Explanation:*** Adding detailed explanation for above `awk` code.
```
awk ' ##Starting awk program from here.
BEGIN{ FS=OFS="," } ##Setting FS and OFS as comma in BEGIN section of this awk program.
NF==3{ ##Checking if there are 3 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),(.*$)/,arr) ##Using match to match regex (^[^,]*),([^,]*),(.*$) to create 3 capturing group to be saved into arr array.
print arr[1],arr[2]"."arr[3] ##Printing 1st element of arr followed by comma followed by 2nd element followed by DOT followed by 3rd element of arr.
next ##next will skip all further statements from here.
}
NF==4{ ##Checking if there are 4 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr) ##Using match to match regex (^[^,]*),([^,]*),([^,]*),(.*)$ to create 4 capturing group to be saved into arr array.
print arr[1]"."arr[2],arr[3]"."arr[4] ##Printing 1st element of arr followed by dot followed by 2nd element followed by comma followed by 3rd element of arr, followed by DOT followed by 4th element of arr.
}
' Input_file ##Mentioning Input_file name here.
``` | The question is internally inconsistent. I will assume if a line has 3 commas then we want to change the first and last comma to a period. Otherwise the line has 2 commas and we only want to change the last comma to a period:
```
$ sed -E '/(,[^,]+){3}/ { s/^([^,]+),/\1./ }; s/,([^,]+)$/.\1/' P7.csv
30,-4.098511E-02
30.05,-4.098511E-02
66.7,-1.865433
```
I suggest you regenerate the data from the original source in an unambitious format if at all possible. The heuristic you asked us to implement which may introduce (data) errors.
This invocation you mention will modify the file P7.csv and write a blank file P7\_test.csv. This is probably not what you want (where ... is some script):
```
sed -i ... P7.csv > P7_test.csv
``` |
73,660,460 | Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that?
```py
with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
fm_data.to_excel(writer, sheet_name='Raw Data1')
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73660460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875567/"
] | Assuming you know there are only 2 columns *and* the second column is always a floating-point number (when there are any), you can use this:
```
awk -F, 'NF == 3 { $0 = $1FS$2"."$3 } NF == 4 { $0 = $1"."$2FS$3"."$4 } 1' infile
``` | You could easily do this tsk in `awk`. Please try following code written and tested in GNU `awk`.
```
awk '
BEGIN{ FS=OFS="," }
NF==3{
match($0,/(^[^,]*),([^,]*),(.*$)/,arr)
print arr[1],arr[2]"."arr[3]
next
}
NF==4{
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr)
print arr[1]"."arr[2],arr[3]"."arr[4]
}
' Input_file
```
***NOTE:*** In case you want to save output into `Input_file` itself then append `> temp && mv temp Input_file` to above code.
***Explanation:*** Adding detailed explanation for above `awk` code.
```
awk ' ##Starting awk program from here.
BEGIN{ FS=OFS="," } ##Setting FS and OFS as comma in BEGIN section of this awk program.
NF==3{ ##Checking if there are 3 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),(.*$)/,arr) ##Using match to match regex (^[^,]*),([^,]*),(.*$) to create 3 capturing group to be saved into arr array.
print arr[1],arr[2]"."arr[3] ##Printing 1st element of arr followed by comma followed by 2nd element followed by DOT followed by 3rd element of arr.
next ##next will skip all further statements from here.
}
NF==4{ ##Checking if there are 4 number of fields in current line then do following.
match($0,/(^[^,]*),([^,]*),([^,]*),(.*)$/,arr) ##Using match to match regex (^[^,]*),([^,]*),([^,]*),(.*)$ to create 4 capturing group to be saved into arr array.
print arr[1]"."arr[2],arr[3]"."arr[4] ##Printing 1st element of arr followed by dot followed by 2nd element followed by comma followed by 3rd element of arr, followed by DOT followed by 4th element of arr.
}
' Input_file ##Mentioning Input_file name here.
``` |
2,243,423 | i want the assemblies (\*.dll) files for silverlight charting controls
or give me path that where does it stoer when we install the toolkit
in our computer | 2010/02/11 | [
"https://Stackoverflow.com/questions/2243423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255609/"
] | When you've installed the toolkit you will find the dlls in:-
`C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Toolkit\Nov09\Bin`
or on a 32 bit system:-
`C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Toolkit\Nov09\Bin`
The above is obviously for the November 09 release, no doubt as this answer ages the latest release will be in a similarly named folder.
However they should be listed in the .NET tab when you add references. | There should be a toolkit folder under C:\Program Files\Microsoft SDKs\Silverlight\v3.0\ after installing toolkit. |
1,774,129 | I'm looking for a good way to find the process ID of a particular Windows Service.
In particular, I need to find the pid of the default "WebClient" service that ships with Windows. It's hosted as a "local service" within a svchost.exe process. I see that when I use netstat to see what processes are using what ports it lists [WebClient] under the process name, so I'm hoping that there is some (relatively) simple mechanism to find this information. | 2009/11/21 | [
"https://Stackoverflow.com/questions/1774129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19404/"
] | [`QueryServiceStatusEx`](http://msdn.microsoft.com/en-us/library/ms684941%28VS.85%29.aspx) returns a [`SERVICE_STATUS_PROCESS`](http://msdn.microsoft.com/en-us/library/ms685992%28VS.85%29.aspx), which contains the process identifier for the process under which the service is running.
You can use [`OpenService`](http://msdn.microsoft.com/en-us/library/ms684330%28VS.85%29.aspx) to obtain a handle to a service from its name. | Here's a minimalist C++ function to do exactly what you want:
```
DWORD GetServicePid(const char* serviceName)
{
const auto hScm = OpenSCManager(nullptr, nullptr, NULL);
const auto hSc = OpenService(hScm, serviceName, SERVICE_QUERY_STATUS);
SERVICE_STATUS_PROCESS ssp = {};
DWORD bytesNeeded = 0;
QueryServiceStatusEx(hSc, SC_STATUS_PROCESS_INFO, reinterpret_cast<LPBYTE>(&ssp), sizeof(ssp), &bytesNeeded);
CloseServiceHandle(hSc);
CloseServiceHandle(hScm);
return ssp.dwProcessId;
}
``` |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | I found a good benchmark comparison web page that basically compares 5 renowned databases:
* LevelDB
* Kyoto TreeDB
* SQLite3
* MDB
* BerkeleyDB
You should check it out before making your choice: <http://symas.com/mdb/microbench/>.
P.S - I know you've already tested them, but you should also consider that your configuration for each of these tests was not optimized as the benchmark shows otherwise. | 300 M \* 8 bytes = 2.4GB. That will probably fit into memory (if the OS does not restrict the address space to 31 bits)
Since you'll also need to handle overflow, (either by a rehashing scheme or by chaining) memory gets even tighter, for linear probing you probably need > 400M slots, chaining will increase the sizeof item to 12 bytes (bit fiddling might gain you a few bits). That would increase the total footprint to circa 3.6 GB.
In any case you will need a specially crafted kernel that restricts it's own "reserved" address space to a few hundred MB. Not impossible, but a major operation. Escaping to a disk-based thing would be too slow, in all cases. (PAE could save you, but it is tricky)
IMHO your best choice would be to migrate to a 64 bits platform. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | 500,000 entries per second without holding the working set in memory? Wow.
In the general case this is not possible using HDDs and even difficult SSDs.
Have you any locality properties that might help to make the task a bit easier? What kind of queries do you have? | Berkely DB could do it for you.
I acheived 50000 inserts per second about 8 years ago and a final database of 70 billion records. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | David Segleau, here. Product Manager for Berkeley DB.
The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior.
From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment.
It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput.
I hope that helps.
Good luck with your application.
Regards,
Dave | Try [ZooLib](http://www.zoolib.org/).
It provides a database with a C++ API, that was originally written for a high-performance multimedia database for educational institutions called Knowledge Forum. It could handle 3,000 simultaneous Mac and Windows clients (also written in ZooLib - it's a cross-platform application framework), all of them streaming audio, video and working with graphically rich documents created by the teachers and students.
It has two low-level APIs for actually writing your bytes to disk. One is very fast but is not fault-tolerant. The other is fault-tolerant but not as fast.
I'm one of ZooLib's developers, but I don't have much experience with ZooLib's database component. There is also no documentation - you'd have to read the source to figure out how it works. That's my own damn fault, as I took on the job of writing ZooLib's manual over ten years ago, but barely started it.
ZooLib's primarily developer [Andy Green](http://www.em.net/) is a great guy and always happy to answer questions. What I suggest you do is subscribe to ZooLib's developer list at SourceForge then ask on the list how to use the database. Most likely Andy will answer you himself but maybe one of our other developers will.
ZooLib is Open Source under the MIT License, and is really high-quality, mature code. It has been under continuous development since 1990 or so, and was placed in Open Source in 2000.
Don't be concerned that we haven't released a tarball since 2003. We probably should, as this leads lots of potential users to think it's been abandoned, but it is very actively used and maintained. Just get the source from Subversion.
Andy is a self-employed consultant. If you don't have time but you do have a budget, he would do a very good job of writing custom, maintainable top-quality C++ code to suit your needs.
I would too, if it were any part of ZooLib other than the database, which as I said I am unfamiliar with. I've done a lot of my own consulting work with ZooLib's UI framework. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | David Segleau, here. Product Manager for Berkeley DB.
The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior.
From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment.
It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput.
I hope that helps.
Good luck with your application.
Regards,
Dave | We use [Redis](http://redis.io/). Written in C, its only slightly more complicated than memcached by design. Never tried to use that many rows but for us latency is very important and it handles those latencies well and lets us store the data in the disk
Here is a [bench mark blog entry](http://antirez.com/post/redis-memcached-benchmark.html), comparing redis and memcached. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | 300 M \* 8 bytes = 2.4GB. That will probably fit into memory (if the OS does not restrict the address space to 31 bits)
Since you'll also need to handle overflow, (either by a rehashing scheme or by chaining) memory gets even tighter, for linear probing you probably need > 400M slots, chaining will increase the sizeof item to 12 bytes (bit fiddling might gain you a few bits). That would increase the total footprint to circa 3.6 GB.
In any case you will need a specially crafted kernel that restricts it's own "reserved" address space to a few hundred MB. Not impossible, but a major operation. Escaping to a disk-based thing would be too slow, in all cases. (PAE could save you, but it is tricky)
IMHO your best choice would be to migrate to a 64 bits platform. | We use [Redis](http://redis.io/). Written in C, its only slightly more complicated than memcached by design. Never tried to use that many rows but for us latency is very important and it handles those latencies well and lets us store the data in the disk
Here is a [bench mark blog entry](http://antirez.com/post/redis-memcached-benchmark.html), comparing redis and memcached. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | Try [ZooLib](http://www.zoolib.org/).
It provides a database with a C++ API, that was originally written for a high-performance multimedia database for educational institutions called Knowledge Forum. It could handle 3,000 simultaneous Mac and Windows clients (also written in ZooLib - it's a cross-platform application framework), all of them streaming audio, video and working with graphically rich documents created by the teachers and students.
It has two low-level APIs for actually writing your bytes to disk. One is very fast but is not fault-tolerant. The other is fault-tolerant but not as fast.
I'm one of ZooLib's developers, but I don't have much experience with ZooLib's database component. There is also no documentation - you'd have to read the source to figure out how it works. That's my own damn fault, as I took on the job of writing ZooLib's manual over ten years ago, but barely started it.
ZooLib's primarily developer [Andy Green](http://www.em.net/) is a great guy and always happy to answer questions. What I suggest you do is subscribe to ZooLib's developer list at SourceForge then ask on the list how to use the database. Most likely Andy will answer you himself but maybe one of our other developers will.
ZooLib is Open Source under the MIT License, and is really high-quality, mature code. It has been under continuous development since 1990 or so, and was placed in Open Source in 2000.
Don't be concerned that we haven't released a tarball since 2003. We probably should, as this leads lots of potential users to think it's been abandoned, but it is very actively used and maintained. Just get the source from Subversion.
Andy is a self-employed consultant. If you don't have time but you do have a budget, he would do a very good job of writing custom, maintainable top-quality C++ code to suit your needs.
I would too, if it were any part of ZooLib other than the database, which as I said I am unfamiliar with. I've done a lot of my own consulting work with ZooLib's UI framework. | We use [Redis](http://redis.io/). Written in C, its only slightly more complicated than memcached by design. Never tried to use that many rows but for us latency is very important and it handles those latencies well and lets us store the data in the disk
Here is a [bench mark blog entry](http://antirez.com/post/redis-memcached-benchmark.html), comparing redis and memcached. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | David Segleau, here. Product Manager for Berkeley DB.
The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior.
From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment.
It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput.
I hope that helps.
Good luck with your application.
Regards,
Dave | 300 M \* 8 bytes = 2.4GB. That will probably fit into memory (if the OS does not restrict the address space to 31 bits)
Since you'll also need to handle overflow, (either by a rehashing scheme or by chaining) memory gets even tighter, for linear probing you probably need > 400M slots, chaining will increase the sizeof item to 12 bytes (bit fiddling might gain you a few bits). That would increase the total footprint to circa 3.6 GB.
In any case you will need a specially crafted kernel that restricts it's own "reserved" address space to a few hundred MB. Not impossible, but a major operation. Escaping to a disk-based thing would be too slow, in all cases. (PAE could save you, but it is tricky)
IMHO your best choice would be to migrate to a 64 bits platform. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | David Segleau, here. Product Manager for Berkeley DB.
The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior.
From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment.
It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput.
I hope that helps.
Good luck with your application.
Regards,
Dave | 500,000 entries per second without holding the working set in memory? Wow.
In the general case this is not possible using HDDs and even difficult SSDs.
Have you any locality properties that might help to make the task a bit easier? What kind of queries do you have? |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | David Segleau, here. Product Manager for Berkeley DB.
The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior.
From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment.
It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput.
I hope that helps.
Good luck with your application.
Regards,
Dave | Berkely DB could do it for you.
I acheived 50000 inserts per second about 8 years ago and a final database of 70 billion records. |
7,229,552 | I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second.
I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries).
I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question.
I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7229552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741628/"
] | I found a good benchmark comparison web page that basically compares 5 renowned databases:
* LevelDB
* Kyoto TreeDB
* SQLite3
* MDB
* BerkeleyDB
You should check it out before making your choice: <http://symas.com/mdb/microbench/>.
P.S - I know you've already tested them, but you should also consider that your configuration for each of these tests was not optimized as the benchmark shows otherwise. | Try [ZooLib](http://www.zoolib.org/).
It provides a database with a C++ API, that was originally written for a high-performance multimedia database for educational institutions called Knowledge Forum. It could handle 3,000 simultaneous Mac and Windows clients (also written in ZooLib - it's a cross-platform application framework), all of them streaming audio, video and working with graphically rich documents created by the teachers and students.
It has two low-level APIs for actually writing your bytes to disk. One is very fast but is not fault-tolerant. The other is fault-tolerant but not as fast.
I'm one of ZooLib's developers, but I don't have much experience with ZooLib's database component. There is also no documentation - you'd have to read the source to figure out how it works. That's my own damn fault, as I took on the job of writing ZooLib's manual over ten years ago, but barely started it.
ZooLib's primarily developer [Andy Green](http://www.em.net/) is a great guy and always happy to answer questions. What I suggest you do is subscribe to ZooLib's developer list at SourceForge then ask on the list how to use the database. Most likely Andy will answer you himself but maybe one of our other developers will.
ZooLib is Open Source under the MIT License, and is really high-quality, mature code. It has been under continuous development since 1990 or so, and was placed in Open Source in 2000.
Don't be concerned that we haven't released a tarball since 2003. We probably should, as this leads lots of potential users to think it's been abandoned, but it is very actively used and maintained. Just get the source from Subversion.
Andy is a self-employed consultant. If you don't have time but you do have a budget, he would do a very good job of writing custom, maintainable top-quality C++ code to suit your needs.
I would too, if it were any part of ZooLib other than the database, which as I said I am unfamiliar with. I've done a lot of my own consulting work with ZooLib's UI framework. |
36,711,068 | My middleware class is in different class library project and controller is in different project. What I am trying to do, if specific condition does not meet then redirect to the Custom Controller/Action method from middleware.
However, I am not able to do that with Response.Redirect method.
How can I do this in middleware class ?
Any help on this appreciated !
Rohit | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421482/"
] | It seems you're using a middleware for the wrong reasons.
I recommend that you either have the middleware return a (very minimal) 404 by simply writing it to the response stream (instead of forwarding to `Next()`), or don't do this in a middleware at all but instead in a globally registered `IActionFilter` in your MVC app.
---
I've explained the rationale for the above advice in the comments, but I think it's important enough to lift into the actual answer:
In a middleware pipeline, you want each component to be as independent as possible. A couple of things enable this loose coupling in OWIN:
* The input to, and output from, each component has the same format, whether there are 10 other middleware components before it, or none at all
* The convention is that each part of the pipeline can do one or more of three things, in this order:
1. Read (and modify) the incoming request.
2. Decide to handle the request entirely, or forward handling to the next component.
3. Write to the response stream.
When sticking to these conventions, it becomes very easy to compose, decompose and re-compose pipelines from reusable middleware components. (Want request logging? Just hook up a middleware component at the start of the pipe. Want some general authentication logic across the board? Add a component in the auth stage of the pipe. Want to switch to a different logging framework? Replace the logging component. Want to apply the same logging across an ecosystem of microservices? Re-use the component. Etcetera, ad infinum...) This works so well, because the components both stay within their boundaries, and work with a contract that the web server itself can understand.
ASP.NET WebAPI might seem to be a different beast, but in reality it's just another OWIN component which is always configured to handle the request, and never to forward to a next component (and thus they've made it difficult to register a component after WebApi in the pipeline...).
What you're trying to do, breaks the contract of the second point there - you want to tell the next component how to handle the request. *But that's not up to you - it's up to the next component.* | Here is middleware that examines the request and redirects. It works with either inline middleware or with a middleware class.
```
public void Configure(IApplicationBuilder app)
{
// use inline middleware
app.Use(async (context, next) =>
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/foo"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await next.Invoke();
}
});
// or use a middleware class
app.UseMiddleware<RedirectMiddleware>();
app.UseMvc();
}
```
Here is the middleware class.
```
public class RedirectMiddleware
{
private readonly RequestDelegate _next;
public RedirectMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/bar"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await _next.Invoke(context);
}
}
}
```
See [Docs Β» Fundamentals Β» Middleware](https://docs.asp.net/en/latest/fundamentals/middleware.html#writing-middleware) for more info. |
36,711,068 | My middleware class is in different class library project and controller is in different project. What I am trying to do, if specific condition does not meet then redirect to the Custom Controller/Action method from middleware.
However, I am not able to do that with Response.Redirect method.
How can I do this in middleware class ?
Any help on this appreciated !
Rohit | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421482/"
] | It seems you're using a middleware for the wrong reasons.
I recommend that you either have the middleware return a (very minimal) 404 by simply writing it to the response stream (instead of forwarding to `Next()`), or don't do this in a middleware at all but instead in a globally registered `IActionFilter` in your MVC app.
---
I've explained the rationale for the above advice in the comments, but I think it's important enough to lift into the actual answer:
In a middleware pipeline, you want each component to be as independent as possible. A couple of things enable this loose coupling in OWIN:
* The input to, and output from, each component has the same format, whether there are 10 other middleware components before it, or none at all
* The convention is that each part of the pipeline can do one or more of three things, in this order:
1. Read (and modify) the incoming request.
2. Decide to handle the request entirely, or forward handling to the next component.
3. Write to the response stream.
When sticking to these conventions, it becomes very easy to compose, decompose and re-compose pipelines from reusable middleware components. (Want request logging? Just hook up a middleware component at the start of the pipe. Want some general authentication logic across the board? Add a component in the auth stage of the pipe. Want to switch to a different logging framework? Replace the logging component. Want to apply the same logging across an ecosystem of microservices? Re-use the component. Etcetera, ad infinum...) This works so well, because the components both stay within their boundaries, and work with a contract that the web server itself can understand.
ASP.NET WebAPI might seem to be a different beast, but in reality it's just another OWIN component which is always configured to handle the request, and never to forward to a next component (and thus they've made it difficult to register a component after WebApi in the pipeline...).
What you're trying to do, breaks the contract of the second point there - you want to tell the next component how to handle the request. *But that's not up to you - it's up to the next component.* | You can use "Request Editing Middleware" to change the nature of the request as it moves down the pipeline. This fits in with the general "best practices" and will be more efficient than sending a redirect notice back to the browser.
This example redirects to an action method than can return an image:
```
public class ResolveImageMiddleware
{
private readonly RequestDelegate _next;
public ResolveImageMiddleware(RequestDelegate deg)
{
_next = deg;
}
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
var path = context.Request.Path;
if (path.HasValue && path.Value.StartsWith("/imgs"))
{
context.Request.Path = "/Home/GetImageFromDb";
context.Request.QueryString = new QueryString("?title=" + path.Value.Replace("/imgs/", ""));
}
await _next(context);
}
}
```
And create an action method that takes a query and can return a file:
```
public class HomeController : Controller
{
private EFImageRepo imageRepository;
public HomeController(EFImageRepo repo)
{
imageRepository = repo;
}
public FileResult GetImageFromDb([FromQuery]string title)
{
var img = imageRepository.GetImg(title);
if (img != null)
{
byte[] contents = img.ImageBytes;
return File(contents, "image/jpg");
}
return null;
}
}
```
If you use a redirect on response, it will cause the user's browser to receive a redirect notice and then send a new request to your application, rather than consuming the original request and spitting out the file right away. |
36,711,068 | My middleware class is in different class library project and controller is in different project. What I am trying to do, if specific condition does not meet then redirect to the Custom Controller/Action method from middleware.
However, I am not able to do that with Response.Redirect method.
How can I do this in middleware class ?
Any help on this appreciated !
Rohit | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421482/"
] | Here is middleware that examines the request and redirects. It works with either inline middleware or with a middleware class.
```
public void Configure(IApplicationBuilder app)
{
// use inline middleware
app.Use(async (context, next) =>
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/foo"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await next.Invoke();
}
});
// or use a middleware class
app.UseMiddleware<RedirectMiddleware>();
app.UseMvc();
}
```
Here is the middleware class.
```
public class RedirectMiddleware
{
private readonly RequestDelegate _next;
public RedirectMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/bar"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await _next.Invoke(context);
}
}
}
```
See [Docs Β» Fundamentals Β» Middleware](https://docs.asp.net/en/latest/fundamentals/middleware.html#writing-middleware) for more info. | You can use "Request Editing Middleware" to change the nature of the request as it moves down the pipeline. This fits in with the general "best practices" and will be more efficient than sending a redirect notice back to the browser.
This example redirects to an action method than can return an image:
```
public class ResolveImageMiddleware
{
private readonly RequestDelegate _next;
public ResolveImageMiddleware(RequestDelegate deg)
{
_next = deg;
}
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
var path = context.Request.Path;
if (path.HasValue && path.Value.StartsWith("/imgs"))
{
context.Request.Path = "/Home/GetImageFromDb";
context.Request.QueryString = new QueryString("?title=" + path.Value.Replace("/imgs/", ""));
}
await _next(context);
}
}
```
And create an action method that takes a query and can return a file:
```
public class HomeController : Controller
{
private EFImageRepo imageRepository;
public HomeController(EFImageRepo repo)
{
imageRepository = repo;
}
public FileResult GetImageFromDb([FromQuery]string title)
{
var img = imageRepository.GetImg(title);
if (img != null)
{
byte[] contents = img.ImageBytes;
return File(contents, "image/jpg");
}
return null;
}
}
```
If you use a redirect on response, it will cause the user's browser to receive a redirect notice and then send a new request to your application, rather than consuming the original request and spitting out the file right away. |
9,837,050 | In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] | I would preffer to exercise all the private methods thru the public available calls. There must be a path to execute each private line from a public call and if it is not there you can delete that code.
Using internal instead of private could end with a big mess, I won't use that approach. | As a Java developer, I do. I don't change access levels, either. I use reflection to get access to private methods. I don't have to grant it to my users, and I don't have to show them my unit tests.
It's a dirty secret of Java: you can always circumvent access restrictions with reflection. I don't know if it's also true of C# and .NET, but you can look into it to see. |
9,837,050 | In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] | 1. No, private methods should not be tested. Your application will interact with public API only. So you should test expected behavior of your class for this interaction. Private methods is a part of inner logic implementation. Users of your class should not be care how it implemented.
2. No, it is not good. See above. You should test public API only.
3. You should test only public methods. You don't care if public method will call to private method or will not until test is passed. If test fails, fix implemetation. But don't test private methods anyway.
UPDATE (how to define what to test):
Ideally (in test-first approach) test is the first user of your class. When you write test, you try to imagine how users will use your class. Users will not interact with private methods (Reflection is cheating). So and your test, as first user of your class, should not interact with private methods. | I would preffer to exercise all the private methods thru the public available calls. There must be a path to execute each private line from a public call and if it is not there you can delete that code.
Using internal instead of private could end with a big mess, I won't use that approach. |
9,837,050 | In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] | To answer your questions briefly:
1. In general, they shouldn't. Most of the times, your private bits will be tested while testing class contract/public API. For the times this is not possible, testing private method is unit test just as anything else.
2. This is fairly common. While changing visibility might be considered bad idea, it's not as bad when it changes only to internal. However, in approaches like TDD, the need of testing usually drives your desing in such way that "hacks" like this are not needed. But like I said, it's fairly common - you shouldn't worry too much about it, unless it gets to ridiculous levels (say, entire private parts of classes exposed).
3. It is unit test as long as it tests *single unit* (or, [one logical *concept*](https://stackoverflow.com/q/9738314/343266)) of your class. Private methods more often than not are created as a results of refactorings in public parts, which most of the times will be targeted by the *single unit* testing. If you feel your private method is not longer an *unit*, it might be a refactoring call.
Also, I suggest having a look [here](https://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods/250719#250719), [here](https://stackoverflow.com/questions/9202862/is-unit-testing-private-methods-a-good-practice/9203039#9203039) and [here](https://stackoverflow.com/questions/9615597/while-unit-testing-i-frequently-require-to-test-internal-private-logic-what-i/9615860#9615860). | I would preffer to exercise all the private methods thru the public available calls. There must be a path to execute each private line from a public call and if it is not there you can delete that code.
Using internal instead of private could end with a big mess, I won't use that approach. |
9,837,050 | In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] | 1. No, private methods should not be tested. Your application will interact with public API only. So you should test expected behavior of your class for this interaction. Private methods is a part of inner logic implementation. Users of your class should not be care how it implemented.
2. No, it is not good. See above. You should test public API only.
3. You should test only public methods. You don't care if public method will call to private method or will not until test is passed. If test fails, fix implemetation. But don't test private methods anyway.
UPDATE (how to define what to test):
Ideally (in test-first approach) test is the first user of your class. When you write test, you try to imagine how users will use your class. Users will not interact with private methods (Reflection is cheating). So and your test, as first user of your class, should not interact with private methods. | As a Java developer, I do. I don't change access levels, either. I use reflection to get access to private methods. I don't have to grant it to my users, and I don't have to show them my unit tests.
It's a dirty secret of Java: you can always circumvent access restrictions with reflection. I don't know if it's also true of C# and .NET, but you can look into it to see. |
9,837,050 | In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] | To answer your questions briefly:
1. In general, they shouldn't. Most of the times, your private bits will be tested while testing class contract/public API. For the times this is not possible, testing private method is unit test just as anything else.
2. This is fairly common. While changing visibility might be considered bad idea, it's not as bad when it changes only to internal. However, in approaches like TDD, the need of testing usually drives your desing in such way that "hacks" like this are not needed. But like I said, it's fairly common - you shouldn't worry too much about it, unless it gets to ridiculous levels (say, entire private parts of classes exposed).
3. It is unit test as long as it tests *single unit* (or, [one logical *concept*](https://stackoverflow.com/q/9738314/343266)) of your class. Private methods more often than not are created as a results of refactorings in public parts, which most of the times will be targeted by the *single unit* testing. If you feel your private method is not longer an *unit*, it might be a refactoring call.
Also, I suggest having a look [here](https://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods/250719#250719), [here](https://stackoverflow.com/questions/9202862/is-unit-testing-private-methods-a-good-practice/9203039#9203039) and [here](https://stackoverflow.com/questions/9615597/while-unit-testing-i-frequently-require-to-test-internal-private-logic-what-i/9615860#9615860). | As a Java developer, I do. I don't change access levels, either. I use reflection to get access to private methods. I don't have to grant it to my users, and I don't have to show them my unit tests.
It's a dirty secret of Java: you can always circumvent access restrictions with reflection. I don't know if it's also true of C# and .NET, but you can look into it to see. |
214,215 | 
I would like to have these expressions aligned so that the kerning and slightly different character widths do not result in an uneven overall appearance. I tried using an `align` environment within `algorithm` but it resulted in errors. Here is a MWE:

```
\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Euclidβs algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
```
Source: <https://www.writelatex.com/examples/euclids-algorithm-an-example-of-how-to-write-algorithms-in-latex/mbysznrmktqf> | 2014/11/27 | [
"https://tex.stackexchange.com/questions/214215",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9610/"
] | Something like this?
```
\begin{tikzpicture}
% Set horizontal range
\pgfmathsetmacro{\nx}{8}
% Set vertical range
\pgfmathsetmacro{\ny}{2.5}
\pgfmathsetmacro{\xmin}{2*(sqrt(\ny+1)-1)/\ny}
\pgfmathsetmacro{\xmint}{2/sqrt(\ny)}
\pgfmathsetmacro{\xminb}{4/\ny}
\pgfmathsetmacro{\xmax}{2*\nx}
\begin{axis}[xmin=0,xmax=\xmax,axis x line*=middle, axis y line*=left, xtick=\empty, ytick=\empty]
\addplot[red,domain=\xmin:\xmax,samples=100]{1/x^2-1/x};
\addplot[domain=\xminb:\xmax,samples=100]{-1/x};
\addplot[domain=\xmint:\xmax,samples=100]{1/x^2};
\end{axis}
\end{tikzpicture}
```
You can set the horizontal and vertical range in the first lines, the units for nx and ny are the coordinates of the minimum point of the graph. | May be this:
```
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmax=1,
xmin=0,
ymax=10,
ymin=-250,
]
\addplot[
red,
%smooth, %% this will spoil the plot
domain=-5:5,
samples=1000,thick
]
{0.5/xΒ²-22/x};
\end{axis}
\end{tikzpicture}
\end{document}
```
 |
214,215 | 
I would like to have these expressions aligned so that the kerning and slightly different character widths do not result in an uneven overall appearance. I tried using an `align` environment within `algorithm` but it resulted in errors. Here is a MWE:

```
\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Euclidβs algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
```
Source: <https://www.writelatex.com/examples/euclids-algorithm-an-example-of-how-to-write-algorithms-in-latex/mbysznrmktqf> | 2014/11/27 | [
"https://tex.stackexchange.com/questions/214215",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9610/"
] | May be this:
```
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmax=1,
xmin=0,
ymax=10,
ymin=-250,
]
\addplot[
red,
%smooth, %% this will spoil the plot
domain=-5:5,
samples=1000,thick
]
{0.5/xΒ²-22/x};
\end{axis}
\end{tikzpicture}
\end{document}
```
 | Try this
```
\documentclass[border=2pt]{standalone}
% Drawing
\usepackage{tikz}
\usepackage{physics}
\usepackage{nicefrac}
\usetikzlibrary{arrows.meta} % to control arrow size
\tikzset{>={Latex[length=4,width=4]}} % for LaTeX arrow head
% Tikz Library
\begin{document}
\begin{tikzpicture}
% Axis
\draw[-latex, thick] (0,-1) -- (0,7) node[left] {$V_{\text{eff}}$};
\draw[-latex, thick] (0,3) -- (9,3) node[below] {$r$};
\draw[rounded corners=30,thick] (8,2.8) to[out=180,in=40] (2,0.3) to[out=120,in=-85] (0.2,7) ;
\draw[dashed,rounded corners=30,thick] (3,1.14) to[out=220,in=60] (1.2,-1);
\node[left=3] at (0,3) {$E_{\text{parabola}}$};
\draw[dashed] (0,0.75)--(2.2,0.75);
\node[left=15] at (0,0.75) {$E_{\text{circle}}$};
\draw[<-,gray] (2.2,0.6) to[out=-60,in=170](6,-0.1)node[below right]{$\boxed{\grad{V}=\nicefrac{mv^2}{r}}$};
\draw[dashed] (0,2)--(4.25,2);
\node[left=13] at (0,2) {$E_{\text{ellipse}}$};
\draw[dashed] (0,5)--(0.425,5);
\node[left] at (0,5) {$E_{\text{hyperbola}}$};
\draw[dashed] (2.2,.75)--(2.2,3);
\node[above] at (2.2,3) {$r_{\text{circle}}$};
\draw[dashed] (1.1,2)--(1.1,3);
\node[above] at (1.1,3) {$r_{\text{min}}$};
\fill (1.1,2) circle (2pt) node[below left,scale=0.4] {$E=V_{\text{eff}}(r_{\text{min}})$};
\draw[dashed] (4.3,2)--(4.3,3);
\fill (4.3,2) circle (2pt) node[below right,scale=0.4] {$E=V_{\text{eff}}(r_{\text{max}})$};
\node[above] at (4.3,3) {$r_{\text{max}}$};
\node[right] at (1.8,-0.3) {$L=0$};
\draw[<->,thick] (2.3,0.75)--(2.3,2);
\draw[<-] (2.4,1.5) to[out=0,in=180] (5,1) node[right] {Radial Kinetic Energy};
\node at (6,6) {$\boxed{V_{\text{eff}}=-\frac{k}{r^n}+\frac{L^2}{2mr^2}}$};
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/67g3X.jpg) |
214,215 | 
I would like to have these expressions aligned so that the kerning and slightly different character widths do not result in an uneven overall appearance. I tried using an `align` environment within `algorithm` but it resulted in errors. Here is a MWE:

```
\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Euclidβs algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
```
Source: <https://www.writelatex.com/examples/euclids-algorithm-an-example-of-how-to-write-algorithms-in-latex/mbysznrmktqf> | 2014/11/27 | [
"https://tex.stackexchange.com/questions/214215",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9610/"
] | Something like this?
```
\begin{tikzpicture}
% Set horizontal range
\pgfmathsetmacro{\nx}{8}
% Set vertical range
\pgfmathsetmacro{\ny}{2.5}
\pgfmathsetmacro{\xmin}{2*(sqrt(\ny+1)-1)/\ny}
\pgfmathsetmacro{\xmint}{2/sqrt(\ny)}
\pgfmathsetmacro{\xminb}{4/\ny}
\pgfmathsetmacro{\xmax}{2*\nx}
\begin{axis}[xmin=0,xmax=\xmax,axis x line*=middle, axis y line*=left, xtick=\empty, ytick=\empty]
\addplot[red,domain=\xmin:\xmax,samples=100]{1/x^2-1/x};
\addplot[domain=\xminb:\xmax,samples=100]{-1/x};
\addplot[domain=\xmint:\xmax,samples=100]{1/x^2};
\end{axis}
\end{tikzpicture}
```
You can set the horizontal and vertical range in the first lines, the units for nx and ny are the coordinates of the minimum point of the graph. | Try this
```
\documentclass[border=2pt]{standalone}
% Drawing
\usepackage{tikz}
\usepackage{physics}
\usepackage{nicefrac}
\usetikzlibrary{arrows.meta} % to control arrow size
\tikzset{>={Latex[length=4,width=4]}} % for LaTeX arrow head
% Tikz Library
\begin{document}
\begin{tikzpicture}
% Axis
\draw[-latex, thick] (0,-1) -- (0,7) node[left] {$V_{\text{eff}}$};
\draw[-latex, thick] (0,3) -- (9,3) node[below] {$r$};
\draw[rounded corners=30,thick] (8,2.8) to[out=180,in=40] (2,0.3) to[out=120,in=-85] (0.2,7) ;
\draw[dashed,rounded corners=30,thick] (3,1.14) to[out=220,in=60] (1.2,-1);
\node[left=3] at (0,3) {$E_{\text{parabola}}$};
\draw[dashed] (0,0.75)--(2.2,0.75);
\node[left=15] at (0,0.75) {$E_{\text{circle}}$};
\draw[<-,gray] (2.2,0.6) to[out=-60,in=170](6,-0.1)node[below right]{$\boxed{\grad{V}=\nicefrac{mv^2}{r}}$};
\draw[dashed] (0,2)--(4.25,2);
\node[left=13] at (0,2) {$E_{\text{ellipse}}$};
\draw[dashed] (0,5)--(0.425,5);
\node[left] at (0,5) {$E_{\text{hyperbola}}$};
\draw[dashed] (2.2,.75)--(2.2,3);
\node[above] at (2.2,3) {$r_{\text{circle}}$};
\draw[dashed] (1.1,2)--(1.1,3);
\node[above] at (1.1,3) {$r_{\text{min}}$};
\fill (1.1,2) circle (2pt) node[below left,scale=0.4] {$E=V_{\text{eff}}(r_{\text{min}})$};
\draw[dashed] (4.3,2)--(4.3,3);
\fill (4.3,2) circle (2pt) node[below right,scale=0.4] {$E=V_{\text{eff}}(r_{\text{max}})$};
\node[above] at (4.3,3) {$r_{\text{max}}$};
\node[right] at (1.8,-0.3) {$L=0$};
\draw[<->,thick] (2.3,0.75)--(2.3,2);
\draw[<-] (2.4,1.5) to[out=0,in=180] (5,1) node[right] {Radial Kinetic Energy};
\node at (6,6) {$\boxed{V_{\text{eff}}=-\frac{k}{r^n}+\frac{L^2}{2mr^2}}$};
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/67g3X.jpg) |
19,640,710 | My buttons aren't lining up correctly... whats wrong?
```
private void loadPuzzleButtons()
{
if (active_puzzle != null)
{
int devider = 5;
int count = 0;
JToggleButton puzzleButton[] = new JToggleButton[active_puzzle.getNumberOfPieces()];
for(int row = 0; row < active_puzzle.getRows(); row++)
{
for(int column = 0; column < active_puzzle.getColumns(); column++)
{
puzzleButton[count] = new JToggleButton(new ImageIcon( active_puzzle.getPieces()[count].getPieceImage() ) );
puzzleButton[count].setLocation(200 + active_puzzle.getPieceWidth() * column + devider * column,
200 + active_puzzle.getPieceHeight() * row + devider * row);
puzzleButton[count].setContentAreaFilled(false);
puzzleButton[count].setBorderPainted(false);
puzzleButton[count].setBorder(null);
mainPuzzlerPanel.add(puzzleButton[count]);
mainPuzzlerPanel.validate();
count++;
}
}
mainPuzzlerPanel.repaint();
}
}
```
Here is a photo of the output: [http://i.imgur.com/Zdink2Q.png](https://i.imgur.com/Zdink2Q.png)

Sorry I'd give you my whole code but its larger and well I'm not going to do that...
Thank you in advance, do ask if you need more info!
I figured it out to those who wan't to see how I solved the problem.
```
private void loadPuzzleButtons()
{
if (active_puzzle != null)
{
int count = 0;
GridLayout puzzleLayout = new GridLayout(active_puzzle.getRows(),active_puzzle.getColumns(),3,3);
puzzlePanel.setLayout(puzzleLayout);
JToggleButton puzzleButton[] = new JToggleButton[active_puzzle.getNumberOfPieces()];
for(int row = 0; row < active_puzzle.getRows(); row++)
{
for(int column = 0; column < active_puzzle.getColumns(); column++)
{
puzzleButton[count] = new JToggleButton(new ImageIcon(active_puzzle.getPieces()[count].getPieceImage()));
puzzleButton[count].setContentAreaFilled(false);
puzzleButton[count].setBorderPainted(false);
puzzleButton[count].setBorder(null);
puzzlePanel.add(puzzleButton[count]);
puzzlePanel.validate();
count++;
}
}
puzzlePanel.repaint();
}
}
``` | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4102299/"
] | Try to use [LayoutManager](http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html) to fill panel properly | what do .getcolumns and getrows output. try it. output the column and row inside the inner loop and make sure you get at least those numbers right. are you sure row ever increments? |
61,849,978 | I'm working to show notifications from Server-Sent Event. I checked that every time the browser tries to reconnect with the source about 3 seconds after each connection is closed. That event is getting a call too fast, so my server is loaded too.
So how do I change the reopening time to increase? I have to do at least 60 seconds, so tell me how to do it?
I'm trying the following code.
```html
<table class="table" id="notification"></table>
<script type="text/javascript">
var ssevent = null;
if (!!window.EventSource) {
ssevent = new EventSource('ssevent.php');
ssevent.addEventListener('message', function(e){
if(e.data){
json = JSON.parse(e.data);
if(json){
json.forEach(function(v,i){
html = "<tr><td>"+ v.text +"</td><td>"+ v.date +"</td></tr>";
});
$('#notification').append(html);
}
}
}, false);
ssevent.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED){
console.log("Connection was closed.");
}
}, false);
} else {
console.log('Server-Sent Events not support in your browser');
}
</script>
```
The file of event stream is as follow.
```php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();
$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();
if($result){
$json = array();
foreach ($result as $row){
$json[] = array(
'text' => $row['event_text'],
'date' => date("Y-m-d H:i", $row['event_time']),
);
}
echo "data: ". json_encode($json) . "\n\n";
flush();
}
``` | 2020/05/17 | [
"https://Stackoverflow.com/questions/61849978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6293856/"
] | There exist universally accepted definitions of lock-freedom and wait-freedom, and the definitions provided in your question are consistent with those. And I would strongly assume that the C++ standard committee certainly sticks to definitions that are universally accepted in the scientific community.
In general, publications on lock-free/wait-free algorithms assume that CPU instructions are wait-free. Instead, the arguments about progress guarantees focus on the *software algorithm*.
Based on this assumption I would argue that any `std::atomic` method that can be translated to a single atomic instruction for some architecture is wait-free on that specific architecture. Whether such a translation is possible sometimes depends on how the method is used though. Take for example `fetch_or`. On x86 this can be translated to `lock or`, but only if you *do not use its return value*, because this instruction does not provide the original value. If you use the return value, then the compiler will create a CAS-loop, which is lock-free, but not wait-free. (And the same goes for `fetch_and`/`fetch_xor`.)
**So which methods are actually wait-free depends not only on the compiler, but mostly on the target architecture.**
Whether it is technically correct to assume that a single instruction is actually wait-free or not is a rather philosophical one IMHO. True, it might not be guaranteed that an instruction finishes execution within a bounded number of "steps" (whatever such a step might be), but the machine instruction is still the smallest unit on the lowest level that we can see and control. Actually, if you cannot assume that a single instruction is *wait-free*, then strictly speaking it is not possible to run any real-time code on that architecture, because real-time also requires strict bounds on time/the number of steps.
---
This is what the C++17 standard states in `[intro.progress]`:
>
> Executions of atomic functions that are either deο¬ned to be lock-free (32.8) or indicated as lock-free (32.5)
> are *lock-free executions*.
>
>
> * If there is only one thread that is not blocked (3.6) in a standard library function, a lock-free execution in that thread shall complete. [ Note: Concurrently executing threads may prevent progress of a lock-free
> execution. For example, this situation can occur with load-locked store-conditional implementations. This property is sometimes termed obstruction-free. β end note ]
> * When one or more lock-free executions run concurrently, at least one should complete. [ Note: It is difficult for some implementations to provide absolute guarantees to this effect, since repeated and particularly inopportune interference from other threads may prevent forward progress, e.g., by repeatedly stealing a cache line for unrelated purposes between load-locked and store-conditional instructions. Implementations should ensure that such effects cannot indefinitely delay progress under expected operating conditions, and that such anomalies can therefore safely be ignored by programmers. Outside this document, this property is sometimes termed lock-free. β end note ]
>
>
>
---
The other answer correctly pointed out that my original answer was a bit imprecise, since there exist two stronger subtypes of wait-freedom.
* **wait-free** - A method is wait-free if it guarantees that every call finishes its execution in a *finite* number of steps, i.e., it is not possible to determine an upper bound, but it must still be guaranteed that the number of steps is *finite*.
* **wait-free bounded** - A method is wait-free bounded if it guarantees that every call finishes its execution in a *bounded* number of steps, where this bound may depend on the number of threads.
* **wait-free population oblivious** - A method is wait-free population oblivious if it guarantees that every call finishes its execution in a *bounded* number of steps, and this bound does not depend on the number of threads.
So strictly speaking, the definition in the question is consistent with the definition of *wait-free bounded*.
In practice, most wait-free algorithms are actually wait-free bounded or even wait-free population oblivious, i.e., it is possible to determine an upper bound on the number of steps. | Since there are many definitions of wait-freedom1 and people choose different ones, I think that a precise definition is paramount, and a distinction between its specializations is necessary and useful.
These [are](https://concurrencyfreaks.blogspot.com/2013/05/lock-free-and-wait-free-definition-and.html) the universally accepted definitions of wait-freedom and its specializations:
* **wait-free**:
All threads will make progress in a finite number of steps.
* **wait-free bounded**:
All threads will make progress in a bounded number of steps, which may depend on the number of threads.
* **wait-free population-oblivious**3:
All threads will make progress in a fixed number of steps, that does not depend on the number of threads.
Overall, the C++ standard makes no distinction between lock-free and wait-free (see [this other answer](https://stackoverflow.com/a/61854691/3453226)). It always gives guarantees no stronger than lock-free.
When [`std::atomic<T>::is_lock_free()`](https://en.cppreference.com/w/cpp/atomic/atomic/is_lock_free) returns `true`, instead of mutexes the implementation utilizes [atomic instructions](https://en.wikipedia.org/wiki/Linearizability#Primitive_atomic_instructions) possibly with [CAS](https://en.wikipedia.org/wiki/Compare-and-swap) loops or [LL/SC](https://en.wikipedia.org/wiki/Load-link/store-conditional) loops.
Atomic instructions are wait-free. CAS and LL/SC loops are lock-free.
How a method is implemented depends on many factors, including its usage, the compiler, the target architecture and its version. For example:
* As someone [says](https://stackoverflow.com/questions/61849972/anything-in-stdatomic-is-wait-free#comment109402899_61849972), on x86 gcc, `fetch_add()` for `std::atomic<double>` [uses](https://godbolt.org/z/qbn4dh) a CAS loop (`lock cmpxchg`), while for `std::atomic<int>` [uses](https://godbolt.org/z/vz94eE) `lock add` or `lock xadd`.
* As someone else [says](https://stackoverflow.com/questions/61849972/anything-in-stdatomic-is-wait-free/63040449#comment111490580_63040449), on architectures featuring LL/SC instructions, `fetch_add()` uses a LL/SC loop if no better instructions are available. For example, this is not the case on ARM versions 8.1 and above, where `ldaddal` is used for non-relaxed `std::atomic<int>` and `ldadd` is used if relaxed.
* As stated in [this other answer](https://stackoverflow.com/a/61865252/3453226), on x86 gcc `fetch_or()` [uses](https://godbolt.org/z/Po74Mj) `lock or` if the return value is not used, otherwise it [uses](https://godbolt.org/z/qT589f) a CAS loop (`lock cmpxchg`).
As explained in [this answer of mine](https://stackoverflow.com/a/62848706/3453226):
* The `store()` method and `lock add`, `lock xadd`, `lock or` instructions are wait-free population-oblivious, while their "algorithm", that is the work performed by the hardware to lock the cache line, is wait-free bounded.
* The `load()` method is always wait-free population-oblivious.
---
1 For example:
* all threads will make progress in a finite number of steps ([source](https://stackoverflow.com/q/61744469/3453226))
* all threads will make progress in a bounded number of steps2
* per "step" that they all execute, all threads will make forward progress without any starvation ([source](https://stackoverflow.com/questions/61849972/anything-in-stdatomic-is-wait-free#comment109441196_61865252))
2 It is not clear whether the bound is constant, or it may depend on the number of threads.
3 A strange name and not good for an acronym, so maybe another one should be chosen. |
48,092,940 | Does anyone have a working function available to use within Oracle using PL/SQL which implements the Luhn Mod 16 Algorithm to generate a check digit for an input code number such as the following example? `0B012722900021AC35B2`
LOGIC
1. Map from HEX into Decimal equivalent `0 B 0 1 2 7 2 2 9 0 0 0 2 1 A C 3 5 B 2` - becomes `0 11 0 1 2 7 2 2 9 0 0 0 2 1 10 12 3 5 11 2`
2. Start with the last character in the string and move left doubling every other number -
Becomes `0 22 0 2 2 14 2 4 9 0 0 0 2 2 10 24 3 10 11 4`
3. Convert the "double" to a Base 16 (Hexadecimal) format. If the conversion results in numeric output, retain the value.
Becomes: `0 16 0 2 2 E 2 4 9 0 0 0 2 2 10 18 3 A 11 4`
4. Reduce by splitting down any resultant values over a single digit in length.
Becomes `0 (1+6) 0 2 2 E 2 4 9 0 0 0 2 2 10 (1+8) 3 A 11 4`
5. Sum all digits. Apply *the last numeric value* returned from the previous sequence of calculations (if the current value is A-F substitute the numeric value from step 1)
Becomes `0 7 0 2 2 7 2 4 9 0 0 0 2 2 10 9 3 5 11 4`
6. The sum of al l digits is 79 `(0+7+0+2+2+7+2+4+9+0+0+0+2+2+10+9+3+5+11+4)`
7. Calculate the value needed to obtain the next multiple of 16, in this case the next multiple 16 is 80 therefore the value is 1
8. The associated check character is `1`
Thanks Lee | 2018/01/04 | [
"https://Stackoverflow.com/questions/48092940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9172160/"
] | How about this?
```
CREATE OR REPLACE TYPE VARCHAR_TABLE_TYPE AS TABLE OF VARCHAR2(1000);
DECLARE
luhn VARCHAR2(100) := '0B012722900021AC35B2';
digits VARCHAR_TABLE_TYPE;
DigitSum INTEGER;
BEGIN
SELECT REGEXP_SUBSTR(luhn, '.', 1, LEVEL)
BULK COLLECT INTO digits
FROM dual
CONNECT BY REGEXP_SUBSTR(luhn, '.', 1, LEVEL) IS NOT NULL;
FOR i IN digits.FIRST..digits.LAST LOOP
digits(i) := TO_NUMBER(digits(i), 'X'); -- Map from HEX into Decimal equivalent
IF digits.COUNT MOD 2 = i MOD 2 THEN -- every second digit from left
digits(i) := 2 * TO_NUMBER(digits(i)); -- doubling number
digits(i) := TO_CHAR(digits(i), 'fmXX'); -- Convert the "double" to a Base 16 (Hexadecimal) format
IF (REGEXP_LIKE(digits(i), '^\d+$')) THEN
-- Reduce by splitting down any resultant values over a single digit in length.
SELECT SUM(REGEXP_SUBSTR(digits(i), '\d', 1, LEVEL))
INTO digits(i)
FROM dual
CONNECT BY REGEXP_SUBSTR(digits(i), '\d', 1, LEVEL) IS NOT NULL;
END IF;
END IF;
END LOOP;
FOR i IN digits.FIRST..digits.LAST LOOP
-- I don't understand step 5), let's simulate it
IF digits(i) = 'E' THEN digits(i) := 7; END IF;
IF digits(i) = 'A' THEN digits(i) := 5; END IF;
END LOOP;
-- The sum of all digits
SELECT SUM(COLUMN_VALUE)
INTO DigitSum
FROM TABLE(digits);
-- Calculate the value needed to obtain the next multiple of 16
DBMS_OUTPUT.PUT_LINE ( 16 - DigitSum MOD 16 );
END;
``` | Here is a function which implements the steps you outlined in your question:
```
create or replace function get_luhn_16_check_digit
( p_str in varchar)
return pls_integer
is
b16 sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll() ;
n16 sys.odcinumberlist := sys.odcinumberlist();
tot simple_integer := 0;
chk_digit pls_integer;
begin
-- step 1)
select to_number(tkn, 'X')
bulk collect into n16
from ( select substr(p_str, level, 1) as tkn
from dual
connect by level <= length(p_str));
b16.extend(n16.count());
for idx in 1..n16.count() loop
if mod(idx, 2) = 0
then
-- step 2) and 3)
b16(idx) := to_char( to_char(n16(idx)) * 2, 'fmXX');
-- step 4)
if length( b16(idx)) = 2 then
b16(idx) := to_number(substr(b16(idx),1,1)) + to_number(substr(b16(idx),2,1));
end if;
else
b16(idx) := trim(to_char(n16(idx)));
end if;
end loop;
-- step 5) and 6)
for idx in 1..b16.count() loop
if b16(idx) not in ('A','B','C','D','E','F') then
tot := tot + to_number(b16(idx));
else
tot := tot + n16(idx);
end if;
end loop;
-- step 7) and 8)
chk_digit := (ceil(tot/16)*16) - tot;
return chk_digit;
end;
/
```
To run:
```
select get_luhn_16_check_digit('0B012722900021AC35B2') from dual;
```
This now returns `1`. Here is [a LiveSQL demo](https://livesql.oracle.com/apex/livesql/s/f26k0wo5kwa89zduns6h1rczg).
---
There is still the question of what happens when the modulus 16 is greater than 9; for instance, this value returns `15`.
```
select get_luhn_16_check_digit('22111111111111111111') from dual;
```
A decimal result such as `15` is obviously not a check **digit**, which suggests you need an additional step 9). Perhaps we need to convert `15` -> `(1+5)` -> `6`. Or Perhaps the digit should be base16? Please edit your question to confirm the appropriate rule. |
238,856 | Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me. | 2022/12/03 | [
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] | Viruses and pathogens can affect everything that is based on genetic expression or biochemistry: there are known examples of pathogens changing the behavior of their hosts, for example, not forgetting that any pathogen tries to turn its host into a replicator of themselves.
What a virus cannot do is changing the laws of physics.
>
> Some even obtain the ability to have their own gravitational pull and not breathe in space
>
>
>
Changing the gravitational pull would require at least one of the three:
1. changing the gravitational constant G
2. changing the mass of the infected
3. changing the distance between the infected and the pulled object
1 is impossible based on what we know today about physics.
2 is trivial, a virus can induce mass weight or mass loss, but the effect is hardly appreciable, unless you want to step in the realm of mama jokes.
3 is also trivial and again hardly appreciable. We get closer or farther to many objects in our daily life, without even realizing that our gravitational pull on them is changing, because it's such a low pull that it can be taken as 0 | In real life many people have genes for diseases they will never have. The unlucky ones are the people who get cancer, for example, after suffering a severe infection. The Epstein-Barr virus "turns on" the genes responsible for a certain kind of blood cancer. This is called epi-genetics. It's still a developing field.
In your story, gaining superpowers by way of a virus infection could be explained by an epi-genetic change kicking in, though your human would have to already have the genes necessary to express that power. That can be explained by their ancestors also having had superpowers which would carry through the generations just like hair colour, height, handedness, and a million other characteristics.
[epi-genetic](/questions/tagged/epi-genetic "show questions tagged 'epi-genetic'") [superpowers](/questions/tagged/superpowers "show questions tagged 'superpowers'") [genetics](/questions/tagged/genetics "show questions tagged 'genetics'") |
238,856 | Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me. | 2022/12/03 | [
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] | Viruses and pathogens can affect everything that is based on genetic expression or biochemistry: there are known examples of pathogens changing the behavior of their hosts, for example, not forgetting that any pathogen tries to turn its host into a replicator of themselves.
What a virus cannot do is changing the laws of physics.
>
> Some even obtain the ability to have their own gravitational pull and not breathe in space
>
>
>
Changing the gravitational pull would require at least one of the three:
1. changing the gravitational constant G
2. changing the mass of the infected
3. changing the distance between the infected and the pulled object
1 is impossible based on what we know today about physics.
2 is trivial, a virus can induce mass weight or mass loss, but the effect is hardly appreciable, unless you want to step in the realm of mama jokes.
3 is also trivial and again hardly appreciable. We get closer or farther to many objects in our daily life, without even realizing that our gravitational pull on them is changing, because it's such a low pull that it can be taken as 0 | I would argue that a sufficiently complex (that is, likely not natural) retro-virus could make some changes like super-strong, super-fast, likely significantly improved senses of sight and hearing. Even there it might only express (either fully or even partially) in children rather than already-grown individuals. And to effect children the retro-virus would need to infect gamete-producing tissues.
To do away with the need to breathe you would need to integrate an entirely different metabolic pathway, I suppose technically feasible, somehow, but seems unlikely. Even more unlikely for that alternative to be as energetically-favorable as using free oxygen from an atmosphere (that is, just as jet engines have better performance than rockets because they don't have to carry their oxidizer along with them). However, none of that seems as unlikely as modifying gravity.
None of those things are 'magical'. Basically imagine the most optimized organism you can think of along any given axis and it could probably be accomplished. |
238,856 | Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me. | 2022/12/03 | [
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] | I would argue that a sufficiently complex (that is, likely not natural) retro-virus could make some changes like super-strong, super-fast, likely significantly improved senses of sight and hearing. Even there it might only express (either fully or even partially) in children rather than already-grown individuals. And to effect children the retro-virus would need to infect gamete-producing tissues.
To do away with the need to breathe you would need to integrate an entirely different metabolic pathway, I suppose technically feasible, somehow, but seems unlikely. Even more unlikely for that alternative to be as energetically-favorable as using free oxygen from an atmosphere (that is, just as jet engines have better performance than rockets because they don't have to carry their oxidizer along with them). However, none of that seems as unlikely as modifying gravity.
None of those things are 'magical'. Basically imagine the most optimized organism you can think of along any given axis and it could probably be accomplished. | In real life many people have genes for diseases they will never have. The unlucky ones are the people who get cancer, for example, after suffering a severe infection. The Epstein-Barr virus "turns on" the genes responsible for a certain kind of blood cancer. This is called epi-genetics. It's still a developing field.
In your story, gaining superpowers by way of a virus infection could be explained by an epi-genetic change kicking in, though your human would have to already have the genes necessary to express that power. That can be explained by their ancestors also having had superpowers which would carry through the generations just like hair colour, height, handedness, and a million other characteristics.
[epi-genetic](/questions/tagged/epi-genetic "show questions tagged 'epi-genetic'") [superpowers](/questions/tagged/superpowers "show questions tagged 'superpowers'") [genetics](/questions/tagged/genetics "show questions tagged 'genetics'") |
238,856 | Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me. | 2022/12/03 | [
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] | There is no conceivable way for a change in a human's genes to enable them to alter the laws of physics (i.e. give them their own gravitational pull).
Not needing to breathe for extended periods could be made possible with some form of extremely efficient [anaerobic respiration](https://en.wikipedia.org/wiki/Anaerobic_respiration), which provides a body with energy without requiring oxygen. Currently, there are no genes in humans which code for a choice between anaerobic or [aerobic respiration](https://en.wikipedia.org/wiki/Cellular_respiration); whether an organism has [metabolic pathways](https://en.wikipedia.org/wiki/Metabolic_pathway) for breathing with oxygen (aerobic) or without oxygen (anerobic) is much more complicated than an on/off switch.
However, [modern gene editing technology](https://en.wikipedia.org/wiki/CRISPR_gene_editing) can splice foreign DNA segments into preexisting DNA strands, and has produced things such as [goats whose milk contains useful spider silk](https://phys.org/news/2010-05-scientists-goats-spider-silk.html) or [strawberries with flounder antifreeze genes for cold resistance](https://www.nytimes.com/2000/12/05/health/personal-health-gene-altered-foods-a-case-against-panic.html). Sometimes, it's done via artificially-altered viruses. It is therefore clearly possible for a virus to splice foreign DNA into an organism's genetic code in a manner causes physical changes (as opposed to simply being [non-coding ["junk"] DNA](https://en.wikipedia.org/wiki/Non-coding_DNA) which doesn't appear to do anything).
Essentially: there's absolutely no way people with their own gravitational pull are possible with anything that follows humanity's current understanding of the basic physical laws of the universe, but, conversely, I'd say it's *quite* likely that, even in real life, gene-altering technology will eventually enable altered people to breathe for *long* periods (if not indefinitely) without oxygen, and our gene-altering technology today already uses viruses on a regular basis. Big no on the gravity, medium yes on the lack of a need to breathe.
Dealing with the dangers posed to the human body by the hard vacuum, cosmic rays, and extreme temperature differences found in space, on the other hand, might be somewhat more difficult. And don't forget that even a human whose bodily processes run off of super-efficient anaerobic respiration will need to breathe oxygen eventually... | In real life many people have genes for diseases they will never have. The unlucky ones are the people who get cancer, for example, after suffering a severe infection. The Epstein-Barr virus "turns on" the genes responsible for a certain kind of blood cancer. This is called epi-genetics. It's still a developing field.
In your story, gaining superpowers by way of a virus infection could be explained by an epi-genetic change kicking in, though your human would have to already have the genes necessary to express that power. That can be explained by their ancestors also having had superpowers which would carry through the generations just like hair colour, height, handedness, and a million other characteristics.
[epi-genetic](/questions/tagged/epi-genetic "show questions tagged 'epi-genetic'") [superpowers](/questions/tagged/superpowers "show questions tagged 'superpowers'") [genetics](/questions/tagged/genetics "show questions tagged 'genetics'") |
238,856 | Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me. | 2022/12/03 | [
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] | There is no conceivable way for a change in a human's genes to enable them to alter the laws of physics (i.e. give them their own gravitational pull).
Not needing to breathe for extended periods could be made possible with some form of extremely efficient [anaerobic respiration](https://en.wikipedia.org/wiki/Anaerobic_respiration), which provides a body with energy without requiring oxygen. Currently, there are no genes in humans which code for a choice between anaerobic or [aerobic respiration](https://en.wikipedia.org/wiki/Cellular_respiration); whether an organism has [metabolic pathways](https://en.wikipedia.org/wiki/Metabolic_pathway) for breathing with oxygen (aerobic) or without oxygen (anerobic) is much more complicated than an on/off switch.
However, [modern gene editing technology](https://en.wikipedia.org/wiki/CRISPR_gene_editing) can splice foreign DNA segments into preexisting DNA strands, and has produced things such as [goats whose milk contains useful spider silk](https://phys.org/news/2010-05-scientists-goats-spider-silk.html) or [strawberries with flounder antifreeze genes for cold resistance](https://www.nytimes.com/2000/12/05/health/personal-health-gene-altered-foods-a-case-against-panic.html). Sometimes, it's done via artificially-altered viruses. It is therefore clearly possible for a virus to splice foreign DNA into an organism's genetic code in a manner causes physical changes (as opposed to simply being [non-coding ["junk"] DNA](https://en.wikipedia.org/wiki/Non-coding_DNA) which doesn't appear to do anything).
Essentially: there's absolutely no way people with their own gravitational pull are possible with anything that follows humanity's current understanding of the basic physical laws of the universe, but, conversely, I'd say it's *quite* likely that, even in real life, gene-altering technology will eventually enable altered people to breathe for *long* periods (if not indefinitely) without oxygen, and our gene-altering technology today already uses viruses on a regular basis. Big no on the gravity, medium yes on the lack of a need to breathe.
Dealing with the dangers posed to the human body by the hard vacuum, cosmic rays, and extreme temperature differences found in space, on the other hand, might be somewhat more difficult. And don't forget that even a human whose bodily processes run off of super-efficient anaerobic respiration will need to breathe oxygen eventually... | I would argue that a sufficiently complex (that is, likely not natural) retro-virus could make some changes like super-strong, super-fast, likely significantly improved senses of sight and hearing. Even there it might only express (either fully or even partially) in children rather than already-grown individuals. And to effect children the retro-virus would need to infect gamete-producing tissues.
To do away with the need to breathe you would need to integrate an entirely different metabolic pathway, I suppose technically feasible, somehow, but seems unlikely. Even more unlikely for that alternative to be as energetically-favorable as using free oxygen from an atmosphere (that is, just as jet engines have better performance than rockets because they don't have to carry their oxidizer along with them). However, none of that seems as unlikely as modifying gravity.
None of those things are 'magical'. Basically imagine the most optimized organism you can think of along any given axis and it could probably be accomplished. |
21,075,929 | I'm trying to preserve the current height of the page when doing an Ajax call. Almost the whole content is hidden before showing the new content, so the browser scrolls to the top of the page because there is no content below during the transition.
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
$('#content').fadeOut();
setTimeout(function() {
$('#content').html(response).fadeIn();
}, 500);
});
});
```
I thought about adding a class like:
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
//$('#content').fadeOut();
$('#content').addClass('cortinaIn');
setTimeout(function() {
$('#content').html(response).fadeIn();
$('#content').removeClass('cortinaIn');
$('#content').addClass('cortinaOut');
}, 500);
$('#content').removeClass('cortinaOut');
});
});
```
and define the `cortinaIn` and `cortinaOut` CSS rules:
```
.cortinaIn {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(0, 1);
transform-origin: center center;
-ms-transform:scale(0, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(0, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(0, 1); /* Opera */
-o-transform-origin: center center;
}
.cortinaOut {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(1, 1);
transform-origin: center center;
-ms-transform:scale(1, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(1, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(1, 1); /* Opera */
-o-transform-origin: center center;
}
```
And this works fine, but I'm not able to find "fade in" and "face out" effects with CSS transforms. Any idea to achieve this behavior? | 2014/01/12 | [
"https://Stackoverflow.com/questions/21075929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571840/"
] | The `popoverControllerDidDismissPopover:` in the delegate is not called when 'dismissPopoverAnimated:' is used.
From the [Apple Documentation](https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#jumpTo_4) for `popoverControllerDidDismissPopover:` in `UIPopoverControllerDelegate`:
>
> The popover controller does not call this method in response to programmatic calls to the dismissPopoverAnimated: method. If you dismiss the popover programmatically, you should perform any cleanup actions immediately after calling the dismissPopoverAnimated: method.
>
>
> | There are two ways to dismiss a popover. (a) tapping outside the popover; and (b) doing it programmatically with
```
[self.popover dismissPopoverAnimated:YES];
```
If you do it programmatically, then the docs (<https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIPopoverControllerDelegate/popoverControllerDidDismissPopover>:) say:
>
> The popover controller does not call this method in response to
> programmatic calls to the dismissPopoverAnimated: method. If you
> dismiss the popover programmatically, you should perform any cleanup
> actions immediately after calling the dismissPopoverAnimated: method.
>
>
>
Thus, not calling the delegate automatically is the normal behavior, and what you're doing (calling it yourself) is fine. |
21,075,929 | I'm trying to preserve the current height of the page when doing an Ajax call. Almost the whole content is hidden before showing the new content, so the browser scrolls to the top of the page because there is no content below during the transition.
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
$('#content').fadeOut();
setTimeout(function() {
$('#content').html(response).fadeIn();
}, 500);
});
});
```
I thought about adding a class like:
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
//$('#content').fadeOut();
$('#content').addClass('cortinaIn');
setTimeout(function() {
$('#content').html(response).fadeIn();
$('#content').removeClass('cortinaIn');
$('#content').addClass('cortinaOut');
}, 500);
$('#content').removeClass('cortinaOut');
});
});
```
and define the `cortinaIn` and `cortinaOut` CSS rules:
```
.cortinaIn {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(0, 1);
transform-origin: center center;
-ms-transform:scale(0, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(0, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(0, 1); /* Opera */
-o-transform-origin: center center;
}
.cortinaOut {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(1, 1);
transform-origin: center center;
-ms-transform:scale(1, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(1, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(1, 1); /* Opera */
-o-transform-origin: center center;
}
```
And this works fine, but I'm not able to find "fade in" and "face out" effects with CSS transforms. Any idea to achieve this behavior? | 2014/01/12 | [
"https://Stackoverflow.com/questions/21075929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571840/"
] | The `popoverControllerDidDismissPopover:` in the delegate is not called when 'dismissPopoverAnimated:' is used.
From the [Apple Documentation](https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#jumpTo_4) for `popoverControllerDidDismissPopover:` in `UIPopoverControllerDelegate`:
>
> The popover controller does not call this method in response to programmatic calls to the dismissPopoverAnimated: method. If you dismiss the popover programmatically, you should perform any cleanup actions immediately after calling the dismissPopoverAnimated: method.
>
>
> | popoverControllerDidDismissPopover is not called on Dismiss, but its called when you click outside the popoverController contentview.
<https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#jumpTo_4> |
21,075,929 | I'm trying to preserve the current height of the page when doing an Ajax call. Almost the whole content is hidden before showing the new content, so the browser scrolls to the top of the page because there is no content below during the transition.
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
$('#content').fadeOut();
setTimeout(function() {
$('#content').html(response).fadeIn();
}, 500);
});
});
```
I thought about adding a class like:
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
//$('#content').fadeOut();
$('#content').addClass('cortinaIn');
setTimeout(function() {
$('#content').html(response).fadeIn();
$('#content').removeClass('cortinaIn');
$('#content').addClass('cortinaOut');
}, 500);
$('#content').removeClass('cortinaOut');
});
});
```
and define the `cortinaIn` and `cortinaOut` CSS rules:
```
.cortinaIn {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(0, 1);
transform-origin: center center;
-ms-transform:scale(0, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(0, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(0, 1); /* Opera */
-o-transform-origin: center center;
}
.cortinaOut {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(1, 1);
transform-origin: center center;
-ms-transform:scale(1, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(1, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(1, 1); /* Opera */
-o-transform-origin: center center;
}
```
And this works fine, but I'm not able to find "fade in" and "face out" effects with CSS transforms. Any idea to achieve this behavior? | 2014/01/12 | [
"https://Stackoverflow.com/questions/21075929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571840/"
] | There are two ways to dismiss a popover. (a) tapping outside the popover; and (b) doing it programmatically with
```
[self.popover dismissPopoverAnimated:YES];
```
If you do it programmatically, then the docs (<https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIPopoverControllerDelegate/popoverControllerDidDismissPopover>:) say:
>
> The popover controller does not call this method in response to
> programmatic calls to the dismissPopoverAnimated: method. If you
> dismiss the popover programmatically, you should perform any cleanup
> actions immediately after calling the dismissPopoverAnimated: method.
>
>
>
Thus, not calling the delegate automatically is the normal behavior, and what you're doing (calling it yourself) is fine. | popoverControllerDidDismissPopover is not called on Dismiss, but its called when you click outside the popoverController contentview.
<https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#jumpTo_4> |
15,951,412 | Sometimes I see constructs like [`$('<img/>')`](https://stackoverflow.com/questions/6124409/image-size-before-is-in-dom). How is `$('<img/>')` different from `$('img')` and where can I read more about this?
I tried looking at [jQuery Selectors](http://api.jquery.com/category/selectors/) but found nothing related to this format. | 2013/04/11 | [
"https://Stackoverflow.com/questions/15951412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257965/"
] | The jQuery function is overloaded to construct new jQuery elements when passed a string that looks like HTML. From the [docs](http://api.jquery.com/jQuery/#jQuery2):
>
> If a string is passed as the parameter to $(), jQuery examines the
> string to see if it looks like HTML (i.e., it starts with `<tag ... >`).
> If not, the string is interpreted as a selector expression, as
> explained above. But if the string appears to be an HTML snippet,
> jQuery attempts to create new DOM elements as described by the HTML.
> Then a jQuery object is created and returned that refers to these
> elements.
>
>
> | `$('<img/>')` **creates** an image, whereas `$('img')` selects all currently existing images. |
15,951,412 | Sometimes I see constructs like [`$('<img/>')`](https://stackoverflow.com/questions/6124409/image-size-before-is-in-dom). How is `$('<img/>')` different from `$('img')` and where can I read more about this?
I tried looking at [jQuery Selectors](http://api.jquery.com/category/selectors/) but found nothing related to this format. | 2013/04/11 | [
"https://Stackoverflow.com/questions/15951412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257965/"
] | `$('<img/>')` **creates** an image, whereas `$('img')` selects all currently existing images. | `$('<img />')` creates a new `<img />` element to be inserted to the DOM.
`$('img')` selects all existing `<img />` elements.
Generally, one would use `$('<img />')` to create elements in the DOM as follows:
```
var toAppend = $('<img />');
toAppend.appendTo($('#myDiv'));
```
Whereas you could use the `$('img');` selector to handle CSS (as an arbitrary example):
```
$('img').css('marginTop', 20);
```
The above will add a 20px margin to the top of each image in the DOM. |
15,951,412 | Sometimes I see constructs like [`$('<img/>')`](https://stackoverflow.com/questions/6124409/image-size-before-is-in-dom). How is `$('<img/>')` different from `$('img')` and where can I read more about this?
I tried looking at [jQuery Selectors](http://api.jquery.com/category/selectors/) but found nothing related to this format. | 2013/04/11 | [
"https://Stackoverflow.com/questions/15951412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257965/"
] | The jQuery function is overloaded to construct new jQuery elements when passed a string that looks like HTML. From the [docs](http://api.jquery.com/jQuery/#jQuery2):
>
> If a string is passed as the parameter to $(), jQuery examines the
> string to see if it looks like HTML (i.e., it starts with `<tag ... >`).
> If not, the string is interpreted as a selector expression, as
> explained above. But if the string appears to be an HTML snippet,
> jQuery attempts to create new DOM elements as described by the HTML.
> Then a jQuery object is created and returned that refers to these
> elements.
>
>
> | `$('<img />')` creates a new `<img />` element to be inserted to the DOM.
`$('img')` selects all existing `<img />` elements.
Generally, one would use `$('<img />')` to create elements in the DOM as follows:
```
var toAppend = $('<img />');
toAppend.appendTo($('#myDiv'));
```
Whereas you could use the `$('img');` selector to handle CSS (as an arbitrary example):
```
$('img').css('marginTop', 20);
```
The above will add a 20px margin to the top of each image in the DOM. |
46,971,445 | This is my `BindingAdapter`:
```
@BindingAdapter(value = *arrayOf("bind:commentsAdapter", "bind:itemClick", "bind:avatarClick", "bind:scrolledUp"), requireAll = false)
fun initWithCommentsAdapter(recyclerView: RecyclerView, commentsAdapter: CommentsAdapter,
itemClick: (item: EntityCommentItem) -> Unit,
avatarClick: ((item: EntityCommentItem) -> Unit)?,
scrolledUp: (() -> Unit)?) {
//Some code here
}
```
`initWithCommentsAdapter` is a top level function
This is my layout (an essential part):
```
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="some.example.path.CommentsViewModel"/>
<variable
name="commentsAdapter"
type="some.example.path.CommentsAdapter"/>
</data>
<android.support.v7.widget.RecyclerView
...
bind:avatarClick="@{(item) -> viewModel.avatarClick(item)}"
bind:itemClick="@{viewModel::commentClick}"
bind:commentsAdapter="@{commentsAdapter}"
bind:isVisible="@{viewModel.commentsVisibility}"
bind:scrolledUp="@{() -> viewModel.scrolledUp()}"
/>
</layout>
```
When I assign lambda with kotlin method call in the layout, I have such error during building:
```
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:cannot find method avatarClick(java.lang.Object)
in class some.example.path.CommentsViewModel
****\ data binding error ****
```
or if I assign method by reference:
```
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Listener class kotlin.jvm.functions.Function1
with method invoke did not match signature of any method viewModel::commentClick
file:C:\Android\Projects\...\fragment_comments.xml
loc:70:12 - 83:17
****\ data binding error ****
```
But I have such methods with proper type, not Object
**Question**
How can I assign Kotlin lambda for custom @BindingAdapter in Kotlin in the layout?
**Edit**
The relevant part of the viewModel:
```
class CommentsViewModel(model: CommentsModel): BaseObservable() {
//Some binded variables here
...
fun commentClick(item: EntityCommentItem) {
//Some code here
}
fun avatarClick(item: EntityCommentItem) {
//Some code here
}
fun scrolledUp() {
//Some code here
}
...
}
```
The variables binding works just fine | 2017/10/27 | [
"https://Stackoverflow.com/questions/46971445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4710549/"
] | **Short Answer**
Instead of using Kotlin generic lambda types, use **interfaces** with a single method that matches both return type and parameters of your method reference (`itemClick`) or your listener (`avatarClick`).
You can also use abstract classes with a single abstract method, also with matching parameters and return type.
**Explanation**
Actually the [Databinding docs](https://developer.android.com/topic/libraries/data-binding/expressions#method_references) never mention that the Kotlin lambda types work as Databinding listeners or method references, probably because under the hood these lambda types translate to Kotlin's `Function1`, `Function2`... which are generics, and thus some of their type information doesn't make it to the executable and therefore is not available at runtime.
Why your `scrolledUp` binding did work though? Because type `() -> Unit` has no need for generics. It could have worked even with `Runnable`.
**Code**
```
interface ItemClickInterface {
// method may have any name
fun doIt(item: EntityCommentItem)
}
@BindingAdapter(
value = ["commentsAdapter", "scrolledUp", "itemClick", "avatarClick"],
requireAll = false
)
fun initWithCommentsAdapter(
view: View,
commentsAdapter: CommentsAdapter,
scrolledUp: () -> Unit, // could have been Runnable!
itemClick: ItemClickInterface,
avatarClick: ItemClickInterface
) {
// Some code here
}
``` | I ran into the same case, and what worked was having it declared as variable defining its type, that worked with the compiler
`val avatarClick:(item: EntityCommentItem)->Unit = {}` |
11,175,453 | This question has been asked before but i still don't understand it fully so here it goes.
If i have a class with a property (a non-nullable double or int) - can i read and write the property with multiple threads?
I have read somewhere that since doubles are 64 bytes, it is possible to read a double property on one thread while it is being written on a different one. This will result in the reading thread returning a value that is neither the original value nor the new written value.
When could this happen? Is it possible with ints as well? Does it happen with both 64 and 32 bit applications?
I haven't been able to replicate this situation in a console | 2012/06/24 | [
"https://Stackoverflow.com/questions/11175453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907734/"
] | >
> If i have a class with a property (a non-nullable double or int) - can i read and write the property with multiple theads?
>
>
>
I assume you mean "without any synchronization".
`double` and `long` are both 64 *bits* (8 bytes) in size, and are *not* guaranteed to be written atomically. So if you were moving from a value with byte pattern ABCD EFGH to a value with byte pattern MNOP QRST, you could *potentially* end up seeing (from a different thread) ABCD QRST or MNOP EFGH.
With properly aligned values of size 32 bits or lower, atomicity is guaranteed. (I don't remember seeing any guarantees that values *will* be properly aligned, but I believe they are by default unless you force a particular layout via attributes.) The C# 4 spec doesn't even mention alignment in section 5.5 which deals with atomicity:
>
> Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.
>
>
>
Additionally, atomicity isn't the same as volatility - so without any extra care being taken, a read from one thread may not "see" a write from a different thread. | These operations are not atomic, that's why the [`Interlocked`](http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx) class exists in the first place, with methods like `Increment(Int32)` and `Increment(Int64)`.
To ensure thread safety, you should use at least this class, if not more complex locking (with `ReaderWriterLockSlim`, for example, in case you want to synchronize access to groups of properties). |
263,517 | I'm trying to set a different existing material on 5 Instances made with Instance on Points. Trying both 3.0.1 and 3.1 to no avail.
Is there any value or attribute that signifies which instance you are on?
I want to build a setup for texture painting with 5 copies of a character and therefore I am linking a rigify rig with the meshes that gets instanced. That seems to make it trickier if not impossible to do custom attributes.
Either want to change material for each copied instance or have some way to swap textures in a shader graph. As long as you can paint a different texture on each copy.
I've tried these three answers to similar issue without results:
[Set material for instances problem (Blender 3.0)](https://blender.stackexchange.com/questions/244208/set-material-for-instances-problem-blender-3-0),
[Control Instance Color with Geometry Nodes](https://blender.stackexchange.com/questions/213224/control-instance-color-with-geometry-nodes),
[How to assign a different material color to each geometry nodes instance](https://blender.stackexchange.com/questions/254648/how-to-assign-a-different-material-color-to-each-geometry-nodes-instance) | 2022/05/13 | [
"https://blender.stackexchange.com/questions/263517",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/27347/"
] | After a bit of faffing around, I've so far established that the *Set Material Index* node will work only if the incoming geometry, with materials assigned to slots, is on the same branch. The materials do not have to be assigned to faces of the incoming geometry... it just has to have its slots filled.
In this example, the incoming geometry is just a plane, with 4 material slots.
[](https://i.stack.imgur.com/Vl4WS.png)
Cubes instanced on a line have their instance indices stashed, before *Realize Instance* wipes them.
A function of the stashed indices is used to *Set Material Index*, while the (material-slot-bearing) incoming geometry is on the same branch.
The incoming geometry has been tagged, so can be selectively deleted before output.
[](https://i.stack.imgur.com/9LAB4.png)
The GN-generated cubes are now assigned the separate materials, per-instance, as expected. | Managed to figure it out with inspiration from this answer:[How to access geonode generated "instance ID" from Cycles material?](https://blender.stackexchange.com/questions/248920/how-to-access-geonode-generated-instance-id-from-cycles-material?rq=1)
My node setup looks like below and assigns materials all in geometry nodes:
[](https://i.stack.imgur.com/864NR.png)
[](https://i.stack.imgur.com/eG7kP.png) |
263,517 | I'm trying to set a different existing material on 5 Instances made with Instance on Points. Trying both 3.0.1 and 3.1 to no avail.
Is there any value or attribute that signifies which instance you are on?
I want to build a setup for texture painting with 5 copies of a character and therefore I am linking a rigify rig with the meshes that gets instanced. That seems to make it trickier if not impossible to do custom attributes.
Either want to change material for each copied instance or have some way to swap textures in a shader graph. As long as you can paint a different texture on each copy.
I've tried these three answers to similar issue without results:
[Set material for instances problem (Blender 3.0)](https://blender.stackexchange.com/questions/244208/set-material-for-instances-problem-blender-3-0),
[Control Instance Color with Geometry Nodes](https://blender.stackexchange.com/questions/213224/control-instance-color-with-geometry-nodes),
[How to assign a different material color to each geometry nodes instance](https://blender.stackexchange.com/questions/254648/how-to-assign-a-different-material-color-to-each-geometry-nodes-instance) | 2022/05/13 | [
"https://blender.stackexchange.com/questions/263517",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/27347/"
] | Managed to figure it out with inspiration from this answer:[How to access geonode generated "instance ID" from Cycles material?](https://blender.stackexchange.com/questions/248920/how-to-access-geonode-generated-instance-id-from-cycles-material?rq=1)
My node setup looks like below and assigns materials all in geometry nodes:
[](https://i.stack.imgur.com/864NR.png)
[](https://i.stack.imgur.com/eG7kP.png) | `STORE NAMED ATTRIBUTE` for points with value as `ID` before `INSTANCE ON POINTS`, then `NAMED ATTRIBUTE` integer using the same name from the `STORED NAMED ATTRIBUTE` on the ID for the selection on a `RANDOM VALUE` using boolean
[](https://i.stack.imgur.com/LB0M9.png) |
263,517 | I'm trying to set a different existing material on 5 Instances made with Instance on Points. Trying both 3.0.1 and 3.1 to no avail.
Is there any value or attribute that signifies which instance you are on?
I want to build a setup for texture painting with 5 copies of a character and therefore I am linking a rigify rig with the meshes that gets instanced. That seems to make it trickier if not impossible to do custom attributes.
Either want to change material for each copied instance or have some way to swap textures in a shader graph. As long as you can paint a different texture on each copy.
I've tried these three answers to similar issue without results:
[Set material for instances problem (Blender 3.0)](https://blender.stackexchange.com/questions/244208/set-material-for-instances-problem-blender-3-0),
[Control Instance Color with Geometry Nodes](https://blender.stackexchange.com/questions/213224/control-instance-color-with-geometry-nodes),
[How to assign a different material color to each geometry nodes instance](https://blender.stackexchange.com/questions/254648/how-to-assign-a-different-material-color-to-each-geometry-nodes-instance) | 2022/05/13 | [
"https://blender.stackexchange.com/questions/263517",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/27347/"
] | After a bit of faffing around, I've so far established that the *Set Material Index* node will work only if the incoming geometry, with materials assigned to slots, is on the same branch. The materials do not have to be assigned to faces of the incoming geometry... it just has to have its slots filled.
In this example, the incoming geometry is just a plane, with 4 material slots.
[](https://i.stack.imgur.com/Vl4WS.png)
Cubes instanced on a line have their instance indices stashed, before *Realize Instance* wipes them.
A function of the stashed indices is used to *Set Material Index*, while the (material-slot-bearing) incoming geometry is on the same branch.
The incoming geometry has been tagged, so can be selectively deleted before output.
[](https://i.stack.imgur.com/9LAB4.png)
The GN-generated cubes are now assigned the separate materials, per-instance, as expected. | `STORE NAMED ATTRIBUTE` for points with value as `ID` before `INSTANCE ON POINTS`, then `NAMED ATTRIBUTE` integer using the same name from the `STORED NAMED ATTRIBUTE` on the ID for the selection on a `RANDOM VALUE` using boolean
[](https://i.stack.imgur.com/LB0M9.png) |
3,068,306 | I am trying to concatenate clobs in a PL/SQL loop and it has been returning null whilst when using DBMS\_OUTPUT prints out the loop values and when executing each result of the clobs gives an output as well.
The system is meant to execute an already stored SQL in a table based on the report name passed into it. This particular report has many report names; hence the concatenation of each of the reports. The arguments passed are the report name, version of the report you're interested in, the kind of separator you want, and an argument list for the unknowns in the SQL if any. There are also two main types of SQL; 1 that needs the table\_name be replaced with a temp table\_name and another that needs an ID be appended to a table\_name in the SQL.
please find below the code for the REPREF1 function.
```
CREATE OR REPLACE FUNCTION REPREF1(P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
L_CLOB CLOB;
FUNCTION GET_CLOB(P_REPNAM IN VARCHAR2,
P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
---------------------------------------------------------------------------------
-- TITLE - GET_CLOB beta - b.0 DATE 2010Mar12
--
-- DESCRIPTION - A function that return a report based on the report name put in
--
-- USAGE - select get_clob(p_repnam,p_ver, p_separator, var(varay(val_1,...val_n), varay(val_1,...val_n))) FROM dual
-----------------------------------------------------------------------------------------------------------------------------
V_SQL VARCHAR2(32767);
L_RESULT CLOB;
V_TITLE VARCHAR2(4000);
V_REPDATE VARCHAR2(30);
V_CNT NUMBER(2);
V_NUMARG NUMBER(3);
V_CDCRU NUMBER(3);
V_BCNT NUMBER(3);
V_NEWTABDAT VARCHAR2(30);
V_NEWTABLIN VARCHAR2(30);
L_COLLIST VARAY;
V_VER VARCHAR2(6);
N PLS_INTEGER;
V_CNTTAB NUMBER(3);
-- EXEC_SQL_CLOB
FUNCTION EXEC_SQL_CLOB(P_SQL IN VARCHAR2,
P_NUMARG IN NUMBER,
P_COLLIST IN VARAY DEFAULT NULL,
P_ARGLIST IN VARAY DEFAULT NULL,
P_SEPARATOR IN VARCHAR2 DEFAULT '') RETURN CLOB IS
------------------------------------------------------------------------------------------------------
-- TITLE - EXEC_SQL_CLOB beta - b.0 DATE 2010Mar22
--
-- DESCRIPTION - A function that returns a clob value after executing the sql query that is passed into it
--
-- USAGE - select exec_sql_clob(p_sql, p_numarg, var(varay(val_1, val_2,...val_n), varay(val_1, val_2,...val_n))) FROM dual
---------------------------------------------------------------------------------------------------------------
L_CUR INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
L_STATUS INTEGER;
V_COL VARCHAR2(4000);
L_RESULT CLOB;
L_COLCNT NUMBER DEFAULT 0;
L_SEPARATOR VARCHAR2(10) DEFAULT '';
V_NUMARG NUMBER(3);
BEGIN
-- parse the query for the report
DBMS_SQL.PARSE(L_CUR, P_SQL, DBMS_SQL.NATIVE);
-- whilst it is not more than 255 per line
FOR I IN 1 .. 255
LOOP
BEGIN
-- define each column in the select list
DBMS_SQL.DEFINE_COLUMN(L_CUR, I, V_COL, 2000);
L_COLCNT := I;
EXCEPTION
WHEN OTHERS THEN
IF (SQLCODE = -1007) THEN
EXIT;
ELSE
RAISE;
END IF;
END;
END LOOP;
-- If query has no bind variables
IF (P_ARGLIST IS NULL) THEN
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
-- Query has bind variables
ELSE
-- Check if the numarg passed is the same has stored in the table
SELECT NUMARG
INTO V_NUMARG
FROM REPVER
WHERE REPCODE = P_SQL;
-- If number of arguments is greater than 0
IF (V_NUMARG > 0) THEN
-- Check if the number of arguments are the same
IF (P_NUMARG = V_NUMARG) THEN
-- Replace the bind variables in the query
FOR J IN 1 .. P_ARGLIST.COUNT
LOOP
DBMS_SQL.BIND_VARIABLE(L_CUR, P_COLLIST(J), P_ARGLIST(J));
END LOOP;
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
ELSE
-- If the number of argument is equal to 0
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
END IF;
END IF;
-- Close cursor
DBMS_SQL.CLOSE_CURSOR(L_CUR);
RETURN L_RESULT;
END EXEC_SQL_CLOB;
BEGIN
-- Check if the version entered is null or latest
IF (P_VER IS NULL)
OR (UPPER(P_VER) = UPPER('LATEST')) THEN
SELECT MAX(VER)
INTO V_VER
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF;
ELSE
V_VER := P_VER;
END IF;
-- Check if the repname and version entered exists
SELECT COUNT(*)
INTO V_CNT
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND VER = V_VER
AND B.REPREF = R.REPREF;
IF (V_CNT > 0) THEN
-- Store the SQL statement, title and number of arguments of the report name passed.
SELECT REPCODE, REPTITLE, NUMARG, COLLIST
INTO V_SQL, V_TITLE, V_NUMARG, L_COLLIST
FROM REPVER R, REPORT B
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
V_REPDATE := TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI');
L_RESULT := V_TITLE || ' (' || P_REPNAM || ' version ' || V_VER || ') generated ' || V_REPDATE || CHR(13) || CHR(13);
-- Check for some specific type of queries
SELECT COUNT(*)
INTO V_CDCRU
FROM REPVER R, REPORT B
WHERE CTDDATA = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
SELECT COUNT(*)
INTO V_BCNT
FROM REPVER R, BODCREPS B
WHERE BENLIST = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
IF (V_CDCRU > 0) THEN
V_NEWTABDATA := 'CT_' || 'DAT_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
V_NEWTABLINK := 'CT_' || 'LIN_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
-- Check if the tables exist
SELECT COUNT(*)
INTO V_CNTTAB
FROM ALL_TABLES
WHERE TABLE_NAME = V_NEWTABDAT
OR TABLE_NAME = V_NEWTABLIN
AND OWNER = 'SCOTT';
IF (V_CNTTAB > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'CT_DAT_CRU', V_NEWTABDAT);
V_SQL := REPLACE(V_SQL, 'CT_LIN_CRU', V_NEWTABLIN);
ELSE
V_SQL := 'SELECT ''THE TABLE NOT CREATED YET''
FROM DUAL';
END IF;
END IF;
IF (V_BCNT > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'LIST', P_ARGLIST(1) (P_ARGLIST(1).LAST));
END IF;
IF (P_ARGLIST IS NULL) THEN
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, NULL, P_SEPARATOR);
ELSE
N := P_ARGLIST.COUNT;
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, P_ARGLIST(N), P_SEPARATOR);
END IF;
RETURN L_RESULT;
ELSE
RAISE_APPLICATION_ERROR(-20012, P_REPNAM || ' or ' || P_VER || ' DOES NOT EXIST ');
END IF;
END GET_CLOB;
BEGIN
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
-- DBMS_OUTPUT.PUT_LINE (COUNT(i.REPNAM));
END LOOP;
RETURN L_CLOB;
END REPREF1;
/
```
Cheers,
Tunde
Many thanks APC for making the code look better.
@Robert, the last loop in the code returns null even with the CONCAT\_CLOB aggregate function that concatenates clobs.
```
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
```
when I try this,
```
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
L_CLOB := L_CLOB || CHR(13) || GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST);
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
```
It also gives null; but this time the dbms output for the repnam are not complete. | 2010/06/18 | [
"https://Stackoverflow.com/questions/3068306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197945/"
] | Don't know about your code. Here is how it works for me:
Whenever I create a function returning a clob value I do this:
```
function foo return clob is
l_clob clob;
begin
dbms_lob.createtemporary(lob_loc => l_clob, cache => true, dur => dbms_lob.call);
...
return l_clob;
end;
```
When concatenating values into a clob I use a function:
```
procedure add_string_to_clob(p_lob in out nocopy clob
,p_string varchar2) is
begin
dbms_lob.writeappend(lob_loc => p_lob, amount => length(p_string), buffer => p_string);
end;
``` | You have to use
`dbms_lob.substr(your clob parameter,start position, length)`
e.g
`dbms_output('my clob value:' || dbms_lob.substr(your clob parameter,start position, length);`
But you can print in a string max 4000 character, you can then use this in a looping function to print 4000 characters in each line. |
28,487 | I want to run a Mathematica code repeatedly, even after the kernel shuts down when it is out of memory, because I have designed my program to continue appending the data to a file. Currently, I have to restart the kernel manually every 10 minutes. Does anyone have an idea how one can automate this process? Thanks. | 2013/07/12 | [
"https://mathematica.stackexchange.com/questions/28487",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/8523/"
] | If you preselect a range of cells before execution you can continue execution past kernel quit using the option below. Selection and evaluation can be automated and done repeatedly.
```
SetOptions[$FrontEnd, "ClearEvaluationQueueOnKernelQuit" -> False]
```
Ref : <https://stackoverflow.com/a/13740555/879601>
(`MemoryConstrained` looks a good solution for your specific problem though.) | Here is what rm -rf just mentioned, in the form of an example:
```
Do[
MemoryConstrained[
a = Range[10^n], 10000];
Print[Total[a]],
{n, 1, 10}
]
```
Output:
```
55
5050
500500
500500
500500
500500
500500
500500
500500
500500
```
By using `MemoryConstrained`, you don't get any changes in the list `a` after the maximum memory is reached in the above loop, but the loop continues to run. |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | I had this problem before and putting a height into the parent widget of `AspectRatio` fixed it. | I solved the problem this way:
```
children: <Widget>[
(controller== null)
? Container()
: controller.value.Initialized
? Container(child: CameraPreview(controller))
: Container(),
],
``` |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | If you have created and assigned value to the variable and still it shows `getter 'value' was called on null`,
try to `Run` or `Restart` your app instead of `Hot Reload`. Because `Hot Reload` will not call `initstate()` (where variables assign their values) which will be only called by `Restarting` the app. | giving height to widget which is throwing error solved my issue |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | In the `initState`, you don't always instantiate a controller.
Which means it can be `null`. Therefore inside the `build` method, you need to check null to not crash
```
(!this.controller?.value?.initialized ?? false) ? new Container() : cameraView ,
``` | giving height to widget which is throwing error solved my issue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.