qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
273,313
|
<p>What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.</p>
|
[
{
"answer_id": 273352,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "var list = new List<T> ();\nfillList (list);\nvar randomizedList = new List<T> ();\nvar rnd = new Random ();\nwhile (list.Count != 0)\n{\n var index = rnd.Next (0, list.Count);\n randomizedList.Add (list [index]);\n list.RemoveAt (index);\n}\n"
},
{
"answer_id": 273355,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": -1,
"selected": false,
"text": "do \n r1 = randomPositionInList()\n r2 = randomPositionInList()\n swap elements at index r1 and index r2 \nfor a certain number of times\n"
},
{
"answer_id": 273666,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 4,
"selected": false,
"text": " public static List<T> Randomize<T>(List<T> list)\n {\n List<T> randomizedList = new List<T>();\n Random rnd = new Random();\n while (list.Count > 0)\n {\n int index = rnd.Next(0, list.Count); //pick a random item from the master list\n randomizedList.Add(list[index]); //place it at the end of the randomized list\n list.RemoveAt(index);\n }\n return randomizedList;\n }\n"
},
{
"answer_id": 1262619,
"author": "grenade",
"author_id": 68115,
"author_profile": "https://Stackoverflow.com/users/68115",
"pm_score": 11,
"selected": true,
"text": "(I)List private static Random rng = new Random(); \n\npublic static void Shuffle<T>(this IList<T> list) \n{ \n int n = list.Count; \n while (n > 1) { \n n--; \n int k = rng.Next(n + 1); \n T value = list[k]; \n list[k] = list[n]; \n list[n] = value; \n } \n}\n List<Product> products = GetProducts();\nproducts.Shuffle();\n using System.Security.Cryptography;\n...\npublic static void Shuffle<T>(this IList<T> list)\n{\n RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();\n int n = list.Count;\n while (n > 1)\n {\n byte[] box = new byte[1];\n do provider.GetBytes(box);\n while (!(box[0] < n * (Byte.MaxValue / n)));\n int k = (box[0] % n);\n n--;\n T value = list[k];\n list[k] = list[n];\n list[n] = value;\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace SimpleLottery\n{\n class Program\n {\n private static void Main(string[] args)\n {\n var numbers = new List<int>(Enumerable.Range(1, 75));\n numbers.Shuffle();\n Console.WriteLine(\"The winning numbers are: {0}\", string.Join(\", \", numbers.GetRange(0, 5)));\n }\n }\n\n public static class ThreadSafeRandom\n {\n [ThreadStatic] private static Random Local;\n\n public static Random ThisThreadsRandom\n {\n get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }\n }\n }\n\n static class MyExtensions\n {\n public static void Shuffle<T>(this IList<T> list)\n {\n int n = list.Count;\n while (n > 1)\n {\n n--;\n int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);\n T value = list[k];\n list[k] = list[n];\n list[n] = value;\n }\n }\n }\n}\n"
},
{
"answer_id": 3456788,
"author": "Denis",
"author_id": 417022,
"author_profile": "https://Stackoverflow.com/users/417022",
"pm_score": 6,
"selected": false,
"text": "public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)\n{\n Random rnd = new Random();\n return source.OrderBy<T, int>((item) => rnd.Next());\n}\n"
},
{
"answer_id": 4262134,
"author": "user453230",
"author_id": 453230,
"author_profile": "https://Stackoverflow.com/users/453230",
"pm_score": 9,
"selected": false,
"text": "var shuffledcards = cards.OrderBy(a => Guid.NewGuid()).ToList();\n private static Random rng = new Random();\n...\nvar shuffledcards = cards.OrderBy(a => rng.Next()).ToList();\n"
},
{
"answer_id": 7913534,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 3,
"selected": false,
"text": "RemoveAt public static IEnumerable<T> Shuffle<T>(\n this IEnumerable<T> source,\n Random generator = null)\n{\n if (generator == null)\n {\n generator = new Random();\n }\n\n var elements = source.ToArray();\n for (var i = elements.Length - 1; i >= 0; i--)\n {\n var swapIndex = generator.Next(i + 1);\n yield return elements[swapIndex];\n elements[swapIndex] = elements[i];\n }\n}\n Random generator Random Random public static IEnumerable<T> Shuffle<T>(this IList<T> list)\n{\n var choices = Enumerable.Range(0, list.Count).ToList();\n var rng = new Random();\n for(int n = choices.Count; n > 1; n--)\n {\n int k = rng.Next(n);\n yield return list[choices[k]];\n choices.RemoveAt(k);\n }\n\n yield return list[choices[0]];\n}\n"
},
{
"answer_id": 14511104,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 0,
"selected": false,
"text": " public byte[] Shuffle(byte[] array, int start, int count)\n {\n int n = array.Length - start;\n byte[] shuffled = new byte[count];\n for(int i = 0; i < count; i++, start++)\n {\n int k = UniformRandomGenerator.Next(n--) + start;\n shuffled[i] = array[k];\n array[k] = array[start];\n array[start] = shuffled[i];\n }\n return shuffled;\n }\n"
},
{
"answer_id": 15688378,
"author": "Christopher Stevenson",
"author_id": 612512,
"author_profile": "https://Stackoverflow.com/users/612512",
"pm_score": -1,
"selected": false,
"text": "public static class EnumerableExtension\n{\n private static Random globalRng = new Random();\n\n [ThreadStatic]\n private static Random _rng;\n\n private static Random rng \n {\n get\n {\n if (_rng == null)\n {\n int seed;\n lock (globalRng)\n {\n seed = globalRng.Next();\n }\n _rng = new Random(seed);\n }\n return _rng;\n }\n }\n\n public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)\n {\n return items.OrderBy (i => rng.Next());\n }\n}\n"
},
{
"answer_id": 20725319,
"author": "Xelights",
"author_id": 3126356,
"author_profile": "https://Stackoverflow.com/users/3126356",
"pm_score": 3,
"selected": false,
"text": "Lists List<int> xList = new List<int>() { 1, 2, 3, 4, 5 };\nList<int> deck = new List<int>();\n\nforeach (int xInt in xList)\n deck.Insert(random.Next(0, deck.Count + 1), xInt);\n"
},
{
"answer_id": 22668974,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 7,
"selected": false,
"text": "r(a,b) b Random.Next(a,b) b public static void Shuffle<T>(this IList<T> list, Random rnd)\n{\n for(var i=list.Count; i > 0; i--)\n list.Swap(0, rnd.Next(0, i));\n}\n\npublic static void Swap<T>(this IList<T> list, int i, int j)\n{\n var temp = list[i];\n list[i] = list[j];\n list[j] = temp;\n}\n"
},
{
"answer_id": 24250251,
"author": "sumit laddha",
"author_id": 3746068,
"author_profile": "https://Stackoverflow.com/users/3746068",
"pm_score": -1,
"selected": false,
"text": " public Deck(IEnumerable<Card> initialCards) \n {\n cards = new List<Card>(initialCards);\n public void Shuffle() \n }\n {\n List<Card> NewCards = new List<Card>();\n while (cards.Count > 0) \n {\n int CardToMove = random.Next(cards.Count);\n NewCards.Add(cards[CardToMove]);\n cards.RemoveAt(CardToMove);\n }\n cards = NewCards;\n }\n\npublic IEnumerable<string> GetCardNames() \n\n{\n string[] CardNames = new string[cards.Count];\n for (int i = 0; i < cards.Count; i++)\n CardNames[i] = cards[i].Name;\n return CardNames;\n}\n\nDeck deck1;\nDeck deck2;\nRandom random = new Random();\n\npublic Form1() \n{\n\nInitializeComponent();\nResetDeck(1);\nResetDeck(2);\nRedrawDeck(1);\n RedrawDeck(2);\n\n}\n\n\n\n private void ResetDeck(int deckNumber) \n {\n if (deckNumber == 1) \n{\n int numberOfCards = random.Next(1, 11);\n deck1 = new Deck(new Card[] { });\n for (int i = 0; i < numberOfCards; i++)\n deck1.Add(new Card((Suits)random.Next(4),(Values)random.Next(1, 14)));\n deck1.Sort();\n}\n\n\n else\n deck2 = new Deck();\n }\n\nprivate void reset1_Click(object sender, EventArgs e) {\nResetDeck(1);\nRedrawDeck(1);\n\n}\n\nprivate void shuffle1_Click(object sender, EventArgs e) \n{\n deck1.Shuffle();\n RedrawDeck(1);\n\n}\n\nprivate void moveToDeck1_Click(object sender, EventArgs e) \n{\n\n if (listBox2.SelectedIndex >= 0)\n if (deck2.Count > 0) {\n deck1.Add(deck2.Deal(listBox2.SelectedIndex));\n\n}\n\n RedrawDeck(1);\n RedrawDeck(2);\n\n}\n"
},
{
"answer_id": 25474564,
"author": "Shehab Fawzy",
"author_id": 1093516,
"author_profile": "https://Stackoverflow.com/users/1093516",
"pm_score": 2,
"selected": false,
"text": "public static class IEnumerableExtensions\n{\n\n public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)\n {\n Random r = new Random();\n\n return target.OrderBy(x=>(r.Next()));\n } \n}\n // use this on any collection that implements IEnumerable!\n// List, Array, HashSet, Collection, etc\n\nList<string> myList = new List<string> { \"hello\", \"random\", \"world\", \"foo\", \"bar\", \"bat\", \"baz\" };\n\nforeach (string s in myList.Randomize())\n{\n Console.WriteLine(s);\n}\n"
},
{
"answer_id": 29580185,
"author": "DavidMc",
"author_id": 4556700,
"author_profile": "https://Stackoverflow.com/users/4556700",
"pm_score": -1,
"selected": false,
"text": "Items = Items.OrderBy(o => Guid.NewGuid().ToString()).ToList();\n"
},
{
"answer_id": 32666693,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 3,
"selected": false,
"text": "source public static IList<T> NextList<T>(this Random r, IEnumerable<T> source)\n{\n var list = new List<T>();\n foreach (var item in source)\n {\n var i = r.Next(list.Count + 1);\n if (i == list.Count)\n {\n list.Add(item);\n }\n else\n {\n var temp = list[i];\n list[i] = item;\n list.Add(temp);\n }\n }\n return list;\n}\n 0 length - 1 Random Random RNGCryptoServiceProvider RNGCryptoServiceProvider var bytes = new byte[8];\n_secureRng.GetBytes(bytes);\nvar v = BitConverter.ToUInt64(bytes, 0);\nreturn (double)v / ((double)ulong.MaxValue + 1);\n x 0 <= x && x < 1 return list[(int)(x * list.Count)];\n"
},
{
"answer_id": 46107526,
"author": "Extragorey",
"author_id": 6680521,
"author_profile": "https://Stackoverflow.com/users/6680521",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<T> private static Random rng = new Random();\n\n/// <summary>\n/// Returns a new list where the elements are randomly shuffled.\n/// Based on the Fisher-Yates shuffle, which has O(n) complexity.\n/// </summary>\npublic static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) {\n var source = list.ToList();\n int n = source.Count;\n var shuffled = new List<T>(n);\n shuffled.AddRange(source);\n while (n > 1) {\n n--;\n int k = rng.Next(n + 1);\n T value = shuffled[k];\n shuffled[k] = shuffled[n];\n shuffled[n] = value;\n }\n return shuffled;\n}\n"
},
{
"answer_id": 51606335,
"author": "Andrey Kucher",
"author_id": 10042064,
"author_profile": "https://Stackoverflow.com/users/10042064",
"pm_score": 4,
"selected": false,
"text": "var result = items.Select(x => new { value = x, order = rnd.Next() })\n .OrderBy(x => x.order).Select(x => x.value).ToList()\n"
},
{
"answer_id": 56836629,
"author": "sultan s. alfaifi",
"author_id": 7767814,
"author_profile": "https://Stackoverflow.com/users/7767814",
"pm_score": 1,
"selected": false,
"text": " List<T> OriginalList = new List<T>();\n List<T> TempList = new List<T>();\n Random random = new Random();\n int length = OriginalList.Count;\n int TempIndex = 0;\n\n while (length > 0) {\n TempIndex = random.Next(0, length); // get random value between 0 and original length\n TempList.Add(OriginalList[TempIndex]); // add to temp list\n OriginalList.RemoveAt(TempIndex); // remove from original list\n length = OriginalList.Count; // get new list <T> length.\n }\n\n OriginalList = new List<T>();\n OriginalList = TempList; // copy all items from temp list to original list.\n"
},
{
"answer_id": 63088730,
"author": "JohnC",
"author_id": 808815,
"author_profile": "https://Stackoverflow.com/users/808815",
"pm_score": 1,
"selected": false,
"text": "collection.TakeRandom(5).SequenceEqual(collection.Shuffle().Take(5)); // true\n public static IList<T> TakeRandom<T>(this IEnumerable<T> collection, int count, Random random) => shuffle(collection, count, random);\npublic static IList<T> Shuffle<T>(this IEnumerable<T> collection, Random random) => shuffle(collection, null, random);\nprivate static IList<T> shuffle<T>(IEnumerable<T> collection, int? take, Random random)\n{\n var a = collection.ToArray();\n var n = a.Length;\n if (take <= 0 || take > n) throw new ArgumentException(\"Invalid number of elements to return.\");\n var end = take ?? n;\n for (int i = 0; i < end; i++)\n {\n var j = random.Next(i, n);\n (a[i], a[j]) = (a[j], a[i]);\n }\n\n if (take.HasValue) return new ArraySegment<T>(a, 0, take.Value);\n return a;\n}\n"
},
{
"answer_id": 63348412,
"author": "Garrison Becker",
"author_id": 9068304,
"author_profile": "https://Stackoverflow.com/users/9068304",
"pm_score": 0,
"selected": false,
"text": "public static void Shuffle<T>(this IList<T> list, Random rnd)\n{\n for (var i = list.Count-1; i > 0; i--)\n {\n var randomIndex = rnd.Next(i + 1); //maxValue (i + 1) is EXCLUSIVE\n list.Swap(i, randomIndex); \n }\n}\n\npublic static void Swap<T>(this IList<T> list, int indexA, int indexB)\n{\n var temp = list[indexA];\n list[indexA] = list[indexB];\n list[indexB] = temp;\n}\n"
},
{
"answer_id": 63799666,
"author": "Seva",
"author_id": 6529286,
"author_profile": "https://Stackoverflow.com/users/6529286",
"pm_score": 2,
"selected": false,
"text": "IComparer<T> List.Sort() public class RandomIntComparer : IComparer<int>\n{\n private readonly Random _random = new Random();\n \n public int Compare(int x, int y)\n {\n return _random.Next(-1, 2);\n }\n}\n list.Sort(new RandomIntComparer());\n"
},
{
"answer_id": 64275044,
"author": "Adrian Rus",
"author_id": 497423,
"author_profile": "https://Stackoverflow.com/users/497423",
"pm_score": 2,
"selected": false,
"text": "using MoreLinq;\n... \nvar randomized = list.Shuffle();\n"
},
{
"answer_id": 64710349,
"author": "Kannan K Mannadiar",
"author_id": 10799923,
"author_profile": "https://Stackoverflow.com/users/10799923",
"pm_score": -1,
"selected": false,
"text": "private List<GameObject> ShuffleList(List<GameObject> ActualList) {\n\n\n List<GameObject> newList = ActualList;\n List<GameObject> outList = new List<GameObject>();\n\n int count = newList.Count;\n\n while (newList.Count > 0) {\n\n int rando = Random.Range(0, newList.Count);\n\n outList.Add(newList[rando]);\n\n newList.RemoveAt(rando);\n\n \n\n }\n\n return (outList);\n\n}\n List<GameObject> GetShuffle = ShuffleList(ActualList);\n"
},
{
"answer_id": 69220421,
"author": "James Bateson",
"author_id": 2768119,
"author_profile": "https://Stackoverflow.com/users/2768119",
"pm_score": 2,
"selected": false,
"text": "private static readonly Random random = new Random();\n\npublic static void Shuffle<T>(this IList<T> list)\n{\n int n = list.Count;\n while (n > 1)\n {\n n--;\n int k = random.Next(n + 1);\n (list[k], list[n]) = (list[n], list[k]);\n }\n}\n"
},
{
"answer_id": 71458345,
"author": "Mark Cilia Vincenti",
"author_id": 9945524,
"author_profile": "https://Stackoverflow.com/users/9945524",
"pm_score": 1,
"selected": false,
"text": "public static class ListExtensions\n{\n public static void Shuffle<T>(this IList<T> list)\n {\n if (list == null) throw new ArgumentNullException(nameof(list));\n int n = list.Count;\n while (n > 1)\n {\n n--;\n int k = ThreadSafeRandom.Next(n + 1);\n (list[n], list[k]) = (list[k], list[n]);\n }\n }\n}\n\ninternal class ThreadSafeRandom\n{\n private static readonly Random _global = new Random();\n private static readonly ThreadLocal<Random> _local = new ThreadLocal<Random>(() =>\n {\n int seed;\n lock (_global)\n {\n seed = _global.Next();\n }\n return new Random(seed);\n });\n\n public static int Next(int maxValue)\n {\n return _local.Value.Next(maxValue);\n }\n}\n"
},
{
"answer_id": 73947663,
"author": "Gennadii Saltyshchak",
"author_id": 1719383,
"author_profile": "https://Stackoverflow.com/users/1719383",
"pm_score": 1,
"selected": false,
"text": "public static class ListExtensions\n{\n public static void Shuffle<T>(this IList<T> list, Random random)\n {\n for (var i = list.Count - 1; i > 0; i--)\n {\n int indexToSwap = random.Next(i + 1);\n (list[indexToSwap], list[i]) = (list[i], list[indexToSwap]);\n }\n }\n}\n var random = new Random();\nvar array = new [] { 1, 2, 3 };\narray.Shuffle(random);\nforeach (var item in array) {\n Console.WriteLine(item);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35286/"
] |
273,314
|
<p>For example, in <a href="http://homepages.cwi.nl/~paulv/papers/algorithmicstatistics.pdf" rel="noreferrer">http://homepages.cwi.nl/~paulv/papers/algorithmicstatistics.pdf</a> at the bottom of page 5 and top of page 6, he uses a plus/equal symbol and a similar plus/lessthan symbol. I can't figure out how to make that symbol, and I'd like to quote him.</p>
<p>Any help?</p>
|
[
{
"answer_id": 273402,
"author": "Noah",
"author_id": 28035,
"author_profile": "https://Stackoverflow.com/users/28035",
"pm_score": 6,
"selected": true,
"text": "$\\stackrel{top}{bottom}$ $X \\stackrel{+}{=} Y$\n $K(x,y|z) \\stackrel{+}{=} K(x|z) \\stackrel{+}{<} I(x:y|z)$\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35600/"
] |
273,353
|
<p>Note: The examples below are C# but this problem should not be specific to any language in particular.</p>
<p>So I am building an object domain using a variant of the <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">S# Architecture</a>. For those unfamiliar with it, and to save you some reading time the idea is simply that you have a Data Access Object Interface for each of your domain objects that is responsible for loading to/from the persistence layer. Everything that might ever need to load/save a given object then accepts that object's data access interface as a dependency. So for example we can have the following where a product will lazy load the customer that purchased it as needed:</p>
<pre><code>public class Product {
private ICustomerDao _customerDao;
private Customer _customer;
public Product(ICustomerDao customerDao) {_customerDao = customerDao;}
public int ProductId {get; set;}
public int CustomerId {get; set;}
public Customer Customer {
get{
if(_customer == null) _customer = _customerDao.GetById(CustomerId);
return _customer;
}
}
public interface ICustomerDao {
public Customer GetById(int id);
}
</code></pre>
<p>This is all well and good until you reach a situation where two objects need to be able to load each other. For example a many-to-one relationship where, as above, a product needs to be able to lazy load its customer, but also customer needs to be able to get a list of his products.</p>
<pre><code>public class Customer {
private IProductDao _productDao;
private Product[] _products;
public Customer(IProductDao productDao) {_productDao = productDao;}
public int CustomerId {get; set;}
public Product[] Products {
get{
if(_products == null) _products = _productDao. GetAllForCustomer(this);
return _products;
}
}
public interface IProductDao {
public Product[] GetAllForCustomer(Customer customer);
}
</code></pre>
<p>I know that this is a really common situation but I am relatively new at this. My stumbling block is what to do when implementing the Data Access Objects. Because a Customer has a dependency on IProductDao, the CustomerDao implementation must also, however the vice versa is also true and ProductDao must take a dependency on ICustomerDao.</p>
<pre><code>public class CustomerDao : ICustomerDao {
private IProductDao _productDao;
public CustomerDao(IProductDao productDao) {_productDao = productDao;}
public Customer GetById(int id) {
Customer c = new Customer(_customerDao);
// Query the database and fill out CustomerId
return c;
}
}
public class ProductDao : IProductDao {
private ICustomerDao _customerDao;
public ProductDao (ICustomerDao customerDao) {_customerDao = customerDao;}
public Product[] GetAllForCustomer(Customer customer) {
// you get the idea
}
}
</code></pre>
<p>And here we have the problem. You cannot instantiate CustomerDao without an IProductDao and vice versa. My inversion of control container (Castle Windsor) hits the circular dependency and chokes.</p>
<p>I have come up with a for-the-time-being solution which involves lazy loading the DAO objects themselves (I will post this as an answer) but I don't like it. What are the time-tested solutions to this problem?</p>
<p><strong>EDIT:</strong> The above is a simplification of the architecture I'm actually using and I am not recommending someone actually pass DAOs to an object. A better implementation closer to what I am actually doing is similar to the way NHibernate works where the actual objects are very simple and the above are actually proxy objects which inherit and override the appropriate fields.</p>
|
[
{
"answer_id": 273395,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "public abstract class BaseDao() {\n private ICustomerDao _customerDao;\n protected ICustomerDao _CustomerDao {\n get {\n if(_customerDao == null) _customerDao = IoC.Container.Resolve<ICustomerDao>();\n return _customerDao;\n }\n private IProductDao _productDao;\n protected IProductDao _ProductDao {\n get {\n if(_productDao == null) _productDao = IoC.Container.Resolve< IProductDao >();\n return _productDao;\n }\n public class CustomerDao : BaseDao, ICustomerDao {\n public Customer GetById(int id) {\n Customer c = new Customer(_CustomerDao);\n // Query the database and fill out CustomerId\n return c;\n }\n }\npublic class ProductDao : BaseDao, IProductDao {\n public Product[] GetAllForCustomer(Customer customer) {\n // use the base class's _ProductDao to instantiate Products\n }\n }\n"
},
{
"answer_id": 274144,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": true,
"text": "public class CustomerDao : ICustomerDao {\n\n private IProductDao _productDao;\n\n public IProductDao ProductDao {\n get { return _productDao; }\n set { _productDao = value; }\n }\n public CustomerDao() { }\n public Customer GetById(int id) {\n Customer c = new Customer(_productDao);\n // Query the database and fill out CustomerId\n return c;\n }\n}\npublic class ProductDao : IProductDao {\n private ICustomerDao _customerDao;\n\n public ProductDao() { }\n\n public ICustomerDao CustomerDao {\n get { return _customerDao; }\n set { _customerDao = value; }\n }\n\n public Product[] GetAllForCustomer(Customer customer) {\n return null;\n }\n\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
273,354
|
<p>I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:</p>
<pre><code>$html = "<input type='text' name='address' value='$address'>";
</code></pre>
<p>Now this is far more readable to me than either</p>
<pre><code>$html = "<input type=\"text\" name=\"address\" value=\"$address\">";
</code></pre>
<p>or</p>
<pre><code>$html = '<input type="text" name="address" values="' . $address . '">' ;
</code></pre>
<p>From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?</p>
|
[
{
"answer_id": 9718124,
"author": "inteblio",
"author_id": 371983,
"author_profile": "https://Stackoverflow.com/users/371983",
"pm_score": 3,
"selected": false,
"text": "<input value='it's gonna break'/>\n <input value=\"i say - \"this is gonna be trouble\" \"/>\n htmlspecialchars"
},
{
"answer_id": 16198937,
"author": "mcandre",
"author_id": 350106,
"author_profile": "https://Stackoverflow.com/users/350106",
"pm_score": -1,
"selected": false,
"text": "END"
},
{
"answer_id": 21870871,
"author": "rchacko",
"author_id": 3056160,
"author_profile": "https://Stackoverflow.com/users/3056160",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset='utf-8'>\n <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>\n <title>Bethanie Inc. data : geographically linked</title>\n <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>\n <script src='https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false' type='text/javascript'></script>\n <script type='text/javascript'> \n // check DOM Ready\n $(document).ready(function() {\n // execute\n (function() {\n /////////////// Addresses ///////////////////\n var locations = new Array();\n var i = 0;\n locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'\n locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'\n locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'\n\n /////// Addresses/////////\n var total_locations = i;\n i = 0;\n console.log('About to look up ' + total_locations + ' locations');\n // map options\n var options = {\n zoom: 10,\n center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie \n mapTypeId: google.maps.MapTypeId.ROADMAP,\n mapTypeControl: true\n };\n // init map\n console.log('Initialise map...');\n var map = new google.maps.Map(document.getElementById('map_canvas'), options);\n // use the Google API to translate addresses to GPS coordinates \n //(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)\n var geocoder = new google.maps.Geocoder();\n if (geocoder) {\n console.log('Got a new instance of Google Geocoder object');\n // Call function 'createNextMarker' every second\n var myVar = window.setInterval(function(){createNextMarker()}, 700);\n function createNextMarker() {\n if (i < locations.length) \n {\n var customer = locations[i];\n var parts = customer.split(','); // split line into parts (fields)\n var type= parts.splice(0,1); // type from location line (remove)\n var name = parts.splice(0,1); // name from location line(remove)\n var address =parts.join(','); // combine remaining parts\n console.log('Looking up ' + name + ' at address ' + address);\n geocoder.geocode({ 'address': address }, makeCallback(name, type));\n i++; // next location in list\n updateProgressBar(i / total_locations);\n\n\n } else \n {\n console.log('Ready looking up ' + i + ' addresses');\n window.clearInterval(myVar);\n }\n }\n\n function makeCallback(name,type) \n {\n var geocodeCallBack = function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var longitude = results[0].geometry.location.lng();\n var latitude = results[0].geometry.location.lat();\n console.log('Received result: lat:' + latitude + ' long:' + longitude);\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(latitude, longitude),\n map: map,\n title: name + ' : ' + '\\r\\n' + results[0].formatted_address});// this is display in tool tip/ icon color\n if (type=='E') {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};\n"
},
{
"answer_id": 55906574,
"author": "connexo",
"author_id": 3744304,
"author_profile": "https://Stackoverflow.com/users/3744304",
"pm_score": 3,
"selected": false,
"text": "<input type='checkbox'>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,356
|
<p>I have some pages on my site that are plain HTML pages, but I want to add some ASP .NET type functionality to these pages. My concern is that if I simple rename the .html page to .aspx that I will break links, and lose SEO, and so on.</p>
<p>I would think there is a "best practice" for how to handle this situation.</p>
|
[
{
"answer_id": 273411,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<html>\n<head>\n<title>Moved to new URL: http://example.com/newurl</title>\n<meta http-equiv=\"refresh\" content=\"0; url=http://example.com/newurl\" />\n<meta name=\"robots\" content=\"noindex,follow\" />\n</head>\n<body>\n<h1>This page has been moved to http://example.com/newurl</h1>\n<p>If your browser doesn't redirect you to the new location please <a href=\"http://example.com/newurl\"><b>click here</b></a>, sorry for the hassles!</p>\n</body>\n</html>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23294/"
] |
273,374
|
<p>So, if i have:</p>
<pre><code>public class Sedan : Car
{
/// ...
}
public class Car : Vehicle, ITurn
{
[MyCustomAttribute(1)]
public int TurningRadius { get; set; }
}
public abstract class Vehicle : ITurn
{
[MyCustomAttribute(2)]
public int TurningRadius { get; set; }
}
public interface ITurn
{
[MyCustomAttribute(3)]
int TurningRadius { get; set; }
}
</code></pre>
<p>What magic can I use to do something like:</p>
<pre><code>[Test]
public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
var property = typeof(Sedan).GetProperty("TurningRadius");
var attributes = SomeMagic(property);
Assert.AreEqual(attributes.Count, 3);
}
</code></pre>
<hr>
<p>Both </p>
<pre><code>property.GetCustomAttributes(true);
</code></pre>
<p>And</p>
<pre><code>Attribute.GetCustomAttributes(property, true);
</code></pre>
<p>Only return 1 attribute. The instance is the one built with MyCustomAttribute(1). This doesn't seem to work as expected.</p>
|
[
{
"answer_id": 273414,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "object[] SomeMagic (PropertyInfo property)\n{\n return property.GetCustomAttributes(true);\n}\n public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()\n{\n\n Assert.AreEqual(checkAttributeCount (typeof (Sedan), \"TurningRadious\"), 3);\n}\n\n\nint checkAttributeCount (Type type, string propertyName)\n{\n var attributesCount = 0;\n\n attributesCount += countAttributes (type, propertyName);\n while (type.BaseType != null)\n {\n type = type.BaseType;\n attributesCount += countAttributes (type, propertyName);\n }\n\n foreach (var i in type.GetInterfaces ())\n attributesCount += countAttributes (type, propertyName);\n return attributesCount;\n}\n\nint countAttributes (Type t, string propertyName)\n{\n var property = t.GetProperty (propertyName);\n if (property == null)\n return 0;\n return (property.GetCustomAttributes (false).Length);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
273,410
|
<p>How can I find out the number of dimensions in an array in Classic ASP ( VBScript ) .</p>
<p>I am being passed an Array with multiple dimensions but I only want to look at the last. Seems easy in other languages.</p>
|
[
{
"answer_id": 273454,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 4,
"selected": true,
"text": "Ubound(MySingleDimensionalArray, 2) ' Number of Array Elements\n\nUbound(MyMultiDimensionalArray, 1) ' Number of Columns\nUbound(MyMultiDimensionalArray, 2) ' Number of Rows\n"
},
{
"answer_id": 273582,
"author": "feihtthief",
"author_id": 320070,
"author_profile": "https://Stackoverflow.com/users/320070",
"pm_score": 2,
"selected": false,
"text": "function ArrayDimensions( theArray )\n dim Result,test\n Result = 0\n if isarray(theArray) then\n on error resume next\n do\n test = -2\n test = ubound(theArray,result+1)\n if test > -2 then result = result + 1\n loop until test=-2\n on error goto 0\n end if\n ArrayDimensions = Result\nend function\n"
},
{
"answer_id": 1342049,
"author": "jammus",
"author_id": 984,
"author_profile": "https://Stackoverflow.com/users/984",
"pm_score": 2,
"selected": false,
"text": "Function NumDimensions(arr)\n Dim dimensions : dimensions = 0\n On Error Resume Next\n Do While Err.number = 0\n dimensions = dimensions + 1\n UBound arr, dimensions\n Loop\n On Error Goto 0\n NumDimensions = dimensions - 1\nEnd Function\n Dim test(9, 5, 4, 3, 9, 1, 3, 5)\nNumDimensions(test)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
273,433
|
<p>I've been Googling around for .htaccess redirection information, but nothing I find is quite what I'm looking for.</p>
<p>Basically, I want a solution that will take a site example.com and allow you to enter URL's like:</p>
<pre><code> 123.example.com
ksdfkjds.example.com
dsf38jif348.example.com
</code></pre>
<p>and this would redirect them to:</p>
<pre><code> example.com/123
example.com/ksdfkjds
example.com/dsf38jif348
</code></pre>
<p>So basically accept any subdomain and automatically redirect to a folder on the root of the domain with the name of that subdomain.</p>
|
[
{
"answer_id": 273456,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "# If we're not on http://example.com\nRewriteCond %{HTTP_HOST} .+\\.example.com\n\n# Add the host to the front of the URL and chain with the next rule\nRewriteRule ^(.*)$ ${HOST}$1 [C,QSA]\n\n# Make the host a directory\nRewriteRule ^(.*)\\.example\\.com(.*)$ http://example.com/$1$2 [QSA]\n"
},
{
"answer_id": 487368,
"author": "Gumbo",
"author_id": 53114,
"author_profile": "https://Stackoverflow.com/users/53114",
"pm_score": 0,
"selected": false,
"text": "RewriteCond %{HTTP_HOST} ^([^.]+)\\.example\\.com$\nRewriteRule ^ http://example.com/%1 [L,R]\n RewriteCond %{HTTP_HOST} ^([^.]+)\\.example\\.com$\nRewriteRule ^ /%1%{REQUEST_URI} [L]\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,437
|
<p>My current process for debugging stored procedures is very simple. I create a table called "debug" where I insert variable values from the stored procedure as it runs. This allows me to see the value of any variable at a given point in the script, but is there a better way to debug MySQL stored procedures?</p>
|
[
{
"answer_id": 11137574,
"author": "Jeremy S.",
"author_id": 231982,
"author_profile": "https://Stackoverflow.com/users/231982",
"pm_score": 3,
"selected": false,
"text": "SELECT 'Message Text' AS `Title`; \n"
},
{
"answer_id": 15687954,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 6,
"selected": false,
"text": "debug_msg DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `debug_msg`$$\nDROP PROCEDURE IF EXISTS `test_procedure`$$\n\nCREATE PROCEDURE debug_msg(enabled INTEGER, msg VARCHAR(255))\nBEGIN\n IF enabled THEN\n select concat('** ', msg) AS '** DEBUG:';\n END IF;\nEND $$\n\nCREATE PROCEDURE test_procedure(arg1 INTEGER, arg2 INTEGER)\nBEGIN\n SET @enabled = TRUE;\n\n call debug_msg(@enabled, 'my first debug message');\n call debug_msg(@enabled, (select concat_ws('','arg1:', arg1)));\n call debug_msg(TRUE, 'This message always shows up');\n call debug_msg(FALSE, 'This message will never show up');\nEND $$\n\nDELIMITER ;\n CALL test_procedure(1,2)\n ** DEBUG:\n** my first debug message\n** DEBUG:\n** arg1:1\n** DEBUG:\n** This message always shows up\n"
},
{
"answer_id": 20755176,
"author": "Eric Leschinski",
"author_id": 445131,
"author_profile": "https://Stackoverflow.com/users/445131",
"pm_score": 5,
"selected": false,
"text": "id INT log VARCHAR(255) delimiter //\nDROP PROCEDURE `log_msg`//\nCREATE PROCEDURE `log_msg`(msg VARCHAR(255))\nBEGIN\n insert into logtable select 0, msg;\nEND\n call log_msg(concat('myvar is: ', myvar, ' and myvar2 is: ', myvar2));\n"
},
{
"answer_id": 28683042,
"author": "Tone Škoda",
"author_id": 3572009,
"author_profile": "https://Stackoverflow.com/users/3572009",
"pm_score": 4,
"selected": false,
"text": "DELIMITER GO$\n\nDROP PROCEDURE IF EXISTS resetLog\n\nGO$\n\nCreate Procedure resetLog() \nBEGIN \n create table if not exists log (ts timestamp default current_timestamp, msg varchar(2048)) engine = myisam; \n truncate table log;\nEND; \n\nGO$\n\nDROP PROCEDURE IF EXISTS doLog \n\nGO$\n\nCreate Procedure doLog(in logMsg nvarchar(2048))\nBEGIN \n insert into log (msg) values(logMsg);\nEND;\n\nGO$\n call dolog(concat_ws(': ','@simple_term_taxonomy_id', @simple_term_taxonomy_id));\n call resetLog ();\ncall stored_proc();\nselect * from log;\n"
},
{
"answer_id": 35834907,
"author": "Marcelo Amorim",
"author_id": 1307507,
"author_profile": "https://Stackoverflow.com/users/1307507",
"pm_score": 3,
"selected": false,
"text": "$install\n$setup yourFunctionName\n $debug yourFunctionName('yourParameter')\n"
},
{
"answer_id": 47219091,
"author": "aniruddha",
"author_id": 1397981,
"author_profile": "https://Stackoverflow.com/users/1397981",
"pm_score": 1,
"selected": false,
"text": "debug_msg debug_msg my_res_set CREATE DEFINER=`root`@`localhost` FUNCTION `debug_msg`(`enabled` INT(11), `msg` TEXT) RETURNS text CHARSET latin1\n READS SQL DATA\nBEGIN\n IF enabled=1 THEN\n return concat('** DEBUG:', \"** \", msg);\n END IF;\nEND\n\nDELIMITER $$\nCREATE DEFINER=`root`@`localhost` PROCEDURE `proc_func_call`(\n IN RegionID VARCHAR(20),\n IN RepCurrency INT(11),\n IN MGID INT(11),\n IN VNC VARCHAR(255)\n)\nBEGIN\n SET @enabled = TRUE;\n SET @mainQuery = \"SELECT * FROM Users u\";\n SELECT `debug_msg`(@enabled, @mainQuery) AS `debug_msg1`;\n SET @lastQuery = CONCAT(@mainQuery, \" WHERE u.age>30);\n SELECT `debug_msg`(@enabled, @lastQuery) AS `debug_msg2`;\nEND $$\nDELIMITER\n"
},
{
"answer_id": 58442790,
"author": "clarkttfu",
"author_id": 1999185,
"author_profile": "https://Stackoverflow.com/users/1999185",
"pm_score": 2,
"selected": false,
"text": "DELIMITER ;;\nCREATE PROCEDURE Foo(tableName VARCHAR(128))\nBEGIN\n SET @stmt = CONCAT('SELECT * FROM ', tableName);\n PREPARE pStmt FROM @stmt;\n EXECUTE pStmt;\n DEALLOCATE PREPARE pStmt;\n -- uncomment after debugging to cleanup\n -- SET @stmt = null;\nEND;;\nDELIMITER ;\n call Foo('foo');\nselect @stmt;\n SELECT * FROM foo\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
273,447
|
<p>I am using the .NET 3.5 SP1 framework and I've implemented URL routing in my application. I was getting javascript errors: </p>
<p><code>
Error: ASP.NET Ajax client-side framework failed to load.<br>
Resource interpreted as script but transferred with MIME type text/html.<br>
ReferenceError: Can't find variable: Sys
</code></p>
<p>Which I believe is because my routing is picking up the microsoft axd files and not properly sending down the javascript. I did some research and found that I could use <code>Routes.IgnoreRoute</code>, which should allow me to ignore the axd like below:</p>
<pre><code>Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
</code></pre>
<p>But, when I add that line to my Global.asax I get this error:</p>
<p><code>
CS1061: 'System.Web.Routing.RouteCollection' does not contain a definition for 'IgnoreRoute' and no extension method 'IgnoreRoute' accepting a first argument of type 'System.Web.Routing.RouteCollection' could be found (are you missing a using directive or an assembly reference?)
</code></p>
<p>I've got the <code>System.Web.Routing</code> namespace imported, any ideas?</p>
|
[
{
"answer_id": 276036,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 6,
"selected": true,
"text": "routes.Add(new Route(\"{resource}.axd/{*pathInfo}\", new StopRoutingHandler()));\n"
},
{
"answer_id": 7889659,
"author": "Ed Graham",
"author_id": 128193,
"author_profile": "https://Stackoverflow.com/users/128193",
"pm_score": 3,
"selected": false,
"text": "routes.Ignore(\"{resource}.axd/{*pathInfo}\");\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32854/"
] |
273,450
|
<p>Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.</p>
<p>There's this somewhat-related method in UIApplication:</p>
<pre><code>[UIApplication sharedApplication].idleTimerDisabled;
</code></pre>
<p>It'd be nice if you instead had something like this:</p>
<pre><code>NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed;
</code></pre>
<p>Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.</p>
<p>Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.</p>
|
[
{
"answer_id": 309535,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 8,
"selected": true,
"text": "- (void)sendEvent:(UIEvent *)event {\n [super sendEvent:event];\n\n // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.\n NSSet *allTouches = [event allTouches];\n if ([allTouches count] > 0) {\n // allTouches count only ever seems to be 1, so anyObject works here.\n UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;\n if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)\n [self resetIdleTimer];\n }\n}\n\n- (void)resetIdleTimer {\n if (idleTimer) {\n [idleTimer invalidate];\n [idleTimer release];\n }\n\n idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];\n}\n\n- (void)idleTimerExceeded {\n NSLog(@\"idle time exceeded\");\n}\n int retVal = UIApplicationMain(argc, argv, @\"AppDelegate\", @\"AppDelegate\");\n"
},
{
"answer_id": 3580685,
"author": "Roby",
"author_id": 432468,
"author_profile": "https://Stackoverflow.com/users/432468",
"pm_score": 3,
"selected": false,
"text": "UIApplication UIApplication fileOwner myApp sendEvent int retVal = UIApplicationMain(argc,argv,@\"myApp.m\",@\"myApp.m\")\n"
},
{
"answer_id": 5269900,
"author": "Chris Miles",
"author_id": 78474,
"author_profile": "https://Stackoverflow.com/users/78474",
"pm_score": 7,
"selected": false,
"text": "resetIdleTimer @interface MainViewController : UIViewController\n{\n NSTimer *idleTimer;\n}\n@end\n\n#define kMaxIdleTimeSeconds 60.0\n\n@implementation MainViewController\n\n#pragma mark -\n#pragma mark Handling idle timeout\n\n- (void)resetIdleTimer {\n if (!idleTimer) {\n idleTimer = [[NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds\n target:self\n selector:@selector(idleTimerExceeded)\n userInfo:nil\n repeats:NO] retain];\n }\n else {\n if (fabs([idleTimer.fireDate timeIntervalSinceNow]) < kMaxIdleTimeSeconds-1.0) {\n [idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];\n }\n }\n}\n\n- (void)idleTimerExceeded {\n [idleTimer release]; idleTimer = nil;\n [self startScreenSaverOrSomethingInteresting];\n [self resetIdleTimer];\n}\n\n- (UIResponder *)nextResponder {\n [self resetIdleTimer];\n return [super nextResponder];\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n [self resetIdleTimer];\n}\n\n@end\n"
},
{
"answer_id": 14725059,
"author": "Kay",
"author_id": 437283,
"author_profile": "https://Stackoverflow.com/users/437283",
"pm_score": 2,
"selected": false,
"text": "setIdleTimerDisabled - (void) enableIdleTimerDelayed {\n [self performSelector:@selector (enableIdleTimer) withObject:nil afterDelay:60];\n}\n\n- (void) enableIdleTimer {\n [NSObject cancelPreviousPerformRequestsWithTarget:self];\n [[UIApplication sharedApplication] setIdleTimerDisabled:NO];\n}\n\n- (void) disableIdleTimer {\n [NSObject cancelPreviousPerformRequestsWithTarget:self];\n [[UIApplication sharedApplication] setIdleTimerDisabled:YES];\n}\n disableIdleTimer enableIdleTimerDelayed enableIdleTimer applicationWillResignActive"
},
{
"answer_id": 25293578,
"author": "Mihai Timar",
"author_id": 757408,
"author_profile": "https://Stackoverflow.com/users/757408",
"pm_score": 2,
"selected": false,
"text": "UITrackingRunLoopMode UITracking ACTIVITY_DETECT_TIMER_RESOLUTION keepAlive _touchesTimer = [NSTimer timerWithTimeInterval:ACTIVITY_DETECT_TIMER_RESOLUTION\n target:self\n selector:@selector(keepAlive)\n userInfo:nil\n repeats:YES];\n[[NSRunLoop mainRunLoop] addTimer:_touchesTimer forMode:UITrackingRunLoopMode];\n"
},
{
"answer_id": 43940042,
"author": "Sergey Stadnik",
"author_id": 4745768,
"author_profile": "https://Stackoverflow.com/users/4745768",
"pm_score": 5,
"selected": false,
"text": "extension NSNotification.Name {\n public static let TimeOutUserInteraction: NSNotification.Name = NSNotification.Name(rawValue: \"TimeOutUserInteraction\")\n}\n\n\nclass InterractionUIApplication: UIApplication {\n\nstatic let ApplicationDidTimoutNotification = \"AppTimout\"\n\n// The timeout in seconds for when to fire the idle timer.\nlet timeoutInSeconds: TimeInterval = 15 * 60\n\nvar idleTimer: Timer?\n\n// Listen for any touch. If the screen receives a touch, the timer is reset.\noverride func sendEvent(_ event: UIEvent) {\n super.sendEvent(event)\n\n if idleTimer != nil {\n self.resetIdleTimer()\n }\n\n if let touches = event.allTouches {\n for touch in touches {\n if touch.phase == UITouchPhase.began {\n self.resetIdleTimer()\n }\n }\n }\n}\n\n// Resent the timer because there was user interaction.\nfunc resetIdleTimer() {\n if let idleTimer = idleTimer {\n idleTimer.invalidate()\n }\n\n idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(self.idleTimerExceeded), userInfo: nil, repeats: false)\n}\n\n// If the timer reaches the limit as defined in timeoutInSeconds, post this notification.\nfunc idleTimerExceeded() {\n NotificationCenter.default.post(name:Notification.Name.TimeOutUserInteraction, object: nil)\n }\n} \n CommandLine.unsafeArgv.withMemoryRebound(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc)) {argv in\n_ = UIApplicationMain(CommandLine.argc, argv, NSStringFromClass(InterractionUIApplication.self), NSStringFromClass(AppDelegate.self))\n}\n NotificationCenter.default.addObserver(self, selector: #selector(someFuncitonName), name: Notification.Name.TimeOutUserInteraction, object: nil)\n"
},
{
"answer_id": 45496010,
"author": "Jlam",
"author_id": 199966,
"author_profile": "https://Stackoverflow.com/users/199966",
"pm_score": 3,
"selected": false,
"text": "fileprivate var timer ... //timer logic here\n\n@objc public class CatchAllGesture : UIGestureRecognizer {\n override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {\n super.touchesBegan(touches, with: event)\n }\n override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {\n //reset your timer here\n state = .failed\n super.touchesEnded(touches, with: event)\n }\n override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {\n super.touchesMoved(touches, with: event)\n }\n}\n\n@objc extension YOURAPPAppDelegate {\n\n func addGesture () {\n let aGesture = CatchAllGesture(target: nil, action: nil)\n aGesture.cancelsTouchesInView = false\n self.window.addGestureRecognizer(aGesture)\n }\n}\n"
},
{
"answer_id": 65919565,
"author": "Dmitriy Miyai",
"author_id": 4730040,
"author_profile": "https://Stackoverflow.com/users/4730040",
"pm_score": 1,
"selected": false,
"text": "@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n var window: UIWindow?\n sendEvent import UIKit\n\nclass MyWindow: UIWindow {\n\n override func sendEvent(_ event: UIEvent){\n super.sendEvent(event)\n NSLog(\"Application received an event. Do whatever you want\")\n }\n}\n self.window = MyWindow(frame: UIScreen.main.bounds)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] |
273,452
|
<p>I can't seem to find a nice clean example of using AES 128 bit encryption.</p>
<p>Does anyone have some sample code?</p>
|
[
{
"answer_id": 273499,
"author": "Dan Esparza",
"author_id": 19020,
"author_profile": "https://Stackoverflow.com/users/19020",
"pm_score": 7,
"selected": false,
"text": "using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace RijndaelManaged_Example\n{\n class RijndaelExample\n {\n public static void Main()\n {\n try\n {\n\n string original = \"Here is some data to encrypt!\";\n\n // Create a new instance of the RijndaelManaged \n // class. This generates a new key and initialization \n // vector (IV). \n using (RijndaelManaged myRijndael = new RijndaelManaged())\n {\n\n myRijndael.GenerateKey();\n myRijndael.GenerateIV();\n // Encrypt the string to an array of bytes. \n byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);\n\n // Decrypt the bytes to a string. \n string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);\n\n //Display the original data and the decrypted data.\n Console.WriteLine(\"Original: {0}\", original);\n Console.WriteLine(\"Round Trip: {0}\", roundtrip);\n }\n\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: {0}\", e.Message);\n }\n }\n static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)\n {\n // Check arguments. \n if (plainText == null || plainText.Length <= 0)\n throw new ArgumentNullException(\"plainText\");\n if (Key == null || Key.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length <= 0)\n throw new ArgumentNullException(\"IV\");\n byte[] encrypted;\n // Create an RijndaelManaged object \n // with the specified key and IV. \n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for encryption. \n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n\n\n // Return the encrypted bytes from the memory stream. \n return encrypted;\n\n }\n\n static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)\n {\n // Check arguments. \n if (cipherText == null || cipherText.Length <= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (Key == null || Key.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length <= 0)\n throw new ArgumentNullException(\"IV\");\n\n // Declare the string used to hold \n // the decrypted text. \n string plaintext = null;\n\n // Create an RijndaelManaged object \n // with the specified key and IV. \n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for decryption. \n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n\n // Read the decrypted bytes from the decrypting stream \n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n\n }\n\n return plaintext;\n\n }\n }\n}\n"
},
{
"answer_id": 8779595,
"author": "Javanese Girl",
"author_id": 1136197,
"author_profile": "https://Stackoverflow.com/users/1136197",
"pm_score": 4,
"selected": false,
"text": "using System.Windows.Forms;\nusing System;\nusing System.Text;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace AES_TESTER\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n try\n {\n\n string original = \"Here is some data to encrypt!\";\n MessageBox.Show(\"Original: \" + original);\n\n // Create a new instance of the RijndaelManaged\n // class. This generates a new key and initialization \n // vector (IV).\n using (RijndaelManaged myRijndael = new RijndaelManaged())\n {\n myRijndael.GenerateKey();\n myRijndael.GenerateIV();\n\n // Encrypt the string to an array of bytes.\n byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);\n\n StringBuilder s = new StringBuilder();\n foreach (byte item in encrypted)\n {\n s.Append(item.ToString(\"X2\") + \" \");\n }\n MessageBox.Show(\"Encrypted: \" + s);\n\n // Decrypt the bytes to a string.\n string decrypted = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);\n\n //Display the original data and the decrypted data.\n MessageBox.Show(\"Decrypted: \" + decrypted);\n }\n\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error: {0}\", ex.Message);\n }\n }\n\n static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)\n {\n // Check arguments.\n if (plainText == null || plainText.Length <= 0)\n throw new ArgumentNullException(\"plainText\");\n if (Key == null || Key.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n byte[] encrypted;\n // Create an RijndaelManaged object\n // with the specified key and IV.\n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n rijAlg.Mode = CipherMode.CBC;\n rijAlg.Padding = PaddingMode.Zeros;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n\n\n // Return the encrypted bytes from the memory stream.\n return encrypted;\n\n }\n\n static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)\n {\n // Check arguments.\n if (cipherText == null || cipherText.Length <= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (Key == null || Key.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length <= 0)\n throw new ArgumentNullException(\"Key\");\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n // Create an RijndaelManaged object\n // with the specified key and IV.\n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n rijAlg.Mode = CipherMode.CBC;\n rijAlg.Padding = PaddingMode.Zeros;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for decryption.\n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n\n }\n\n return plaintext;\n }\n }\n}\n"
},
{
"answer_id": 13369641,
"author": "YD4",
"author_id": 1815264,
"author_profile": "https://Stackoverflow.com/users/1815264",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\nusing System.Security.Cryptography;\n\nnamespace ExampleCrypto\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n string strOriginalData = string.Empty;\n string strEncryptedData = string.Empty;\n string strDecryptedData = string.Empty;\n\n strOriginalData = \"this is original data 1234567890\"; // your original data in here\n MessageBox.Show(\"ORIGINAL DATA:\\r\\n\" + strOriginalData);\n\n clsCrypto aes = new clsCrypto();\n aes.IV = \"this is your IV\"; // your IV\n aes.KEY = \"this is your KEY\"; // your KEY \n strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode\n MessageBox.Show(\"ENCRYPTED DATA:\\r\\n\" + strEncryptedData);\n\n strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);\n MessageBox.Show(\"DECRYPTED DATA:\\r\\n\" + strDecryptedData);\n }\n\n }\n}\n using System;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.IO;\nusing System.Runtime.Remoting.Metadata.W3cXsd2001;\n\nnamespace ExampleCrypto\n{\n public class clsCrypto\n {\n private string _KEY = string.Empty;\n protected internal string KEY\n {\n get\n {\n return _KEY;\n }\n set\n {\n if (!string.IsNullOrEmpty(value))\n {\n _KEY = value;\n }\n }\n }\n\n private string _IV = string.Empty;\n protected internal string IV\n {\n get\n {\n return _IV;\n }\n set\n {\n if (!string.IsNullOrEmpty(value))\n {\n _IV = value;\n }\n }\n }\n\n private string CalcMD5(string strInput)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n StringBuilder strHex = new StringBuilder();\n using (MD5 md5 = MD5.Create())\n {\n byte[] bytArText = Encoding.Default.GetBytes(strInput);\n byte[] bytArHash = md5.ComputeHash(bytArText);\n for (int i = 0; i < bytArHash.Length; i++)\n {\n strHex.Append(bytArHash[i].ToString(\"X2\"));\n }\n strOutput = strHex.ToString();\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n private byte[] GetBytesFromHexString(string strInput)\n {\n byte[] bytArOutput = new byte[] { };\n if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)\n {\n SoapHexBinary hexBinary = null;\n try\n {\n hexBinary = SoapHexBinary.Parse(strInput);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n bytArOutput = hexBinary.Value;\n }\n return bytArOutput;\n }\n\n private byte[] GenerateIV()\n {\n byte[] bytArOutput = new byte[] { };\n try\n {\n string strIV = CalcMD5(IV);\n bytArOutput = GetBytesFromHexString(strIV);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n return bytArOutput;\n }\n\n private byte[] GenerateKey()\n {\n byte[] bytArOutput = new byte[] { };\n try\n {\n string strKey = CalcMD5(KEY);\n bytArOutput = GetBytesFromHexString(strKey);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n return bytArOutput;\n }\n\n protected internal string Encrypt(string strInput, CipherMode cipherMode)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n byte[] bytePlainText = Encoding.Default.GetBytes(strInput);\n using (RijndaelManaged rijManaged = new RijndaelManaged())\n {\n rijManaged.Mode = cipherMode;\n rijManaged.BlockSize = 128;\n rijManaged.KeySize = 128;\n rijManaged.IV = GenerateIV();\n rijManaged.Key = GenerateKey();\n rijManaged.Padding = PaddingMode.Zeros;\n ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);\n using (MemoryStream memStream = new MemoryStream())\n {\n using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))\n {\n cpoStream.Write(bytePlainText, 0, bytePlainText.Length);\n cpoStream.FlushFinalBlock();\n }\n strOutput = Encoding.Default.GetString(memStream.ToArray());\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n protected internal string Decrypt(string strInput, CipherMode cipherMode)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n byte[] byteCipherText = Encoding.Default.GetBytes(strInput);\n byte[] byteBuffer = new byte[strInput.Length];\n using (RijndaelManaged rijManaged = new RijndaelManaged())\n {\n rijManaged.Mode = cipherMode;\n rijManaged.BlockSize = 128;\n rijManaged.KeySize = 128;\n rijManaged.IV = GenerateIV();\n rijManaged.Key = GenerateKey();\n rijManaged.Padding = PaddingMode.Zeros;\n ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);\n using (MemoryStream memStream = new MemoryStream(byteCipherText))\n {\n using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))\n {\n cpoStream.Read(byteBuffer, 0, byteBuffer.Length);\n }\n strOutput = Encoding.Default.GetString(byteBuffer);\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n }\n}\n"
},
{
"answer_id": 14286740,
"author": "Troy Alford",
"author_id": 1454806,
"author_profile": "https://Stackoverflow.com/users/1454806",
"pm_score": 6,
"selected": false,
"text": "AesManaged using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Your.Namespace.Security {\n public static class Cryptography {\n #region Settings\n\n private static int _iterations = 2;\n private static int _keySize = 256;\n\n private static string _hash = \"SHA1\";\n private static string _salt = \"aselrias38490a32\"; // Random\n private static string _vector = \"8947az34awl34kjq\"; // Random\n\n #endregion\n\n public static string Encrypt(string value, string password) {\n return Encrypt<AesManaged>(value, password);\n }\n public static string Encrypt<T>(string value, string password) \n where T : SymmetricAlgorithm, new() {\n byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);\n byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);\n byte[] valueBytes = GetBytes<UTF8Encoding>(value);\n\n byte[] encrypted;\n using (T cipher = new T()) {\n PasswordDeriveBytes _passwordBytes = \n new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);\n byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);\n\n cipher.Mode = CipherMode.CBC;\n\n using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {\n using (MemoryStream to = new MemoryStream()) {\n using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {\n writer.Write(valueBytes, 0, valueBytes.Length);\n writer.FlushFinalBlock();\n encrypted = to.ToArray();\n }\n }\n }\n cipher.Clear();\n }\n return Convert.ToBase64String(encrypted);\n }\n\n public static string Decrypt(string value, string password) {\n return Decrypt<AesManaged>(value, password);\n }\n public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {\n byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);\n byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);\n byte[] valueBytes = Convert.FromBase64String(value);\n\n byte[] decrypted;\n int decryptedByteCount = 0;\n\n using (T cipher = new T()) {\n PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);\n byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);\n\n cipher.Mode = CipherMode.CBC;\n\n try {\n using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {\n using (MemoryStream from = new MemoryStream(valueBytes)) {\n using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {\n decrypted = new byte[valueBytes.Length];\n decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);\n }\n }\n }\n } catch (Exception ex) {\n return String.Empty;\n }\n\n cipher.Clear();\n }\n return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);\n }\n\n }\n}\n string encrypted = Cryptography.Encrypt(data, \"testpass\");\nstring decrypted = Cryptography.Decrypt(encrypted, \"testpass\");\n SymmetricAlgorithm SymmetricAlgorithm AesManaged RijndaelManaged DESCryptoServiceProvider RC2CryptoServiceProvider TripleDESCryptoServiceProvider RijndaelManaged string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);\nstring decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);\n"
},
{
"answer_id": 17561816,
"author": "0xEE00",
"author_id": 1175886,
"author_profile": "https://Stackoverflow.com/users/1175886",
"pm_score": 2,
"selected": false,
"text": " public class Rijndael\n{\n private byte[] key;\n private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };\n\n ICryptoTransform EnkValue, DekValue;\n\n public Rijndael(byte[] key)\n {\n this.key = key;\n RijndaelManaged rm = new RijndaelManaged();\n rm.Padding = PaddingMode.PKCS7;\n EnkValue = rm.CreateEncryptor(key, vector);\n DekValue = rm.CreateDecryptor(key, vector);\n }\n\n public byte[] Encrypt(byte[] byte)\n {\n\n byte[] enkByte= byte;\n byte[] enkNewByte;\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))\n {\n cs.Write(enkByte, 0, enkByte.Length);\n cs.FlushFinalBlock();\n\n ms.Position = 0;\n enkNewByte= new byte[ms.Length];\n ms.Read(enkNewByte, 0, enkNewByte.Length);\n }\n }\n return enkNeyByte;\n }\n\n public byte[] Dekrypt(byte[] enkByte)\n {\n byte[] dekByte;\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))\n {\n cs.Write(enkByte, 0, enkByte.Length);\n cs.FlushFinalBlock();\n\n ms.Position = 0;\n dekByte= new byte[ms.Length];\n ms.Read(dekByte, 0, dekByte.Length);\n }\n }\n return dekByte;\n }\n}\n private byte[] ConvertPasswordToByte(string password)\n {\n byte[] key = new byte[32];\n for (int i = 0; i < passwprd.Length; i++)\n {\n key[i] = Convert.ToByte(passwprd[i]);\n }\n return key;\n }\n"
},
{
"answer_id": 24963085,
"author": "siddharth",
"author_id": 3876812,
"author_profile": "https://Stackoverflow.com/users/3876812",
"pm_score": 3,
"selected": false,
"text": "//Code to encrypt Data : \n public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv) \n { \n AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider(); \n //Block size : Gets or sets the block size, in bits, of the cryptographic operation. \n dataencrypt.BlockSize = 128; \n //KeySize: Gets or sets the size, in bits, of the secret key \n dataencrypt.KeySize = 128; \n //Key: Gets or sets the symmetric key that is used for encryption and decryption. \n dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key); \n //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm \n dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv); \n //Padding: Gets or sets the padding mode used in the symmetric algorithm \n dataencrypt.Padding = PaddingMode.PKCS7; \n //Mode: Gets or sets the mode for operation of the symmetric algorithm \n dataencrypt.Mode = CipherMode.CBC; \n //Creates a symmetric AES encryptor object using the current key and initialization vector (IV). \n ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV); \n //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream. \n //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of \n //information returned at the end might be larger than a single block when padding is added. \n byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length); \n crypto1.Dispose(); \n //return the encrypted data \n return encrypteddata; \n } \n\n//code to decrypt data\n private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv) \n { \n\n AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider(); \n keydecrypt.BlockSize = 128; \n keydecrypt.KeySize = 128; \n keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key); \n keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv); \n keydecrypt.Padding = PaddingMode.PKCS7; \n keydecrypt.Mode = CipherMode.CBC; \n ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV); \n\n byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length); \n crypto1.Dispose(); \n return returnbytearray; \n }\n"
},
{
"answer_id": 26758901,
"author": "Zeeshan Amber",
"author_id": 3962935,
"author_profile": "https://Stackoverflow.com/users/3962935",
"pm_score": 2,
"selected": false,
"text": "encryptedstring = cryptObj.Encrypt(username, \"AGARAMUDHALA\", \"EZHUTHELLAM\", \"SHA1\", 3, \"@1B2c3D4e5F6g7H8\", 256); public class Crypt\n{\n public string Encrypt(string passtext, string passPhrase, string saltV, string hashstring, int Iterations, string initVect, int keysize)\n {\n string functionReturnValue = null;\n // Convert strings into byte arrays.\n // Let us assume that strings only contain ASCII codes.\n // If strings include Unicode characters, use Unicode, UTF7, or UTF8\n // encoding.\n byte[] initVectorBytes = null;\n initVectorBytes = Encoding.ASCII.GetBytes(initVect);\n byte[] saltValueBytes = null;\n saltValueBytes = Encoding.ASCII.GetBytes(saltV);\n\n // Convert our plaintext into a byte array.\n // Let us assume that plaintext contains UTF8-encoded characters.\n byte[] plainTextBytes = null;\n plainTextBytes = Encoding.UTF8.GetBytes(passtext);\n // First, we must create a password, from which the key will be derived.\n // This password will be generated from the specified passphrase and\n // salt value. The password will be created using the specified hash\n // algorithm. Password creation can be done in several iterations.\n PasswordDeriveBytes password = default(PasswordDeriveBytes);\n password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashstring, Iterations);\n // Use the password to generate pseudo-random bytes for the encryption\n // key. Specify the size of the key in bytes (instead of bits).\n byte[] keyBytes = null;\n keyBytes = password.GetBytes(keysize/8);\n // Create uninitialized Rijndael encryption object.\n RijndaelManaged symmetricKey = default(RijndaelManaged);\n symmetricKey = new RijndaelManaged();\n\n // It is reasonable to set encryption mode to Cipher Block Chaining\n // (CBC). Use default options for other symmetric key parameters.\n symmetricKey.Mode = CipherMode.CBC;\n // Generate encryptor from the existing key bytes and initialization\n // vector. Key size will be defined based on the number of the key\n // bytes.\n ICryptoTransform encryptor = default(ICryptoTransform);\n encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n MemoryStream memoryStream = default(MemoryStream);\n memoryStream = new MemoryStream();\n\n // Define cryptographic stream (always use Write mode for encryption).\n CryptoStream cryptoStream = default(CryptoStream);\n cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);\n // Start encrypting.\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n\n // Finish encrypting.\n cryptoStream.FlushFinalBlock();\n // Convert our encrypted data from a memory stream into a byte array.\n byte[] cipherTextBytes = null;\n cipherTextBytes = memoryStream.ToArray();\n\n // Close both streams.\n memoryStream.Close();\n cryptoStream.Close();\n\n // Convert encrypted data into a base64-encoded string.\n string cipherText = null;\n cipherText = Convert.ToBase64String(cipherTextBytes);\n\n functionReturnValue = cipherText;\n return functionReturnValue;\n }\n public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)\n {\n string functionReturnValue = null;\n\n // Convert strings defining encryption key characteristics into byte\n // arrays. Let us assume that strings only contain ASCII codes.\n // If strings include Unicode characters, use Unicode, UTF7, or UTF8\n // encoding.\n\n\n byte[] initVectorBytes = null;\n initVectorBytes = Encoding.ASCII.GetBytes(initVector);\n\n byte[] saltValueBytes = null;\n saltValueBytes = Encoding.ASCII.GetBytes(saltValue);\n\n // Convert our ciphertext into a byte array.\n byte[] cipherTextBytes = null;\n cipherTextBytes = Convert.FromBase64String(cipherText);\n\n // First, we must create a password, from which the key will be\n // derived. This password will be generated from the specified\n // passphrase and salt value. The password will be created using\n // the specified hash algorithm. Password creation can be done in\n // several iterations.\n PasswordDeriveBytes password = default(PasswordDeriveBytes);\n password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);\n\n // Use the password to generate pseudo-random bytes for the encryption\n // key. Specify the size of the key in bytes (instead of bits).\n byte[] keyBytes = null;\n keyBytes = password.GetBytes(keySize / 8);\n\n // Create uninitialized Rijndael encryption object.\n RijndaelManaged symmetricKey = default(RijndaelManaged);\n symmetricKey = new RijndaelManaged();\n\n // It is reasonable to set encryption mode to Cipher Block Chaining\n // (CBC). Use default options for other symmetric key parameters.\n symmetricKey.Mode = CipherMode.CBC;\n\n // Generate decryptor from the existing key bytes and initialization\n // vector. Key size will be defined based on the number of the key\n // bytes.\n ICryptoTransform decryptor = default(ICryptoTransform);\n decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n MemoryStream memoryStream = default(MemoryStream);\n memoryStream = new MemoryStream(cipherTextBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n CryptoStream cryptoStream = default(CryptoStream);\n cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n\n // Since at this point we don't know what the size of decrypted data\n // will be, allocate the buffer long enough to hold ciphertext;\n // plaintext is never longer than ciphertext.\n byte[] plainTextBytes = null;\n plainTextBytes = new byte[cipherTextBytes.Length + 1];\n\n // Start decrypting.\n int decryptedByteCount = 0;\n decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n\n // Close both streams.\n memoryStream.Close();\n cryptoStream.Close();\n\n // Convert decrypted data into a string.\n // Let us assume that the original plaintext string was UTF8-encoded.\n string plainText = null;\n plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n\n // Return decrypted string.\n functionReturnValue = plainText;\n\n\n return functionReturnValue;\n }\n}\n"
},
{
"answer_id": 38075808,
"author": "ARTAGE",
"author_id": 6184711,
"author_profile": "https://Stackoverflow.com/users/6184711",
"pm_score": 3,
"selected": false,
"text": "using System.Security.Cryptography;\nusing System.IO;\n public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)\n{\n byte[] encryptedBytes = null;\n byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n using (MemoryStream ms = new MemoryStream())\n {\n using (RijndaelManaged AES = new RijndaelManaged())\n {\n AES.KeySize = 256;\n AES.BlockSize = 128;\n var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);\n AES.Key = key.GetBytes(AES.KeySize / 8);\n AES.IV = key.GetBytes(AES.BlockSize / 8);\n AES.Mode = CipherMode.CBC;\n using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);\n cs.Close();\n }\n encryptedBytes = ms.ToArray();\n }\n }\n return encryptedBytes;\n}\n\npublic byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)\n{\n byte[] decryptedBytes = null;\n byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n using (MemoryStream ms = new MemoryStream())\n {\n using (RijndaelManaged AES = new RijndaelManaged())\n {\n AES.KeySize = 256;\n AES.BlockSize = 128;\n var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);\n AES.Key = key.GetBytes(AES.KeySize / 8);\n AES.IV = key.GetBytes(AES.BlockSize / 8);\n AES.Mode = CipherMode.CBC;\n using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);\n cs.Close();\n }\n decryptedBytes = ms.ToArray();\n }\n }\n return decryptedBytes;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,461
|
<p>In Microsoft Access I have a table called Time Sheet and in this I have Time sheet no. , waiter no. , date and hours worked. I have 10 waiters. </p>
<p>I have another table called Service Charge Distribution. In this table I have Service Charge No. , waiter no. , week no. and distribution amount. </p>
<p>There is a Bill table where the Service charge distribution is worked out from the bill. </p>
<p>i need to calculate the distribution amount in the service charge distribution table but I do not know how to do this. I would like to do this in Forms. I do know how to work out the total for a week. </p>
<p>Could anyone help?</p>
|
[
{
"answer_id": 273611,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "Answer=DSum(\"NameOfField\",\"NameOfTable\", _\n \"SomeDate Between #2008/1/20# And #2008/1/27#\")\n Answer=DSum(\"NameOfField\",\"NameOfTable\",\"SomeDate Between #\"\n & date()-weekday(date())+1 & \"# And #\" & date()-weekday(date())+7 & \"#\")\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,485
|
<p>Seems likes it might be useful to have the assert display a message when an assertion fails.</p>
<p>Currently an <code>AssertionError</code> gets thrown, can you specify a custom message for it?</p>
<p>Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?</p>
|
[
{
"answer_id": 273488,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "assert x > 0 : \"x must be greater than zero, but x = \" + x;\n"
},
{
"answer_id": 273492,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 4,
"selected": false,
"text": "assert importantVar != null : \"The important var was null!\";\n"
},
{
"answer_id": 273493,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "assert Expression1 : Expression2 ;\n"
},
{
"answer_id": 492499,
"author": "matt burns",
"author_id": 276093,
"author_profile": "https://Stackoverflow.com/users/276093",
"pm_score": 4,
"selected": false,
"text": "assert (condition) : \"some message\";\n assert (y > x): \"y is too small. y = \" + y;\n assert isTrue() ? true : false : \"some message\";\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
273,489
|
<p>I am looking at the pricing of various cloud computing platforms, particularly Amazon's EC2, and a lot of the quotes are based on a unit called an Instance-Hour. </p>
<p>I am trying to get a handle on the exact definition of an instance-hour to better compare the costs of continuing to host a web-application versus putting it out on the cloud. </p>
<p>(1) Does it correspond to any of the Windows performance counters in such a way that I could benchmark our current implmentation and use it in their pricing calculators?</p>
<p>(2) How does a multi-processor instance figure into the instance-hour calculation?</p>
|
[
{
"answer_id": 23718002,
"author": "Mike S",
"author_id": 1941995,
"author_profile": "https://Stackoverflow.com/users/1941995",
"pm_score": 1,
"selected": false,
"text": "--alive"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30018/"
] |
273,508
|
<p>How do I make an activeX control in a C# library project and then reference it in another ASP.NET wet site project?</p>
|
[
{
"answer_id": 273521,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<object...>...</object>"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22769/"
] |
273,516
|
<p>Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out.</p>
<p>Where can one find a good list of swear words in various languages and dialects? </p>
<p>Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters?</p>
<p>What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55?</p>
<p>Bonus points if you offer solutions for PHP. :)</p>
<h2><em>Edit: Response to answers that say simply avoid the programmatic issue:</em></h2>
<p>I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question.</p>
<p>So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)</p>
|
[
{
"answer_id": 273520,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 9,
"selected": true,
"text": "$filterRegex = \"(boogers|snot|poop|shucks|argh)\"\n"
},
{
"answer_id": 273532,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 1,
"selected": false,
"text": "/[\\s]dooby (doo?)[\\s]/i /[\\s]doob(er|ed|est)[\\s]/"
},
{
"answer_id": 7073043,
"author": "andrew",
"author_id": 895890,
"author_profile": "https://Stackoverflow.com/users/895890",
"pm_score": 2,
"selected": false,
"text": "$errors = array(); //Initialize error array (I use this with all my PHP form validations)\n\n$SCREENNAME = mysql_real_escape_string($_POST['SCREENNAME']); //Escape the input data to prevent SQL injection when you query the profanity table.\n\n$ProfanityCheckString = strtoupper($SCREENNAME); //Make the input string uppercase (so that 'BaDwOrD' is the same as 'BADWORD'). All your values in the profanity table will need to be UPPERCASE for this to work.\n\n$ProfanityCheckString = preg_replace('/[_-]/','',$ProfanityCheckString); //I allow alphanumeric, underscores, and dashes...nothing else (I control this with PHP form validation). Pull out non-alphanumeric characters so 'B-A-D-W-O-R-D' shows up as 'BADWORD'.\n\n$ProfanityCheckString = preg_replace('/1/','I',$ProfanityCheckString); //Replace common numeric representations of letters so '84DW0RD' shows up as 'BADWORD'.\n\n$ProfanityCheckString = preg_replace('/3/','E',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/4/','A',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/5/','S',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/6/','G',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/7/','T',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/8/','B',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/0/','O',$ProfanityCheckString); //Replace ZERO's with O's (Capital letter o's).\n\n$ProfanityCheckString = preg_replace('/Z/','S',$ProfanityCheckString); //Replace Z's with S's, another common substitution. Make sure you replace Z's with S's in your profanity database for this to work properly. Same with all the numbers too--having S3X7 in your database won't work, since this code would render that string as 'SEXY'. The profanity table should have the \"rendered\" version of the bad words.\n\n$CheckProfanity = mysql_query(\"SELECT * FROM DATABASE.TABLE p WHERE p.WORD = '\".$ProfanityCheckString.\"'\");\nif(mysql_num_rows($CheckProfanity) > 0) {$errors[] = 'Please select another Screen Name.';} //Check your profanity table for the scrubbed input. You could get real crazy using LIKE and wildcards, but I only want a simple profanity filter.\n\nif (count($errors) > 0) {foreach($errors as $error) {$errorString .= \"<span class='PHPError'>$error</span><br /><br />\";} echo $errorString;} //Echo any PHP errors that come out of the validation, including any profanity flagging.\n\n\n//You can also use these lines to troubleshoot.\n//echo $ProfanityCheckString;\n//echo \"<br />\";\n//echo mysql_error();\n//echo \"<br />\";\n"
},
{
"answer_id": 13115492,
"author": "Chase Florell",
"author_id": 124069,
"author_profile": "https://Stackoverflow.com/users/124069",
"pm_score": 2,
"selected": false,
"text": "<div id=\"foo\">\n ass will fail but password will not\n</div>\n\n<script>\n // code:\n $('#foo').profanityFilter({\n customSwears: ['ass']\n });\n</script>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27899/"
] |
273,530
|
<p>Does anybody have a suggestion for a java library that performs automatic cropping and deskewing of images (like those retrieved from a flatbed scanner)?</p>
|
[
{
"answer_id": 36248013,
"author": "delkant",
"author_id": 1250805,
"author_profile": "https://Stackoverflow.com/users/1250805",
"pm_score": 3,
"selected": false,
"text": "public void testDoOCR_SkewedImage() throws Exception {\n logger.info(\"doOCR on a skewed PNG image\");\n File imageFile = new File(this.testResourcesDataPath, \"eurotext_deskew.png\");\n BufferedImage bi = ImageIO.read(imageFile);\n ImageDeskew id = new ImageDeskew(bi);\n double imageSkewAngle = id.getSkewAngle(); // determine skew angle\n if ((imageSkewAngle > MINIMUM_DESKEW_THRESHOLD || imageSkewAngle < -(MINIMUM_DESKEW_THRESHOLD))) {\n bi = ImageHelper.rotateImage(bi, -imageSkewAngle); // deskew image\n }\n\n String expResult = \"The (quick) [brown] {fox} jumps!\\nOver the $43,456.78 <lazy> #90 dog\";\n String result = instance.doOCR(bi);\n logger.info(result);\n assertEquals(expResult, result.substring(0, expResult.length()));\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25939/"
] |
273,534
|
<p>Hey all, I need some advice on this...</p>
<p>We have certain permissions setup in the database for certain levels of control a user can have over the application. Disabled, ReadOnly and Edit. </p>
<p>My question is: Are there more generic/better ways to handle permissions applied to a form element on the page than writing a security method/check per page to enable/disable/hide/show proper controls depending on the permissions allowed?</p>
<p>Anyone have any experience handling this in different ways?</p>
<p>Edit:</p>
<p>I just thought about the possibility of adding constants for each layer that needs security and then adding an IsAuthorized function in the user class that would accept a constant from the form that the control is on, and return boolean to enable/disable controls, this would really reduce the amount of places I'd have to hit when/if I ever need to modify the security for all forms.</p>
<p>Cheers!</p>
|
[
{
"answer_id": 1743792,
"author": "Julian Bromwich",
"author_id": 212262,
"author_profile": "https://Stackoverflow.com/users/212262",
"pm_score": 1,
"selected": false,
"text": "/** NO permissions.\n * Presentation: \"hidden\"\n * Database: \"no access\"\n */\nNONE(0),\n\n/** VIEW permissions.\n * Presentation: \"read-only\"\n * Database: \"read access\"\n */\nVIEW(1),\n\n/** VIEW and POPULATE permissions.\n * Presentation: \"required/highlighted\"\n * Database: \"non-null\"\n */\nREQUIRED(2),\n\n/** VIEW, POPULATE, and DEPOPULATE permissions.\n * Presentation: \"editable\"\n * Database: \"nullable\"\n */\nEDIT(3);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14045/"
] |
273,546
|
<p>I'm trying to get a user control working asynchronously, yet no matter what I do it continues to work synchronously. I've stripped it down to its bare minimum as a test web application. This would be the user control:</p>
<pre><code><%@ Control Language="C#" %>
<script runat="server">
SqlConnection m_oConnection;
SqlCommand m_oCommand;
void Page_Load(object sender, EventArgs e)
{
Trace.Warn("Page_Load");
string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true";
string strSQL = "waitfor delay '00:00:10'; select * from MyTable";
m_oConnection = new SqlConnection(strDSN);
m_oCommand = new SqlCommand(strSQL, m_oConnection);
m_oConnection.Open();
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true));
Page.ExecuteRegisteredAsyncTasks();
}
IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state)
{
Trace.Warn("BeginHandler");
return m_oCommand.BeginExecuteReader(cb, state);
}
void EndHandler(IAsyncResult ar)
{
Trace.Warn("EndHandler");
GridView1.DataSource = m_oCommand.EndExecuteReader(ar);
GridView1.DataBind();
m_oConnection.Close();
}
void TimeoutHandler(IAsyncResult ar)
{
Trace.Warn("TimeoutHandler");
}
</script>
<asp:gridview id="GridView1" runat="server" />
</code></pre>
<p>And this would be the page in which I host the control three times:</p>
<pre><code><%@ page language="C#" trace="true" async="true" asynctimeout="60" %>
<%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %>
<html>
<body>
<form id="form1" runat="server">
<uc:mycontrol id="MyControl1" runat="server" />
<uc:mycontrol id="MyControl2" runat="server" />
<uc:mycontrol id="MyControl3" runat="server" />
</form>
</body>
</html>
</code></pre>
<p>The page gets displayed without errors, but the trace at the bottom of the page shows each control instance is processed synchronously. What am I doing wrong? Is there a configuration setting somewhere I'm missing?</p>
|
[
{
"answer_id": 273717,
"author": "Charles",
"author_id": 24898,
"author_profile": "https://Stackoverflow.com/users/24898",
"pm_score": 4,
"selected": true,
"text": "Page.ExecuteRegisteredAsyncTasks Page.RegisterAsyncTask RegistereAsyncTask <%@ Control Language=\"C#\" %>\n<script runat=\"server\">\n SqlConnection m_oConnection;\n SqlCommand m_oCommand;\n\n void Page_Load(object sender, EventArgs e)\n {\n Trace.Warn(ID, \"Page_Load - \" + Thread.CurrentThread.GetHashCode().ToString());\n string strDSN = ConfigurationManager.ConnectionStrings[\"DSN\"].ConnectionString + \";async=true\";\n string strSQL = \"waitfor delay '00:00:10'; select * from TEProcessedPerDay where Date > dateadd(day, -90, getutcdate()) order by Date asc\";\n\n m_oConnection = new SqlConnection(strDSN);\n m_oCommand = new SqlCommand(strSQL, m_oConnection);\n m_oConnection.Open();\n\n Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true));\n }\n\n IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state)\n {\n Trace.Warn(ID, \"BeginHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n return m_oCommand.BeginExecuteReader(cb, state);\n }\n\n void EndHandler(IAsyncResult ar)\n {\n Trace.Warn(ID, \"EndHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n GridView1.DataSource = m_oCommand.EndExecuteReader(ar);\n GridView1.DataBind();\n m_oConnection.Close();\n }\n\n void TimeoutHandler(IAsyncResult ar)\n {\n Trace.Warn(ID, \"TimeoutHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n }\n</script>\n<asp:gridview id=\"GridView1\" runat=\"server\" />\n <%@ page language=\"C#\" async=\"true\" trace=\"true\" %>\n<%@ register tagprefix=\"uc\" tagname=\"mycontrol\" src=\"~/MyControl.ascx\" %>\n<html>\n <body>\n <form id=\"form1\" runat=\"server\">\n <uc:mycontrol id=\"MyControl1\" runat=\"server\" />\n <uc:mycontrol id=\"MyControl2\" runat=\"server\" />\n <uc:mycontrol id=\"MyControl3\" runat=\"server\" />\n </form>\n </body>\n</html>\n"
},
{
"answer_id": 5229916,
"author": "Nandun",
"author_id": 649470,
"author_profile": "https://Stackoverflow.com/users/649470",
"pm_score": 1,
"selected": false,
"text": "ExecuteRegisteredAsyncTassk OnPrerender ExecuteRegisteredAsyncTasks ExecuteRegisteredAsyncTasks"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24898/"
] |
273,567
|
<p>Every Christmas we draw names for gift exchanges in my family. This usually involves mulitple redraws until no one has pulled their spouse. So this year I coded up my own name drawing app that takes in a bunch of names, a bunch of disallowed pairings, and sends off an email to everyone with their chosen giftee.</p>
<p>Right now, the algorithm works like this (in pseudocode):</p>
<pre><code>function DrawNames(list allPeople, map disallowedPairs) returns map
// Make a list of potential candidates
foreach person in allPeople
person.potentialGiftees = People
person.potentialGiftees.Remove(person)
foreach pair in disallowedPairs
if pair.first = person
person.Remove(pair.second)
// Loop through everyone and draw names
while allPeople.count > 0
currentPerson = allPeople.findPersonWithLeastPotentialGiftees
giftee = pickRandomPersonFrom(currentPerson.potentialGiftees)
matches[currentPerson] = giftee
allPeople.Remove(currentPerson)
foreach person in allPeople
person.RemoveIfExists(giftee)
return matches
</code></pre>
<p>Does anyone who knows more about graph theory know some kind of algorithm that would work better here? For my purposes, this works, but I'm curious.</p>
<p>EDIT: Since the emails went out a while ago, and I'm just hoping to learn something I'll rephrase this as a graph theory question. I'm not so interested in the special cases where the exclusions are all pairs (as in spouses not getting each other). I'm more interested in the cases where there are enough exclusions that finding any solution becomes the hard part. My algorithm above is just a simple greedy algorithm that I'm not sure would succeed in all cases.</p>
<p>Starting with a complete directed graph and a list of vertex pairs. For each vertex pair, remove the edge from the first vertex to the second.</p>
<p>The goal is to get a graph where each vertex has one edge coming in, and one edge leaving.</p>
|
[
{
"answer_id": 303476,
"author": "wxs",
"author_id": 12981,
"author_profile": "https://Stackoverflow.com/users/12981",
"pm_score": 3,
"selected": false,
"text": "import random\nfrom collections import deque\ndef pairup(people):\n \"\"\" Given a list of people, assign each one a secret santa partner\n from the list and return the pairings as a dict. Implemented to always\n create a perfect cycle\"\"\"\n random.shuffle(people)\n partners = deque(people)\n partners.rotate()\n return dict(zip(people,partners))\n"
},
{
"answer_id": 12839952,
"author": "suizo",
"author_id": 836948,
"author_profile": "https://Stackoverflow.com/users/836948",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n ArrayList<String> donor = new ArrayList<String>();\n donor.add(\"Micha\");\n donor.add(\"Christoph\");\n donor.add(\"Benj\");\n donor.add(\"Andi\");\n donor.add(\"Test\");\n ArrayList<String> receiver = (ArrayList<String>) donor.clone();\n\n Collections.shuffle(donor);\n for (int i = 0; i < donor.size(); i++) {\n Collections.shuffle(receiver);\n int target = 0;\n if(receiver.get(target).equals(donor.get(i))){ \n target++;\n } \n System.out.println(donor.get(i) + \" => \" + receiver.get(target));\n receiver.remove(receiver.get(target));\n }\n}\n"
},
{
"answer_id": 47478187,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "(person, tags) example_sequence= [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n]\n import random, collections\n\nclass Statistics(object):\n def __init__(self):\n self.tags = collections.defaultdict(int)\n\n def account(self, tags):\n for tag in tags:\n self.tags[tag] += 1\n\n def tags_value(self, tags):\n return sum(1./self.tags[tag] for tag in tags)\n\n def most_disjoined(self, tags, groups):\n return max(\n groups.items(),\n key=lambda kv: (\n -self.tags_value(kv[0] & tags),\n len(kv[1]),\n self.tags_value(tags - kv[0]) - self.tags_value(kv[0] - tags),\n )\n )\n\ndef secret_santa(people_and_their_tags):\n \"\"\"Secret santa algorithm.\n\n The lottery function expects a sequence of:\n (name, tags)\n\n For example:\n\n [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n ]\n\n husband1 is married to wife1 as seen by the common marriage1 tag\n person1, person3 and wife1 work at the same company.\n …\n\n The algorithm will try to match people with the least common characteristics\n between them, to maximize entrop— ehm, mingling!\n\n Have fun.\"\"\"\n\n # let's split the persons into groups\n\n groups = collections.defaultdict(list)\n stats = Statistics()\n\n for person, tags in people_and_their_tags:\n tags = frozenset(tag.lower() for tag in tags)\n stats.account(tags)\n person= \"%s [%s]\" % (person, \",\".join(tags))\n groups[tags].append(person)\n\n # shuffle all lists\n for group in groups.values():\n random.shuffle(group)\n\n output_chain = []\n prev_tags = frozenset()\n while 1:\n next_tags, next_group = stats.most_disjoined(prev_tags, groups)\n output_chain.append(next_group.pop())\n if not next_group: # it just got empty\n del groups[next_tags]\n if not groups: break\n prev_tags = next_tags\n\n return output_chain\n\nif __name__ == \"__main__\":\n example_sequence = [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n ]\n print(\"suggested chain (each person gives present to next person)\")\n import pprint\n pprint.pprint(secret_santa(example_sequence))\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
273,578
|
<p><a href="https://web.archive.org/web/20210126032647/http://geekswithblogs.net/michelotti/archive/2007/12/17/117791.aspx" rel="nofollow noreferrer">Link</a></p>
<p>I'm using ASP.NET with C# and trying to use linq to sql to update a data context as exhibited on the blog linked above. I created the timestamp field in the table just as stated and am using the following method:</p>
<pre><code>private void updateRecord(TableName updatedRecord)
{
context db = new context();
db.TableName.Attach(updatedRecord,true);
db.SubmitChanges();
}
</code></pre>
<p>My question is, are you supposed to assign the timeStamp field to anything in your updatedRecord before trying to call the Attach method on your data context?</p>
<p>When I run this code I get the following exception: <code>System.Data.Linq.ChangeConflictException: Row not found or changed. </code> I update all of the fields, including the primary key of the record that I'm updating before passing the object to this update method. During debugging the TimeStamp attribute of the object shows as null. I'm not sure if it's supposed to be that way or not.</p>
<p>Every book and resource I have says that this is the way to do it, but none of them go into great detail about this TimeStamp attribute.</p>
<p>I know this is quick and easy, so if anybody knows, please let me know.</p>
|
[
{
"answer_id": 273740,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "AutoGenerated = true\nAuto-Sync = Always\nTime Stamp = True\nUpdate Check = Never\n rowversion NOT NULL UpdateCheck Never"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35617/"
] |
273,606
|
<p>I am designing a WCF service which a client will call to get a list of GUID's from a server.</p>
<p>How should I define my endpoint contract?</p>
<p>Should I just return an Array? </p>
<p>If so, will the array just be serialized by WCF?</p>
|
[
{
"answer_id": 273616,
"author": "Adron",
"author_id": 29345,
"author_profile": "https://Stackoverflow.com/users/29345",
"pm_score": 2,
"selected": false,
"text": "[DataMember] List<Guid> SomeGuidsGoInHere {get;set;}\n [DataMember] List<String> SomeGuidsAsStringsGoInHere {get;set;}\n"
},
{
"answer_id": 1354324,
"author": "Blue Toque",
"author_id": 116268,
"author_profile": "https://Stackoverflow.com/users/116268",
"pm_score": 0,
"selected": false,
"text": "<s:simpleType name=\"guid\">\n <s:restriction base=\"s:string\">\n <s:pattern value=\"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\" />\n </s:restriction>\n</s:simpleType>\n <s:element name=\"GetToken\">\n <s:complexType>\n <s:sequence>\n <s:element minOccurs=\"1\" maxOccurs=\"1\" name=\"objUserGUID\" type=\"s1:guid\" />\n <s:element minOccurs=\"0\" maxOccurs=\"1\" name=\"strPassword\" type=\"s:string\" />\n </s:sequence>\n </s:complexType>\n</s:element>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,612
|
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p>
<p>"loop again? y/n"</p>
|
[
{
"answer_id": 273618,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 5,
"selected": true,
"text": "while True:\n func()\n answer = raw_input( \"Loop again? \" )\n if answer != 'y':\n break\n"
},
{
"answer_id": 273620,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 3,
"selected": false,
"text": "keepLooping = True\nwhile keepLooping:\n # do stuff here\n\n # Prompt the user to continue\n q = raw_input(\"Keep looping? [yn]: \")\n if not q.startswith(\"y\"):\n keepLooping = False\n"
},
{
"answer_id": 273677,
"author": "Jason L",
"author_id": 35616,
"author_profile": "https://Stackoverflow.com/users/35616",
"pm_score": 3,
"selected": false,
"text": "while True:\n do_stuff() # and eventually...\n break; # break out of the loop\n x = True\nwhile x:\n do_stuff() # and eventually...\n x = False # set x to False to break the loop\n break"
},
{
"answer_id": 321040,
"author": "J.T. Hurley",
"author_id": 39851,
"author_profile": "https://Stackoverflow.com/users/39851",
"pm_score": 1,
"selected": false,
"text": "While raw_input(\"loop again? y/n \") != 'n':\n do_stuff()\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
273,623
|
<p>I have a list of numbers, say {2,4,5,6,7}
I have a table, foos, with foos.ID, including say, {1,2,3,4,8,9}</p>
<p>Id like to take my list of numbers, and find those without a counterpart in the ID field of my table.</p>
<p>One way to achieve this would be to create a table bars, loaded with {2,4,5,6,7} in the ID field.
Then, I would do </p>
<pre>
SELECT bars.* FROM bars LEFT JOIN foos ON bars.ID = foos.ID WHERE foos.ID IS NULL
</pre>
<p>However, I'd like to accomplish this sans temp table. </p>
<p>Anyone have any input on how it might happen?</p>
|
[
{
"answer_id": 273649,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": false,
"text": "SELECT bars.* FROM bars WHERE bars.ID NOT IN (SELECT ID FROM foos)\n SELECT * FROM foos WHERE foos.ID NOT IN (2, 4, 5, 6, 7)\n"
},
{
"answer_id": 273703,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": false,
"text": "SELECT n.id\nFROM\n (SELECT 2 AS id \n UNION SELECT 3 \n UNION SELECT 4 \n UNION SELECT 5 \n UNION SELECT 6 \n UNION SELECT 7) AS n\n LEFT OUTER JOIN foos USING (id)\nWHERE foos.id IS NULL;\n UNION CREATE TABLE num (i int);\nINSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);\n\nSELECT n.id\nFROM \n (SELECT n1.i + n10.i*10 AS id\n FROM num AS n1 CROSS JOIN num AS n10\n WHERE n1.i + n10.i*10 IN (2, 3, 4, 5, 6, 7)) AS n\n LEFT OUTER JOIN foos USING (id)\nWHERE foos.id IS NULL;\n num UNION"
},
{
"answer_id": 2683561,
"author": "Daniel",
"author_id": 322357,
"author_profile": "https://Stackoverflow.com/users/322357",
"pm_score": 1,
"selected": false,
"text": "select count(*) from node where nid > 1962 select n2.nid from node n1 right join node n2 on n1.nid = (n2.nid - 1) where n1.nid is null and n2.nid > 1962"
},
{
"answer_id": 5891079,
"author": "Alex Matulich",
"author_id": 582329,
"author_profile": "https://Stackoverflow.com/users/582329",
"pm_score": 3,
"selected": false,
"text": "SELECT ID FROM foos WHERE foos.ID IN (2, 4, 5, 6, 7)\n $no_counterparts = array_diff($list, $result);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26001/"
] |
273,624
|
<p>How do you create a 1 bit per pixel mask from an image using GDI in C#? The image I am trying to create the mask from is held in a System.Drawing.Graphics object.</p>
<p>I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like <a href="http://www.vbaccelerator.com/home/VB/Tips/Mask_Images/article.asp" rel="nofollow noreferrer">this</a>. I just can't get it to work in C#, any help is much appreciated.</p>
|
[
{
"answer_id": 273686,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 3,
"selected": false,
"text": "using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Runtime.InteropServices;\n public static Bitmap BitmapTo1Bpp(Bitmap img) {\n int w = img.Width;\n int h = img.Height;\n Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);\n BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);\n for (int y = 0; y < h; y++) {\n byte[] scan = new byte[(w + 7) / 8];\n for (int x = 0; x < w; x++) {\n Color c = img.GetPixel(x, y);\n if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));\n }\n Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);\n }\n bmp.UnlockBits(data);\n return bmp;\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24201/"
] |
273,630
|
<p>Actually my question is all in the title.<br>
Anyway:<br>
I have a class and I use explicit constructor:
<br>.h<br></p>
<pre><code>class MyClass
{
public:
explicit MyClass(const string& s): query(s) {}
private:
string query;
}
</code></pre>
<p>Is it obligatory or not to put <b>explicit</b> keyword in implementation(.cpp) file?</p>
|
[
{
"answer_id": 273633,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "explicit test.cpp:6: error: only declarations of constructors can be 'explicit'\n class foo {\npublic:\n explicit foo(int);\n};\n\nexplicit foo::foo(int) {}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
273,639
|
<p>I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.</p>
<p>I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.</p>
<p>Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.</p>
<p><strong>MORE INFORMATION:</strong> I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?</p>
<p>I'm going to pull my hair out! This can't be that hard!</p>
<p><strong>SOLUTION</strong>: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:</p>
<pre><code> Public Sub New()
If My.Application.OpenForms(0).Equals(Me) Then
Me.IsFirstForm = True
End If
End Sub
</code></pre>
<p>Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):</p>
<pre><code> Public Sub EventHandler()
If Not IsFirstForm Then
Dim f As Form1 = My.Application.OpenForms(0)
f.EventHandler()
Me.Close()
ElseIf InvokeRequired Then
Me.Invoke(New HandlerDelegate(AddressOf EventHandler))
Else
' Do your event handling code '
End If
End Sub
</code></pre>
<p>First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!</p>
<p>Again, thanks for all the help - this was going to drive me nuts!</p>
|
[
{
"answer_id": 273653,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 3,
"selected": true,
"text": " Dim main As Form1 = CType(Application.OpenForms(0), Form1)\n if (main.InvokeRequired)\n ' etc...\n"
},
{
"answer_id": 335769,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 0,
"selected": false,
"text": "private EventHandler StatusHandler = new EventHandler(eventHandlerCode)\nvoid eventHandlerCode(object sender, EventArgs e)\n {\n if (this.InvokeRequired)\n {\n this.Invoke(StatusHandler, sender, e);\n }\n else\n {\n //do work\n }\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114/"
] |
273,641
|
<p>This question has been discussed in two blog posts (<a href="http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/</a>, <a href="http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/</a>), but I haven't heard a definitive answer yet. If we have one thread that does this:</p>
<pre><code>public class HeartBeatThread extends Thread {
public static int counter = 0;
public static volatile int cacheFlush = 0;
public HeartBeatThread() {
setDaemon(true);
}
static {
new HeartBeatThread().start();
}
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
counter++;
cacheFlush++;
}
}
}
</code></pre>
<p>And many clients that run the following:</p>
<pre><code>if (counter == HeartBeatThread.counter) return;
counter = HeartBeatThread.cacheFlush;
</code></pre>
<p>is it threadsafe or not?</p>
|
[
{
"answer_id": 273690,
"author": "jiriki",
"author_id": 19907,
"author_profile": "https://Stackoverflow.com/users/19907",
"pm_score": 1,
"selected": false,
"text": "if (counter == HeartBeatThread.counter) \n return;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20022/"
] |
273,662
|
<p>With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view.</p>
<p>So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that. Bob might have several revision control clients/views/workspaces he works with so he could have /bob1, /bob2, /bob3, etc.</p>
<p>The install location is specified in the build.properties file. Is there a way to avoid checking that file out and changing it for each specific user and revision control view?</p>
<p>Can "ant install" take arguments or be configured to consider environment variables for the install target?</p>
|
[
{
"answer_id": 275622,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 2,
"selected": false,
"text": "ant -Dinstall.location=/bob1 install\n"
},
{
"answer_id": 275794,
"author": "SAL9000",
"author_id": 11609,
"author_profile": "https://Stackoverflow.com/users/11609",
"pm_score": 0,
"selected": false,
"text": "<property file=\"default.properties\" />\n"
},
{
"answer_id": 294776,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 4,
"selected": true,
"text": "<property file=\"local.properties\" />\n<property file=\"default.properties\" />\n"
},
{
"answer_id": 7097507,
"author": "Dooze",
"author_id": 899223,
"author_profile": "https://Stackoverflow.com/users/899223",
"pm_score": 1,
"selected": false,
"text": "<property environment=\"env\" />\n <fileset dir=\"${env.BEA_HOME}/wlserver_10.0/server/lib\">\n <include name=\"api.jar\" />\n</fileset>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22917/"
] |
273,664
|
<p>I find AWK really useful. Here is a one liner I put together to manipulate data.</p>
<pre><code>ls | awk '{ print "awk " "'"'"'" " {print $1,$2,$3} " "'"'"'" " " $1 ".old_ext > " $1 ".new_ext" }' > file.csh
</code></pre>
<p>I used this AWK to make a script file that would rename some files and only print out selective columns. Anyone know a better way to do this? What are you best AWK one liners or clever manipulations?</p>
|
[
{
"answer_id": 273737,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 1,
"selected": false,
"text": "ls -1 *.mp3 | awk '{printf(\"mv %s newDir/%s\\n\",$1,$1)}' | /bin/sh\n ps -ef | grep -v username | awk '{printf(\"kill -9 %s\\n\",$2)}' | /bin/sh\n"
},
{
"answer_id": 274539,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/other/old/bin)\n : \"@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $\"\n#\n# Print minimal version of $PATH, possibly removing some items\n\ncase $# in\n0) chop=\"\"; path=${PATH:?};;\n1) chop=\"\"; path=$1;;\n2) chop=$2; path=$1;;\n*) echo \"Usage: `basename $0 .sh` [$PATH [remove:list]]\" >&2\n exit 1;;\nesac\n\n# Beware of the quotes in the assignment to chop!\necho \"$path\" |\n${AWK:-awk} -F: '#\nBEGIN { # Sort out which path components to omit\n chop=\"'\"$chop\"'\";\n if (chop != \"\") nr = split(chop, remove); else nr = 0;\n for (i = 1; i <= nr; i++)\n omit[remove[i]] = 1;\n }\n{\n for (i = 1; i <= NF; i++)\n {\n x=$i;\n if (x == \"\") x = \".\";\n if (omit[x] == 0 && path[x]++ == 0)\n {\n output = output pad x;\n pad = \":\";\n }\n }\n print output;\n}'\n"
},
{
"answer_id": 424776,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "df -m | awk '{p+=$3}; END {print p}'\n"
},
{
"answer_id": 433035,
"author": "PEZ",
"author_id": 44639,
"author_profile": "https://Stackoverflow.com/users/44639",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/awk -f\nBEGIN {\n lines=10\n}\n\n{\n high = NR % lines + 1\n a[high] = $0\n}\n\nEND {\n for (i = 0; i < lines; i++) {\n n = (i + high) % lines + 1\n if (n in a) {\n print a[n]\n }\n }\n}\n"
},
{
"answer_id": 1597829,
"author": "Jim",
"author_id": 118850,
"author_profile": "https://Stackoverflow.com/users/118850",
"pm_score": 0,
"selected": false,
"text": "ps -ylC httpd | awk '/[0-9]/ {SUM += $8} END {print SUM/1024}'\n"
},
{
"answer_id": 11468566,
"author": "Juan Diego Godoy Robles",
"author_id": 1200821,
"author_profile": "https://Stackoverflow.com/users/1200821",
"pm_score": 0,
"selected": false,
"text": "find . -type d -print 2>/dev/null|awk '{for (i=1;i< NF;i++)printf(\"%\"length($i)\"s\",\"|\");gsub(/[^\\/]*\\//,\"--\",$0);print $NF}' FS='/'\n"
},
{
"answer_id": 14119098,
"author": "Juan Diego Godoy Robles",
"author_id": 1200821,
"author_profile": "https://Stackoverflow.com/users/1200821",
"pm_score": 0,
"selected": false,
"text": "awk '/END/{flag=0}flag;/START/{flag=1}' inputFile\n"
},
{
"answer_id": 31574445,
"author": "Andrew",
"author_id": 2708215,
"author_profile": "https://Stackoverflow.com/users/2708215",
"pm_score": 0,
"selected": false,
"text": "NR == 1 {\n for (i = 1 ; i <= NF ; i++)\n {\n print i \"\\t\" $i\n }\n }\nNR > 1 {\n exit\n }\n 1 64.242.88.10\n2 -\n3 -\n4 [07/Mar/2004:16:05:49\n5 -0800]\n6 \"GET\n7 /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables\n8 HTTP/1.1\"\n9 401\n10 12846\n NR == 1 {\n for (i = 1 ; i <= NF ; i++)\n {\n field[$i] = i\n }\n }\n metric,time,val,location,http_status,http_request val NR > 1 {\n SUM += $field[\"val\"]\n }\n"
},
{
"answer_id": 38797072,
"author": "Zlemini ",
"author_id": 6684013,
"author_profile": "https://Stackoverflow.com/users/6684013",
"pm_score": 0,
"selected": false,
"text": "awk '{print $1,$3}' file\n awk '{$1=$3=\"\"}1' file\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30181/"
] |
273,668
|
<p>I'm working on a Java based project that has a client program which needs to connect to a MySQL database on a remote server. This was implemented is as follows:</p>
<p>Use JDBC to write the SQL queries to be executed which are then hosted as a servlet using Apache Tomcat and made accessible via XML-RPC. The client code uses XML-RPC to remotely execute these JDBC based functions. This allows us to keep our MySQL database non-public, restricts use to the pre-defined functions, and allows Tomcat to manage the database transactions (which I've been told is better than letting MySQL do it alone, but I really don't understand why). However, this approach requires a lot of boiler-plate code, and Tomcat is a huge memory hog on our server.</p>
<p>I'm looking for a better way to do this. One way I'm considering is to make the MySQL database publicly accessible, re-writing the JDBC based code as stored procedures, and restricting public use to these procedures only. The problem I see with this are that translating all the JDBC code to stored procedures will be difficult and time consuming. I'm also not too familiar with MySQL's permissions. Can one grant access to a stored procedure which performs select statements on a table, but also deny arbitrary select statements on that same table?</p>
<p>Any other ideas are welcome, as are thoughts and or sugguestions on the stored procedure solution.</p>
<p>Thank you! </p>
|
[
{
"answer_id": 273737,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 1,
"selected": false,
"text": "ls -1 *.mp3 | awk '{printf(\"mv %s newDir/%s\\n\",$1,$1)}' | /bin/sh\n ps -ef | grep -v username | awk '{printf(\"kill -9 %s\\n\",$2)}' | /bin/sh\n"
},
{
"answer_id": 274539,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/other/old/bin)\n : \"@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $\"\n#\n# Print minimal version of $PATH, possibly removing some items\n\ncase $# in\n0) chop=\"\"; path=${PATH:?};;\n1) chop=\"\"; path=$1;;\n2) chop=$2; path=$1;;\n*) echo \"Usage: `basename $0 .sh` [$PATH [remove:list]]\" >&2\n exit 1;;\nesac\n\n# Beware of the quotes in the assignment to chop!\necho \"$path\" |\n${AWK:-awk} -F: '#\nBEGIN { # Sort out which path components to omit\n chop=\"'\"$chop\"'\";\n if (chop != \"\") nr = split(chop, remove); else nr = 0;\n for (i = 1; i <= nr; i++)\n omit[remove[i]] = 1;\n }\n{\n for (i = 1; i <= NF; i++)\n {\n x=$i;\n if (x == \"\") x = \".\";\n if (omit[x] == 0 && path[x]++ == 0)\n {\n output = output pad x;\n pad = \":\";\n }\n }\n print output;\n}'\n"
},
{
"answer_id": 424776,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "df -m | awk '{p+=$3}; END {print p}'\n"
},
{
"answer_id": 433035,
"author": "PEZ",
"author_id": 44639,
"author_profile": "https://Stackoverflow.com/users/44639",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/awk -f\nBEGIN {\n lines=10\n}\n\n{\n high = NR % lines + 1\n a[high] = $0\n}\n\nEND {\n for (i = 0; i < lines; i++) {\n n = (i + high) % lines + 1\n if (n in a) {\n print a[n]\n }\n }\n}\n"
},
{
"answer_id": 1597829,
"author": "Jim",
"author_id": 118850,
"author_profile": "https://Stackoverflow.com/users/118850",
"pm_score": 0,
"selected": false,
"text": "ps -ylC httpd | awk '/[0-9]/ {SUM += $8} END {print SUM/1024}'\n"
},
{
"answer_id": 11468566,
"author": "Juan Diego Godoy Robles",
"author_id": 1200821,
"author_profile": "https://Stackoverflow.com/users/1200821",
"pm_score": 0,
"selected": false,
"text": "find . -type d -print 2>/dev/null|awk '{for (i=1;i< NF;i++)printf(\"%\"length($i)\"s\",\"|\");gsub(/[^\\/]*\\//,\"--\",$0);print $NF}' FS='/'\n"
},
{
"answer_id": 14119098,
"author": "Juan Diego Godoy Robles",
"author_id": 1200821,
"author_profile": "https://Stackoverflow.com/users/1200821",
"pm_score": 0,
"selected": false,
"text": "awk '/END/{flag=0}flag;/START/{flag=1}' inputFile\n"
},
{
"answer_id": 31574445,
"author": "Andrew",
"author_id": 2708215,
"author_profile": "https://Stackoverflow.com/users/2708215",
"pm_score": 0,
"selected": false,
"text": "NR == 1 {\n for (i = 1 ; i <= NF ; i++)\n {\n print i \"\\t\" $i\n }\n }\nNR > 1 {\n exit\n }\n 1 64.242.88.10\n2 -\n3 -\n4 [07/Mar/2004:16:05:49\n5 -0800]\n6 \"GET\n7 /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables\n8 HTTP/1.1\"\n9 401\n10 12846\n NR == 1 {\n for (i = 1 ; i <= NF ; i++)\n {\n field[$i] = i\n }\n }\n metric,time,val,location,http_status,http_request val NR > 1 {\n SUM += $field[\"val\"]\n }\n"
},
{
"answer_id": 38797072,
"author": "Zlemini ",
"author_id": 6684013,
"author_profile": "https://Stackoverflow.com/users/6684013",
"pm_score": 0,
"selected": false,
"text": "awk '{print $1,$3}' file\n awk '{$1=$3=\"\"}1' file\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,671
|
<p>In an attempt to hide the Safari UI components for an web-app bookmarked as a Homescreen Icon. I am using this meta tag </p>
<pre><code><meta name="apple-mobile-web-app-capable" content="yes" />
</code></pre>
<p>as specified on <a href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW2" rel="nofollow noreferrer">iPhone Dev Center</a> but the address bar and toolbar are still there when launched from the home screen icon. What do I need to do different? Does anyone have an example?</p>
|
[
{
"answer_id": 2002558,
"author": "Benoit",
"author_id": 222769,
"author_profile": "https://Stackoverflow.com/users/222769",
"pm_score": 3,
"selected": false,
"text": "<meta name=\"apple-touch-fullscreen\" content=\"yes\" />\n"
},
{
"answer_id": 3049787,
"author": "mbxtr",
"author_id": 205815,
"author_profile": "https://Stackoverflow.com/users/205815",
"pm_score": 2,
"selected": false,
"text": "window.top.scrollTo(0, 1);\n"
},
{
"answer_id": 3286565,
"author": "Steve Jorgensen",
"author_id": 396373,
"author_profile": "https://Stackoverflow.com/users/396373",
"pm_score": 5,
"selected": false,
"text": "window.top.scrollTo(0, 1);\n <meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n <meta name=\"viewport\" \n content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" />\n"
},
{
"answer_id": 12193324,
"author": "Pierre",
"author_id": 1635519,
"author_profile": "https://Stackoverflow.com/users/1635519",
"pm_score": 1,
"selected": false,
"text": "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n<meta name=\"viewport\" content=\"width=device-width; user-scalable=0;\">\n<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\">\n<link rel=\"apple-touch-icon\" href=\"icon.png\">\n"
},
{
"answer_id": 12392872,
"author": "Samuel Lindblom",
"author_id": 407397,
"author_profile": "https://Stackoverflow.com/users/407397",
"pm_score": 0,
"selected": false,
"text": "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n"
},
{
"answer_id": 15271110,
"author": "Charles Ingalls",
"author_id": 1874138,
"author_profile": "https://Stackoverflow.com/users/1874138",
"pm_score": 0,
"selected": false,
"text": "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n"
},
{
"answer_id": 22546030,
"author": "B.Asselin",
"author_id": 418229,
"author_profile": "https://Stackoverflow.com/users/418229",
"pm_score": 0,
"selected": false,
"text": "minimal-ui <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, minimal-ui\">\n"
},
{
"answer_id": 23705271,
"author": "Cristian Dinu",
"author_id": 2552781,
"author_profile": "https://Stackoverflow.com/users/2552781",
"pm_score": 1,
"selected": false,
"text": "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui\">"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,675
|
<p>From an application I'm building I need to print existing PDFs (created by another app).
How can I do this in C# and provide a mechanism so the user can select a different printer or other properties. </p>
<p>I've looked at the PrintDialog but not sure what file it is attempting to print, if any, b/c the output is always a blank page. Maybe I'm just missing something there.</p>
<p>Do I need to use "iTextSharp" (as suggested else where)? That seems odd to me since I can "send the the file to the printer" I just don't have any nice dialog before hand to set the printer etc. and I don't really want to write a printing dialog from the ground up but it seems like a lot of examples I found by searching did just that.</p>
<p>Any advice, examples or sample code would be great!</p>
<p>Also if PDF is the issue the files could be created by the other app in a diff format such as bitmap or png if that makes things easier.</p>
|
[
{
"answer_id": 273729,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 5,
"selected": false,
"text": "PrinterSettings.InstalledPrinters private void PrintFormPdfData(byte[] formPdfData)\n {\n string tempFile;\n\n tempFile = Path.GetTempFileName();\n\n using (FileStream fs = new FileStream(tempFile, FileMode.Create))\n {\n fs.Write(formPdfData, 0, formPdfData.Length);\n fs.Flush();\n }\n\n try\n {\n string gsArguments;\n string gsLocation;\n ProcessStartInfo gsProcessInfo;\n Process gsProcess;\n\n gsArguments = string.Format(\"-grey -noquery -printer \\\"HP LaserJet 5M\\\" \\\"{0}\\\"\", tempFile);\n gsLocation = @\"C:\\Program Files\\Ghostgum\\gsview\\gsprint.exe\";\n\n gsProcessInfo = new ProcessStartInfo();\n gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;\n gsProcessInfo.FileName = gsLocation;\n gsProcessInfo.Arguments = gsArguments;\n\n gsProcess = Process.Start(gsProcessInfo);\n gsProcess.WaitForExit();\n }\n finally\n {\n File.Delete(tempFile);\n }\n }\n"
},
{
"answer_id": 273822,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "''' <summary>\n''' Start Adobe Process to print document\n''' </summary>\n''' <param name=\"p\"></param>\n''' <remarks></remarks>\nPrivate Function printDoc(ByVal p As PrintObj) As PrintObj\n Dim myProcess As New Process()\n Dim myProcessStartInfo As New ProcessStartInfo(adobePath)\n Dim errMsg As String = String.Empty\n Dim outFile As String = String.Empty\n myProcessStartInfo.UseShellExecute = False\n myProcessStartInfo.RedirectStandardOutput = True\n myProcessStartInfo.RedirectStandardError = True\n\n Try\n\n If canIprintFile(p.sourceFolder & p.sourceFileName) Then\n isAdobeRunning(p)'Make sure Adobe is not running; wait till it's done\n Try\n myProcessStartInfo.Arguments = \" /t \" & \"\"\"\" & p.sourceFolder & p.sourceFileName & \"\"\"\" & \" \" & \"\"\"\" & p.destination & \"\"\"\"\n myProcess.StartInfo = myProcessStartInfo\n myProcess.Start()\n myProcess.CloseMainWindow()\n isAdobeRunning(p)\n myProcess.Dispose()\n Catch ex As Exception\n End Try\n p.result = \"OK\"\n Else\n p.result = \"The file that the Document Printer is tryng to print is missing.\"\n sendMailNotification(\"The file that the Document Printer is tryng to print\" & vbCrLf & _\n \"is missing. The file in question is: \" & vbCrLf & _\n p.sourceFolder & p.sourceFileName, p)\n End If\n Catch ex As Exception\n p.result = ex.Message\n sendMailNotification(ex.Message, p)\n Finally\n myProcess.Dispose()\n End Try\n Return p\nEnd Function\n"
},
{
"answer_id": 11131365,
"author": "Parvej Solkar",
"author_id": 1434525,
"author_profile": "https://Stackoverflow.com/users/1434525",
"pm_score": 1,
"selected": false,
"text": "Process p = new Process();\np.EnableRaisingEvents = true; //Important line of code\np.StartInfo = new ProcessStartInfo()\n{\n CreateNoWindow = true,\n Verb = \"print\",\n FileName = file,\n Arguments = \"/d:\"+printDialog1.PrinterSettings.PrinterName\n}; \ntry\n{\n p.Start();\n} \ncatch \n{ \n /* your fallback code */ \n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,691
|
<p>In the C / Unix environment I work in, I see some developers using <code>__progname</code> instead of <code>argv[0]</code> for usage messages. Is there some advantage to this? What's the difference between <code>__progname</code> and <code>argv[0]</code>. Is it portable?</p>
|
[
{
"answer_id": 273701,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 5,
"selected": true,
"text": "__progname argv[0] __progname argv[0]"
},
{
"answer_id": 273706,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": false,
"text": "__progname argv[] getopt() argv[] strcopy argv[0] progname"
},
{
"answer_id": 3001532,
"author": "Victor Zamanian",
"author_id": 243089,
"author_profile": "https://Stackoverflow.com/users/243089",
"pm_score": 3,
"selected": false,
"text": "program_invocation_short_name program_invocation_name argv[0] program_invocation_name argv[0]"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10888/"
] |
273,695
|
<p>I've been using a local git repository interacting with my group's CVS repository for several months, now. I've made an almost neurotic number of branches, most of which have thankfully merged back into my trunk. But naming is starting to become an issue. If I have a task easily named with a simple label, but I accomplish it in three stages which each include their own branch and merge situation, then I can repeat the branch name each time, but that makes the history a little confusing. If I get more specific in the names, with a separate description for each stage, then the branch names start to get long and unwieldy.</p>
<p>I did learn looking through old threads here that I could start naming branches with a / in the name, i.e., topic/task, or something like that. I may start doing that and seeing if it helps keep things better organized.</p>
<p>What are some best practices for naming git branches?</p>
<p>Edit:
Nobody has actually suggested any naming conventions.
I do delete branches when I'm done with them. I just happen to have several around due to management constantly adjusting my priorities. :)
As an example of why I might need more than one branch on a task, suppose I need to commit the first discrete milestone in the task to the group's CVS repository. At that point, due to my imperfect interaction with CVS, I would perform that commit and then kill that branch. (I've seen too much weirdness interacting with CVS if I try to continue to use the same branch at that point.)</p>
|
[
{
"answer_id": 273760,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "git branch"
},
{
"answer_id": 280157,
"author": "farktronix",
"author_id": 677,
"author_profile": "https://Stackoverflow.com/users/677",
"pm_score": 5,
"selected": false,
"text": "\"ResizeWindow-43523\" --squash"
},
{
"answer_id": 4258654,
"author": "Brian Carlton",
"author_id": 20147,
"author_profile": "https://Stackoverflow.com/users/20147",
"pm_score": 9,
"selected": false,
"text": "master develop rc1.1"
},
{
"answer_id": 6065944,
"author": "Phil Hord",
"author_id": 33342,
"author_profile": "https://Stackoverflow.com/users/33342",
"pm_score": 10,
"selected": false,
"text": "group1/foo\ngroup2/foo\ngroup1/bar\ngroup2/bar\ngroup3/bar\ngroup1/baz\n wip Works in progress; stuff I know won't be finished soon\nfeat Feature I'm adding or expanding\nbug Bug fix or experiment\njunk Throwaway branch created to experiment\n new/frabnotz\nnew/foo\nnew/bar\ntest/foo\ntest/frabnotz\nver/foo\n $ git branch --list \"test/*\"\ntest/foo\ntest/frabnotz\n\n$ git branch --list \"*/foo\"\nnew/foo\ntest/foo\nver/foo\n\n$ gitk --branches=\"*/foo\"\n $ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*'\n$ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*'\n $ git checkout new<TAB>\nMenu: new/frabnotz new/foo new/bar\n\n\n$ git checkout foo<TAB>\nMenu: new/foo test/foo ver/foo\n git branch --list \"feature/*\"\ngit log --graph --oneline --decorate --branches=\"feature/*\" \ngitk --branches=\"feature/*\" \n $ git checkout CR15032<TAB>\nMenu: fix/CR15032 test/CR15032\n Merge branch 'branch-name' Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted' Merge branch 'fix/CR15032'"
},
{
"answer_id": 24223634,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "git check-ref-format -"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] |
273,711
|
<p>I have an Eclipse RCP application that displays a lot (10k+) of small images next to each other, like a film strip. For each image, I am using a SWT <code>Image</code> object. This uses an excessive amount of memory and resources. I am looking for a more efficient way. I thought of taking all of these images and concatenating them by creating an <code>ImageData</code> object of the proper total, concatenated width (with a constant height) and using <code>setPixel()</code> for the rest of the pixels. However, the <code>Palette</code> used in the <code>ImageData</code> constructor I can't figure out.</p>
<p>I also searched for SWT tiling or mosaic functionality to create one image from a group of images, but found nothing.</p>
<p>Any ideas how I can display thousands of small images next to each other efficiently? Please note that once the images are displayed, they are not manipulated, so this is a one-time cost.</p>
|
[
{
"answer_id": 290904,
"author": "Herman Lintvelt",
"author_id": 27602,
"author_profile": "https://Stackoverflow.com/users/27602",
"pm_score": 3,
"selected": true,
"text": " final List<Image> images;\n final Image bigImage = new Image(Display.getCurrent(), combinedWidth, height);\n final GC gc = new GC(bigImage);\n //loop thru all the images while increasing x as necessary:\n int x = 0;\n int y = 0;\n for (Image curImage : images) {\n gc.drawImage(curImage, x, y);\n x += curImage.getBounds().width;\n }\n //very important to dispose GC!!!\n gc.dispose();\n //now you can use bigImage\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/725/"
] |
273,720
|
<p>Should Singleton objects that don't use instance/reference counters be considered memory leaks in C++?</p>
<p>Without a counter that calls for explicit deletion of the singleton instance when the count is zero, how does the object get deleted? Is it cleaned up by the OS when the application is terminated? What if that Singleton had allocated memory on the heap?</p>
<p>In a nutshell, do I have to call a Singelton's destructor or can I rely on it getting cleaned up when the application terminates?</p>
|
[
{
"answer_id": 273749,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 2,
"selected": false,
"text": "signal(SIGTERM,exit);"
},
{
"answer_id": 273826,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 3,
"selected": false,
"text": "Singleton &get_singleton()\n{\n static Singleton singleton;\n return singleton;\n}\n"
},
{
"answer_id": 274612,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 4,
"selected": false,
"text": "class Tempfile\n{\nTempfile() {}; // creates a temporary file \nvirtual ~Tempfile(); // close AND DELETE the temporary file \n};\n\nTempfile &singleton()\n{\n static Tempfile t;\n return t;\n}\n Tempfile &singleton()\n{\n static Tempfile *t = NULL;\n if (t == NULL)\n t = new Tempfile(); \n return *t;\n}\n"
},
{
"answer_id": 274794,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n\nclass Test\n{\n const char *msg;\n\npublic:\n\n Test(const char *msg)\n : msg(msg)\n {}\n\n ~Test()\n {\n std::cout << \"In destructor: \" << msg << std::endl;\n }\n};\n\nTest globalTest(\"GlobalTest\");\n\nint main(int, char *argv[])\n{\n static Test staticTest(\"StaticTest\");\n\n return 0;\n}\n In destructor: StaticTest \nIn destructor: GlobalTest\n"
},
{
"answer_id": 41254875,
"author": "Dan Lin",
"author_id": 5899169,
"author_profile": "https://Stackoverflow.com/users/5899169",
"pm_score": 1,
"selected": false,
"text": "class Singleton{\n...\n friend class Singleton_Cleanup;\n};\nclass Singleton_Cleanup{\npublic:\n ~Singleton_Cleanup(){\n delete Singleton::ptr;\n }\n};\n"
},
{
"answer_id": 52447862,
"author": "Ben",
"author_id": 874660,
"author_profile": "https://Stackoverflow.com/users/874660",
"pm_score": 0,
"selected": false,
"text": "Singleton &get_singleton() {\n static Singleton singleton;\n return singleton;\n}\n Singleton &get_singleton() {\n static std::shared_ptr<Singleton> singleton = std::make_shared<Singleton>();\n static thread_local std::shared_ptr<Singleton> local = singleton;\n return *local;\n}\n singleton local shared_ptr Singleton"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34731/"
] |
273,721
|
<p>I wonder if there is an example which html files and java files are resides in different folders. </p>
|
[
{
"answer_id": 273818,
"author": "Loren_",
"author_id": 13703,
"author_profile": "https://Stackoverflow.com/users/13703",
"pm_score": 3,
"selected": false,
"text": "IResourceSettings resourceSettings = getResourceSettings();\nresourceSettings.addResourceFolder(\"pages\"); //the full path to your folder, relative to the context root\nresourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator());\n"
},
{
"answer_id": 326827,
"author": "ThaDon",
"author_id": 33689,
"author_profile": "https://Stackoverflow.com/users/33689",
"pm_score": 2,
"selected": false,
"text": "src/main/resources/same/package/name/as/corresponding/java/file"
},
{
"answer_id": 450057,
"author": "emeraldjava",
"author_id": 55794,
"author_profile": "https://Stackoverflow.com/users/55794",
"pm_score": 1,
"selected": false,
"text": "\nweb.root = ${project.home}/web\nweb.java.dir = ${web.root}/java\nweb.html.dir = ${web.root}/html\n\nwar.root = ${project.home}/war\nweb.inf.dir = ${war.root}/WEB-INF\nwar.lib.dir = ${web.inf.dir}/lib\nwar.classes.dir = ${web.inf.dir}/classes\n\nwicket.version = 1.3.5\nwicket.jar = ${war.lib.dir}/wicket-${wicket.version}.jar\nwicket-extend.jar = ${war.lib.dir}/wicket-extensions-${wicket.version}.jar\nwicket-spring.jar = ${war.lib.dir}/wicket-spring-${wicket.version}.jar\n <target name=\"compile-web\">\n <path id=\"wicket.build.classpath\">\n <filelist>\n <file name=\"${wicket.jar}\"/>\n <file name=\"${wicket-extend.jar}\"/>\n <file name=\"${wicket-spring.jar}\"/>\n <file name=\"${externaljars.path}/spring/2.5.6/spring.jar\"/>\n </filelist>\n </path>\n\n <javac destdir=\"${war.classes.dir}\" classpathref=\"wicket.build.classpath\" \n debug=\"on\" srcdir=\"${web.java.dir}\">\n <include name=\"**/*.java\"/>\n </javac>\n</target>\n\n<target name=\"assemble-war\" depends=\"compile-web\">\n <copy todir=\"${war.classes.dir}\" overwrite=\"true\">\n <fileset dir=\"${web.html.dir}\"/>\n </copy>\n <delete file=\"${dist.dir}/validationservice.war\"/>\n <war destfile=\"${dist.dir}/validationservice.war\" webxml=\"${web.inf.dir}/web.xml\" basedir=\"${war.dir}\">\n </war>\n</target> \n"
},
{
"answer_id": 3016494,
"author": "rcl",
"author_id": 113800,
"author_profile": "https://Stackoverflow.com/users/113800",
"pm_score": 2,
"selected": false,
"text": "src/main/resources <project>\n[...]\n <build>\n <resources>\n <resource>\n <filtering>false</filtering>\n <directory>src/main/html</directory>\n </resource>\n </resources>\n[...]\n </build>\n[...]\n</project>\n src/main/html/com/your/package"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34367/"
] |
273,732
|
<p>I have an application where, in the course of using the application, a user might click from</p>
<pre><code>virginia.usa.com
</code></pre>
<p>to</p>
<pre><code>newyork.usa.com
</code></pre>
<p>Since I'd rather not create a new session each time a user crosses from one subdomain to another, what's a good way to share session info across multiple subdomains?</p>
|
[
{
"answer_id": 273775,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": ".usa.com session.use_cookies = 1\nsession.use_only_cookies = 1\nsession.cookie_domain = .usa.com\n"
},
{
"answer_id": 2088853,
"author": "Matt Connolly",
"author_id": 2845,
"author_profile": "https://Stackoverflow.com/users/2845",
"pm_score": 6,
"selected": true,
"text": "<httpCookies domain=\".usa.com\"/>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28118/"
] |
273,743
|
<p>I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:</p>
<pre><code>http://mysite.com/configs/.vim/
</code></pre>
<p>.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?</p>
|
[
{
"answer_id": 273755,
"author": "Conor McDermottroe",
"author_id": 63985,
"author_profile": "https://Stackoverflow.com/users/63985",
"pm_score": 3,
"selected": false,
"text": "wget -r http://mysite.com/configs/.vim/\n"
},
{
"answer_id": 273757,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": -1,
"selected": false,
"text": "wget -r http://stackoverflow.com/\n"
},
{
"answer_id": 273776,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 11,
"selected": true,
"text": "-np --no-parent wget -r --recursive wget --recursive --no-parent http://example.com/configs/.vim/\n index.html -R --reject wget -r -np -R \"index.html*\" http://example.com/configs/.vim/\n"
},
{
"answer_id": 5335576,
"author": "Sri",
"author_id": 435912,
"author_profile": "https://Stackoverflow.com/users/435912",
"pm_score": 7,
"selected": false,
"text": "wget -r -nH --cut-dirs=2 --no-parent --reject=\"index.html*\" http://mysite.com/dir1/dir2/data\n"
},
{
"answer_id": 13519665,
"author": "Sean Villani",
"author_id": 463188,
"author_profile": "https://Stackoverflow.com/users/463188",
"pm_score": 7,
"selected": false,
"text": "robots.txt wget -e robots=off http://www.example.com/\n"
},
{
"answer_id": 14894734,
"author": "Erich Eichinger",
"author_id": 51264,
"author_profile": "https://Stackoverflow.com/users/51264",
"pm_score": 5,
"selected": false,
"text": "robots.txt wget -e robots=off --cut-dirs=3 --user-agent=Mozilla/5.0 --reject=\"index.html*\" --no-parent --recursive --relative --level=1 --no-directories http://www.example.com/archive/example/5.3.0/\n"
},
{
"answer_id": 16587702,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "--no-parent --include http://<host>/downloads/good\nhttp://<host>/downloads/bad\n downloads/good downloads/bad wget --include downloads/good --mirror --execute robots=off --no-host-directories --cut-dirs=1 --reject=\"index.html*\" --continue http://<host>/downloads/good\n"
},
{
"answer_id": 21983475,
"author": "SamGoody",
"author_id": 87520,
"author_profile": "https://Stackoverflow.com/users/87520",
"pm_score": 5,
"selected": false,
"text": "wget -m http://example.com/configs/.vim/\n wget -m -e robots=off --no-parent http://example.com/configs/.vim/\n"
},
{
"answer_id": 26478435,
"author": "prayagupa",
"author_id": 432903,
"author_profile": "https://Stackoverflow.com/users/432903",
"pm_score": 3,
"selected": false,
"text": "wget -r --user=(put username here) --password='(put password here)' --no-parent http://example.com/\n"
},
{
"answer_id": 42501032,
"author": "Devon",
"author_id": 3008405,
"author_profile": "https://Stackoverflow.com/users/3008405",
"pm_score": 2,
"selected": false,
"text": "wget --recursive (...)\n"
},
{
"answer_id": 46820751,
"author": "rkok",
"author_id": 3018750,
"author_profile": "https://Stackoverflow.com/users/3018750",
"pm_score": 3,
"selected": false,
"text": "wgetod() {\n NSLASH=\"$(echo \"$1\" | perl -pe 's|.*://[^/]+(.*?)/?$|\\1|' | grep -o / | wc -l)\"\n NCUT=$((NSLASH > 0 ? NSLASH-1 : 0))\n wget -r -nH --user-agent=Mozilla/5.0 --cut-dirs=$NCUT --no-parent --reject=\"index.html*\" \"$1\"\n}\n ~/.bashrc wgetod \"http://example.com/x/\""
},
{
"answer_id": 49063898,
"author": "Jordan Gee",
"author_id": 416688,
"author_profile": "https://Stackoverflow.com/users/416688",
"pm_score": 2,
"selected": false,
"text": "\"-r\" \"--no-parent\" -np '.' \"..\" wget -r --no-parent http://example.com/configs/.vim/ ./example.com/configs/.vim --cut-dirs=2 wget -r --no-parent --cut-dirs=2 http://example.com/configs/.vim/ ./.vim/"
},
{
"answer_id": 57834913,
"author": "pr-pal",
"author_id": 5785743,
"author_profile": "https://Stackoverflow.com/users/5785743",
"pm_score": 2,
"selected": false,
"text": " -nd\n --no-directories\n Do not create a hierarchy of directories when retrieving recursively. With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the\n filenames will get extensions .n).\n\n\n -np\n --no-parent\n Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.\n"
},
{
"answer_id": 62584994,
"author": "Tumelo Mapheto",
"author_id": 12005685,
"author_profile": "https://Stackoverflow.com/users/12005685",
"pm_score": 1,
"selected": false,
"text": "wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'\n"
},
{
"answer_id": 65442746,
"author": "berezovskyi",
"author_id": 464590,
"author_profile": "https://Stackoverflow.com/users/464590",
"pm_score": 3,
"selected": false,
"text": "wget --recursive ${comment# self-explanatory} \\\n --no-parent ${comment# will not crawl links in folders above the base of the URL} \\\n --convert-links ${comment# convert links with the domain name to relative and uncrawled to absolute} \\\n --random-wait --wait 3 --no-http-keep-alive ${comment# do not get banned} \\\n --no-host-directories ${comment# do not create folders with the domain name} \\\n --execute robots=off --user-agent=Mozilla/5.0 ${comment# I AM A HUMAN!!!} \\\n --level=inf --accept '*' ${comment# do not limit to 5 levels or common file formats} \\\n --reject=\"index.html*\" ${comment# use this option if you need an exact mirror} \\\n --cut-dirs=0 ${comment# replace 0 with the number of folders in the path, 0 for the whole domain} \\\n$URL\n main.css?crc=12324567 python3 -m http.server --convert-links"
},
{
"answer_id": 69024542,
"author": "SentientFlesh",
"author_id": 11019416,
"author_profile": "https://Stackoverflow.com/users/11019416",
"pm_score": 2,
"selected": false,
"text": "wget robots.txt /robots.txt public_html www configs wget wget wget -e robots=off 'http://your-site.com/configs/.vim/'\n wget mirror wget -mpEk 'http://your-site.com/configs/.vim/'\n\n# If robots.txt is present:\n\nwget -mpEk robots=off 'http://your-site.com/configs/.vim/'\n\n# Good practice to only deal with the highest level directory you specify (instead of downloading all of `mysite.com` you're just mirroring from `.vim`\n\nwget -mpEk robots=off --no-parent 'http://your-site.com/configs/.vim/'\n -m -r -p -E -k -k /.vim ftp:// wait wget -mpEk --no-parent robots=off --random-wait 'http://your-site.com/configs/.vim/'\n ../config/.vim/"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476/"
] |
273,751
|
<p>I have a SSIS package that eventually I would like to pass parameters too, these parameters will come from a .NET application (VB or C#) so I was curious if anyone knows of how to do this, or better yet a website with helpful hints on how to do it. </p>
<p>So basically I want to execute a SSIS package from .NET passing the SSIS package parameters that it can use within it. </p>
<p>For instance, the SSIS package will use flat file importing into a SQL db however the Path and name of the file could be the parameter that is passed from the .Net application.</p>
|
[
{
"answer_id": 1920083,
"author": "Craig Schwarze",
"author_id": 226235,
"author_profile": "https://Stackoverflow.com/users/226235",
"pm_score": 6,
"selected": false,
"text": "using Microsoft.SqlServer.Dts.Runtime;\n\nprivate void Execute_Package()\n { \n string pkgLocation = @\"c:\\test.dtsx\";\n\n Package pkg;\n Application app;\n DTSExecResult pkgResults;\n Variables vars;\n\n app = new Application();\n pkg = app.LoadPackage(pkgLocation, null);\n\n vars = pkg.Variables;\n vars[\"A_Variable\"].Value = \"Some value\"; \n\n pkgResults = pkg.Execute(null, vars, null, null, null);\n\n if (pkgResults == DTSExecResult.Success)\n Console.WriteLine(\"Package ran successfully\");\n else\n Console.WriteLine(\"Package failed\");\n }\n"
},
{
"answer_id": 26012658,
"author": "Faiz",
"author_id": 82961,
"author_profile": "https://Stackoverflow.com/users/82961",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing Microsoft.SqlServer.Dts.Runtime;\n\nnamespace RunFromClientAppWithEventsCS\n{\n class MyEventListener : DefaultEvents\n {\n public override bool OnError(DtsObject source, int errorCode, string subComponent, \n string description, string helpFile, int helpContext, string idofInterfaceWithError)\n {\n // Add application-specific diagnostics here.\n Console.WriteLine(\"Error in {0}/{1} : {2}\", source, subComponent, description);\n return false;\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n string pkgLocation;\n Package pkg;\n Application app;\n DTSExecResult pkgResults;\n\n MyEventListener eventListener = new MyEventListener();\n\n pkgLocation =\n @\"C:\\Program Files\\Microsoft SQL Server\\100\\Samples\\Integration Services\" +\n @\"\\Package Samples\\CalculatedColumns Sample\\CalculatedColumns\\CalculatedColumns.dtsx\";\n app = new Application();\n pkg = app.LoadPackage(pkgLocation, eventListener);\n pkgResults = pkg.Execute(null, null, eventListener, null, null);\n\n Console.WriteLine(pkgResults.ToString());\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 28603315,
"author": "Paul Hatcher",
"author_id": 102792,
"author_profile": "https://Stackoverflow.com/users/102792",
"pm_score": 5,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Data.SqlClient;\n\nusing Microsoft.SqlServer.Management.IntegrationServices;\n\npublic List<string> ExecutePackage(string folder, string project, string package)\n{\n // Connection to the database server where the packages are located\n SqlConnection ssisConnection = new SqlConnection(@\"Data Source=.\\SQL2012;Initial Catalog=master;Integrated Security=SSPI;\");\n\n // SSIS server object with connection\n IntegrationServices ssisServer = new IntegrationServices(ssisConnection);\n\n // The reference to the package which you want to execute\n PackageInfo ssisPackage = ssisServer.Catalogs[\"SSISDB\"].Folders[folder].Projects[project].Packages[package];\n\n // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)\n Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();\n\n // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = \"SYNCHRONIZED\", ParameterValue = 1 });\n\n // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = \"LOGGING_LEVEL\", ParameterValue = 3 });\n\n // Add a project parameter (value) to fill a project parameter\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = \"MyProjectParameter\", ParameterValue = \"some value\" });\n\n // Add a project package (value) to fill a package parameter\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = \"MyPackageParameter\", ParameterValue = \"some value\" });\n\n // Get the identifier of the execution to get the log\n long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);\n\n // Loop through the log and do something with it like adding to a list\n var messages = new List<string>();\n foreach (OperationMessage message in ssisServer.Catalogs[\"SSISDB\"].Executions[executionIdentifier].Messages)\n {\n messages.Add(message.MessageType + \": \" + message.Message);\n }\n\n return messages;\n}\n"
},
{
"answer_id": 58619403,
"author": "rafayel ahmed",
"author_id": 5263516,
"author_profile": "https://Stackoverflow.com/users/5263516",
"pm_score": 0,
"selected": false,
"text": " Package pkg;\n\n Microsoft.SqlServer.Dts.Runtime.Application app;\n DTSExecResult pkgResults;\n Variables vars;\n\n app = new Microsoft.SqlServer.Dts.Runtime.Application();\n pkg = app.LoadPackage(\" Location of your SSIS package\", null);\n\n vars = pkg.Variables;\n\n // your variables\n vars[\"somevariable1\"].Value = \"yourvariable1\";\n vars[\"somevariable2\"].Value = \"yourvariable2\";\n\n pkgResults = pkg.Execute(null, vars, null, null, null);\n\n if (pkgResults == DTSExecResult.Success)\n {\n Console.WriteLine(\"Package ran successfully\");\n }\n else\n {\n\n Console.WriteLine(\"Package failed\");\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,789
|
<p>In javascript, is there an equivalent of String.indexOf() that takes a regular expression instead of a string for the first first parameter while still allowing a second parameter ?</p>
<p>I need to do something like </p>
<pre><code>str.indexOf(/[abc]/ , i);
</code></pre>
<p>and</p>
<pre><code>str.lastIndexOf(/[abc]/ , i);
</code></pre>
<p>While String.search() takes a regexp as a parameter it does not allow me to specify a second argument!</p>
<p>Edit:<br>
This turned out to be harder than I originally thought so I wrote a small test function to test all the provided solutions... it assumes regexIndexOf and regexLastIndexOf have been added to the String object.</p>
<pre><code>function test (str) {
var i = str.length +2;
while (i--) {
if (str.indexOf('a',i) != str.regexIndexOf(/a/,i))
alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ;
if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) )
alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ;
}
}
</code></pre>
<p>and I am testing as follow to make sure that at least for one character regexp, the result is the same as if we used indexOf</p>
<p>//Look for the a among the xes<br>
test('xxx');<br>
test('axx');<br>
test('xax');<br>
test('xxa');<br>
test('axa');<br>
test('xaa');<br>
test('aax');<br>
test('aaa'); </p>
|
[
{
"answer_id": 273797,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 3,
"selected": false,
"text": "str.substr(i).match(/[abc]/);\n"
},
{
"answer_id": 273810,
"author": "Glenn",
"author_id": 25191,
"author_profile": "https://Stackoverflow.com/users/25191",
"pm_score": 8,
"selected": false,
"text": "String .search() .indexOf() slice i str.slice(i).search(/re/)\n i -1 function regexIndexOf(text, re, i) {\n var indexInSuffix = text.slice(i).search(re);\n return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;\n}\n"
},
{
"answer_id": 273829,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n\nString.prototype.regexIndexOf = function( pattern, startIndex )\n{\n startIndex = startIndex || 0;\n var searchResult = this.substr( startIndex ).search( pattern );\n return ( -1 === searchResult ) ? -1 : searchResult + startIndex;\n}\n\nString.prototype.regexLastIndexOf = function( pattern, startIndex )\n{\n startIndex = startIndex === undefined ? this.length : startIndex;\n var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 );\n return ( -1 === searchResult ) ? -1 : this.length - ++searchResult;\n}\n\nString.prototype.reverse = function()\n{\n return this.split('').reverse().join('');\n}\n\n// Indexes 0123456789\nvar str = 'caabbccdda';\n\nalert( [\n str.regexIndexOf( /[cd]/, 4 )\n , str.regexLastIndexOf( /[cd]/, 4 )\n , str.regexIndexOf( /[yz]/, 4 )\n , str.regexLastIndexOf( /[yz]/, 4 )\n , str.lastIndexOf( 'd', 4 )\n , str.regexLastIndexOf( /d/, 4 )\n , str.lastIndexOf( 'd' )\n , str.regexLastIndexOf( /d/ )\n ]\n);\n\n</script>\n"
},
{
"answer_id": 273902,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "-1 .lastIndex /g String.prototype.regexIndexOf = function(re, startPos) {\n startPos = startPos || 0;\n\n if (!re.global) {\n var flags = \"g\" + (re.multiline?\"m\":\"\") + (re.ignoreCase?\"i\":\"\");\n re = new RegExp(re.source, flags);\n }\n\n re.lastIndex = startPos;\n var match = re.exec(this);\n\n if (match) return match.index;\n else return -1;\n}\n\nString.prototype.regexLastIndexOf = function(re, startPos) {\n startPos = startPos === undefined ? this.length : startPos;\n\n if (!re.global) {\n var flags = \"g\" + (re.multiline?\"m\":\"\") + (re.ignoreCase?\"i\":\"\");\n re = new RegExp(re.source, flags);\n }\n\n var lastSuccess = -1;\n for (var pos = 0; pos <= startPos; pos++) {\n re.lastIndex = pos;\n\n var match = re.exec(this);\n if (!match) break;\n\n pos = match.index;\n if (pos <= startPos) lastSuccess = pos;\n }\n\n return lastSuccess;\n}\n"
},
{
"answer_id": 273954,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": -1,
"selected": false,
"text": "function mIndexOf( str , chars, offset )\n{\n var first = -1; \n for( var i = 0; i < chars.length; i++ )\n {\n var p = str.indexOf( chars[i] , offset ); \n if( p < first || first === -1 )\n {\n first = p;\n }\n }\n return first; \n}\nString.prototype.mIndexOf = function( chars, offset )\n{\n return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching. \n};\nmIndexOf( \"hello world\", ['a','o','w'], 0 );\n>> 4 \nmIndexOf( \"hello world\", ['a'], 0 );\n>> -1 \nmIndexOf( \"hello world\", ['a','o','w'], 4 );\n>> 4\nmIndexOf( \"hello world\", ['a','o','w'], 5 );\n>> 6\nmIndexOf( \"hello world\", ['a','o','w'], 7 );\n>> -1 \nmIndexOf( \"hello world\", ['a','o','w','d'], 7 );\n>> 10\nmIndexOf( \"hello world\", ['a','o','w','d'], 10 );\n>> 10\nmIndexOf( \"hello world\", ['a','o','w','d'], 11 );\n>> -1\n"
},
{
"answer_id": 274094,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "function regexIndexOf(string, regex, startpos) {\n var indexOf = string.substring(startpos || 0).search(regex);\n return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;\n}\n\nfunction regexLastIndexOf(string, regex, startpos) {\n regex = (regex.global) ? regex : new RegExp(regex.source, \"g\" + (regex.ignoreCase ? \"i\" : \"\") + (regex.multiLine ? \"m\" : \"\"));\n if(typeof (startpos) == \"undefined\") {\n startpos = string.length;\n } else if(startpos < 0) {\n startpos = 0;\n }\n var stringToWorkWith = string.substring(0, startpos + 1);\n var lastIndexOf = -1;\n var nextStop = 0;\n while((result = regex.exec(stringToWorkWith)) != null) {\n lastIndexOf = result.index;\n regex.lastIndex = ++nextStop;\n }\n return lastIndexOf;\n}\n regexLastIndexOf() lastIndexOf()"
},
{
"answer_id": 274680,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "String.prototype.regexIndexOf = function(elt /*, from*/)\n {\n var arr = this.split('');\n var len = arr.length;\n\n var from = Number(arguments[1]) || 0;\n from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n if (from < 0)\n from += len;\n\n for (; from < len; from++) {\n if (from in arr && elt.exec(arr[from]) ) \n return from;\n }\n return -1;\n};\n\nString.prototype.regexLastIndexOf = function(elt /*, from*/)\n {\n var arr = this.split('');\n var len = arr.length;\n\n var from = Number(arguments[1]);\n if (isNaN(from)) {\n from = len - 1;\n } else {\n from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n if (from < 0)\n from += len;\n else if (from >= len)\n from = len - 1;\n }\n\n for (; from > -1; from--) {\n if (from in arr && elt.exec(arr[from]) )\n return from;\n }\n return -1;\n };\n"
},
{
"answer_id": 274850,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 3,
"selected": false,
"text": "RexExp exec lastIndex function reIndexOf(reIn, str, startIndex) {\n var re = new RegExp(reIn.source, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nfunction reLastIndexOf(reIn, str, startIndex) {\n var src = /\\$$/.test(reIn.source) && !/\\\\\\$$/.test(reIn.source) ? reIn.source : reIn.source + '(?![\\\\S\\\\s]*' + reIn.source + ')';\n var re = new RegExp(src, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nreIndexOf(/[abc]/, \"tommy can eat\"); // Returns 6\nreIndexOf(/[abc]/, \"tommy can eat\", 8); // Returns 11\nreLastIndexOf(/[abc]/, \"tommy can eat\"); // Returns 11\n RegExp.prototype.indexOf = function(str, startIndex) {\n var re = new RegExp(this.source, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nRegExp.prototype.lastIndexOf = function(str, startIndex) {\n var src = /\\$$/.test(this.source) && !/\\\\\\$$/.test(this.source) ? this.source : this.source + '(?![\\\\S\\\\s]*' + this.source + ')';\n var re = new RegExp(src, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\n\n/[abc]/.indexOf(\"tommy can eat\"); // Returns 6\n/[abc]/.indexOf(\"tommy can eat\", 8); // Returns 11\n/[abc]/.lastIndexOf(\"tommy can eat\"); // Returns 11\n RegExp indexOf lastIndexOf RegExp"
},
{
"answer_id": 12228895,
"author": "jakov",
"author_id": 1100709,
"author_profile": "https://Stackoverflow.com/users/1100709",
"pm_score": 2,
"selected": false,
"text": "regexIndexOf Array.prototype.regexIndexOf = function (regex, startpos = 0) {\n len = this.length;\n for(x = startpos; x < len; x++){\n if(typeof this[x] != 'undefined' && (''+this[x]).match(regex)){\n return x;\n }\n }\n return -1;\n}\n\narr = [];\narr.push(null);\narr.push(NaN);\narr[3] = 7;\narr.push('asdf');\narr.push('qwer');\narr.push(9);\narr.push('...');\nconsole.log(arr);\narr.regexIndexOf(/\\d/, 4);\n"
},
{
"answer_id": 16558822,
"author": "amwinter",
"author_id": 329867,
"author_profile": "https://Stackoverflow.com/users/329867",
"pm_score": 1,
"selected": false,
"text": "function regexlast(string,re){\n var tokens=string.split(re);\n return (tokens.length>1)?(string.length-tokens[tokens.length-1].length):null;\n}\n /\\s\\w/"
},
{
"answer_id": 21420210,
"author": "pmrotule",
"author_id": 1895428,
"author_profile": "https://Stackoverflow.com/users/1895428",
"pm_score": 6,
"selected": false,
"text": "var match = str.match(/[abc]/gi);\nvar firstIndex = str.indexOf(match[0]);\nvar lastIndex = str.lastIndexOf(match[match.length-1]);\n String.prototype.indexOfRegex = function(regex){\n var match = this.match(regex);\n return match ? this.indexOf(match[0]) : -1;\n}\n\nString.prototype.lastIndexOfRegex = function(regex){\n var match = this.match(regex);\n return match ? this.lastIndexOf(match[match.length-1]) : -1;\n}\n String.prototype.indexOfRegex = function(regex, fromIndex){\n var str = fromIndex ? this.substring(fromIndex) : this;\n var match = str.match(regex);\n return match ? str.indexOf(match[0]) + fromIndex : -1;\n}\n\nString.prototype.lastIndexOfRegex = function(regex, fromIndex){\n var str = fromIndex ? this.substring(0, fromIndex) : this;\n var match = str.match(regex);\n return match ? str.lastIndexOf(match[match.length-1]) : -1;\n}\n var firstIndex = str.indexOfRegex(/[abc]/gi);\nvar lastIndex = str.lastIndexOfRegex(/[abc]/gi);\n"
},
{
"answer_id": 23177741,
"author": "npjohns",
"author_id": 1331851,
"author_profile": "https://Stackoverflow.com/users/1331851",
"pm_score": 0,
"selected": false,
"text": "function lastIndexOfSearch(string, regex, index) {\n if(index === 0 || index)\n string = string.slice(0, Math.max(0,index));\n var idx;\n var offset = -1;\n while ((idx = string.search(regex)) !== -1) {\n offset += idx + 1;\n string = string.slice(idx + 1);\n }\n return offset;\n}\n function lastIndexOfGroupSimple(string, regex, index) {\n if (index === 0 || index) string = string.slice(0, Math.max(0, index + 1));\n regex.lastIndex = 0;\n var lastRegex, index\n flags = 'g' + (regex.multiline ? 'm' : '') + (regex.ignoreCase ? 'i' : ''),\n key = regex.source + '$' + flags,\n match = regex.exec(string);\n if (!match) return -1;\n if (lastIndexOfGroupSimple.cache === undefined) lastIndexOfGroupSimple.cache = {};\n lastRegex = lastIndexOfGroupSimple.cache[key];\n if (!lastRegex)\n lastIndexOfGroupSimple.cache[key] = lastRegex = new RegExp('.*(' + regex.source + ')(?!.*?' + regex.source + ')', flags);\n index = match.index;\n lastRegex.lastIndex = match.index;\n return (match = lastRegex.exec(string)) ? lastRegex.lastIndex - match[1].length : index;\n};\n"
},
{
"answer_id": 30792707,
"author": "Eli",
"author_id": 117588,
"author_profile": "https://Stackoverflow.com/users/117588",
"pm_score": 0,
"selected": false,
"text": "//Jason Bunting's\nString.prototype.regexIndexOf = function(regex, startpos) {\nvar indexOf = this.substring(startpos || 0).search(regex);\nreturn (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;\n}\n\nString.prototype.regexLastIndexOf = function(regex, startpos) {\nvar lastIndex = -1;\nvar index = this.regexIndexOf( regex );\nstartpos = startpos === undefined ? this.length : startpos;\n\nwhile ( index >= 0 && index < startpos )\n{\n lastIndex = index;\n index = this.regexIndexOf( regex, index + 1 );\n}\nreturn lastIndex;\n}\n"
},
{
"answer_id": 31373042,
"author": "rmg.n3t",
"author_id": 3672064,
"author_profile": "https://Stackoverflow.com/users/3672064",
"pm_score": 4,
"selected": false,
"text": "str.search(regex)\n"
},
{
"answer_id": 32232028,
"author": "Xotic750",
"author_id": 592253,
"author_profile": "https://Stackoverflow.com/users/592253",
"pm_score": 0,
"selected": false,
"text": "String.prototype searchOf searchLastOf /*jslint maxlen:80, browser:true */\n\n/*\n * Properties used by searchOf and searchLastOf implementation.\n */\n\n/*property\n MAX_SAFE_INTEGER, abs, add, apply, call, configurable, defineProperty,\n enumerable, exec, floor, global, hasOwnProperty, ignoreCase, index,\n lastIndex, lastIndexOf, length, max, min, multiline, pow, prototype,\n remove, replace, searchLastOf, searchOf, source, toString, value, writable\n*/\n\n/*\n * Properties used in the testing of searchOf and searchLastOf implimentation.\n */\n\n/*property\n appendChild, createTextNode, getElementById, indexOf, lastIndexOf, length,\n searchLastOf, searchOf, unshift\n*/\n\n(function () {\n 'use strict';\n\n var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1,\n getNativeFlags = new RegExp('\\\\/([a-z]*)$', 'i'),\n clipDups = new RegExp('([\\\\s\\\\S])(?=[\\\\s\\\\S]*\\\\1)', 'g'),\n pToString = Object.prototype.toString,\n pHasOwn = Object.prototype.hasOwnProperty,\n stringTagRegExp;\n\n /**\n * Defines a new property directly on an object, or modifies an existing\n * property on an object, and returns the object.\n *\n * @private\n * @function\n * @param {Object} object\n * @param {string} property\n * @param {Object} descriptor\n * @returns {Object}\n * @see https://goo.gl/CZnEqg\n */\n function $defineProperty(object, property, descriptor) {\n if (Object.defineProperty) {\n Object.defineProperty(object, property, descriptor);\n } else {\n object[property] = descriptor.value;\n }\n\n return object;\n }\n\n /**\n * Returns true if the operands are strictly equal with no type conversion.\n *\n * @private\n * @function\n * @param {*} a\n * @param {*} b\n * @returns {boolean}\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4\n */\n function $strictEqual(a, b) {\n return a === b;\n }\n\n /**\n * Returns true if the operand inputArg is undefined.\n *\n * @private\n * @function\n * @param {*} inputArg\n * @returns {boolean}\n */\n function $isUndefined(inputArg) {\n return $strictEqual(typeof inputArg, 'undefined');\n }\n\n /**\n * Provides a string representation of the supplied object in the form\n * \"[object type]\", where type is the object type.\n *\n * @private\n * @function\n * @param {*} inputArg The object for which a class string represntation\n * is required.\n * @returns {string} A string value of the form \"[object type]\".\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2\n */\n function $toStringTag(inputArg) {\n var val;\n if (inputArg === null) {\n val = '[object Null]';\n } else if ($isUndefined(inputArg)) {\n val = '[object Undefined]';\n } else {\n val = pToString.call(inputArg);\n }\n\n return val;\n }\n\n /**\n * The string tag representation of a RegExp object.\n *\n * @private\n * @type {string}\n */\n stringTagRegExp = $toStringTag(getNativeFlags);\n\n /**\n * Returns true if the operand inputArg is a RegExp.\n *\n * @private\n * @function\n * @param {*} inputArg\n * @returns {boolean}\n */\n function $isRegExp(inputArg) {\n return $toStringTag(inputArg) === stringTagRegExp &&\n pHasOwn.call(inputArg, 'ignoreCase') &&\n typeof inputArg.ignoreCase === 'boolean' &&\n pHasOwn.call(inputArg, 'global') &&\n typeof inputArg.global === 'boolean' &&\n pHasOwn.call(inputArg, 'multiline') &&\n typeof inputArg.multiline === 'boolean' &&\n pHasOwn.call(inputArg, 'source') &&\n typeof inputArg.source === 'string';\n }\n\n /**\n * The abstract operation throws an error if its argument is a value that\n * cannot be converted to an Object, otherwise returns the argument.\n *\n * @private\n * @function\n * @param {*} inputArg The object to be tested.\n * @throws {TypeError} If inputArg is null or undefined.\n * @returns {*} The inputArg if coercible.\n * @see https://goo.gl/5GcmVq\n */\n function $requireObjectCoercible(inputArg) {\n var errStr;\n\n if (inputArg === null || $isUndefined(inputArg)) {\n errStr = 'Cannot convert argument to object: ' + inputArg;\n throw new TypeError(errStr);\n }\n\n return inputArg;\n }\n\n /**\n * The abstract operation converts its argument to a value of type string\n *\n * @private\n * @function\n * @param {*} inputArg\n * @returns {string}\n * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring\n */\n function $toString(inputArg) {\n var type,\n val;\n\n if (inputArg === null) {\n val = 'null';\n } else {\n type = typeof inputArg;\n if (type === 'string') {\n val = inputArg;\n } else if (type === 'undefined') {\n val = type;\n } else {\n if (type === 'symbol') {\n throw new TypeError('Cannot convert symbol to string');\n }\n\n val = String(inputArg);\n }\n }\n\n return val;\n }\n\n /**\n * Returns a string only if the arguments is coercible otherwise throws an\n * error.\n *\n * @private\n * @function\n * @param {*} inputArg\n * @throws {TypeError} If inputArg is null or undefined.\n * @returns {string}\n */\n function $onlyCoercibleToString(inputArg) {\n return $toString($requireObjectCoercible(inputArg));\n }\n\n /**\n * The function evaluates the passed value and converts it to an integer.\n *\n * @private\n * @function\n * @param {*} inputArg The object to be converted to an integer.\n * @returns {number} If the target value is NaN, null or undefined, 0 is\n * returned. If the target value is false, 0 is returned\n * and if true, 1 is returned.\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4\n */\n function $toInteger(inputArg) {\n var number = +inputArg,\n val = 0;\n\n if ($strictEqual(number, number)) {\n if (!number || number === Infinity || number === -Infinity) {\n val = number;\n } else {\n val = (number > 0 || -1) * Math.floor(Math.abs(number));\n }\n }\n\n return val;\n }\n\n /**\n * Copies a regex object. Allows adding and removing native flags while\n * copying the regex.\n *\n * @private\n * @function\n * @param {RegExp} regex Regex to copy.\n * @param {Object} [options] Allows specifying native flags to add or\n * remove while copying the regex.\n * @returns {RegExp} Copy of the provided regex, possibly with modified\n * flags.\n */\n function $copyRegExp(regex, options) {\n var flags,\n opts,\n rx;\n\n if (options !== null && typeof options === 'object') {\n opts = options;\n } else {\n opts = {};\n }\n\n // Get native flags in use\n flags = getNativeFlags.exec($toString(regex))[1];\n flags = $onlyCoercibleToString(flags);\n if (opts.add) {\n flags += opts.add;\n flags = flags.replace(clipDups, '');\n }\n\n if (opts.remove) {\n // Would need to escape `options.remove` if this was public\n rx = new RegExp('[' + opts.remove + ']+', 'g');\n flags = flags.replace(rx, '');\n }\n\n return new RegExp(regex.source, flags);\n }\n\n /**\n * The abstract operation ToLength converts its argument to an integer\n * suitable for use as the length of an array-like object.\n *\n * @private\n * @function\n * @param {*} inputArg The object to be converted to a length.\n * @returns {number} If len <= +0 then +0 else if len is +INFINITY then\n * 2^53-1 else min(len, 2^53-1).\n * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n */\n function $toLength(inputArg) {\n return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);\n }\n\n /**\n * Copies a regex object so that it is suitable for use with searchOf and\n * searchLastOf methods.\n *\n * @private\n * @function\n * @param {RegExp} regex Regex to copy.\n * @returns {RegExp}\n */\n function $toSearchRegExp(regex) {\n return $copyRegExp(regex, {\n add: 'g',\n remove: 'y'\n });\n }\n\n /**\n * Returns true if the operand inputArg is a member of one of the types\n * Undefined, Null, Boolean, Number, Symbol, or String.\n *\n * @private\n * @function\n * @param {*} inputArg\n * @returns {boolean}\n * @see https://goo.gl/W68ywJ\n * @see https://goo.gl/ev7881\n */\n function $isPrimitive(inputArg) {\n var type = typeof inputArg;\n\n return type === 'undefined' ||\n inputArg === null ||\n type === 'boolean' ||\n type === 'string' ||\n type === 'number' ||\n type === 'symbol';\n }\n\n /**\n * The abstract operation converts its argument to a value of type Object\n * but fixes some environment bugs.\n *\n * @private\n * @function\n * @param {*} inputArg The argument to be converted to an object.\n * @throws {TypeError} If inputArg is not coercible to an object.\n * @returns {Object} Value of inputArg as type Object.\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.9\n */\n function $toObject(inputArg) {\n var object;\n\n if ($isPrimitive($requireObjectCoercible(inputArg))) {\n object = Object(inputArg);\n } else {\n object = inputArg;\n }\n\n return object;\n }\n\n /**\n * Converts a single argument that is an array-like object or list (eg.\n * arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap\n * (used by attributes property)) into a new Array() and returns it.\n * This is a partial implementation of the ES6 Array.from\n *\n * @private\n * @function\n * @param {Object} arrayLike\n * @returns {Array}\n */\n function $toArray(arrayLike) {\n var object = $toObject(arrayLike),\n length = $toLength(object.length),\n array = [],\n index = 0;\n\n array.length = length;\n while (index < length) {\n array[index] = object[index];\n index += 1;\n }\n\n return array;\n }\n\n if (!String.prototype.searchOf) {\n /**\n * This method returns the index within the calling String object of\n * the first occurrence of the specified value, starting the search at\n * fromIndex. Returns -1 if the value is not found.\n *\n * @function\n * @this {string}\n * @param {RegExp|string} regex A regular expression object or a String.\n * Anything else is implicitly converted to\n * a String.\n * @param {Number} [fromIndex] The location within the calling string\n * to start the search from. It can be any\n * integer. The default value is 0. If\n * fromIndex < 0 the entire string is\n * searched (same as passing 0). If\n * fromIndex >= str.length, the method will\n * return -1 unless searchValue is an empty\n * string in which case str.length is\n * returned.\n * @returns {Number} If successful, returns the index of the first\n * match of the regular expression inside the\n * string. Otherwise, it returns -1.\n */\n $defineProperty(String.prototype, 'searchOf', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (regex) {\n var str = $onlyCoercibleToString(this),\n args = $toArray(arguments),\n result = -1,\n fromIndex,\n match,\n rx;\n\n if (!$isRegExp(regex)) {\n return String.prototype.indexOf.apply(str, args);\n }\n\n if ($toLength(args.length) > 1) {\n fromIndex = +args[1];\n if (fromIndex < 0) {\n fromIndex = 0;\n }\n } else {\n fromIndex = 0;\n }\n\n if (fromIndex >= $toLength(str.length)) {\n return result;\n }\n\n rx = $toSearchRegExp(regex);\n rx.lastIndex = fromIndex;\n match = rx.exec(str);\n if (match) {\n result = +match.index;\n }\n\n return result;\n }\n });\n }\n\n if (!String.prototype.searchLastOf) {\n /**\n * This method returns the index within the calling String object of\n * the last occurrence of the specified value, or -1 if not found.\n * The calling string is searched backward, starting at fromIndex.\n *\n * @function\n * @this {string}\n * @param {RegExp|string} regex A regular expression object or a String.\n * Anything else is implicitly converted to\n * a String.\n * @param {Number} [fromIndex] Optional. The location within the\n * calling string to start the search at,\n * indexed from left to right. It can be\n * any integer. The default value is\n * str.length. If it is negative, it is\n * treated as 0. If fromIndex > str.length,\n * fromIndex is treated as str.length.\n * @returns {Number} If successful, returns the index of the first\n * match of the regular expression inside the\n * string. Otherwise, it returns -1.\n */\n $defineProperty(String.prototype, 'searchLastOf', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (regex) {\n var str = $onlyCoercibleToString(this),\n args = $toArray(arguments),\n result = -1,\n fromIndex,\n length,\n match,\n pos,\n rx;\n\n if (!$isRegExp(regex)) {\n return String.prototype.lastIndexOf.apply(str, args);\n }\n\n length = $toLength(str.length);\n if (!$strictEqual(args[1], args[1])) {\n fromIndex = length;\n } else {\n if ($toLength(args.length) > 1) {\n fromIndex = $toInteger(args[1]);\n } else {\n fromIndex = length - 1;\n }\n }\n\n if (fromIndex >= 0) {\n fromIndex = Math.min(fromIndex, length - 1);\n } else {\n fromIndex = length - Math.abs(fromIndex);\n }\n\n pos = 0;\n rx = $toSearchRegExp(regex);\n while (pos <= fromIndex) {\n rx.lastIndex = pos;\n match = rx.exec(str);\n if (!match) {\n break;\n }\n\n pos = +match.index;\n if (pos <= fromIndex) {\n result = pos;\n }\n\n pos += 1;\n }\n\n return result;\n }\n });\n }\n}());\n\n(function () {\n 'use strict';\n\n /*\n * testing as follow to make sure that at least for one character regexp,\n * the result is the same as if we used indexOf\n */\n\n var pre = document.getElementById('out');\n\n function log(result) {\n pre.appendChild(document.createTextNode(result + '\\n'));\n }\n\n function test(str) {\n var i = str.length + 2,\n r,\n a,\n b;\n\n while (i) {\n a = str.indexOf('a', i);\n b = str.searchOf(/a/, i);\n r = ['Failed', 'searchOf', str, i, a, b];\n if (a === b) {\n r[0] = 'Passed';\n }\n\n log(r);\n a = str.lastIndexOf('a', i);\n b = str.searchLastOf(/a/, i);\n r = ['Failed', 'searchLastOf', str, i, a, b];\n if (a === b) {\n r[0] = 'Passed';\n }\n\n log(r);\n i -= 1;\n }\n }\n\n /*\n * Look for the a among the xes\n */\n\n test('xxx');\n test('axx');\n test('xax');\n test('xxa');\n test('axa');\n test('xaa');\n test('aax');\n test('aaa');\n}()); <pre id=\"out\"></pre>"
},
{
"answer_id": 56451404,
"author": "Armin Bu",
"author_id": 2587809,
"author_profile": "https://Stackoverflow.com/users/2587809",
"pm_score": 0,
"selected": false,
"text": "interface String {\n reverse(): string;\n lastIndex(regex: RegExp): number;\n}\n\nString.prototype.reverse = function(this: string) {\n return this.split(\"\")\n .reverse()\n .join(\"\");\n};\n\nString.prototype.lastIndex = function(this: string, regex: RegExp) {\n const exec = regex.exec(this.reverse());\n return exec === null ? -1 : this.length - 1 - exec.index;\n};\n"
},
{
"answer_id": 57053741,
"author": "wfreude",
"author_id": 7796844,
"author_profile": "https://Stackoverflow.com/users/7796844",
"pm_score": 0,
"selected": false,
"text": "String.prototype.match(regex) regex function getLastIndex(text, regex, limit = text.length) {\n const matches = text.match(regex);\n\n // no matches found\n if (!matches) {\n return -1;\n }\n\n // matches found but first index greater than limit\n if (text.indexOf(matches[0] + matches[0].length) > limit) {\n return -1;\n }\n\n // reduce index until smaller than limit\n let i = matches.length - 1;\n let index = text.lastIndexOf(matches[i]);\n while (index > limit && i >= 0) {\n i--;\n index = text.lastIndexOf(matches[i]);\n }\n return index > limit ? -1 : index;\n}\n\n// expect -1 as first index === 14\nconsole.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\\. /g, 10));\n\n// expect 29\nconsole.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\\. /g));"
},
{
"answer_id": 57740885,
"author": "user984003",
"author_id": 984003,
"author_profile": "https://Stackoverflow.com/users/984003",
"pm_score": 0,
"selected": false,
"text": "var mystring = \"abc ab a\";\nvar re = new RegExp(\"ab\"); // any regex here\n\nif ( re.exec(mystring) != null ){ \n alert(\"matches\"); // true in this case\n}\n var re = new RegExp(\"^ab\"); // At front\nvar re = new RegExp(\"ab$\"); // At end\nvar re = new RegExp(\"ab(c|d)\"); // abc or abd\n"
},
{
"answer_id": 68181020,
"author": "Oliver",
"author_id": 2046109,
"author_profile": "https://Stackoverflow.com/users/2046109",
"pm_score": 2,
"selected": false,
"text": "String.prototype.replace let firstIndex = -1;\n\"the 1st numb3r\".replace(/\\d/,(p,i) => { firstIndex = i; });\n// firstIndex === 4\n let lastIndex = -1;\n\"the l4st numb3r\".replace(/\\d/g,(p,i) => { lastIndex = i; });\n// lastIndex === 13\n -1 function indexOfRegex(str,regex,start = 0) {\n regex = regex.global ? regex : new RegExp(regex.source,regex.flags + \"g\");\n let index = -1;\n str.replace(regex,function() {\n const pos = arguments[arguments.length - 2];\n if(index < 0 && pos >= start)\n index = pos;\n });\n return index;\n}\n\nfunction lastIndexOfRegex(str,regex,start = str.length - 1) {\n regex = regex.global ? regex : new RegExp(regex.source,regex.flags + \"g\");\n let index = -1;\n str.replace(regex,function() {\n const pos = arguments[arguments.length - 2];\n if(pos <= start)\n index = pos;\n });\n return index;\n}\n"
},
{
"answer_id": 69110638,
"author": "user16864806",
"author_id": 16864806,
"author_profile": "https://Stackoverflow.com/users/16864806",
"pm_score": 0,
"selected": false,
"text": "let regExp; // your RegExp here\narr.map(x => !!x.toString().match(regExp)).indexOf(true)"
},
{
"answer_id": 71609276,
"author": "Tyler V.",
"author_id": 1038564,
"author_profile": "https://Stackoverflow.com/users/1038564",
"pm_score": 1,
"selected": false,
"text": "function regexLastIndexOf(string, regex, startpos=0) {\n return text.length - regexIndexOf([...text].reverse().join(\"\"), regex, startpos) - 1;\n}\n"
},
{
"answer_id": 73584108,
"author": "ruohola",
"author_id": 9835872,
"author_profile": "https://Stackoverflow.com/users/9835872",
"pm_score": 0,
"selected": false,
"text": "String.prototype.matchAll() Array.prototype.at() const str = \"foo a foo B\";\nconst matches = [...str.matchAll(/[abc]/gi)];\n\nif (matches.length) {\n const indexOfFirstMatch = matches.at(0).index;\n const indexOfLastMatch = matches.at(-1).index;\n console.log(indexOfFirstMatch, indexOfLastMatch)\n}"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] |
273,794
|
<p>Similar to <a href="https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships">this question</a> but for MySQL....</p>
<p>How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with:</p>
<pre><code>SHOW TABLE STATUS WHERE Name = 'MyTableName';
</code></pre>
<p>...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it. There must be some other way...</p>
<p>I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works.</p>
<p>Note: I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.</p>
|
[
{
"answer_id": 273812,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS"
},
{
"answer_id": 273907,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": true,
"text": "INFORMATION_SCHEMA.TABLE_CONSTRAINTS INFORMATION_SCHEMA.KEY_COLUMN_USAGE SELECT CONCAT( table_name, '.', column_name, ' -> ', \n referenced_table_name, '.', referenced_column_name ) AS list_of_fks \nFROM INFORMATION_SCHEMA.key_column_usage \nWHERE referenced_table_schema = 'test' \n AND referenced_table_name IS NOT NULL \nORDER BY table_name, column_name;\n test"
},
{
"answer_id": 11860718,
"author": "JavierCane",
"author_id": 967124,
"author_profile": "https://Stackoverflow.com/users/967124",
"pm_score": 3,
"selected": false,
"text": "SELECT CONSTRAINT_SCHEMA AS db,\n CONCAT (\n TABLE_NAME,\n '.',\n COLUMN_NAME,\n ' -> ',\n REFERENCED_TABLE_NAME,\n '.',\n REFERENCED_COLUMN_NAME\n ) AS relationship \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_NAME = 'your_table_name'\nORDER BY CONSTRAINT_SCHEMA,\n TABLE_NAME,\n COLUMN_NAME;\n"
},
{
"answer_id": 37545164,
"author": "Bkeshh Mhrjn",
"author_id": 6404516,
"author_profile": "https://Stackoverflow.com/users/6404516",
"pm_score": -1,
"selected": false,
"text": "SELECT TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_NAME = 'table_name'\n AND TABLE_SCHEMA = 'table_schema';\n"
},
{
"answer_id": 60381666,
"author": "kinsay",
"author_id": 9156012,
"author_profile": "https://Stackoverflow.com/users/9156012",
"pm_score": 0,
"selected": false,
"text": "SELECT kcu.referenced_table_schema, kcu.constraint_name, kcu.table_name, kcu.column_name, kcu.referenced_table_name, kcu.referenced_column_name, \n rc.update_rule, rc.delete_rule \nFROM INFORMATION_SCHEMA.key_column_usage kcu\nJOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on kcu.constraint_name = rc.constraint_name\nWHERE kcu.referenced_table_schema = 'db_name' \nAND kcu.referenced_table_name IS NOT NULL \nORDER BY kcu.table_name, kcu.column_name\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23934/"
] |
273,809
|
<p>I have a bunch of controls on my window. One of them is a refresh button that performs a cumbersome task on a background thread.</p>
<p>When the user clicks the refresh button, I put the cursor in a wait (hourglass) status and disable the whole window -- <code>Me.IsEnabled = False</code>.</p>
<p>I'd like to support cancellation of the refresh action by letting the user click a cancel button, but I can't facilitate this while the whole window is disabled.</p>
<p>Is there a way to do this besides disabling each control (except for the cancel button) one by one and then re-enabling them one by one when the user clicks cancel?</p>
|
[
{
"answer_id": 273852,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 6,
"selected": true,
"text": "<StackPanel Orientation=\"Horizontal\">\n <StackPanel x:Name=\"controlContainer\" Orientation=\"Horizontal\">\n <!-- Other Buttons Here -->\n </StackPanel>\n <Button Content=\"Cancel\" />\n</StackPanel>\n controlContainer.IsEnabled = false;\n"
},
{
"answer_id": 4927138,
"author": "DJR",
"author_id": 607211,
"author_profile": "https://Stackoverflow.com/users/607211",
"pm_score": 3,
"selected": false,
"text": "foreach (Control ctrl in this.Controls)\n ctrl.Enabled = false;\n\nCancelButton.Enabled = true;\n this.Enabled = false;"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
273,847
|
<p>I'm developing multi-language support for our web app. We're using <a href="http://docs.djangoproject.com/en/dev/topics/i18n/" rel="noreferrer">Django's helpers</a> around the <a href="http://en.wikipedia.org/wiki/Gettext" rel="noreferrer">gettext</a> library. Everything has been surprisingly easy, except for the question of how to handle sentences that include significant HTML markup. Here's a simple example:</p>
<pre><code>Please <a href="/login/">log in</a> to continue.
</code></pre>
<p>Here are the approaches I can think of:</p>
<ol>
<li><p>Change the link to include the whole sentence. Regardless of whether the change is a good idea in this case, the problem with this solution is that UI becomes dependent on the needs of i18n when the two are ideally independent.</p></li>
<li><p>Mark the whole string above for translation (formatting included). The translation strings would then also include the HTML directly. The problem with this is that changing the HTML formatting requires changing all the translation.</p></li>
<li><p>Tightly couple multiple translations, then use string interpolation to combine them. For the example, the phrase "Please %s to continue" and "log in" could be marked separately for translation, then combined. The "log in" is localized, then wrapped in the HREF, then inserted into the translated phrase, which keeps the %s in translation to mark where the link should go. This approach complicates the code and breaks the independence of translation strings.</p></li>
</ol>
<p>Are there any other options? How have others solved this problem?</p>
|
[
{
"answer_id": 273914,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 3,
"selected": false,
"text": "<strong /> Please <a href=\"%s\">log in</a> to continue.\n"
},
{
"answer_id": 274037,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 4,
"selected": false,
"text": "loginLink=Please <a href=\"/login\">log in</a> to continue\n // tokens in this string add html links\nloginLink=Please {0}log in{1} to continue\n loginLink=Please %startlink%log in%endlink% to continue\n"
},
{
"answer_id": 276526,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 1,
"selected": false,
"text": "makemessages {% load i18n %}\n{% trans 'hello <a href=\"/\">world</a>' %}\n python manage.py makemessages #: templates/out.html:3\nmsgid \"hello <a href=\\\"/\\\">world</a>\"\nmsgstr \"\"\n #: templates/out.html:3\nmsgid \"hello <a href=\\\"/\\\">world</a>\"\nmsgstr \"bonjour <a href=\\\"/\\\">monde</a>\"\n blocktrans"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,848
|
<p>I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this:</p>
<pre><code>public string GetCheckboxHtml()
{
return ("&lt;input type="checkbox" name="somename" /&gt;");
}
</code></pre>
<p>Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead:</p>
<pre><code>var checkbox = new HtmlCheckbox(attributes);
return checkbox.Html();
</code></pre>
<p>I just can't think of the correct namespace to look for this or the correct search term to use in Google.</p>
|
[
{
"answer_id": 273866,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 2,
"selected": false,
"text": "var input = new XElement(\"input\",\n new XAttribute(\"type\", \"checkbox\"),\n new XAttribute(\"name\", \"somename\"));\n\nreturn input.ToString();\n"
},
{
"answer_id": 273873,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "HtmlInputCheckBox box = new HtmlInputCheckBox();\n\nStringBuilder sb = new StringBuilder();\nusing(StringWriter sw = new StringWriter(sb))\nusing(HtmlTextWriter htw = new HtmlTextWriter(sw))\n{\n box.RenderControl(htw);\n}\nstring html = sb.ToString();\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,854
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/26094/most-efficient-implementation-of-a-large-number-class">Most efficient implementation of a large number class</a> </p>
</blockquote>
<p>Suppose I needed to calculate 2^150000. Obviously that number is going to exceed the size of an int, float, or double. How can I make a data type that allows normal math functions but exceeds the basic number types?</p>
<p>If this is a "depends which language you use" kind of deal. I will say C#.</p>
|
[
{
"answer_id": 273861,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 1,
"selected": false,
"text": "bc"
},
{
"answer_id": 273893,
"author": "Bjarke Ebert",
"author_id": 31890,
"author_profile": "https://Stackoverflow.com/users/31890",
"pm_score": 2,
"selected": false,
"text": "2**150000"
},
{
"answer_id": 273906,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 1,
"selected": false,
"text": "cl-user(2): (time (expt 2 150000))\n; cpu time (non-gc) 0 msec user, 0 msec system\n; cpu time (gc) 0 msec user, 0 msec system\n; cpu time (total) 0 msec user, 0 msec system\n; real time 1 msec\n; space allocation:\n; 2 cons cells, 18,784 other bytes, 0 static bytes\n"
},
{
"answer_id": 274181,
"author": "AndyUK",
"author_id": 6795,
"author_profile": "https://Stackoverflow.com/users/6795",
"pm_score": 1,
"selected": false,
"text": " 3 * (4 + 1)\n 15\n 3 * 19 ^ 43 - 1\n 29075426613099201338473141505176993450849249622191102976\n 2 ^ 23209 - 1\n 402874115778988778181873329071 ... loads of digits ... 3779264511\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
] |
273,869
|
<p>The topic generically says it all. Basically in a situation like this:</p>
<pre><code>boost::scoped_array<int> p(new int[10]);
</code></pre>
<p>Is there any appreciable difference in performance between doing: <code>&p[0]</code> and <code>p.get()</code>?</p>
<p>I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace p with a native pointer or array and not have to change anything else.</p>
<p>I am guessing since get is a one liner "<code>return ptr;</code>" that the compiler will inline that, and I hope that it is smart enough to to inline <code>operator[]</code> in such a way that it is able to not dereference and then immediately reference.</p>
<p>Anyone know?</p>
|
[
{
"answer_id": 273900,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "T * scoped_array::get() const // never throws\n{\n return ptr;\n}\n\nT & scoped_array::operator[](std::ptrdiff_t i) const // never throws\n{\n BOOST_ASSERT(ptr != 0);\n BOOST_ASSERT(i >= 0);\n return ptr[i];\n}\n"
},
{
"answer_id": 273945,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": true,
"text": "&p[0] p.get() operator[] &p[0] operator[] operator[] #if #include <boost/scoped_array.hpp>\n#include <cstdio>\n\nint main() {\n boost::scoped_array<int> p(new int[10]);\n#if 1\n printf(\"%p\\n\", &p[0]);\n#else\n printf(\"%p\\n\", p.get());\n#endif\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13430/"
] |
273,898
|
<p>I have two forms in microsoft access, one called Bill and the other one called Payment. They both have Total amount as a field in both of the forms. I am trying to reference the Bill total amount to the Payment total amount. </p>
<p>I have tried in the Payment total amount control source : =Forms!Bill![Total Amount]</p>
<p>but this doesnt seem to work. In Design view it says '#Name?' in the text box. </p>
<p>How would you do this? </p>
|
[
{
"answer_id": 273950,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "Me.Parent.[Total order]\nMe.[Subform Control name Here].form.[Total order]\n"
},
{
"answer_id": 274059,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "=Forms(\"Bill\")![Total order]\n"
},
{
"answer_id": 277718,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "dsum(Forms(\"Bill\").recordsource, \"unitPrice*lineQuantity\")\n Dim rs as DAO.recordset, _\n myBillNumber as variant, _\n myBillAmount as variant\n\nset rs = currentDb.openRecordset(_ \n \"SELECT billNumber, sum(unitPrice*lineQuantity) as totalPrice FROM \" & _\n Forms(\"Bill\").recordset.name \" GROUP BY billNumber\")\n\nmyBillNumber = rs.fields(0)\nmyBillAmount = rs.fields(1)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
273,908
|
<p>Problem: I have an integer; this integer needs to be converted to a stl::string type. </p>
<p>In the past, I've used <code>stringstream</code> to do a conversion, and that's just kind of cumbersome. I know the C way is to do a <code>sprintf</code>, but I'd much rather do a C++ method that is typesafe(er).</p>
<p>Is there a better way to do this? </p>
<p>Here is the stringstream approach I have used in the past:</p>
<pre><code>std::string intToString(int i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
</code></pre>
<p>Of course, this could be rewritten as so:</p>
<pre><code>template<class T>
std::string t_to_string(T i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
</code></pre>
<p>However, I have the notion that this is a fairly 'heavy-weight' implementation.</p>
<p>Zan noted that the invocation is pretty nice, however:</p>
<pre><code>std::string s = t_to_string(my_integer);
</code></pre>
<p>At any rate, a nicer way would be... nice. </p>
<blockquote>
<h3>Related:</h3>
<p><a href="https://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c">Alternative to itoa() for converting integer to string C++?</a> </p>
</blockquote>
|
[
{
"answer_id": 273961,
"author": "Mic",
"author_id": 35656,
"author_profile": "https://Stackoverflow.com/users/35656",
"pm_score": 5,
"selected": false,
"text": "#include <boost/lexical_cast.hpp>\nstd::string s = boost::lexical_cast<std::string>(i);\n try{\n std::string s = boost::lexical_cast<std::string>(i);\n}catch(boost::bad_lexical_cast &){\n ...\n}\n"
},
{
"answer_id": 8362045,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": true,
"text": "#include <string>\nstring s = std::to_string(123);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26227/"
] |
273,909
|
<p>Is there a idiomatic way of removing elements from PATH-like shell variables?</p>
<p>That is I want to take</p>
<pre><code>PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:/path/to/app/bin:.
</code></pre>
<p>and <strong>remove</strong> or <strong>replace</strong> the <code>/path/to/app/bin</code> without clobbering the rest of the variable. Extra points for allowing me <em>put</em> new elements in arbitrary positions. The target will be recognizable by a well defined string, and may occur at any point in the list.</p>
<p>I know I've seen this done, and can probably cobble something together on my own, but I'm looking for a nice approach. Portability and standardization a plus.</p>
<p>I use bash, but example are welcome in your favorite shell as well.</p>
<hr>
<p>The context here is one of needing to switch conveniently between multiple versions (one for doing analysis, another for working on the framework) of a large scientific analysis package which produces a couple dozen executables, has data stashed around the filesystem, and uses environment variable to help find all this stuff. I would like to write a script that selects a version, and need to be able to remove the <code>$PATH</code> elements relating to the currently active version and replace them with the same elements relating to the new version.</p>
<hr>
<p>This is related to the problem of preventing repeated <code>$PATH</code> elements when re-running login scripts and the like.</p>
<hr>
<ul>
<li>Previous similar question: <a href="https://stackoverflow.com/questions/135754/how-to-keep-from-duplicating-path-variable-in-csh">How to keep from duplicating path variable in csh</a></li>
<li>Subsequent similar question: <a href="https://stackoverflow.com/questions/370047/what-is-the-most-elegant-way-to-remove-a-path-from-the-path-variable-in-bash">What is the most elegant way to remove a path from the $PATH variable in Bash?</a></li>
</ul>
|
[
{
"answer_id": 273998,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\nNEW_PATH=$(echo -n $PATH | tr \":\" \"\\n\" | sed \"/foo/d\" | tr \"\\n\" \":\")\nexport PATH=$NEW_PATH\n echo -n $PATH | tr \":\" \"\\n\" | sort | uniq -c | sed -n \"/ 1 / s/.*1 \\(.*\\)/\\1/p\" | sed \"/foo/d\" | tr \"\\n\" \":\"\n"
},
{
"answer_id": 274448,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "export PATH=$(clnpath $head_dirs:$PATH:$tail_dirs $remove_dirs)\n"
},
{
"answer_id": 275035,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "# path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace-path PATH $PATH /exact/path/to/remove \n# replace-path-pattern PATH $PATH <grep pattern for target path> \n#\n# To replace a path:\n# replace-path PATH $PATH /exact/path/to/remove /replacement/path \n# replace-path-pattern PATH $PATH <target pattern> /replacement/path\n# \n###############################################################################\n# Finds the _first_ list element matching $2\n#\n# $1 name of a shell variable to be set\n# $2 name of a variable with a path-like structure\n# $3 a grep pattern to match the desired element of $1\nfunction path-element-by-pattern (){ \n target=$1;\n list=$2;\n pat=$3;\n\n export $target=$(echo -n $list | tr \":\" \"\\n\" | grep -m 1 $pat);\n return\n}\n\n# Removes or replaces an element of $1\n#\n# $1 name of the shell variable to set (i.e. PATH) \n# $2 a \":\" delimited list to work from (i.e. $PATH)\n# $2 the precise string to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace-path () {\n path=$1;\n list=$2;\n removestr=$3;\n replacestr=$4; # Allowed to be \"\"\n\n export $path=$(echo -n $list | tr \":\" \"\\n\" | sed \"s|$removestr|$replacestr|\" | tr \"\\n\" \":\" | sed \"s|::|:|g\");\n unset removestr\n return \n}\n\n# Removes or replaces an element of $1\n#\n# $1 name of the shell variable to set (i.e. PATH) \n# $2 a \":\" delimited list to work from (i.e. $PATH)\n# $2 a grep pattern identifying the element to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace-path-pattern () {\n path=$1;\n list=$2;\n removepat=$3; \n replacestr=$4; # Allowed to be \"\"\n\n path-element-by-pattern removestr $list $removepat;\n replace-path $path $list $removestr $replacestr;\n}\n . /include/path/path_tools.bash replace-path*"
},
{
"answer_id": 294025,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "export replace-path PATH $PATH /usr .\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n replace-path PATH $PATH /usr .\n/Users/jleffler/bin\n/local/postgresql/bin\n/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/local/bin\n/bin\n/bin\n/sw/bin\n/sbin\n/sbin\n replace-path sed export $path=$(echo -n $list | tr \":\" \"\\n\" | sed \"s:^$removestr\\$:$replacestr:\" |\n tr \"\\n\" \":\" | sed \"s|::|:|g\")\n sed PATH=/bin::/usr/local/bin\n path-element-by-pattern export $target=$(echo -n $list | tr \":\" \"\\n\" | grep -m 1 \"^$pat\\$\")\n grep -m 1 -n echo $removestr # path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace_path PATH $PATH /exact/path/to/remove\n# replace_path_pattern PATH $PATH <grep pattern for target path>\n#\n# To replace a path:\n# replace_path PATH $PATH /exact/path/to/remove /replacement/path\n# replace_path_pattern PATH $PATH <target pattern> /replacement/path\n#\n###############################################################################\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a \":\" delimited list to work from (e.g. $PATH)\n# $3 the precise string to be removed/replaced\n# $4 the replacement string (use \"\" for removal)\nfunction replace_path () {\n path=$1\n list=$2\n remove=$3\n replace=$4 # Allowed to be empty or unset\n\n export $path=$(echo \"$list\" | tr \":\" \"\\n\" | sed \"s:^$remove\\$:$replace:\" |\n tr \"\\n\" \":\" | sed 's|:$||')\n}\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a \":\" delimited list to work from (e.g. $PATH)\n# $3 a grep pattern identifying the element to be removed/replaced\n# $4 the replacement string (use \"\" for removal)\nfunction replace_path_pattern () {\n path=$1\n list=$2\n removepat=$3\n replacestr=$4 # Allowed to be empty or unset\n\n removestr=$(echo \"$list\" | tr \":\" \"\\n\" | grep -m 1 \"^$removepat\\$\")\n replace_path \"$path\" \"$list\" \"$removestr\" \"$replacestr\"\n}\n echopath #!/usr/bin/perl -w\n#\n# \"@(#)$Id: echopath.pl,v 1.7 1998/09/15 03:16:36 jleffler Exp $\"\n#\n# Print the components of a PATH variable one per line.\n# If there are no colons in the arguments, assume that they are\n# the names of environment variables.\n\n@ARGV = $ENV{PATH} unless @ARGV;\n\nforeach $arg (@ARGV)\n{\n $var = $arg;\n $var = $ENV{$arg} if $arg =~ /^[A-Za-z_][A-Za-z_0-9]*$/;\n $var = $arg unless $var;\n @lst = split /:/, $var;\n foreach $val (@lst)\n {\n print \"$val\\n\";\n }\n}\n echo\nxpath=$PATH\nreplace_path xpath $xpath /usr\nechopath $xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath $xpath /usr/bin /work/bin\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath $xpath \"/usr/.*/bin\" /work/bin\nechopath xpath\n .\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n\n.\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/work/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n\n.\n/Users/jleffler/bin\n/work/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n echopath LD_LIBRARY_PATH $LD_LIBRARY_PATH replace_path PATH /usr/bin /work/bin\n list=$(eval echo '$'$path)\n # path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace_path PATH /exact/path/to/remove\n# replace_path_pattern PATH <grep pattern for target path>\n#\n# To replace a path:\n# replace_path PATH /exact/path/to/remove /replacement/path\n# replace_path_pattern PATH <target pattern> /replacement/path\n#\n###############################################################################\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 the precise string to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace_path () {\n path=$1\n list=$(eval echo '$'$path)\n remove=$2\n replace=$3 # Allowed to be empty or unset\n\n export $path=$(echo \"$list\" | tr \":\" \"\\n\" | sed \"s:^$remove\\$:$replace:\" |\n tr \"\\n\" \":\" | sed 's|:$||')\n}\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a grep pattern identifying the element to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace_path_pattern () {\n path=$1\n list=$(eval echo '$'$path)\n removepat=$2\n replacestr=$3 # Allowed to be empty or unset\n\n removestr=$(echo \"$list\" | tr \":\" \"\\n\" | grep -m 1 \"^$removepat\\$\")\n replace_path \"$path\" \"$removestr\" \"$replacestr\"\n}\n echo\nxpath=$PATH\nreplace_path xpath /usr\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath /usr/bin /work/bin\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath \"/usr/.*/bin\" /work/bin\nechopath xpath\n"
},
{
"answer_id": 294156,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 2,
"selected": false,
"text": "${parameter/pattern/string} / # % / @ * @ * $IFS"
},
{
"answer_id": 346860,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "{\n for(i=1;i<=NF;i++) \n if($i == REM) \n if(REP)\n print REP; \n else\n continue;\n else \n print $i; \n}\n function path_repl {\n echo $PATH | awk -F: -f rem.awk REM=\"$1\" REP=\"$2\" | paste -sd:\n}\n\n$ echo $PATH\n/bin:/usr/bin:/home/js/usr/bin\n$ path_repl /bin /baz\n/baz:/usr/bin:/home/js/usr/bin\n$ path_repl /bin\n/usr/bin:/home/js/usr/bin\n { \n if(IDX < 1) IDX = NF + IDX + 1\n for(i = 1; i <= NF; i++) {\n if(IDX == i) \n print REP \n print $i\n }\n if(IDX == NF + 1)\n print REP\n}\n function path_app {\n echo $PATH | awk -F: -f app.awk REP=\"$1\" IDX=\"$2\" | paste -sd:\n}\n\n$ echo $PATH\n/bin:/usr/bin:/home/js/usr/bin\n$ path_app /baz 0\n/bin:/usr/bin:/home/js/usr/bin:/baz\n$ path_app /baz -1\n/bin:/usr/bin:/baz:/home/js/usr/bin\n$ path_app /baz 1\n/baz:/bin:/usr/bin:/home/js/usr/bin\n { \n for(i = 1; i <= NF; i++) {\n if(!used[$i]) {\n print $i\n used[$i] = 1\n }\n }\n}\n echo $PATH | awk -F: -f rem_dup.awk | paste -sd:\n echo -n $PATH | xargs -d: stat -c %n\n test echo -n $PATH | xargs -d: -n1 test -d\n"
},
{
"answer_id": 373476,
"author": "nicerobot",
"author_id": 23056,
"author_profile": "https://Stackoverflow.com/users/23056",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\nIFS=:\n# convert it to an array\nt=($PATH)\nunset IFS\n# perform any array operations to remove elements from the array\nt=(${t[@]%%*usr*})\nIFS=:\n# output the new array\necho \"${t[*]}\"\n PATH=$(IFS=':';t=($PATH);unset IFS;t=(${t[@]%%*usr*});IFS=':';echo \"${t[*]}\");\n"
},
{
"answer_id": 7593620,
"author": "nash",
"author_id": 970554,
"author_profile": "https://Stackoverflow.com/users/970554",
"pm_score": 1,
"selected": false,
"text": "echo $PATH\n/usr/lib/jvm/java-1.6.0/bin:lib/jvm/java-1.6.0/bin/:/lib/jvm/java-1.6.0/bin/:/usr/lib/qt-3.3/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/tvnadeesh/bin\n export PATH=$(echo $PATH | sed 's/\\/lib\\/jvm\\/java-1.6.0\\/bin\\/://g')\n sed echo $PATH"
},
{
"answer_id": 11939195,
"author": "GreenFox",
"author_id": 1594168,
"author_profile": "https://Stackoverflow.com/users/1594168",
"pm_score": 1,
"selected": false,
"text": "function __path_add(){ \n if [ -d \"$1\" ] ; then \n local D=\":${PATH}:\"; \n [ \"${D/:$1:/:}\" == \"$D\" ] && PATH=\"$PATH:$1\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n fi \n}\nfunction __path_remove(){ \n local D=\":${PATH}:\"; \n [ \"${D/:$1:/:}\" != \"$D\" ] && PATH=\"${D/:$1:/:}\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n} \n# Just for the shake of completeness\nfunction __path_replace(){ \n if [ -d \"$2\" ] ; then \n local D=\":${PATH}:\"; \n if [ \"${D/:$1:/:}\" != \"$D\" ] ; then\n PATH=\"${D/:$1:/:$2:}\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n fi\n fi \n} \n"
},
{
"answer_id": 25749546,
"author": "derekm",
"author_id": 2355587,
"author_profile": "https://Stackoverflow.com/users/2355587",
"pm_score": 0,
"selected": false,
"text": "ld_library_path=${ORACLE_HOME}/lib\nLD_LIBRARY_PATH=${LD_LIBRARY_PATH//${ld_library_path}?(:)/}\nexport LD_LIBRARY_PATH=${ld_library_path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n"
},
{
"answer_id": 56151409,
"author": "Steeve McCauley",
"author_id": 916462,
"author_profile": "https://Stackoverflow.com/users/916462",
"pm_score": 1,
"selected": false,
"text": "# add it to the path\nPATH=~/bin/:$PATH:~/bin\nexport PATH=$(ruby -e 'puts ENV[\"PATH\"].split(/:/).uniq.join(\":\")')\n mungepath() {\n export PATH=$(ruby -e 'puts ENV[\"PATH\"].split(/:/).uniq.join(\":\")')\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2509/"
] |
273,929
|
<p><strong>In Oracle I can declare a reference cursor...</strong></p>
<pre><code>TYPE t_spool IS REF CURSOR RETURN spool%ROWTYPE;
</code></pre>
<p><strong>...and use it to pass a cursor as the return value...</strong></p>
<pre><code>FUNCTION end_spool
RETURN t_spool
AS
v_spool t_spool;
BEGIN
COMMIT;
OPEN v_spool FOR
SELECT
*
FROM
spool
WHERE
key = g_spool_key
ORDER BY
seq;
RETURN v_spool;
END end_spool;
</code></pre>
<p><strong>...and then capture it as a result set using JDBC...</strong></p>
<pre><code>private Connection conn;
private CallableStatement stmt;
private OracleResultSet rset;
[...clip...]
stmt = conn.prepareCall("{ ? = call " + call + "}");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.execute();
rset = (OracleResultSet)stmt.getObject(1);
</code></pre>
<p><strong>What is the equivalent in MySQL?</strong></p>
|
[
{
"answer_id": 445434,
"author": "Yoni",
"author_id": 36071,
"author_profile": "https://Stackoverflow.com/users/36071",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE `TEST`()\nMODIFIES SQL DATA\nBEGIN\n SELECT * FROM test_table;\nEND;\n String query = \"{CALL TEST()}\";\nCallableStatement cs = con.prepareCall(query,\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY);\nResultSet rs = cs.executeQuery();\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
273,937
|
<p>I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. </p>
<p>Here is the code</p>
<pre><code>import wx
class mainPanel(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450))
wx.Panel(self,-1)
wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10))
menubar = wx.MenuBar()
parser = wx.Menu()
one =wx.MenuItem(parser,1,'&Extract Tables with One Heading or Label')
two =wx.MenuItem(parser,1,'&Extract Tables with Two Headings or Labels')
three =wx.MenuItem(parser,1,'&Extract Tables with Three Headings or Labels')
four =wx.MenuItem(parser,1,'&Extract Tables with Four Headings or Labels')
quit = wx.MenuItem(parser, 2, '&Quit\tCtrl+Q')
parser.AppendItem(one)
parser.AppendItem(two)
parser.AppendItem(three)
parser.AppendItem(four)
parser.AppendItem(quit)
menubar.Append(parser, '&Table Parsers')
textRip = wx.Menu()
section =wx.MenuItem(parser,1,'&Extract Text With Section Headings')
textRip.AppendItem(section)
menubar.Append(textRip, '&Text Rippers')
dataHandling = wx.Menu()
deHydrate =wx.MenuItem(dataHandling,1,'&Extract Data from Tables')
dataHandling.AppendItem(deHydrate)
menubar.Append(dataHandling, '&Data Extraction')
self.Bind(wx.EVT_MENU, self.OnQuit, id=2)
</code></pre>
<h1>this is where I think I am being clever by using a button click to create an instance</h1>
<h1>of subPanel.</h1>
<pre><code> self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1)
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
def OnQuit(self, event):
self.Close()
class subPanel(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450))
wx.Panel(self,-1)
wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10))
getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350))
getDirectory.SetDefault()
getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400))
getTerm1.SetDefault()
#getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button)
self.Centre()
self.Show(True)
app = wx.App()
mainPanel(None, -1, '')
app.MainLoop()
</code></pre>
|
[
{
"answer_id": 274004,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 1,
"selected": false,
"text": "self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1)\n self.Bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n self.Bind(wx.EVT_MENU, lambda(x): subPanel(None, -1, 'TEST'),id=1)\n"
},
{
"answer_id": 274145,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 1,
"selected": false,
"text": "import wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title=\"My Frame\", num=1):\n\n self.num = num\n wx.Frame.__init__(self, parent, -1, title)\n panel = wx.Panel(self)\n\n button = wx.Button(panel, -1, \"New Panel\")\n button.SetPosition((15, 15))\n self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button)\n self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\n # Now create a menu\n menubar = wx.MenuBar()\n self.SetMenuBar(menubar)\n\n # Panel menu\n panel_menu = wx.Menu()\n\n # The menu item\n menu_newpanel = wx.MenuItem(panel_menu,\n wx.NewId(),\n \"&New Panel\",\n \"Creates a new panel\",\n wx.ITEM_NORMAL)\n panel_menu.AppendItem(menu_newpanel)\n\n menubar.Append(panel_menu, \"&Panels\")\n # Bind the menu event\n self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel)\n\n def OnNewPanel(self, event):\n panel = MyFrame(self, \"Panel %s\" % self.num, self.num+1)\n panel.Show()\n\n def OnCloseWindow(self, event):\n self.Destroy()\n\ndef main():\n application = wx.PySimpleApp()\n frame = MyFrame(None)\n frame.Show()\n application.MainLoop()\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"answer_id": 274160,
"author": "DrBloodmoney",
"author_id": 35681,
"author_profile": "https://Stackoverflow.com/users/35681",
"pm_score": 1,
"selected": true,
"text": "self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n self.bind(wx.EVT_MENU, <event handler>, <id of menu item>)\n def OnMenuItem(self, evt): #don't forget the evt\n sp = SubPanel(self, wx.ID_ANY, 'TEST')\n #I assume you will add it to a sizer\n #if you aren't... you should\n test_sizer.Add(sp, 1, wx.EXPAND)\n #force the frame to refresh the sizers:\n self.Layout()\n __init__ subpanel.Hide() subpanel.Show() #!usr/bin/env python\n\nimport wx\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent, *args, **kwargs):\n wx.Frame.__init__(self, parent, *args, **kwargs)\n framesizer = wx.BoxSizer(wx.VERTICAL)\n mainpanel = MainPanel(self, wx.ID_ANY)\n self.subpanel = SubPanel(self, wx.ID_ANY)\n self.subpanel.Hide()\n framesizer.Add(mainpanel, 1, wx.EXPAND)\n framesizer.Add(self.subpanel, 1, wx.EXPAND)\n self.SetSizerAndFit(framesizer)\n\nclass MainPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n panelsizer = wx.BoxSizer(wx.VERTICAL)\n but = wx.Button(self, wx.ID_ANY, \"Add\")\n self.Bind(wx.EVT_BUTTON, self.OnAdd, but)\n self.panel_shown = False\n panelsizer.Add(but, 0)\n self.SetSizer(panelsizer)\n\n def OnAdd(self, evt):\n if not self.panel_shown:\n self.GetParent().subpanel.Show()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = True\n else:\n self.GetParent().subpanel.Hide()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = False\n\nclass SubPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n spsizer = wx.BoxSizer(wx.VERTICAL)\n text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel')\n spsizer.Add(text, 1, wx.EXPAND)\n self.SetSizer(spsizer)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = TestFrame(None, wx.ID_ANY, \"Test Frame\")\n frame.Show()\n app.MainLoop()\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30105/"
] |
273,941
|
<p>I am trying to write a function that will pull the name of a property and the type using syntax like below:</p>
<pre><code>private class SomeClass
{
Public string Col1;
}
PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>();
propertyMapper.MapProperty(x => x.Col1)
</code></pre>
<p>Is there any way to pass the property through to the function without any major changes to this syntax?</p>
<p>I would like to get the property name and the property type.</p>
<p>So in the example below i would want to retrieve </p>
<p><code>Name = "Col1"</code> and <code>Type = "System.String"</code></p>
<p>Can anyone help?</p>
|
[
{
"answer_id": 273971,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 7,
"selected": true,
"text": "public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)\n{\n var member = expression.Body as MemberExpression;\n if (member != null)\n return member.Member;\n\n throw new ArgumentException(\"Expression is not a member access\", \"expression\");\n}\n public class Program\n{\n public string Name\n {\n get { return \"My Program\"; }\n }\n\n static void Main()\n {\n MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name);\n Console.WriteLine(member.Name);\n }\n}\n (Program p) => p.Name"
},
{
"answer_id": 26766261,
"author": "chapacool",
"author_id": 4220232,
"author_profile": "https://Stackoverflow.com/users/4220232",
"pm_score": 2,
"selected": false,
"text": "public class PropertyMapper<T>\n{\n public virtual PropertyInfo PropertyInfo<U>(Expression<Func<T, U>> expression)\n {\n var member = expression.Body as MemberExpression;\n if (member != null && member.Member is PropertyInfo)\n return member.Member as PropertyInfo;\n\n throw new ArgumentException(\"Expression is not a Property\", \"expression\");\n }\n\n public virtual string PropertyName<U>(Expression<Func<T, U>> expression)\n {\n return PropertyInfo<U>(expression).Name;\n }\n\n public virtual Type PropertyType<U>(Expression<Func<T, U>> expression)\n {\n return PropertyInfo<U>(expression).PropertyType;\n }\n}\n PropertyMapper<SomeClass> propertyMapper = new PropertyMapper<SomeClass>();\nstring name = propertyMapper.PropertyName(x => x.Col1);\n"
},
{
"answer_id": 36487242,
"author": "TheRock",
"author_id": 5121114,
"author_profile": "https://Stackoverflow.com/users/5121114",
"pm_score": 2,
"selected": false,
"text": "public static class Helpers\n{\n public static string PropertyName<T>(Expression<Func<T>> expression)\n {\n var member = expression.Body as MemberExpression;\n if (member != null && member.Member is PropertyInfo)\n return member.Member.Name;\n\n throw new ArgumentException(\"Expression is not a Property\", \"expression\");\n }\n}\n Helpers.PropertyName(() => TestModel.TestProperty);\n"
},
{
"answer_id": 37966790,
"author": "Anand Patel",
"author_id": 6495286,
"author_profile": "https://Stackoverflow.com/users/6495286",
"pm_score": 2,
"selected": false,
"text": "nameof(User.UserId)\n typeof(User.UserId)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213936/"
] |
273,943
|
<p>Presuming I have a class named <code>A</code>, and I want to use the decorator design pattern. Correct me if I'm wrong, but for that to work , we'll need to create a decorator class, say <code>ADecorator</code>, which will hold a reference to an <code>A</code> instance, and all the other decorators will extend this to add functionality.</p>
<p>I don't understand why do we have to create a decorator class, instead of using an <code>A</code> instance?</p>
|
[
{
"answer_id": 274234,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 6,
"selected": true,
"text": "public double cost(){\n return 3.45;\n}\n public double cost(){\n return 3.80;\n}\n public abstract class Item{\n public abstract double cost();\n}\n public class Coffee extends Item{\n public double cost(){\n return 3.45;\n }\n}\n public abstract class CoffeeDecorator extends Item{\n private Item item;\n ...\n}\n public class Mocha extends CoffeeDecorator{\n\n public double cost(){\n return item.cost() + 0.5;\n }\n\n}\n public class Cream extends CoffeeDecorator{\n\n public double cost(){\n return item.cost() + 0.35;\n }\n\n}\n Item drink = new Cream(new Mocha(new Coffee))); //Mocha with cream\n Item drink = new Cream(new Mocha(new Cream(new Coffee))));//Mocha with double cream\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
273,946
|
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
|
[
{
"answer_id": 273962,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 10,
"selected": true,
"text": "min(maxwidth/width, maxheight/height) oldsize*ratio Image.thumbnail import os, sys\nimport Image\n\nsize = 128, 128\n\nfor infile in sys.argv[1:]:\n outfile = os.path.splitext(infile)[0] + \".thumbnail\"\n if infile != outfile:\n try:\n im = Image.open(infile)\n im.thumbnail(size, Image.Resampling.LANCZOS)\n im.save(outfile, \"JPEG\")\n except IOError:\n print \"cannot create thumbnail for '%s'\" % infile\n"
},
{
"answer_id": 364789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "half = 0.5\nout = im.resize( [int(half * s) for s in im.size] )\n"
},
{
"answer_id": 451580,
"author": "tomvon",
"author_id": 55959,
"author_profile": "https://Stackoverflow.com/users/55959",
"pm_score": 9,
"selected": false,
"text": "from PIL import Image\n\nbasewidth = 300\nimg = Image.open('somepic.jpg')\nwpercent = (basewidth/float(img.size[0]))\nhsize = int((float(img.size[1])*float(wpercent)))\nimg = img.resize((basewidth,hsize), Image.Resampling.LANCZOS)\nimg.save('somepic.jpg')\n"
},
{
"answer_id": 940368,
"author": "Franz",
"author_id": 79427,
"author_profile": "https://Stackoverflow.com/users/79427",
"pm_score": 6,
"selected": false,
"text": "im.thumbnail(size)\n im.thumbnail(size,Image.ANTIALIAS)\n"
},
{
"answer_id": 16689816,
"author": "Nips",
"author_id": 671391,
"author_profile": "https://Stackoverflow.com/users/671391",
"pm_score": 2,
"selected": false,
"text": "def imageResize(filepath):\n from PIL import Image\n file_dir=os.path.split(filepath)\n img = Image.open(filepath)\n\n if img.size[0] > img.size[1]:\n aspect = img.size[1]/120\n new_size = (img.size[0]/aspect, 120)\n else:\n aspect = img.size[0]/120\n new_size = (120, img.size[1]/aspect)\n img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])\n img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])\n\n if img.size[0] > img.size[1]:\n new_img = img.crop( (\n (((img.size[0])-120)/2),\n 0,\n 120+(((img.size[0])-120)/2),\n 120\n ) )\n else:\n new_img = img.crop( (\n 0,\n (((img.size[1])-120)/2),\n 120,\n 120+(((img.size[1])-120)/2)\n ) )\n\n new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])\n"
},
{
"answer_id": 30227474,
"author": "muZk",
"author_id": 2056593,
"author_profile": "https://Stackoverflow.com/users/2056593",
"pm_score": 6,
"selected": false,
"text": "new_width = 680\nnew_height = new_width * height / width \n new_height = 680\nnew_width = new_height * width / height\n img = img.resize((new_width, new_height), Image.ANTIALIAS)\n"
},
{
"answer_id": 32806728,
"author": "guettli",
"author_id": 633961,
"author_profile": "https://Stackoverflow.com/users/633961",
"pm_score": 3,
"selected": false,
"text": "from PIL import Image\nfrom resizeimage import resizeimage\n\ndef resize_file(in_file, out_file, size):\n with open(in_file) as fd:\n image = resizeimage.resize_thumbnail(Image.open(fd), size)\n image.save(out_file)\n image.close()\n\nresize_file('foo.tif', 'foo_small.jpg', (256, 256))\n pip install python-resize-image\n"
},
{
"answer_id": 36036843,
"author": "Mohideen bin Mohammed",
"author_id": 4453737,
"author_profile": "https://Stackoverflow.com/users/4453737",
"pm_score": 4,
"selected": false,
"text": "from PIL import Image\n\nimg = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg\nnew_width = 200\nnew_height = 300\nimg = img.resize((new_width, new_height), Image.ANTIALIAS)\nimg.save('output image name.png') # format may what you want *.png, *jpg, *.gif\n"
},
{
"answer_id": 50347460,
"author": "Shanness",
"author_id": 1606452,
"author_profile": "https://Stackoverflow.com/users/1606452",
"pm_score": 3,
"selected": false,
"text": "from PIL import Image\nfrom resizeimage import resizeimage\n\nfd_img = open('test-image.jpeg', 'r')\nimg = Image.open(fd_img)\nimg = resizeimage.resize_width(img, 200)\nimg.save('test-image-width.jpeg', img.format)\nfd_img.close()\n"
},
{
"answer_id": 50618150,
"author": "Alex",
"author_id": 3511819,
"author_profile": "https://Stackoverflow.com/users/3511819",
"pm_score": 2,
"selected": false,
"text": "def resize(img_path, max_px_size, output_folder):\n with Image.open(img_path) as img:\n width_0, height_0 = img.size\n out_f_name = os.path.split(img_path)[-1]\n out_f_path = os.path.join(output_folder, out_f_name)\n\n if max((width_0, height_0)) <= max_px_size:\n print('writing {} to disk (no change from original)'.format(out_f_path))\n img.save(out_f_path)\n return\n\n if width_0 > height_0:\n wpercent = max_px_size / float(width_0)\n hsize = int(float(height_0) * float(wpercent))\n img = img.resize((max_px_size, hsize), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path)\n return\n\n if width_0 < height_0:\n hpercent = max_px_size / float(height_0)\n wsize = int(float(width_0) * float(hpercent))\n img = img.resize((max_px_size, wsize), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path)\n return\n"
},
{
"answer_id": 54176442,
"author": "hoohoo-b",
"author_id": 5544999,
"author_profile": "https://Stackoverflow.com/users/5544999",
"pm_score": 3,
"selected": false,
"text": "from PIL import Image\n\nnew_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))\n"
},
{
"answer_id": 54314043,
"author": "noEmbryo",
"author_id": 5985925,
"author_profile": "https://Stackoverflow.com/users/5985925",
"pm_score": 2,
"selected": false,
"text": "Image.thumbnail from PIL import Image\n\ndef get_resized_img(img_path, video_size):\n img = Image.open(img_path)\n width, height = video_size # these are the MAX dimensions\n video_ratio = width / height\n img_ratio = img.size[0] / img.size[1]\n if video_ratio >= 1: # the video is wide\n if img_ratio <= video_ratio: # image is not wide enough\n width_new = int(height * img_ratio)\n size_new = width_new, height\n else: # image is wider than video\n height_new = int(width / img_ratio)\n size_new = width, height_new\n else: # the video is tall\n if img_ratio >= video_ratio: # image is not tall enough\n height_new = int(width / img_ratio)\n size_new = width, height_new\n else: # image is taller than video\n width_new = int(height * img_ratio)\n size_new = width_new, height\n return img.resize(size_new, resample=Image.LANCZOS)\n"
},
{
"answer_id": 55580396,
"author": "Siddhartha Mukherjee",
"author_id": 8548160,
"author_profile": "https://Stackoverflow.com/users/8548160",
"pm_score": 2,
"selected": false,
"text": "from io import BytesIO\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nimport os, sys\nfrom PIL import Image\n\n\ndef imageResize(image):\n outputIoStream = BytesIO()\n imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) \n imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') \n outputIoStream.seek(0)\n uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', \"%s.jpg\" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)\n\n ## For upload local folder\n fs = FileSystemStorage()\n filename = fs.save(uploadedImage.name, uploadedImage)\n"
},
{
"answer_id": 57990437,
"author": "Kanish Mathew",
"author_id": 8937480,
"author_profile": "https://Stackoverflow.com/users/8937480",
"pm_score": 2,
"selected": false,
"text": "from PIL import Image\n\nimg = Image.open(image_path)\n\nwidth, height = img.size[:2]\n\nif height > width:\n baseheight = 64\n hpercent = (baseheight/float(img.size[1]))\n wsize = int((float(img.size[0])*float(hpercent)))\n img = img.resize((wsize, baseheight), Image.ANTIALIAS)\n img.save('resized.jpg')\nelse:\n basewidth = 64\n wpercent = (basewidth/float(img.size[0]))\n hsize = int((float(img.size[1])*float(wpercent)))\n img = img.resize((basewidth,hsize), Image.ANTIALIAS)\n img.save('resized.jpg')\n"
},
{
"answer_id": 60273833,
"author": "user391339",
"author_id": 391339,
"author_profile": "https://Stackoverflow.com/users/391339",
"pm_score": 3,
"selected": false,
"text": "from PIL import Image\nim = Image.open(\"image.png\")\n display(im.resize((int(im.size[0]),int(im.size[1])), 0) )\n display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )\n display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )\n display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )\n"
},
{
"answer_id": 61567040,
"author": "RockOGOlic",
"author_id": 12720264,
"author_profile": "https://Stackoverflow.com/users/12720264",
"pm_score": 3,
"selected": false,
"text": "from PIL import Image\n\nimg_path = \"filename.png\";\nimg = Image.open(img_path); # puts our image to the buffer of the PIL.Image object\n\nwidth, height = img.size;\nasp_rat = width/height;\n\n# Enter new width (in pixels)\nnew_width = 50;\n\n# Enter new height (in pixels)\nnew_height = 54;\n\nnew_rat = new_width/new_height;\n\nif (new_rat == asp_rat):\n img = img.resize((new_width, new_height), Image.ANTIALIAS); \n\n# adjusts the height to match the width\n# NOTE: if you want to adjust the width to the height, instead -> \n# uncomment the second line (new_width) and comment the first one (new_height)\nelse:\n new_height = round(new_width / asp_rat);\n #new_width = round(new_height * asp_rat);\n img = img.resize((new_width, new_height), Image.ANTIALIAS);\n\n# usage: resize((x,y), resample)\n# resample filter -> PIL.Image.BILINEAR, PIL.Image.NEAREST (default), PIL.Image.BICUBIC, etc..\n# https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize\n\n# Enter the name under which you would like to save the new image\nimg.save(\"outputname.png\");\n"
},
{
"answer_id": 63224327,
"author": "666",
"author_id": 14017226,
"author_profile": "https://Stackoverflow.com/users/14017226",
"pm_score": -1,
"selected": false,
"text": "import cv2\nfrom skimage import data \nimport matplotlib.pyplot as plt\nfrom skimage.util import img_as_ubyte\nfrom skimage import io\nfilename='abc.png'\nimage=plt.imread(filename)\nim=cv2.imread('abc.png')\nprint(im.shape)\nim.resize(300,300)\nprint(im.shape)\nplt.imshow(image)\n"
},
{
"answer_id": 64680872,
"author": "Riz.Khan",
"author_id": 10485321,
"author_profile": "https://Stackoverflow.com/users/10485321",
"pm_score": 0,
"selected": false,
"text": "from PIL import Image\nimg = Image.open(\"D:\\\\Pictures\\\\John.jpg\")\nimg.thumbnail((680,680))\nimg.save(\"D:\\\\Pictures\\\\John_resize.jpg\")\n"
},
{
"answer_id": 65904414,
"author": "Vito Gentile",
"author_id": 738017,
"author_profile": "https://Stackoverflow.com/users/738017",
"pm_score": 3,
"selected": false,
"text": "Image.thumbnail sys.maxsize import sys\nfrom PIL import Image\n\nimage.thumbnail([sys.maxsize, 100], Image.ANTIALIAS)\n Image.thumbnail Image.resize Image.ANTIALIAS Resampling.LANCZOS import sys\nfrom PIL import Image\nfrom PIL.Image import Resampling\n\nimage.thumbnail([sys.maxsize, 100], Resampling.LANCZOS)\n"
},
{
"answer_id": 69232569,
"author": "mustafa candan",
"author_id": 6482263,
"author_profile": "https://Stackoverflow.com/users/6482263",
"pm_score": 2,
"selected": false,
"text": "image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)\n from PIL import Image, ImageGrab\nimage = ImageGrab.grab(bbox=(0,0,400,600)) #take screenshot\nimage = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)\nimage.save('Screen.png')\n"
},
{
"answer_id": 69866695,
"author": "Ruhul Amin",
"author_id": 5421542,
"author_profile": "https://Stackoverflow.com/users/5421542",
"pm_score": 2,
"selected": false,
"text": " from PIL import Image\n im = Image.open(\"image.jpg\")\n resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))\n \n #Save the cropped image\n resized_im.save('resizedimage.jpg')\n from PIL import Image\nnew_width = 300\nim = Image.open(\"img/7.jpeg\")\nconcat = int(new_width/float(im.size[0]))\nsize = int((float(im.size[1])*float(concat)))\nresized_im = im.resize((new_width,size), Image.ANTIALIAS)\n#Save the cropped image\nresized_im.save('resizedimage.jpg')\n"
},
{
"answer_id": 69989692,
"author": "Mohamed TOUATI",
"author_id": 11394480,
"author_profile": "https://Stackoverflow.com/users/11394480",
"pm_score": 2,
"selected": false,
"text": "# Importing Image class from PIL module\nfrom PIL import Image\n\n# Opens a image in RGB mode\nim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\ybear.jpg\")\n\n# Size of the image in pixels (size of original image)\n# (This is not mandatory)\nwidth, height = im.size\n\n# Setting the points for cropped image\nleft = 4\ntop = height / 5\nright = 154\nbottom = 3 * height / 5\n\n# Cropped image of above dimension\n# (It will not change original image)\nim1 = im.crop((left, top, right, bottom))\nnewsize = (300, 300)\nim1 = im1.resize(newsize)\n# Shows the image in image viewer\nim1.show()\n"
},
{
"answer_id": 70719475,
"author": "24_saurabh sharma",
"author_id": 17900612,
"author_profile": "https://Stackoverflow.com/users/17900612",
"pm_score": 0,
"selected": false,
"text": "######get resize coordinate after resize the image using this function#####\ndef scale_img_pixel(points,original_dim,resize_dim):\n multi_list = [points]\n new_point_list = []\n multi_list_point = []\n for point in multi_list:\n multi_list_point.append([point[0],point[1]])\n multi_list_point.append([point[2],point[3]])\n for lsingle_point in multi_list_point:\n x1 = int((lsingle_point[0] * (resize_dim[0] / original_dim[0])))\n y1 = int((lsingle_point[1] * (resize_dim[1] / original_dim[1])))\n new_point_list.append(x1)\n new_point_list.append(y1)\n \n return new_point_list\n \n \n points = [774,265,909,409]\n original_dim = (1237,1036)\n resize_dim = (640,480)\n result = scale_img_pixel(points,original_dim,resize_dim)\n print(\"result: \", result) \n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3912/"
] |
273,949
|
<p>For some reason I'm not getting this. (Example model below) If I write: </p>
<pre><code>var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)
</code></pre>
<p>the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling</p>
<pre><code>MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))
</code></pre>
<p>returns nothing while calling</p>
<pre><code>MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))
</code></pre>
<p>returns MyAttribute(1)?</p>
<hr>
<p>Example Model:</p>
<pre><code>public class Sedan : Car
{
// ...
}
public class Car : Vehicle
{
[MyAttribute(2)]
public override int TurningRadius { get; set; }
}
public abstract class Vehicle
{
[MyAttribute(1)]
public virtual int TurningRadius { get; set; }
}
</code></pre>
|
[
{
"answer_id": 274005,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Reflection;\n\npublic class MyAttribute : Attribute\n{\n public MyAttribute(int x) {}\n}\n\npublic class Sedan : Car\n{\n // ...\n}\n\npublic class Car : Vehicle\n{\n public override int TurningRadius { get; set; }\n}\n\npublic abstract class Vehicle\n{\n [MyAttribute(1)]\n public virtual int TurningRadius { get; set; }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MagicAttributeSearcher(typeof(Sedan));\n MagicAttributeSearcher(typeof(Vehicle));\n }\n\n static void MagicAttributeSearcher(Type type)\n {\n PropertyInfo prop = type.GetProperty(\"TurningRadius\");\n var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);\n Console.WriteLine(\"{0}: {1}\", type, attr);\n }\n}\n Sedan:\nVehicle: MyAttribute\n"
},
{
"answer_id": 276252,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 2,
"selected": false,
"text": "var property = typeof(sedan).GetProperty(\"TurningRadius\");\n"
},
{
"answer_id": 276255,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "GetProperty GetProperty PropertyInfo prop = type.GetProperty(\"TurningRadius\",\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);\n prop static bool MagicAttributeSearcher(Type type)\n{\n PropertyInfo prop = type.GetProperty(\"TurningRadius\", BindingFlags.Instance | \n BindingFlags.Public | BindingFlags.DeclaredOnly);\n\n if (prop == null)\n {\n return false;\n }\n var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);\n return attr != null;\n}\n true TurningRadius MyAttribute"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
273,964
|
<p>I have a CSS rule like this:</p>
<pre><code>a:hover { background-color: #fff; }
</code></pre>
<p>But this results in a bad-looking gap at the bottom on image links, and what's even worse, if I have transparent images, the link's background color can be seen through the image.</p>
<p>I have stumbled upon this problem many times before, but I always solved it using the quick-and-dirty approach of assigning a class to image links:</p>
<pre><code>a.imagelink:hover { background-color: transparent; }
</code></pre>
<p>Today I was looking for a more elegant solution to this problem when I stumbled upon <a href="https://developer.mozilla.org/en/Images%2c_Tables%2c_and_Mysterious_Gaps" rel="noreferrer">this</a>.</p>
<p>Basically what it suggests is using <code>display: block</code>, and this really solves the problem for non-transparent images. However, it results in another problem: now the link is as wide as the paragraph, although the image is not.</p>
<p>Is there a nice way to solve this problem, or do I have to use the dirty approach again?</p>
<p>Thanks,</p>
|
[
{
"answer_id": 273973,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "a:hover {background-color: #fff;}\nimg:hover { background-color: transparent;}\n"
},
{
"answer_id": 273993,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 0,
"selected": false,
"text": " a:hover { background-color: #fff; }\n a:imagelink:hover { background-color: inherit; }\n"
},
{
"answer_id": 274240,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<a> <img> <a><img /></a>"
},
{
"answer_id": 274301,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "<a ...><img src=\"...\" /></a>\n a:hover { background: SomeColor }\na:hover img { background-color: #fff; }\n"
},
{
"answer_id": 274400,
"author": "Gabe",
"author_id": 9835,
"author_profile": "https://Stackoverflow.com/users/9835",
"pm_score": 4,
"selected": true,
"text": "<a> <img> a img{vertical-align:text-bottom;}\n"
},
{
"answer_id": 274629,
"author": "Massimiliano Torromeo",
"author_id": 35069,
"author_profile": "https://Stackoverflow.com/users/35069",
"pm_score": 2,
"selected": false,
"text": "img {\n display: block;\n float: left;\n}\n"
},
{
"answer_id": 4514276,
"author": "Kim",
"author_id": 52025,
"author_profile": "https://Stackoverflow.com/users/52025",
"pm_score": 0,
"selected": false,
"text": "display: block baseline <a>TEXT HERE</a> body div#wrapper body {\n background-color: #112233; \n}\na:hover {\n background-color: red;\n}\na img {\n border-style: none; /* not need for this solution, but removes borders around images which have a link */\n vertical-align: bottom; /* here */\n}\na:hover img {\n background-color: #112233; /* MUST match the container background, or you arent masking the hover effect */\n}\n"
},
{
"answer_id": 8697949,
"author": "Paulish",
"author_id": 1115844,
"author_profile": "https://Stackoverflow.com/users/1115844",
"pm_score": 2,
"selected": false,
"text": "a[href$=jpg], a[href$=jpeg], a[href$=jpe], a[href$=png], a[href$=gif] {\n text-decoration: none;\n border: 0 none;\n background-color: transparent;\n }\n"
},
{
"answer_id": 13104102,
"author": "Balu",
"author_id": 1775414,
"author_profile": "https://Stackoverflow.com/users/1775414",
"pm_score": 0,
"selected": false,
"text": "background-image: url(file:\"use the same background image or color\");\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119/"
] |
273,969
|
<p>I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like:</p>
<pre><code><input type="text" name="something" value="Whatever value you entered" />
</code></pre>
<p>However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to:</p>
<pre><code><input type="text" this?="" do="" i="" how="" value="" name="something"/>
</code></pre>
<p>How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP?</p>
|
[
{
"answer_id": 273976,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": true,
"text": "<input type=\"text\" value=\"<?php echo htmlentities($myValue); ?>\">"
},
{
"answer_id": 274002,
"author": "thesmart",
"author_id": 20176,
"author_profile": "https://Stackoverflow.com/users/20176",
"pm_score": 4,
"selected": false,
"text": "htmlspecialchars($myValue, ENT_QUOTES, 'utf-8');\n '&' (ampersand) becomes '&'\n'\"' (double quote) becomes '"' when ENT_NOQUOTES is not set.\n''' (single quote) becomes ''' only when ENT_QUOTES is set.\n'<' (less than) becomes '<'\n'>' (greater than) becomes '>'\n"
},
{
"answer_id": 12838206,
"author": "mcmlxxxvi",
"author_id": 1614641,
"author_profile": "https://Stackoverflow.com/users/1614641",
"pm_score": 2,
"selected": false,
"text": "htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_DISALLOWED | ENT_HTML5, 'UTF-8')\n ENT_QUOTES ENT_SUBSTITUTE ENT_DISALLOWED ENT_HTML5 UTF-8 ISO-8859-1 htmlspecialchars htmlentities php.ini php_flag magic_quotes_gpc Off\n .htaccess"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
273,970
|
<p>Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages. They do this using PHP's header() function:</p>
<pre><code>header("Location: /other_page.php");
</code></pre>
<p>This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" rel="nofollow noreferrer">[HTTP 1.1 spec]</a></p>
<p>Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing. It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it. We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field. Thoughts?</p>
|
[
{
"answer_id": 273989,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "header('Location: /foo.php', true, 303);"
},
{
"answer_id": 274036,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": true,
"text": "Location"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20903/"
] |
273,978
|
<p>What makes all the words of a programming language actually do anything? I mean, what's actually happening to make the computer know what all of those words mean? If I verbally tell my my computer to do something, it doesn't do it, because it doesn't understand. So how exactly can these human words written into a language actually cause the computer to do some desirable activity? </p>
|
[
{
"answer_id": 273984,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": -1,
"selected": false,
"text": "print(\"Hello World\");\n"
},
{
"answer_id": 273988,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "Person.WalkForward(10 steps)\n Lift Persons Left Foot Up\nLean Forward\nPlace Left Foot Down\nLift Right Foot up\nLean Forward \nPlace Right Foot Down\netc\n"
},
{
"answer_id": 274020,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": false,
"text": "4 + 5\n 001 00000100 00000101\n"
},
{
"answer_id": 415091,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "(Start)\n*\n2\n+\n1\n=\n(Stop)\n PRINT 5*4\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35661/"
] |
273,995
|
<p>How does one prevent an inclusion cycle in C? ie. You shouldn't have a.h #include "b.h", which #include's "c.h" which #include's "a.h". I'm looking for a way of preventing this from happening using some sort of C directive.</p>
<p>I had originally thought this would've prevented this from happening:</p>
<p>Contents of a.h:</p>
<pre><code>#ifndef __A_H
#define __A_H
#include "b.h"
#endif // __A_H
</code></pre>
<p>Contents of b.h:</p>
<pre><code>#ifndef __B_H
#define __B_H
#include "c.h"
#endif // __B_H
</code></pre>
<p>Contents of c.h:</p>
<pre><code>#ifndef __C_H
#define __C_H
#include "a.h"
#endif // __C_H
</code></pre>
<p>But it doesn't seem to work.</p>
|
[
{
"answer_id": 274008,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 4,
"selected": true,
"text": "gcc -E $(CFLAGS) -o foo.i foo.cpp\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/273995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19026/"
] |
274,009
|
<p>I have a "username" TEdit on a Delphi 2006 login form. When the application starts up the user is asked to enter the username. The TEdit gets focus and the caret is placed in its horizontal center for some reason. As soon as anything is typed the caret is left aligned again and everything looks normal. </p>
<p>It is also strange that it wasn't always like this. This behaviour suddenly started a few years ago (I believe we still used Delphi 6 at that time). Any idea what might be causing this?</p>
<p>Additional info (has been asked for):
<li>The problem is widespread: D2006 and D6 (I believe), 5 or 6 Delphi instances on as much computers, all applications using that login form. The effect is limited to the form however, it does not occur on other TEdits.</li>
<li>The TEdit is not filled with spaces (that would be strange to do in the first place).</li>
<br>
More info (Nov 13):
<li>The caret is not centered exactly, it is <i>almost</i> centered.</li>
<li>Currently it seems to occur in a DLL only. The same login dialog is used in regular executables and does not show the problem there (although I believe it did at some time).</li>
<li>The edit field is a password edit, the OnChange handler sets an integer field of that form only, there are no other event handlers on that edit field.</li>
<li>I added another plain TEdit, which is also the ActiveControl so that it has focus when the form shows (as it was with the password edit). I also removed the default text "Edit1". Now the issue is present in that TEdit in the same way.</li>
<li>The "centered" caret goes back to normal if either a character is entered or if I tab through the controls - when I come back to the TEdit it looks normal. This was the same with the password edit.</li></p>
|
[
{
"answer_id": 2103150,
"author": "DamienD",
"author_id": 254839,
"author_profile": "https://Stackoverflow.com/users/254839",
"pm_score": 2,
"selected": false,
"text": " ../..\n Focused := IsActiveControl;\n if Focused and (CurRow = Row) and (CurCol = Col) then\n begin\n SetCaretPos(Where.Left, Where.Top); \n Include(DrawState, gdFocused);\n end;\n ../.. \n // new function introduced to fix a bug\n// this function is a duplicate of the function IsActiveControl\n// with a minor modification (see comment)\nfunction TCustomGrid.IsFocusedControl: Boolean;\nvar\n H: Hwnd;\n ParentForm: TCustomForm;\nbegin\n Result := False;\n ParentForm := GetParentForm(Self);\n if Assigned(ParentForm) then\n begin\n if (ParentForm.ActiveControl = Self) then\n //Result := True; // removed by DamienD\n Result := ParentForm.Active; // added by DamienD\n end\n else\n begin\n H := GetFocus;\n while IsWindow(H) and (Result = False) do\n begin\n if H = WindowHandle then\n Result := True\n else\n H := GetParent(H);\n end;\n end;\nend;\n"
},
{
"answer_id": 2323230,
"author": "Michael Chen",
"author_id": 279995,
"author_profile": "https://Stackoverflow.com/users/279995",
"pm_score": 0,
"selected": false,
"text": "Gird.BeginUpdate;\n\ntry\n\n //Show the second form here\n\nfinally\n\n Grid.EndUpdate;\n\nend;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35657/"
] |
274,011
|
<p>I would like to know if there is software that, given a regex and of course some other constraints like length, produces random text that always matches the given regex.
Thanks</p>
|
[
{
"answer_id": 274035,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 1,
"selected": false,
"text": "def generate_problem(level):\n keep_trying = True\n while(keep_trying):\n regex = gen_regex(level)\n # print 'regex = ' + regex\n counter = 0\n match = 0\n notmatch = 0\n goodwords = []\n badwords = []\n num_words = 2 + level * 3\n if num_words > 18:\n num_words = 18\n max_word_length = level + 4\n while (counter < 10000) and ((match < num_words) or (notmatch < num_words)):\n counter += 1\n rand_word = words[random.randint(0,max_word)]\n if len(rand_word) > max_word_length:\n continue\n mo = re.search(regex, rand_word)\n if mo:\n match += 1\n if len(goodwords) < num_words:\n goodwords.append(rand_word)\n else:\n notmatch += 1\n if len(badwords) < num_words:\n badwords.append(rand_word)\n if counter < 10000:\n new_prob = problem.problem()\n new_prob.title = 'Level ' + str(level)\n new_prob.explanation = 'This is a level %d puzzle. ' % level\n new_prob.goodwords = goodwords\n new_prob.badwords = badwords\n new_prob.regex = regex\n keep_trying = False\n return new_prob\n"
},
{
"answer_id": 1590617,
"author": "Wilfred Springer",
"author_id": 136476,
"author_profile": "https://Stackoverflow.com/users/136476",
"pm_score": 5,
"selected": true,
"text": "String regex = \"[ab]{4,6}c\";\nXeger generator = new Xeger(regex);\nString result = generator.generate();\nassert result.matches(regex);\n"
},
{
"answer_id": 24659692,
"author": "Mifmif",
"author_id": 1250229,
"author_profile": "https://Stackoverflow.com/users/1250229",
"pm_score": 2,
"selected": false,
"text": " Generex generex = new Generex(\"[0-3]([a-c]|[e-g]{1,2})\");\n\n // generate the second String in lexicographical order that match the given Regex.\n String secondString = generex.getMatchedString(2);\n System.out.println(secondString);// it print '0b'\n\n // Generate all String that matches the given Regex.\n List<String> matchedStrs = generex.getAllMatchedStrings();\n\n // Using Generex iterator\n Iterator iterator = generex.iterator();\n while (iterator.hasNext()) {\n System.out.print(iterator.next() + \" \");\n }\n // it print 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e\n // 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g\n // 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee\n\n // Generate random String\n String randomStr = generex.random();\n System.out.println(randomStr);// a random value from the previous String list\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11906/"
] |
274,022
|
<p>I very rarely meet any other programmers!</p>
<p>My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.</p>
<p>So how do I say or read "=>" as in:-</p>
<pre><code>IEnumerable<Person> Adults = people.Where(p => p.Age > 16)
</code></pre>
<p>Or is there even an agreed way of saying it?</p>
|
[
{
"answer_id": 274025,
"author": "Erik Forbes",
"author_id": 16942,
"author_profile": "https://Stackoverflow.com/users/16942",
"pm_score": 8,
"selected": true,
"text": "x => x * 2;\n"
},
{
"answer_id": 274247,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "// \"Func f equals x to x times two\"\nFunc f = x=> x * 2;\n\n// \"Func test equals c to c dot City equals London\"\nFunc test = c => c.City == \"London\"\n"
},
{
"answer_id": 16270890,
"author": "Jonesopolis",
"author_id": 1786428,
"author_profile": "https://Stackoverflow.com/users/1786428",
"pm_score": 2,
"selected": false,
"text": "(n => n == String.Empty)\n"
},
{
"answer_id": 30714993,
"author": "Allan",
"author_id": 4987218,
"author_profile": "https://Stackoverflow.com/users/4987218",
"pm_score": 0,
"selected": false,
"text": "s => s.Age > 12 && s.Age < 20\n return s.Age > 12 && s.Age < 20; delegate(Student s) { return s.Age > 12 && s.Age < 20; };\n"
},
{
"answer_id": 60467168,
"author": "Arthur",
"author_id": 12983089,
"author_profile": "https://Stackoverflow.com/users/12983089",
"pm_score": 0,
"selected": false,
"text": "'result = s => s.Age > 12 && s.Age < 20'\n 'result = x => x * 2'\n 'result = c => c.City == \"London\"'\n 'result = n => n == String.Empty'\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29411/"
] |
274,024
|
<p>I'm increasingly becoming aware that there must be major differences in the ways that regular expressions will be interpreted by browsers.<br />
As an example, a co-worker had written this regular expression, to validate that a file being uploaded would have a PDF extension:</p>
<pre><code>^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$
</code></pre>
<p>This works in Internet Explorer, and in Google Chrome, but does NOT work in Firefox. The test always fails, even for an actual PDF. So I decided that the extra stuff was irrelevant and simplified it to:</p>
<pre><code>^.+\.pdf$
</code></pre>
<p>and now it works fine in Firefox, as well as continuing to work in IE and Chrome.<br />
Is this a quirk specific to asp:FileUpload and RegularExpressionValidator controls in ASP.NET, or is it simply due to different browsers supporting regex in different ways? Either way, what are some of the latter that you've encountered?</p>
|
[
{
"answer_id": 274052,
"author": "Mauricio",
"author_id": 33913,
"author_profile": "https://Stackoverflow.com/users/33913",
"pm_score": 1,
"selected": false,
"text": "var regex = /^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))(.pdf)$/;"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12975/"
] |
274,039
|
<p>I would like to do this:</p>
<pre><code>[RequiresAuthentication(CompanyType.Client)]
public class FooController
{
public ActionResult OnlyClientUsersCanDoThis()
public ActionResult OnlyClientUsersCanDoThisToo()
[RequiresAuthentication]
public ActionResult AnyTypeOfUserCanDoThis()
</code></pre>
<p>You can see why this won't work. On the third action the controller-level filter will block non-clients. I would like instead to "resolve" conflicting filters. I would like for the more specific filter (action filter) to always win. This seems natural and intuitive.</p>
<p>Once upon a time filterContext exposed MethodInfo for the executing action. That would have made this pretty easy. I considered doing some reflection myself using route info. That won't work because the action it might be overloaded and I cannot tell which one is the current executing one.</p>
<p>The alternative is to scope filters either at the controller level or the action level, but no mix, which will create a lot of extra attribute noise.</p>
|
[
{
"answer_id": 2060147,
"author": "Thomas",
"author_id": 250207,
"author_profile": "https://Stackoverflow.com/users/250207",
"pm_score": 0,
"selected": false,
"text": "public override void OnActionExecuting(ActionExecutingContext filterContext) {\n base.OnActionExecuting(filterContext);\n new RequiresAuthentication()\n { /* initialization */ }.OnActionExecuting(filterContext);\n}\n"
},
{
"answer_id": 7937692,
"author": "saintedlama",
"author_id": 263251,
"author_profile": "https://Stackoverflow.com/users/263251",
"pm_score": 0,
"selected": false,
"text": "[RequiresAuthentication]\npublic class FooController\n{\n [RequiresAuthentication(CompanyType.Client)]\n public ActionResult OnlyClientUsersCanDoThis()\n\n [RequiresAuthentication(CompanyType.Client)]\n public ActionResult OnlyClientUsersCanDoThisToo()\n\n public ActionResult AnyTypeOfUserCanDoThis()\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29493/"
] |
274,051
|
<p>Is keeping JMS connections / sessions / consumer always open a bad practice?</p>
<p>Code draft example:</p>
<pre><code>// app startup code
ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME);
Connection connection = cf.createConnection(user,pass);
Session session = connection.createSession(true,Session.TRANSACTIONAL);
MessageConsumer consumer = session.createConsumer(new Queue(queueName));
consumer.setMessageListener(new MyListener());
connection.start();
connection.setExceptionListener(new MyExceptionHandler()); // handle connection error
// ... Message are processed on MyListener asynchronously ...
// app shutdown code
consumer.close();
session.close();
connection.close();
</code></pre>
<p>Any suggestions to improve this pattern of JMS usage? </p>
|
[
{
"answer_id": 40217347,
"author": "eparvan",
"author_id": 5202500,
"author_profile": "https://Stackoverflow.com/users/5202500",
"pm_score": 2,
"selected": false,
"text": "try { \n this.connection.close();\n } catch (JMSException e) {\n //\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/274051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35323/"
] |
274,056
|
<p>I'm setting up a User Control driven by a XML configuration. It is easier to explain by example. Take a look at the following configuration snippet:</p>
<pre><code><node>
<text lbl="Text:"/>
<checkbox lbl="Check me:" checked="true"/>
</node>
</code></pre>
<p>What I'm trying to achieve to translate that snippet into a single text box and a checkbox control. Of course, had the snippet contained more nodes more controls would be generated automatically.</p>
<p>Give the iterative nature of the task, I have chosen to use Repeater. Within it I have placed two (well more, see bellow) Controls, one CheckBox and one Editbox. In order to choose which control get activate, I used an inline switch command, checking the name of the current configuration node.</p>
<p>Sadly, that doesn't work. The problem lies in the fact that the switch is being run during rendering time, long after data binding had happened. That alone would not be a problem, was not for the fact that a configuration node might offer the needed info to data bind. Consider what would happen if the check box control will try to bind to the text node in the snippet above, desperately looking for it's "checked" attribute.</p>
<p>Any ideas how to make this possible?</p>
<p>Thanks,
Boaz</p>
<p>Here is my current code:</p>
<p>Here is my code (which runs on a more complex syntax than the one above):</p>
<pre><code><asp:Repeater ID="settingRepeater" runat="server">
<ItemTemplate>
<%
switch (((XmlNode)Page.GetDataItem()).LocalName)
{
case "text":
%>
<asp:Label ID="settingsLabel" CssClass="editlabel" Text='<%# XPath("@lbl") %>' runat="server" />
<asp:TextBox ID="settingsLabelText" Text='<%# SettingsNode.SelectSingleNode(XPath("@xpath").ToString()).InnerText %>'
runat="server" AutoPostBack="true" Columns='<%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),"@width",20) %>'
/>
<% break;
case "checkbox":
%>
<asp:CheckBox ID="settingsCheckBox" Text='<%# XPath("@lbl") %>' runat="server"
Checked='<%# ((XmlElement)SettingsNode.SelectSingleNode(XPath("@xpath").ToString())).HasAttribute(XPath("@att").ToString()) %>'
/>
<% break;
} %>
&nbsp;&nbsp;
</ItemTemplate>
</asp:Repeater>
</code></pre>
|
[
{
"answer_id": 274249,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 1,
"selected": false,
"text": "<ItemTemplate>\n <%# GetContent(Page.GetDataItem()) %>\n</ItemTemplate>\n"
},
{
"answer_id": 276591,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 3,
"selected": true,
"text": " <asp:Repeater ID=\"settingRepeater\" runat=\"server\" \n onitemcreated=\"settingRepeater_ItemCreated\" \n >\n <ItemTemplate>\n <asp:PlaceHolder ID=\"text\" runat=\"server\">\n <asp:Label ID=\"settingsLabel\" CssClass=\"editlabel\" Text='<%# XPath(\"@lbl\") %>' runat=\"server\" />\n <asp:TextBox ID=\"settingsLabelText\" runat=\"server\"\n Text='<%# SettingsNode.SelectSingleNode(XPath(\"@xpath\").ToString()).InnerText %>'\n Columns='<%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),\"@width\",20) %>'\n\n />\n\n </asp:PlaceHolder>\n <asp:PlaceHolder ID=\"att_adder\" runat=\"server\">\n <asp:CheckBox ID=\"settingsAttAdder\" Text='<%# XPath(\"@lbl\") %>' runat=\"server\"\n Checked='<%# ((XmlElement)SettingsNode.SelectSingleNode(XPath(\"@xpath\").ToString())).HasAttribute(XPath(\"@att\").ToString()) %>'\n />\n </asp:PlaceHolder>\n </ItemTemplate>\n </asp:Repeater>\n protected List<string> repeaterItemTypes\n {\n get\n {\n List<string> ret = (List<string>)ViewState[\"repeaterItemTypes\"];\n if (ret == null)\n {\n ret = new List<string>();\n ViewState[\"repeaterItemTypes\"] = ret;\n }\n return ret;\n }\n }\n\n protected void settingRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)\n {\n string type;\n if (e.Item.DataItem != null)\n {\n // data binding mode..\n type = ((XmlNode)e.Item.DataItem).LocalName;\n int i = e.Item.ItemIndex;\n if (i == repeaterItemTypes.Count)\n repeaterItemTypes.Add(type);\n else\n repeaterItemTypes.Insert(e.Item.ItemIndex, type);\n }\n else\n {\n // restoring from ViewState\n type = repeaterItemTypes[e.Item.ItemIndex];\n }\n\n for (int i = e.Item.Controls.Count - 1; i >= 0; i--)\n {\n if (e.Item.Controls[i].ID != type) e.Item.Controls.RemoveAt(i);\n }\n }\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892/"
] |
274,066
|
<p>I have a large existing c++ codebase. Typically the users of the codebase edit the source with gvim, but we'd like to start using the nifty IDE features in Eclipse. The codebase has an extensive directory hierarchy, but the source files use include directives without paths due to some voodoo we use in our build process. When I link the source to my project in Eclipse, the indexer complains that it can't find any header files (because we don't specify paths in our includes.) If I manually add the directories from the workspace to the include path then everything works wonderfully, but obviously adding hundreds of directories manually isn't feasible. Would there be a simple method to tell Eclipse to look anywhere in the project for the include files without having to add them one by one? If not, then can anyone suggest a good starting place, like what classes to extend, for writing a plugin to just scan the project at creation/modification and programatically add all directories to the include path?</p>
|
[
{
"answer_id": 274194,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 3,
"selected": false,
"text": "<option id=\"gnu.c.compiler.option.include.paths....>\n<listoptionValue builtIn=\"false\" value=\""${workspace_loc:/some/path}$quot;\" />\n<listOptionValue ... />\n\n...\n</option>\n"
},
{
"answer_id": 287273,
"author": "Josh Kelley",
"author_id": 25507,
"author_profile": "https://Stackoverflow.com/users/25507",
"pm_score": 1,
"selected": false,
"text": "gcc g++ gcc g++"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152/"
] |
274,149
|
<p>Is it possible in CSS using a property inside an @page to say that table headers (th) should be repeated on every page if the table spreads over multiple pages?</p>
|
[
{
"answer_id": 274186,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "thead thead {display: table-header-group;}\ntfoot {display: table-footer-group;}\n"
},
{
"answer_id": 2633761,
"author": "Eero",
"author_id": 4505,
"author_profile": "https://Stackoverflow.com/users/4505",
"pm_score": 6,
"selected": false,
"text": " table {\n -fs-table-paginate: paginate;\n }\n"
},
{
"answer_id": 34334591,
"author": "SantoshK",
"author_id": 5680730,
"author_profile": "https://Stackoverflow.com/users/5680730",
"pm_score": 3,
"selected": false,
"text": "thead {display: table-header-group;}"
},
{
"answer_id": 47919120,
"author": "Urooj Khan",
"author_id": 1453834,
"author_profile": "https://Stackoverflow.com/users/1453834",
"pm_score": 3,
"selected": false,
"text": "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n <script type=\"text/javascript\">\n function PrintPage() {\n document.getElementById('print').style.display = 'none';\n window.resizeTo(960, 600);\n document.URL = \"\";\n window.location.href = \"\";\n window.print();\n }\n\n </script>\n <style type=\"text/css\" media=\"print\">\n @page\n {\n size: auto; /* auto is the initial value */\n margin: 2mm 4mm 0mm 0mm; /* this affects the margin in the printer settings */\n }\n thead\n {\n display: table-header-group;\n }\n tfoot\n {\n display: table-footer-group;\n }\n </style>\n <style type=\"text/css\" media=\"screen\">\n thead\n {\n display: block;\n }\n tfoot\n {\n display: block;\n }\n </style>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <table style=\"width: 500px; margin: 0 auto;\">\n <thead>\n <tr>\n <td>\n header comes here for each page\n </td>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n 1\n </td>\n </tr>\n <tr>\n <td>\n 2\n </td>\n </tr>\n <tr>\n <td>\n 3\n </td>\n </tr>\n <tr>\n <td>\n 4\n </td>\n </tr>\n <tr>\n <td>\n 5\n </td>\n </tr>\n <tr>\n <td>\n 6\n </td>\n </tr>\n <tr>\n <td>\n 7\n </td>\n </tr>\n <tr>\n <td>\n 8\n </td>\n </tr>\n <tr>\n <td>\n 9\n </td>\n </tr>\n <tr>\n <td>\n 10\n </td>\n </tr>\n <tr>\n <td>\n 11\n </td>\n </tr>\n <tr>\n <td>\n 12\n </td>\n </tr>\n <tr>\n <td>\n 13\n </td>\n </tr>\n <tr>\n <td>\n 14\n </td>\n </tr>\n <tr>\n <td>\n 15\n </td>\n </tr>\n <tr>\n <td>\n 16\n </td>\n </tr>\n <tr>\n <td>\n 17\n </td>\n </tr>\n <tr>\n <td>\n 18\n </td>\n </tr>\n <tr>\n <td>\n 19\n </td>\n </tr>\n <tr>\n <td>\n 20\n </td>\n </tr>\n <tr>\n <td>\n 21\n </td>\n </tr>\n <tr>\n <td>\n 22\n </td>\n </tr>\n <tr>\n <td>\n 23\n </td>\n </tr>\n <tr>\n <td>\n 24\n </td>\n </tr>\n <tr>\n <td>\n 25\n </td>\n </tr>\n <tr>\n <td>\n 26\n </td>\n </tr>\n <tr>\n <td>\n 27\n </td>\n </tr>\n <tr>\n <td>\n 28\n </td>\n </tr>\n <tr>\n <td>\n 29\n </td>\n </tr>\n <tr>\n <td>\n 30\n </td>\n </tr>\n <tr>\n <td>\n 31\n </td>\n </tr>\n <tr>\n <td>\n 32\n </td>\n </tr>\n <tr>\n <td>\n 33\n </td>\n </tr>\n <tr>\n <td>\n 34\n </td>\n </tr>\n <tr>\n <td>\n 35\n </td>\n </tr>\n <tr>\n <td>\n 36\n </td>\n </tr>\n <tr>\n <td>\n 37\n </td>\n </tr>\n <tr>\n <td>\n 38\n </td>\n </tr>\n <tr>\n <td>\n 39\n </td>\n </tr>\n <tr>\n <td>\n 40\n </td>\n </tr>\n <tr>\n <td>\n 41\n </td>\n </tr>\n <tr>\n <td>\n 42\n </td>\n </tr>\n <tr>\n <td>\n 43\n </td>\n </tr>\n <tr>\n <td>\n 44\n </td>\n </tr>\n <tr>\n <td>\n 45\n </td>\n </tr>\n <tr>\n <td>\n 46\n </td>\n </tr>\n <tr>\n <td>\n 47\n </td>\n </tr>\n <tr>\n <td>\n 48\n </td>\n </tr>\n <tr>\n <td>\n 49\n </td>\n </tr>\n <tr>\n <td>\n 50\n </td>\n </tr>\n <tr>\n <td>\n 51\n </td>\n </tr>\n <tr>\n <td>\n 52\n </td>\n </tr>\n <tr>\n <td>\n 53\n </td>\n </tr>\n <tr>\n <td>\n 54\n </td>\n </tr>\n <tr>\n <td>\n 55\n </td>\n </tr>\n </tbody>\n <tfoot>\n <tr>\n <td>\n footer comes here for each page\n </td>\n </tr>\n </tfoot>\n </table>\n </div>\n <br clear=\"all\" />\n <input type=\"button\" id=\"print\" name=\"print\" value=\"Print\" onclick=\"javascript:PrintPage();\"\n class=\"button\" />\n </form>\n</body>\n</html>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
274,157
|
<p>Wordpress provides a function called "the_permalink()" that returns, you guessed it!, the permalink to a given post while in a loop of posts.</p>
<p>I am trying to URL encode that permalink and when I execute this code:</p>
<pre><code><?php
print(the_permalink());
$permalink = the_permalink();
print($permalink);
print(urlencode(the_permalink()));
print(urlencode($permalink));
$url = 'http://wpmu.local/graphjam/2008/11/06/test4/';
print($url);
print(urlencode($url));
?>
</code></pre>
<p>it produces these results in HTML:</p>
<pre><code>http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http%3A%2F%2Fwpmu.local%2Fgraphjam%2F2008%2F11%2F06%2Ftest4%2F
</code></pre>
<p>I would expect lines 2, 3 and 5 of the output to be URL encoded, but only line 5 is so. Thoughts?</p>
|
[
{
"answer_id": 274163,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 4,
"selected": false,
"text": "the_permalink urlencode get_permalink <?php\nprint(the_permalink()); // prints (1)\n$permalink = the_permalink(); // prints (2)\nprint($permalink); // nothing\nprint(urlencode(the_permalink())); // prints (3)\nprint(urlencode($permalink)); // nothing\n$url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; \nprint($url); // prints (4)\nprint(urlencode($url)); // prints (5)\n?>\n"
},
{
"answer_id": 274304,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": "ob_start();\nthe_permalink();\n$permalink = ob_get_clean();\nprint(urlencode($permalink));\n"
},
{
"answer_id": 283439,
"author": "Ozh",
"author_id": 36850,
"author_profile": "https://Stackoverflow.com/users/36850",
"pm_score": 3,
"selected": false,
"text": "the_permalink() get_the_permalink()"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33754/"
] |
274,158
|
<p>I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier. </p>
<p>So how do I make a ushort array into a string by bytes? I've tried:</p>
<pre><code>int i;
String theOutData = "";
ushort[] theImageData = inImageData.DataArray;
//this is as slow like molasses in January
for (i = 0; i < theImageData.Length; i++) {
byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]);
theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]);
}
</code></pre>
<p>I can do it this way, but it doesn't finish in anything remotely close to a sane amount of time.</p>
<p>What should I do here? Go unsafe? Go through some kind of IntPtr intermediate?</p>
<p>If it were a char* in C++, this would be significantly easier...</p>
<p>edit: the function call is</p>
<pre><code>DataElement.SetByteValue(string inArray, VL Length);
</code></pre>
<p>where VL is a 'Value Length', a DICOM type, and the function itself is generated as a wrapper to a C++ library by SWIG. It seems that the representation chosen is string, because that can cross managed/unmanaged boundaries relatively easily, but throughout the C++ code in the project (this is GDCM), the char* is simply used as a byte buffer. So, when you want to set your image buffer pointer, in C++ it's fairly simple, but in C#, I'm stuck with this weird problem.</p>
<p>This is hackeration, and I know that probably the best thing is to make the SWIG library work right. I really don't know how to do that, and would rather a quick workaround on the C# side, if such exists.</p>
|
[
{
"answer_id": 274207,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "ushort[] data = new ushort[10];\nfor (int i = 0; i < data.Length; ++i)\n data[i] = (char) ('A' + i);\n\nstring asString;\nbyte[] asBytes = new byte[data.Length * sizeof(ushort)];\nBuffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length);\nasString = Encoding.Unicode.GetString(asBytes);\n string asString;\nunsafe\n{\n fixed (ushort *dataPtr = &data[0])\n asString = new string((char *) dataPtr, 0, data.Length);\n}\n"
},
{
"answer_id": 274222,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 0,
"selected": false,
"text": " ushort[] data = inData; // The ushort array source\n\n Byte[] bytes = new Byte[data.Length]; // Assumption - only need one byte per ushort\n\n int i = 0;\n foreach(ushort x in data) {\n byte[] tmp = System.BitConverter.GetBytes(x);\n bytes[i++] = tmp[0];\n // Note: not using tmp[1] as all characters in 0 < x < 127 use one byte.\n }\n\n String str = Encoding.ASCII.GetString(bytes);\n"
},
{
"answer_id": 274224,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "ushort[] theImageData = inImageData.DataArray;\n\nbyte[] buf = new byte[Buffer.ByteLength(theImageData)]; // 2 bytes per short\nBuffer.BlockCopy(theImageData, 0, buf, 0, Buffer.ByteLength(theImageData));\n\nstring theOutData = System.Text.Encoding.ASCII.GetString(buf);\n"
},
{
"answer_id": 65860043,
"author": "KVM",
"author_id": 1830854,
"author_profile": "https://Stackoverflow.com/users/1830854",
"pm_score": 0,
"selected": false,
"text": "public static class Helpers\n{\n public static string ConvertToString(this ushort[] uSpan)\n {\n byte[] bytes = new byte[sizeof(ushort) * uSpan.Length];\n\n for (int i = 0; i < uSpan.Length; i++)\n {\n Unsafe.As<byte, ushort>(ref bytes[i * 2]) = uSpan[i];\n }\n\n return Encoding.Unicode.GetString(bytes);\n }\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21981/"
] |
274,162
|
<p>Is there a specific reason why I should be using the <code>Html.CheckBox</code>, <code>Html.TextBox</code>, etc methods instead of just manually writing the HTML?</p>
<pre><code><%= Html.TextBox("uri") %>
</code></pre>
<p>renders the following HTML</p>
<pre><code><input type="text" value="" name="uri" id="uri"/>
</code></pre>
<p>It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?</p>
|
[
{
"answer_id": 274272,
"author": "user17060",
"author_id": 17060,
"author_profile": "https://Stackoverflow.com/users/17060",
"pm_score": 3,
"selected": false,
"text": "ViewData[\"FirstName\"] = \"Joe Bloggs\"; \n\n<%=Html.TextBox(\"FirstName\") %>\n <input type=\"text\" value=\"Joe Bloggs\" id=\"FirstName\" />\n"
},
{
"answer_id": 274273,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<input value=\"<%Html.Encode(ViewData.Model.Uri\"%>\" />"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
274,172
|
<p>VB.Net2005</p>
<p>Simplified Code:</p>
<pre><code> MustInherit Class InnerBase(Of Inheritor)
End Class
MustInherit Class OuterBase(Of Inheritor)
Class Inner
Inherits InnerBase(Of Inner)
End Class
End Class
Class ChildClass
Inherits OuterBase(Of ChildClass)
End Class
Class ChildClassTwo
Inherits OuterBase(Of ChildClassTwo)
End Class
MustInherit Class CollectionClass(Of _
Inheritor As CollectionClass(Of Inheritor, Member), _
Member As OuterBase(Of Member))
Dim fails As Member.Inner ' Type parameter cannot be used as qualifier
Dim works As New ChildClass.Inner
Dim failsAsExpected As ChildClassTwo.Inner = works ' type conversion failure
End Class
</code></pre>
<p>The error message on the "fails" line is in the subject, and "Member.Inner" is highlighted. Incidentally, the same error occurs with trying to call a shared method of OuterBase.</p>
<p>The "works" line works, but there are a dozen (and counting) ChildClass classes in real life.</p>
<p>The "failsAsExpected" line is there to show that, with generics, each ChildClass has its own distinct Inner class.</p>
<p>My question: is there a way to get a variable, in class CollectionClass, defined as type Member.Inner? what's the critical difference that the compiler can't follow?</p>
<p>(I was eventually able to generate an object by creating a dummy object of type param and calling a method defined in OuterBase. Not the cleanest approach.)</p>
<p>Edit 2008/12/2 altered code to make the two "base" classes generic.</p>
|
[
{
"answer_id": 274272,
"author": "user17060",
"author_id": 17060,
"author_profile": "https://Stackoverflow.com/users/17060",
"pm_score": 3,
"selected": false,
"text": "ViewData[\"FirstName\"] = \"Joe Bloggs\"; \n\n<%=Html.TextBox(\"FirstName\") %>\n <input type=\"text\" value=\"Joe Bloggs\" id=\"FirstName\" />\n"
},
{
"answer_id": 274273,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<input value=\"<%Html.Encode(ViewData.Model.Uri\"%>\" />"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
274,179
|
<p>I have followed the instructions to setup rxtx on windows from <a href="http://www.jcontrol.org/download/readme_rxtx_en.html" rel="nofollow noreferrer">http://www.jcontrol.org/download/readme_rxtx_en.html</a>.</p>
<p>What I did exactly was copy rxtxSerial.dll to "C:\Program Files\Java\jdk1.6.0_07\jre\bin"
and copied RXTXcomm.jar to "C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext"
(my JAVA_HOME variable is set to C:\Program Files\Java\jdk1.6.0_07\jre)</p>
<p>I also added RXTXcomm.jar to my eclipse project.</p>
<p>But when I run it, it still says "NoSuchPortException"</p>
<pre>
Devel Library
=========================================
Native lib Version = RXTX-2.0-7pre1
Java lib Version = RXTX-2.0-7pre1
java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver
gnu.io.NoSuchPortException
at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218)
at TwoWaySerialComm.connect(TwoWaySerialComm.java:20)
at TwoWaySerialComm.main(TwoWaySerialComm.java:107)
</pre>
<p>In my java file, I tell it:</p>
<pre>
try
{
(new TwoWaySerialComm()).connect("COM4");
}
</pre>
<p>and I've also tried the Java Comm API. Both cannot recognize my serial port but I am sure I followed the instruction correctly. There files are there.</p>
<p>Does anybody have any idea what it could be?</p>
|
[
{
"answer_id": 274257,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "rxtxSerial.dll C:\\Program Files\\Java\\jdk1.6.0_07\\jre\\lib\\bin\n ^^^\n"
},
{
"answer_id": 274464,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 0,
"selected": false,
"text": "// name comes from config and is \"COM1\", \"COM2\", ...\nSerialPort port=(SerialPort)CommPortIdentifier.getPortIdentifier(name).open(\"YourPortOwnerIdHere\",5000); // owner and ms timeout\nport.setSerialPortParams(bau,dtb,stb,par);\nport.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN|SerialPort.FLOWCONTROL_RTSCTS_OUT);\nport.enableReceiveTimeout(1000);\n"
},
{
"answer_id": 746771,
"author": "Daniel Schneller",
"author_id": 1252368,
"author_profile": "https://Stackoverflow.com/users/1252368",
"pm_score": 1,
"selected": false,
"text": "java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver\n"
},
{
"answer_id": 2736618,
"author": "Memafe",
"author_id": 328783,
"author_profile": "https://Stackoverflow.com/users/328783",
"pm_score": 0,
"selected": false,
"text": "if (idPuerto == null)\n{\n formulario = form;\n boolean encontrado = false;\n\n\n listaPuertos = CommPortIdentifier.getPortIdentifiers();\n\n while( listaPuertos.hasMoreElements() && encontrado == false )\n {\n idPuerto = (CommPortIdentifier)listaPuertos.nextElement();\n //System.out.println(idPuerto.getName());\n\n if( idPuerto.getPortType() == CommPortIdentifier.PORT_SERIAL )\n {\n if( idPuerto.getName().equals(RFIDBascApp.ComBasc) )\n { \n encontrado = true;\n logger.AddInfoUser(\"Puerto serie encontrado\");\n\n }\n }\n }\n"
},
{
"answer_id": 4935149,
"author": "Hamedz",
"author_id": 464219,
"author_profile": "https://Stackoverflow.com/users/464219",
"pm_score": 0,
"selected": false,
"text": "NoSuchPortException import gnu.io.CommPortIdentifier; \nimport java.util.Enumeration; \n\npublic class ListAvailablePorts { \n\n public void list() { \n Enumeration ports = CommPortIdentifier.getPortIdentifiers(); \n\n while(ports.hasMoreElements()){ \n CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();\n System.out.println(port.getName());\n }\n } \n\n public static void main(String[] args) { \n new ListAvailablePorts().list(); \n } \n} \n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
274,185
|
<p>Let's say there's a.gz, and b.gz.</p>
<p>$ gzip_merge a.gz b.gz -output c.gz</p>
<p>I'd like to have this program. Of course,</p>
<p>$ cat a.gz b.gz > c.gz</p>
<p>doesn't work. Because the final DEFLATE block of a.gz has BFINAL, and the GZIP header of b.gz. (Refer to RFC1951, RFC1952) But if you unset BFINAL, throw away the second GZIP header and walk through the byte boundaries of the second gzip file, you can merge it.</p>
<p>In fact, I thought of writing an open source program for this matter, but didn't know how to publish it. So I asked the Joel to be my program manager, and I walked him through my explanation and defense, he finally understood what I wanted to do, but said he was too busy. :(</p>
<p>Of course, I could write one myself and try my way to publish it. But I can't do this alone because my day work belongs to the property of my employer.</p>
<p>Is there any volunteers? We could work as programmer(me), publisher(you) or programmer(you), publisher(me). All I need is some credit. I once implemented a Universal Decompressor Virtual Machine described in RFC3320. So I know this is feasible. </p>
<p>OR, you could point me to THAT program. It would be very useful for managing log files like merging 365 (day) gzipped log files to one. ;)</p>
<p>Thanks.</p>
|
[
{
"answer_id": 274190,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 6,
"selected": true,
"text": " Multiple compressed files can be concatenated. In this case, gunzip\n will extract all members at once. For example:\n\n gzip -c file1 > foo.gz\n gzip -c file2 >> foo.gz\n\n Then\n\n gunzip -c foo\n\n is equivalent to\n\n cat file1 file2\n"
},
{
"answer_id": 11461282,
"author": "Suman",
"author_id": 1203129,
"author_profile": "https://Stackoverflow.com/users/1203129",
"pm_score": 3,
"selected": false,
"text": "zcat a.gz b.gz > c.txt && gzip c.txt\n zcat a.gz b.gz | gzip -c > c.txt.gz\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24349/"
] |
274,196
|
<p>I've got a large number of integer arrays. Each one has a few thousand integers in it, and each integer is generally the same as the one before it or is different by only a single bit or two. I'd like to shrink each array down as small as possible to reduce my disk IO. </p>
<p>Zlib shrinks it to about 25% of its original size. That's nice, but I don't think its algorithm is particularly well suited for the problem. Does anyone know a compression library or simple algorithm that might perform better for this type of information?</p>
<p>Update: zlib after converting it to an array of xor deltas shrinks it to about 20% of the original size. </p>
|
[
{
"answer_id": 274278,
"author": "Jay Kominek",
"author_id": 32878,
"author_profile": "https://Stackoverflow.com/users/32878",
"pm_score": 4,
"selected": true,
"text": "1101\n1101\n1110\n1110\n0110\n 1101\n0000\n0010\n0000\n1000\n compressed[0] = uncompressed[0]\nloop\n compressed[i] = uncompressed[i-1] ^ uncompressed[i]\n uncompressed[0] = compressed[0]\nloop\n uncompressed[i] = uncompressed[i-1] ^ compressed[i]\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
] |
274,213
|
<p>All paint programs, independent of how simple or complex they are, come with a fill tool. This basically replaces the color of a closed region with another color. I know that there are different APIs to do this, but I am interested in the algorithm. What would be an efficient algorithm to implement this tool?</p>
<p>A couple of things I can think of quickly are:</p>
<ol>
<li>Convert image into a binary map, where pixels in the color to be replaced are <code>1</code> and all other colors are <code>0</code>.</li>
<li>Find a closed region around the point you want to change such that all the pixels inside are 1 and all the neighbouring pixels are 0.</li>
</ol>
<p><a href="http://img206.imageshack.us/my.php?image=toolfillsv5.jpg" rel="nofollow noreferrer">Sample Image</a></p>
|
[
{
"answer_id": 274227,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Vis[] Busy[] Busy while you have a point P in Busy:\n{\n for each neighbour N of the point P for which Vis[N] is still false\n {\n if appropriate (not crossing the boundary of the fill region)\n {\n set Vis[N] to true\n update the colour of N in the bitmap\n add N to the end of Busy[]\n }\n remove P from Busy[]\n }\n}\n"
},
{
"answer_id": 274353,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 3,
"selected": false,
"text": "void floodFill4 (int x, int y, int fillColor, int interiorColor)\n{\n int color;\n\n /* Set current color to fillColor, then perform the following operations */\n getPixel(x, y, color);\n if (color == interiorColor) \n {\n setPixel(x,y); // Set color of pixel to fillColor.\n floodFill4(x + 1, y, fillColor, interiorColor);\n floodFill4(x - 1, y, fillColor, interiorColor);\n floodFill4(x, y + 1, fillColor, interiorColor);\n floodFill4(x, y - 1, fillColor, interiorColor);\n }\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33885/"
] |
274,265
|
<p>I can't for the life of me find a way to make this work.</p>
<p>If I have 3 divs (a left sidebar, a main body, and a footer), how can I have the sidebar and main body sit next to each other without setting their positions as "absolute" or floating them? Doing either of these options result in the footer div not being pushed down by one or the other.</p>
<p>How might I accomplish this regardless of what comes before these elements (say another header div or something)?</p>
<p>In case it helps, here's an illustration of the two cases I'm trying to allow for:</p>
<p><img src="https://i.stack.imgur.com/zjEzC.jpg" alt="alt text"></p>
<p>Here's a simplified version of the HTML I currently have set up:</p>
<pre><code><div id="sidebar"></div>
<div id="content"></div>
<div id="footer"></div>
</code></pre>
|
[
{
"answer_id": 274269,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 5,
"selected": true,
"text": "#footer{\n clear: both;\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
274,286
|
<p>I have a new VPS server, and I'm trying to get it to connect to another server at the same ISP. When I connect via mysql's command line tool, the connection is very fast.</p>
<p>When I use PHP to connect to the remote DB, the connection time may take up to 5 seconds. Queries after this are executed quickly.</p>
<p>This is not limited to mysql, using file_get_contents() to download a file from nearly any other server gives the same lag. Using wget to get the file does not have this lag.</p>
<p>I timed DNS queries from within PHP using dns_get_record(), and these are fast (1-2 milliseconds).</p>
<p>Any thoughts on what in the php config may be causing this? </p>
<p>Thanks.</p>
|
[
{
"answer_id": 275204,
"author": "Jay",
"author_id": 31479,
"author_profile": "https://Stackoverflow.com/users/31479",
"pm_score": 2,
"selected": true,
"text": "gethostbyname('example.com')\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31479/"
] |
274,296
|
<p>Does anyone know of an already implemented money type for the .NET framework that supports i18n (currencies, formatting, etc)? I have been looking for a well implemented type and can't seem to find one.</p>
|
[
{
"answer_id": 274316,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "CultureInfo current = CultureInfo.CurrentCulture;\ndecimal myMoney = 99.99m;\n\n//formats as money in current culture, like $99.99\nstring formattedMoney = myMoney.ToString(\"C\", current); \n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2220/"
] |
274,307
|
<p>Just as an example, if I have a <code>Book</code> model and a <code>BooksController</code>, autotest, part of the ZenTest suite will pick up the association between the two and load <code>test/unit/book_test.rb</code> and <code>test/functional/books_controller_test.rb</code> into the test suite. On the other hand, if I have a <code>Story</code> model and a <code>StoriesController</code>, autotest refuse to "notice" the <code>test/functional/stories_controller_test.rb</code></p>
|
[
{
"answer_id": 274316,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "CultureInfo current = CultureInfo.CurrentCulture;\ndecimal myMoney = 99.99m;\n\n//formats as money in current culture, like $99.99\nstring formattedMoney = myMoney.ToString(\"C\", current); \n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31891/"
] |
274,308
|
<p>Is which IPs are assigned to which ISPs public information? How do geo IP services obtain this information and maintain this information?</p>
<p>How can I personally figure out where a certain IP belongs without using one of these services?</p>
|
[
{
"answer_id": 277537,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 7,
"selected": true,
"text": "whois whois"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
274,309
|
<p>Is there any benefit on Windows to use the WSA winsock functions compared to the BSD-style ones?</p>
|
[
{
"answer_id": 276688,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": true,
"text": "read write"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
274,315
|
<p>I'm writing a C# app using the WebBrowser control, and I want all content I display to come from embedded resources - not static local files, and not remote files.</p>
<p>Setting the initial text of the control to an embedded HTML file works great with this code inspired by <a href="http://blog.topholt.com/2008/03/18/c-trick-load-embedded-resources-in-a-class-library/" rel="nofollow noreferrer">this post</a>:</p>
<pre><code>browser.DocumentText=loadResourceText("myapp.index.html");
private string loadResourceText(string name)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream(name);
StreamReader streamReader = new StreamReader(stream);
String myText = streamReader.ReadToEnd();
return myText;
}
</code></pre>
<p>As good as that is, files referred to in the HTML - javascript, images like <code><img src="whatever.png"/></code> etc, don't work. I found similar questions <a href="https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840">here</a> and <a href="https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript">here</a>, but neither is asking <em>exactly</em> what I mean, namely referring to <em>embedded</em> resources in the exe, not files. </p>
<p>I tried <code>res://...</code> and using a <code><base href='..."</code> but neither seemed to work (though I may have not got it right).</p>
<p>Perhaps (following my own suggestion on <a href="https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840">this question</a>), using a little embedded C# webserver is the only way... but I would have thought there is some trick to get this going?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 274530,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "WebBrowser HttpListener"
},
{
"answer_id": 1471460,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/// Hi try this may help u.\nprivate string CheckImages(ExtendedWebBrowser browser)\n{\n StringBuilder builderHTML = new StringBuilder(browser.Document.Body.Parent.OuterHtml);\n ProcessURLS(browser, builderHTML, \"img\", \"src\"); \n ProcessURLS(browser, builderHTML, \"link\", \"href\");\n // ext...\n\n return builderHTML.ToString();\n\n}\n\nprivate static void ProcessURLS(ExtendedWebBrowser browser, StringBuilder builderHTML, string strLink, string strHref)\n{\n for (int k = 0; k < browser.Document.Body.Parent.GetElementsByTagName(strLink).Count; k++)\n {\n string strURL = browser.Document.Body.Parent.GetElementsByTagName(strLink)[k].GetAttribute(strHref);\n string strOuterHTML = browser.Document.Body.Parent.GetElementsByTagName(strLink)[k].OuterHtml;\n string[] strlist = strOuterHTML.Split(new string[] { \" \" }, StringSplitOptions.None);\n StringBuilder builder = new StringBuilder();\n for (int p = 0; p < strlist.Length; p++)\n {\n if (strlist[p].StartsWith(strHref)) \n builder.Append (strlist[p].Contains(\"http\")? strlist[p] + \" \":\n (strURL.StartsWith(\"http\") ? strHref + \"=\" + strURL + \" \":\n strHref + \"= \" + \"http://xyz.com\" + strURL + \" \" )); \n else\n builder.Append(strlist[p] + \" \");\n }\n\n builderHTML.Replace(strOuterHTML, builder.ToString());\n }\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25362/"
] |
274,319
|
<p>I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?</p>
|
[
{
"answer_id": 274325,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 6,
"selected": false,
"text": "-(IBAction)userDoneEnteringText:(id)sender\n{\n UITextField theField = (UITextField*)sender;\n // do whatever you want with this text field\n}\n"
},
{
"answer_id": 274354,
"author": "kubi",
"author_id": 28422,
"author_profile": "https://Stackoverflow.com/users/28422",
"pm_score": 9,
"selected": true,
"text": "UITextField ViewController - (BOOL)textFieldShouldReturn:(UITextField *)textField {\n [textField resignFirstResponder];\n return NO;\n}\n"
},
{
"answer_id": 286109,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "UITextField delegate viewDidLoad - (void)viewDidLoad \n{\n // sets the textField delegates to equal this viewController ... this allows for the keyboard to disappear after pressing done\n daTextField.delegate = self;\n}\n"
},
{
"answer_id": 813097,
"author": "Hugo",
"author_id": 99595,
"author_profile": "https://Stackoverflow.com/users/99595",
"pm_score": 5,
"selected": false,
"text": " -(IBAction)editingEnded:(id)sender{\n [sender resignFirstResponder]; \n}\n"
},
{
"answer_id": 1501581,
"author": "mobibob",
"author_id": 157804,
"author_profile": "https://Stackoverflow.com/users/157804",
"pm_score": 2,
"selected": false,
"text": "- (BOOL)textFieldShouldReturn:(UITextField *)textField {\n NSLog(@\"%s\", __FUNCTION__);\n\n bool fDidResign = [textField resignFirstResponder];\n\n NSLog(@\"%s: did %resign the keyboard\", __FUNCTION__, fDidResign ? @\"\" : @\"not \");\n\n return fDidResign;\n}\n - (BOOL)textFieldShouldEndEditing:(UITextField *)textField {\n NSLog(@\"%s\", __FUNCTION__);\n\n if( [[textField text] isEqualToString:@\"NO!\"] ) {\n NSLog(@\"%@\", textField.text);\n return NO;\n } else {\n return YES;\n }\n}\n"
},
{
"answer_id": 3517932,
"author": "user415897",
"author_id": 415897,
"author_profile": "https://Stackoverflow.com/users/415897",
"pm_score": 4,
"selected": false,
"text": "[textField endEditing:YES];\n"
},
{
"answer_id": 4445098,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 4,
"selected": false,
"text": "dummy: dummy: dummy:"
},
{
"answer_id": 11142987,
"author": "Ryan Bourne",
"author_id": 1472792,
"author_profile": "https://Stackoverflow.com/users/1472792",
"pm_score": 2,
"selected": false,
"text": "-(IBAction)backgroundIsTapped:(id)sender\n [answerField resignFirstResponder];\n IBOutlet UITextField * <nameoftextfieldhere>;\n"
},
{
"answer_id": 17281631,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": -1,
"selected": false,
"text": "textField.returnKeyType = UIReturnKeyDone;\n"
},
{
"answer_id": 18761422,
"author": "pooja_chaudhary",
"author_id": 2572580,
"author_profile": "https://Stackoverflow.com/users/2572580",
"pm_score": 0,
"selected": false,
"text": "-(IBAction)Hidekeyboard \n{ \n textfield_name.resignFirstResponder; \n} \n"
},
{
"answer_id": 19950504,
"author": "chandru",
"author_id": 2955364,
"author_profile": "https://Stackoverflow.com/users/2955364",
"pm_score": 0,
"selected": false,
"text": "-(IBAction)dismissKeyboard:(id)sender\n{\n[sender resignFirstResponder];\n}\n"
},
{
"answer_id": 21481747,
"author": "Vineesh TP",
"author_id": 1213364,
"author_profile": "https://Stackoverflow.com/users/1213364",
"pm_score": 0,
"selected": false,
"text": "- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text\n{\n if ([text isEqualToString:@\"\\n\"]) {\n [textView resignFirstResponder];\n return NO;\n }\n return YES;\n}\n"
},
{
"answer_id": 25829644,
"author": "jake",
"author_id": 3092976,
"author_profile": "https://Stackoverflow.com/users/3092976",
"pm_score": 0,
"selected": false,
"text": "//====================================================\n// textFieldShouldReturn:\n//====================================================\n-(BOOL) textFieldShouldReturn:(UITextField*) textField { \n [textField resignFirstResponder];\n if(textField.returnKeyType != UIReturnKeyDone){\n [[textField.superview viewWithTag: self.nextTextField] becomeFirstResponder];\n }\n return YES;\n}\n"
},
{
"answer_id": 25863083,
"author": "Metalhead1247",
"author_id": 1837565,
"author_profile": "https://Stackoverflow.com/users/1837565",
"pm_score": 2,
"selected": false,
"text": " - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event \n {\n\n [self.yourTextField resignFirstResponder];\n\n }\n - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n { \n [self.view endEditing:YES];\n }\n"
},
{
"answer_id": 32447740,
"author": "Moose",
"author_id": 441197,
"author_profile": "https://Stackoverflow.com/users/441197",
"pm_score": 1,
"selected": false,
"text": "#import <UIKit/UIKit.h>\n\n@interface UIFormView : UIView<UITextFieldDelegate>\n\n-(BOOL)textFieldValueIsValid:(UITextField*)textField;\n-(void)endEdit;\n\n@end\n #import \"UIFormView.h\"\n\n@implementation UIFormView\n{\n UITextField* currentEditingTextField;\n}\n\n// Automatically register fields\n\n-(void)addSubview:(UIView *)view\n{\n [super addSubview:view];\n if ([view isKindOfClass:[UITextField class]]) {\n if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];\n }\n}\n\n// UITextField Protocol\n\n-(void)textFieldDidBeginEditing:(UITextField *)textField\n{\n currentEditingTextField = textField;\n}\n\n-(void)textFieldDidEndEditing:(UITextField *)textField\n{\n currentEditingTextField = NULL;\n}\n\n-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event\n{\n [self endEdit];\n}\n\n- (BOOL)textFieldShouldReturn:(UITextField *)textField\n{\n if ([self textFieldValueIsValid:textField]) {\n [self endEdit];\n return YES;\n } else {\n return NO;\n }\n}\n\n// Own functions\n\n-(void)endEdit\n{\n if (currentEditingTextField) {\n [currentEditingTextField endEditing:YES];\n currentEditingTextField = NULL;\n }\n}\n\n\n// Override this in your subclass to handle eventual values that may prevent validation.\n\n-(BOOL)textFieldValueIsValid:(UITextField*)textField\n{\n return YES;\n}\n\n@end\n textFieldValueIsValid:"
},
{
"answer_id": 33496692,
"author": "Abhimanyu Rathore",
"author_id": 3811649,
"author_profile": "https://Stackoverflow.com/users/3811649",
"pm_score": 1,
"selected": false,
"text": "[[self view]endEditing:YES];\n <UITextFieldDelegate>\n"
},
{
"answer_id": 37105867,
"author": "Safin Ahmed",
"author_id": 4023670,
"author_profile": "https://Stackoverflow.com/users/4023670",
"pm_score": 4,
"selected": false,
"text": "@IBAction func returnPressed(sender: UITextField) {\n self.view.endEditing(true)\n}\n"
},
{
"answer_id": 41509280,
"author": "Burf2000",
"author_id": 369313,
"author_profile": "https://Stackoverflow.com/users/369313",
"pm_score": 1,
"selected": false,
"text": "func textFieldShouldReturn(textField: UITextField) -> Bool { \n textField.resignFirstResponder() \nreturn false }\n"
},
{
"answer_id": 46044623,
"author": "Artem Deviatov",
"author_id": 3110071,
"author_profile": "https://Stackoverflow.com/users/3110071",
"pm_score": -1,
"selected": false,
"text": "@IBAction private func noteFieldDidEndOnExit(_ sender: UITextField) {}"
},
{
"answer_id": 48002031,
"author": "Tanjima Kothiya",
"author_id": 9135954,
"author_profile": "https://Stackoverflow.com/users/9135954",
"pm_score": 1,
"selected": false,
"text": " lazy var firstNameTF: UITextField = {\n\n let firstname = UITextField()\n firstname.placeholder = \"FirstName\"\n firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)\n firstname.textAlignment = .center\n firstname.borderStyle = UITextBorderStyle.roundedRect\n firstname.keyboardType = UIKeyboardType.default\n firstname.delegate = self\n return firstname\n}()\n\nlazy var lastNameTF: UITextField = {\n\n let lastname = UITextField()\n lastname.placeholder = \"LastName\"\n lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)\n lastname.textAlignment = .center\n lastname.borderStyle = UITextBorderStyle.roundedRect\n lastname.keyboardType = UIKeyboardType.default\n lastname.delegate = self\n return lastname\n}()\n\nlazy var emailIdTF: UITextField = {\n\n let emailid = UITextField()\n emailid.placeholder = \"EmailId\"\n emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)\n emailid.textAlignment = .center\n emailid.borderStyle = UITextBorderStyle.roundedRect\n emailid.keyboardType = UIKeyboardType.default\n emailid.delegate = self\n return emailid\n}()\n override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {\n view.endEditing(true)\n}\n\nfunc textFieldShouldReturn(_ textField: UITextField) -> Bool {\n\n if textField == firstNameTF {\n\n lastNameTF.becomeFirstResponder()\n }\n\n else if textField == lastNameTF {\n\n emailIdTF.becomeFirstResponder()\n }\n else {\n view.emailIdTF(true)\n }\n return true\n}\n"
},
{
"answer_id": 54823250,
"author": "Prakhar Prakash Bhardwaj",
"author_id": 10739965,
"author_profile": "https://Stackoverflow.com/users/10739965",
"pm_score": 0,
"selected": false,
"text": " override func viewDidLoad() {\n super.viewDidLoad()\n\n let tap = UITapGestureRecognizer(target: self, action: \n #selector(dismissKeyboard))\n\n view.addGestureRecognizer(tap)\n }\n\n @objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {\n numberField.resignFirstResponder()\n }\n"
},
{
"answer_id": 56944913,
"author": "Gulsan Borbhuiya",
"author_id": 8593710,
"author_profile": "https://Stackoverflow.com/users/8593710",
"pm_score": 4,
"selected": false,
"text": "Swift 4.2 import UIKit\n\nclass ViewController: UIViewController, UITextFieldDelegate {\n\n @IBOutlet weak var textField: UITextField!\n\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n self.textField.delegate = self\n\n }\n\n // hide key board when the user touches outside keyboard\n\n override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {\n self.view.endEditing(true)\n }\n\n // user presses return key\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n textField.resignFirstResponder()\n return true\n }\n\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28422/"
] |
274,344
|
<p>When you lock an object is that object locked throughout the whole application?</p>
<p>For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types":</p>
<pre><code>static void AddItems( )
{
for (int i = 0; i < 100; i++)
lock (list)
list.Add ("Item " + list.Count);
string[] items;
lock (list) items = list.ToArray( );
foreach (string s in items) Console.WriteLine (s);
}
</code></pre>
<p>Does the first lock:</p>
<pre><code>lock (list)
list.Add ("Item " + list.Count);
</code></pre>
<p>prevent another thread from accessing:</p>
<pre><code>lock (list) items = list.ToArray( );
</code></pre>
<p>or can both be executed at the same time?</p>
<p>And does the CLR automatically make your static methods thread safe? Or is that up to the developer?</p>
<p>Thanks,
John</p>
|
[
{
"answer_id": 274357,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 3,
"selected": true,
"text": "class UsefulStuff {\n object _TheLock = new object { };\n public void UsefulThingNumberOne() {\n lock(_TheLock) {\n //CodeBlockA\n }\n }\n public void UsefulThingNumberTwo() {\n lock(_TheLock) {\n //CodeBlockB\n }\n }\n}\n CodeBlockA CodeBlockB _TheLock _TheLock"
},
{
"answer_id": 274564,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": false,
"text": "public class Foo\n{\n private static Foo instance = new Foo();\n\n public static Foo Instance\n {\n get { return instance; }\n }\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19490/"
] |
274,348
|
<p>In my small WPF project, I have a <code>TabControl</code> with three tabs. On each tab is a <code>ListBox</code>. This project keeps track of groceries we need to buy. (No, it's not homework, it's for my wife.) So I have a list of <code>ShoppingListItem</code>s, each of which has a <code>Name</code> and a <code>Needed</code> property: <code>true</code> when we need the item, and <code>false</code> after we buy it.</p>
<p>So the three tabs are All, Bought, and Needed. They should all point to the same <code>ShoppingListItemCollection</code> (which inherits from <code>ObservableCollection<ShoppingListItem></code>). But Bought should only show the items where Needed is false, and Needed should only show items where Needed is true. (The All tab has checkboxes on the items.)</p>
<p>This doesn't seem <em>that</em> hard, but after a couple hours, I'm no closer to figuring this out. It seems like a CollectionView or CollectionViewSource is what I need, but I can't get anything to happen; I check and uncheck the boxes on the All tab, and the items on the other two tabs just sit there staring at me.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 274458,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 2,
"selected": false,
"text": "<Window.Resources>\n <CollectionViewSource x:Key=\"NeededItems\" Source=\"{Binding Items}\" Filter=\"NeededCollectionViewSource_Filter\" />\n <CollectionViewSource x:Key=\"BoughtItems\" Source=\"{Binding Items}\" Filter=\"BoughtCollectionViewSource_Filter\" />\n</Window.Resources>\n\n<TabControl>\n <TabItem Header=\"All\">\n <ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Items}\" />\n </TabItem>\n <TabItem Header=\"Bought\">\n <ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Source={StaticResource BoughtItems}}\" />\n </TabItem>\n <TabItem Header=\"Needed\">\n <ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Source={StaticResource NeededItems}}\" />\n </TabItem>\n</TabControl>\n private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e)\n{\n e.Accepted = ((ShoppingListItem) e.Item).Needed;\n}\n\nprivate void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e)\n{\n e.Accepted = !((ShoppingListItem) e.Item).Needed;\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
274,349
|
<p>As title. </p>
<p>ruby test/functionals/whatevertest.rb doesn't work, that requires me to replace all <code>require 'test_helper'</code> to <code>require File.dirname(__FILE__) + '/../test_helper'</code>. For some reason most of those test templates have such issue, so I rather to see if there is a hack I could get around it.</p>
|
[
{
"answer_id": 274507,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "(cd test && ruby functionals/whatevertest.rb) fork"
},
{
"answer_id": 3577710,
"author": "Szymon Jeż",
"author_id": 408011,
"author_profile": "https://Stackoverflow.com/users/408011",
"pm_score": 2,
"selected": false,
"text": "ruby unit/post_test.rb -n selected_test # use to run only one selected test\n"
},
{
"answer_id": 7986304,
"author": "user664833",
"author_id": 664833,
"author_profile": "https://Stackoverflow.com/users/664833",
"pm_score": 6,
"selected": false,
"text": "ruby -I test test/functional/whatevertest.rb\n functional ruby -I test test/functional/whatevertest.rb -n test_should_get_index\n ruby -I test test/functional/whatevertest.rb -n 'test should get index'\n unit functional unit bundle exec bundle exec ruby -I test test/unit/specific_model_test.rb\nbundle exec ruby -I test test/unit/specific_model_test.rb -n test_divide_by_zero\nbundle exec ruby -I test test/unit/specific_model_test.rb -n 'test divide by zero'\n -n test test \"should get high\" do\n assert true\nend\n\ndef test_should_get_high\n assert true\nend\n bundle exec ruby -I test test/integration/misc_test.rb -n 'test should get high'\nbundle exec ruby -I test test/integration/misc_test.rb -n test_should_get_high\n"
},
{
"answer_id": 12282921,
"author": "B Seven",
"author_id": 336920,
"author_profile": "https://Stackoverflow.com/users/336920",
"pm_score": 2,
"selected": false,
"text": "ruby -I test test/functional/users_controller_test.rb -n \"/the_test_name/\"\n test \"the test name\" do\n ruby -I test test/functional/alerts_controller_test.rb -n \"/foo/\"\nruby -I test test/functional/alerts_controller_test.rb -n \"/do_foo/\"\n ruby -I test test/functional/alerts_controller_test.rb -n \"/do foo/\"\n"
},
{
"answer_id": 21598535,
"author": "Swanand",
"author_id": 18768,
"author_profile": "https://Stackoverflow.com/users/18768",
"pm_score": 3,
"selected": false,
"text": "rake test test/unit/user_test.rb\nrake test test/unit\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16371/"
] |
274,360
|
<p>Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?</p>
|
[
{
"answer_id": 274363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "interface IInterface\n{\n}\n\nclass TheClass implements IInterface\n{\n}\n\n$cls = new TheClass();\nif ($cls instanceof IInterface) {\n echo \"yes\";\n}\n"
},
{
"answer_id": 274476,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": false,
"text": "instanceof instanceof IInterface $class = new ReflectionClass('TheClass');\nif ($class->implementsInterface('IInterface'))\n{\n print \"Yep!\\n\";\n}\n"
},
{
"answer_id": 12031401,
"author": "Jess Telford",
"author_id": 473961,
"author_profile": "https://Stackoverflow.com/users/473961",
"pm_score": 7,
"selected": false,
"text": "class_implements() interface IInterface\n{\n}\n\nclass TheClass implements IInterface\n{\n}\n\n$interfaces = class_implements('TheClass');\n\nif (isset($interfaces['IInterface'])) {\n echo \"Yes!\";\n}\n class_implements() public function __construct() {\n $tmp = array(\n 'foo' => 'bar',\n 'this' => 'that'\n ); \n\n $in = in_array('those', $tmp);\n}\n"
},
{
"answer_id": 21826939,
"author": "d.raev",
"author_id": 1621821,
"author_profile": "https://Stackoverflow.com/users/1621821",
"pm_score": 5,
"selected": false,
"text": "if (is_subclass_of($my_class_instance, 'ISomeInterfaceName')){\n echo 'I can do it!';\n}\n"
},
{
"answer_id": 32307868,
"author": "Starx",
"author_id": 295264,
"author_profile": "https://Stackoverflow.com/users/295264",
"pm_score": 3,
"selected": false,
"text": "public function yourMethod(YourInterface $objectSupposedToBeImplementing) {\n //.....\n}\n $objectSupposedToBeImplementing YourInterface"
},
{
"answer_id": 60517838,
"author": "SirPilan",
"author_id": 9968486,
"author_profile": "https://Stackoverflow.com/users/9968486",
"pm_score": 4,
"selected": false,
"text": "is_a instanceof [object] took 7.67 ms | + 0% | ..........\n is_a [object] took 12.30 ms | + 60% | ................\n is_a [class] took 17.43 ms | +127% | ......................\nclass_implements [object] took 28.37 ms | +270% | ....................................\n reflection [class] took 34.17 ms | +346% | ............................................\n instanceof is_a is_a is_a(<className>, <interfaceName>, true); bool"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
274,361
|
<p>ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that
does this operation: </p>
<pre><code>strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30)
</code></pre>
<p>I get this error: </p>
<blockquote>
<p>chr() arg not in range(256)</p>
</blockquote>
<p>If I try to encode the string as latin-1 first I get this error:</p>
<blockquote>
<p>'latin-1' codec can't encode characters in position 0-3: ordinal not
in range(256)</p>
</blockquote>
<p>I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!</p>
|
[
{
"answer_id": 274403,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": ">>> a = '\\222\\222\\223\\225'\n>>> u = unicode(a,'latin-1')\n>>> u\nu'\\x92\\x92\\x93\\x95'\n>>> print u.encode('utf-8')\nÂÂÂÂ\n>>> print u.encode('utf-16')\nÿþ\n>>> print u.encode('latin-1')\n\n>>> for c in u:\n... print chr(ord(c) - 3 - 0 -30)\n...\nq\nq\nr\nt\n>>> for c in u:\n... print chr(ord(c) - 3 -200 -30)\n...\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\nValueError: chr() arg not in range(256)\n"
},
{
"answer_id": 274440,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "\\222 = 0x92 => PRIVATE USE TWO\n\\223 = 0x93 => SET TRANSMIT STATE\n\\225 = 0x95 => MESSAGE WAITING\n U+0092 = %11000010 %10010010 = 0xC2 0x92\nU+0093 = %11000010 %10010011 = 0xC2 0x93\nU+0095 = %11000010 %10010101 = 0xC2 0x95\n Now I need to pass the string into a function that does this operation:\n\n strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30)\n\nI get this error: chr() arg not in range(256). If I try to encode the\nstring as Latin-1 first I get this error: 'latin-1' codec can't encode\ncharacters in position 0-3: ordinal not in range(256).\n ord(c) - 3 - intCounter - 30 ord(c) - intCounter - 33 chr() chr() chr(mod(ord(c) - mod(intCounter, 255) + 479, 255))\n chr() mod() mod()"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35697/"
] |
274,375
|
<p>I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my proxy, the proxy would then delegate the intercepted messages to an awaiting thread/fork to pass the message on and recieve the results. The other was to try and sniff the traffic between client & service.</p>
<p>My primary goal is to avoid any serious loss in transmission speed between client & application but get 100% complete communications between client & service.</p>
<p>Environment: UBuntu 8.04</p>
<p>Language: c/c++</p>
<p>In the background I was thinking of using a sqlite DB running completely in memory or a 20-25MB memcache dameon slaved to my process.</p>
<p>Update:
Specifically I am trying to track the usage of keys for a memcache daemon, storing the # of sets/gets success/fails on the key. The idea is that most keys have some sort of separating character [`|_-#] to create a sort of namespace. The idea is to step in between the daemon and the client, split the keys apart by a configured separator and record statistics on them. </p>
|
[
{
"answer_id": 274393,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "iptables iptables -I INPUT -p tcp -d $HOST_IP --dport $HOST_PORT -j LOG $LOG_OPTIONS\n iptables ULOG"
},
{
"answer_id": 274481,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 1,
"selected": true,
"text": "- If you do the packet capture approach, you have to reassemble the TCP\n streams into something usable yourself. OTOH, if your monitor program\n gets bogged down, it'll just lose some packets, it won't break the cache.\n Same if it crashes. You also don't have to reconfigure anything; packet\n capture is transparent. \n\n- If you do the proxy approach, the kernel handles all the TCP work for\n you. You'll never lose requests. But if your monitor bogs down, it'll bog\n down the app. And if your monitor crashes, it'll break caching. You\n probably will have to reconfigure your app and/or memcached servers so\n that the connections go through the proxy.\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] |
274,384
|
<p>Is anyone aware of any gems, tutorials, or solutions enabling a user to sign in to a website at one domain and automatically given access to other partner domains in the same session? </p>
<p>I have two rails apps running, let's call them App-A and App-B. App-A has a database associated with it, powering the registration and login at App-A.com. I'd now like to give all of those users with App-A.com accounts access to App-B.com, without making them reregister or manually login to App-B.com separately.</p>
<p>Thanks in advance for any help!
--Mark</p>
|
[
{
"answer_id": 274640,
"author": "Ricardo Acras",
"author_id": 19224,
"author_profile": "https://Stackoverflow.com/users/19224",
"pm_score": 4,
"selected": true,
"text": "Rails::Initializer.run do |config|\n ... \n config.action_controller.session = {\n :session_key => '_portal_session',\n :secret => '72bf006c18d459acf51836d2aea01e0afd0388f860fe4b07a9a57dedd25c631749ba9b65083a85af38bd539cc810e81f559e76d6426c5e77b6064f42e14f7415'\n }\n ...\nend\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
274,404
|
<p>How can I know in a C#-Application, in which direction the screen of the mobile device is orientated? (i.e. horizontal or vertical).</p>
|
[
{
"answer_id": 274456,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 0,
"selected": false,
"text": "var rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;\n// or var rect = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;\n\nvar ratio = rect.Width / rect.Height;\n\nif (ratio == 1.0) // square screen.\nif (ratio > 1.0) // landscape.\nif (ratio < 1.0) // portrait.\n"
},
{
"answer_id": 961519,
"author": "mSafdel",
"author_id": 100265,
"author_profile": "https://Stackoverflow.com/users/100265",
"pm_score": 1,
"selected": false,
"text": "int orientation=Microsoft.WindowsMobile.Status.SystemState.DisplayRotation;\nif(orientation== 90 || orientation==-90 || orientation==270) //Landscape is 90 or -90 or 270\n{\n //your code;\n}\nelse\n{\n //your code;\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26070/"
] |
274,408
|
<p>I'm trying to create a database scripter tool for a local database I'm using.</p>
<p>I've been able to generate create scripts for the tables, primary keys, indexes, and foreign keys, but I can't find any way to generate create scripts for the table defaults.</p>
<p>For indexes, it's as easy as </p>
<pre><code>foreach (Index index in table.Indexes)
{
ScriptingOptions drop = new ScriptingOptions();
drop.ScriptDrops = true;
drop.IncludeIfNotExists = true;
foreach (string dropstring in index.Script(drop))
{
createScript.Append(dropstring);
}
ScriptingOptions create = new ScriptingOptions();
create.IncludeIfNotExists = true;
foreach (string createstring in index.Script(create))
{
createScript.Append(createstring);
}
}
</code></pre>
<p>But the Table object doesn't have a Defaults property. Is there some other way to generate scripts for the table defaults?</p>
|
[
{
"answer_id": 274578,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 3,
"selected": false,
"text": "Server server = new Server(@\".\\SQLEXPRESS\");\nDatabase db = server.Databases[\"AdventureWorks\"];\nList<Urn> list = new List<Urn>();\nDataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);\nforeach (DataRow row in dataTable.Rows)\n{\n list.Add(new Urn((string)row[\"Urn\"]));\n}\nScripter scripter = new Scripter();\nscripter.Server = server;\nscripter.Options.IncludeHeaders = true;\nscripter.Options.SchemaQualify = true;\nscripter.Options.SchemaQualifyForeignKeysReferences = true;\nscripter.Options.NoCollation = true;\nscripter.Options.DriAllConstraints = true;\nscripter.Options.DriAll = true;\nscripter.Options.DriAllKeys = true;\nscripter.Options.DriIndexes = true;\nscripter.Options.ClusteredIndexes = true;\nscripter.Options.NonClusteredIndexes = true;\nscripter.Options.ToFileOnly = true;\nscripter.Options.FileName = @\"C:\\tables.sql\";\nscripter.Script(list.ToArray());\n"
},
{
"answer_id": 45218123,
"author": "Goldfish",
"author_id": 3355999,
"author_profile": "https://Stackoverflow.com/users/3355999",
"pm_score": 0,
"selected": false,
"text": "/*get a particular table script only*/\nTable myTable = db.Tables[\"TableName\", \"SchemaName\"];\nscripter.Script(new Urn[] { myTable.Urn});\n StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });\nforeach (string script in sc)\n{\n sb.AppendLine();\n sb.AppendLine(\"--create table\");\n sb.Append(script + \";\");\n}\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
274,411
|
<p>Jeff Atwood wrote about this <a href="https://blog.codinghorror.com/who-needs-stored-procedures-anyways/" rel="noreferrer">here</a>, and while I understand the theoretical performance boost a stored procedure could offer, it does seem like a tremendous pain.</p>
<p>What types of queries would you see the most performance increase using stored procedures, and what types of queries would you rather just build on the fly?</p>
<p>Any documentation one way or another would be greatly appreciated.</p>
|
[
{
"answer_id": 275010,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 4,
"selected": false,
"text": "-- First, clear the cache\nDBCC FREEPROCCACHE\n\n-- Look at what executable plans are in cache\nSELECT sc.*\nFROM master.dbo.syscacheobjects AS sc\nWHERE sc.cacheobjtype = 'Executable Plan'\n\n-- Execute the following statement\nSELECT t.*\nFROM pubs.dbo.titles AS t\nWHERE t.price = 19.99\n\n-- Look at what executable plans are in cache and you'll \n-- find that there's a plan for a NUMERIC(4,2)\nSELECT sc.*\nFROM master.dbo.syscacheobjects AS sc\nWHERE sc.cacheobjtype = 'Executable Plan'\n\n-- If you execute the EXACT same statement with a 4,2 \n-- then you will get THAT plan. But if you execute with a 5,2\n-- then you'll get a new plan. Try this:\nSELECT t.*\nFROM pubs.dbo.titles AS t\nWHERE price = 199.99\n\n-- Look again at the cached executable plans, and you'll see a NEW one...\nSELECT sc.*\nFROM master.dbo.syscacheobjects AS sc\nWHERE sc.cacheobjtype = 'Executable Plan'\n DECLARE @ExecStr nvarchar(4000)\nSELECT @ExecStr = N'SELECT t.* FROM dbo.titles AS t WHERE t.price = @price'\nEXEC sp_executesql @ExecStr, N'@price money', 19.99\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25538/"
] |
274,439
|
<p>How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140. </p>
<p>I can easily do it by hand</p>
<pre><code>return ((int)(number / 10)) * 10;
</code></pre>
<p>But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above. </p>
|
[
{
"answer_id": 274453,
"author": "Armstrongest",
"author_id": 26931,
"author_profile": "https://Stackoverflow.com/users/26931",
"pm_score": 5,
"selected": false,
"text": "int number = 236;\nnumber = (int)(Math.Ceiling(number / 10.0d) * 10);\n // number = 236 + 10 - 6\n public static int roundupbyten(this int i){\n // return i + (10 - i % 10); <-- logic error. Oops!\n return (int)(Math.Ceiling(i / 10.0d)*10); // fixed\n}\n\n// call like so:\nint number = 236.roundupbyten();\n"
},
{
"answer_id": 274487,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 8,
"selected": true,
"text": "public static class ExtensionMethods\n{\n public static int RoundOff (this int i)\n {\n return ((int)Math.Round(i / 10.0)) * 10;\n }\n}\n\nint roundedNumber = 236.RoundOff(); // returns 240\nint roundedNumber2 = 11.RoundOff(); // returns 10\n int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240\nint roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10\n"
},
{
"answer_id": 1788392,
"author": "Jronny",
"author_id": 217606,
"author_profile": "https://Stackoverflow.com/users/217606",
"pm_score": 5,
"selected": false,
"text": "public int RoundOff(int number, int interval){\n int remainder = number % interval;\n number += (remainder < interval / 2) ? -remainder : (interval - remainder);\n return number;\n}\n int number = 11;\nint roundednumber = RoundOff(number, 10);\n"
},
{
"answer_id": 11822721,
"author": "Dave",
"author_id": 389665,
"author_profile": "https://Stackoverflow.com/users/389665",
"pm_score": 2,
"selected": false,
"text": "Math int MyRoundedUp1024Int = ((lSomeInteger + 1023) / 1024) * 1024;\n"
},
{
"answer_id": 14493950,
"author": "Lucas925",
"author_id": 2006170,
"author_profile": "https://Stackoverflow.com/users/2006170",
"pm_score": 2,
"selected": false,
"text": " private double Rounding(double d, int digits)\n {\n int neg = 1;\n if (d < 0)\n {\n d = d * (-1);\n neg = -1;\n }\n\n int n = 0;\n if (d > 1)\n {\n while (d > 1)\n {\n d = d / 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d * Math.Pow(10, n - digits);\n }\n else\n {\n while (d < 0.1)\n {\n d = d * 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d / Math.Pow(10, n + digits);\n }\n\n return d*neg;\n }\n\n\n private void testing()\n {\n double a = Rounding(1230435.34553,3);\n double b = Rounding(0.004567023523,4);\n double c = Rounding(-89032.5325,2);\n double d = Rounding(-0.123409,4);\n double e = Rounding(0.503522,1);\n Console.Write(a.ToString() + \"\\n\" + b.ToString() + \"\\n\" + \n c.ToString() + \"\\n\" + d.ToString() + \"\\n\" + e.ToString() + \"\\n\");\n }\n"
},
{
"answer_id": 71622330,
"author": "Jon",
"author_id": 2350083,
"author_profile": "https://Stackoverflow.com/users/2350083",
"pm_score": 0,
"selected": false,
"text": "int.MinValue + 1 int.MaxValue Round(x) = sgn(x)*Floor(Abs(x) + 0.5) Floor(z) = z - (z%1) F(value, factor) = Round(value/factor)*factor public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n{\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n}\n int long /// <summary>\n/// Extension methods for rounding integral numeric types\n/// </summary>\npublic static class IntegralRoundingExtensions\n{\n /// <summary>\n /// Rounds to the nearest multiple of a <paramref name=\"factor\"/> using <see cref=\"MidpointRounding.AwayFromZero\"/> for midpoints.\n /// <para>\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// </para>\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <remarks>\n /// Uses math derived from the <see href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\">Round half away from zero equation</see>: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// </remarks>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n /// <seealso cref=\"MidpointRounding\"/>\n public static long RoundToNearestMultipleOfFactor(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude less than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static long RoundToMultipleOfFactorTowardZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude greater than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static long RoundToMultipleOfFactorAwayFromZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n\n /// <summary>\n /// Rounds to the nearest multiple of a <paramref name=\"factor\"/> using <see cref=\"MidpointRounding.AwayFromZero\"/> for midpoints.\n /// <para>\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// </para>\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <remarks>\n /// Uses math derived from the <see href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\">Round half away from zero equation</see>: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// </remarks>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n /// <seealso cref=\"MidpointRounding\"/>\n public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude less than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static int RoundToMultipleOfFactorTowardZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude greater than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static int RoundToMultipleOfFactorAwayFromZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n}\n"
},
{
"answer_id": 72225775,
"author": "Snap",
"author_id": 7993601,
"author_profile": "https://Stackoverflow.com/users/7993601",
"pm_score": 0,
"selected": false,
"text": "if/else switch case public static int RoundIntToTens(int anInt)\n => (anInt, (anInt < 0 ? 0 - anInt : anInt) % 10) switch\n {\n // If int needs to be \"round down\" and is negative or positive\n (>= 0, < 5) or (< 0, < 5) => anInt - anInt % 10,\n // If int needs to be \"round up\" and is NOT negative (but might be 0)\n (>= 0, >= 5) => anInt + (10 - anInt % 10),\n // If int needs to be \"round up\" and is negative\n (< 0, >= 5) => anInt - (10 + anInt % 10)\n };\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
274,457
|
<p>I created a project using the default tab-controller project. I am using interface builder to edit the .xib file and add images and buttons. I hook them up to the FirstViewController object in interface builder (that I created and set it's class to the same as the code file). I hooked everything up using <code>IBoutlets</code> and <code>IBActions</code>. </p>
<p>Everything was working fine, but then I made some changes in interface builder (added a <code>UILabel</code>) and now a method that is run when clicked (I ran through it with the debugger) has a line that adds a subview to the view controller, and it acts as if it wasn't executed. The method (and code is run through) is executed with no errors (per the debugger) but the view is simply not being added. This happened after I made some change via interface builder. </p>
<p>Now, if I hook-up my button to "Selected First View Controller" by clicking on the appropriate tab and dragging the <code>IBOutlet</code> to the <code>UILabel</code>, that label now has multiple referencing outlets. Now, if I do the same thing for the button, the method (the <code>IBAction</code>) is executed twice but the subview is actually added and displayed. But, I get a memory access error because my <code>IBAction</code> (button) method access a property that stores something. I am guessing this has to do with somehow creating the memory in the First View Controller but trying to access it in the Selected First View Controller? If that makes any sense?</p>
<p>I have no idea why this is happening and why it just the button suddenly stopped working. I tried to explain this problem the best I could, it is sort of confusing. But if anyone has any tips or ideas I would love to hear what you guys think about this problem and how to solve it.</p>
|
[
{
"answer_id": 274453,
"author": "Armstrongest",
"author_id": 26931,
"author_profile": "https://Stackoverflow.com/users/26931",
"pm_score": 5,
"selected": false,
"text": "int number = 236;\nnumber = (int)(Math.Ceiling(number / 10.0d) * 10);\n // number = 236 + 10 - 6\n public static int roundupbyten(this int i){\n // return i + (10 - i % 10); <-- logic error. Oops!\n return (int)(Math.Ceiling(i / 10.0d)*10); // fixed\n}\n\n// call like so:\nint number = 236.roundupbyten();\n"
},
{
"answer_id": 274487,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 8,
"selected": true,
"text": "public static class ExtensionMethods\n{\n public static int RoundOff (this int i)\n {\n return ((int)Math.Round(i / 10.0)) * 10;\n }\n}\n\nint roundedNumber = 236.RoundOff(); // returns 240\nint roundedNumber2 = 11.RoundOff(); // returns 10\n int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240\nint roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10\n"
},
{
"answer_id": 1788392,
"author": "Jronny",
"author_id": 217606,
"author_profile": "https://Stackoverflow.com/users/217606",
"pm_score": 5,
"selected": false,
"text": "public int RoundOff(int number, int interval){\n int remainder = number % interval;\n number += (remainder < interval / 2) ? -remainder : (interval - remainder);\n return number;\n}\n int number = 11;\nint roundednumber = RoundOff(number, 10);\n"
},
{
"answer_id": 11822721,
"author": "Dave",
"author_id": 389665,
"author_profile": "https://Stackoverflow.com/users/389665",
"pm_score": 2,
"selected": false,
"text": "Math int MyRoundedUp1024Int = ((lSomeInteger + 1023) / 1024) * 1024;\n"
},
{
"answer_id": 14493950,
"author": "Lucas925",
"author_id": 2006170,
"author_profile": "https://Stackoverflow.com/users/2006170",
"pm_score": 2,
"selected": false,
"text": " private double Rounding(double d, int digits)\n {\n int neg = 1;\n if (d < 0)\n {\n d = d * (-1);\n neg = -1;\n }\n\n int n = 0;\n if (d > 1)\n {\n while (d > 1)\n {\n d = d / 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d * Math.Pow(10, n - digits);\n }\n else\n {\n while (d < 0.1)\n {\n d = d * 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d / Math.Pow(10, n + digits);\n }\n\n return d*neg;\n }\n\n\n private void testing()\n {\n double a = Rounding(1230435.34553,3);\n double b = Rounding(0.004567023523,4);\n double c = Rounding(-89032.5325,2);\n double d = Rounding(-0.123409,4);\n double e = Rounding(0.503522,1);\n Console.Write(a.ToString() + \"\\n\" + b.ToString() + \"\\n\" + \n c.ToString() + \"\\n\" + d.ToString() + \"\\n\" + e.ToString() + \"\\n\");\n }\n"
},
{
"answer_id": 71622330,
"author": "Jon",
"author_id": 2350083,
"author_profile": "https://Stackoverflow.com/users/2350083",
"pm_score": 0,
"selected": false,
"text": "int.MinValue + 1 int.MaxValue Round(x) = sgn(x)*Floor(Abs(x) + 0.5) Floor(z) = z - (z%1) F(value, factor) = Round(value/factor)*factor public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n{\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n}\n int long /// <summary>\n/// Extension methods for rounding integral numeric types\n/// </summary>\npublic static class IntegralRoundingExtensions\n{\n /// <summary>\n /// Rounds to the nearest multiple of a <paramref name=\"factor\"/> using <see cref=\"MidpointRounding.AwayFromZero\"/> for midpoints.\n /// <para>\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// </para>\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <remarks>\n /// Uses math derived from the <see href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\">Round half away from zero equation</see>: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// </remarks>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n /// <seealso cref=\"MidpointRounding\"/>\n public static long RoundToNearestMultipleOfFactor(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude less than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static long RoundToMultipleOfFactorTowardZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude greater than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static long RoundToMultipleOfFactorAwayFromZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n\n /// <summary>\n /// Rounds to the nearest multiple of a <paramref name=\"factor\"/> using <see cref=\"MidpointRounding.AwayFromZero\"/> for midpoints.\n /// <para>\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// </para>\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <remarks>\n /// Uses math derived from the <see href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\">Round half away from zero equation</see>: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// </remarks>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n /// <seealso cref=\"MidpointRounding\"/>\n public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var halfAbsFactor = Math.Abs(factor) >> 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude less than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static int RoundToMultipleOfFactorTowardZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// <summary>\n /// Round to the nearest multiple of <paramref name=\"factor\"/> with magnitude greater than or equal to <paramref name=\"value\"/>.\n /// </summary>\n /// <param name=\"value\">The value to round.</param>\n /// <param name=\"factor\">The factor to round to a multiple of. Must not be zero. Sign does not matter.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If <paramref name=\"factor\"/> is zero</exception>\n public static int RoundToMultipleOfFactorAwayFromZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, \"Cannot be zero\");\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n}\n"
},
{
"answer_id": 72225775,
"author": "Snap",
"author_id": 7993601,
"author_profile": "https://Stackoverflow.com/users/7993601",
"pm_score": 0,
"selected": false,
"text": "if/else switch case public static int RoundIntToTens(int anInt)\n => (anInt, (anInt < 0 ? 0 - anInt : anInt) % 10) switch\n {\n // If int needs to be \"round down\" and is negative or positive\n (>= 0, < 5) or (< 0, < 5) => anInt - anInt % 10,\n // If int needs to be \"round up\" and is NOT negative (but might be 0)\n (>= 0, >= 5) => anInt + (10 - anInt % 10),\n // If int needs to be \"round up\" and is negative\n (< 0, >= 5) => anInt - (10 + anInt % 10)\n };\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.