qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
19,610,082
I have 2 tables with the same schema already created. I want to insert rows from table1 -> table2 with the constraint of Age(column) not being duplicates. The query executes but nothing gets inserted. ``` CREATE TABLE #Global (dbName varchar(100) NULL) INSERT INTO #Global VALUES ('db1') DECLARE @temp nvarchar(1000) SELECT @temp = dbName from #Global DECLARE @sql nvarchar(max) SELECT @sql = 'INSERT INTO [dbo].[Person] ([age], [name]) SELECT [age], [name] FROM [' + @temp + ']..[Person] WHERE [Person].[age] <> [' + @temp + ']..[Person].[age]' exec sp_executesql @sql ``` Any help would be much appreciated!
2013/10/26
[ "https://Stackoverflow.com/questions/19610082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359151/" ]
Your where clause would exclude all rows. You should try something like this: ``` DECLARE @sql nvarchar(max) SELECT @sql = 'INSERT INTO [dbo].[Person] ([id], [age], [name]) SELECT min([id]) as id, [age], min([name]) as name FROM [' + @temp + ']..[Person] group by age' exec sp_executesql @sql ```
try this as the select statement: ``` INSERT INTO [dbo].[Person] ([age], [name]) SELECT [age], [name] FROM [' + @temp + ']..[Person] WHERE [' + @temp + ']..[Person].[age] not in (select distinct age from [dbo].[Person]) ```
19,610,082
I have 2 tables with the same schema already created. I want to insert rows from table1 -> table2 with the constraint of Age(column) not being duplicates. The query executes but nothing gets inserted. ``` CREATE TABLE #Global (dbName varchar(100) NULL) INSERT INTO #Global VALUES ('db1') DECLARE @temp nvarchar(1000) SELECT @temp = dbName from #Global DECLARE @sql nvarchar(max) SELECT @sql = 'INSERT INTO [dbo].[Person] ([age], [name]) SELECT [age], [name] FROM [' + @temp + ']..[Person] WHERE [Person].[age] <> [' + @temp + ']..[Person].[age]' exec sp_executesql @sql ``` Any help would be much appreciated!
2013/10/26
[ "https://Stackoverflow.com/questions/19610082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359151/" ]
Write as: ``` CREATE TABLE #Global (dbName varchar(100) NULL) INSERT INTO #Global VALUES ('db1') DECLARE @temp nvarchar(1000) SELECT @temp = dbName from #Global DECLARE @sql nvarchar(max) SELECT @sql = 'INSERT INTO [dbo].[Person] ([age], [name]) SELECT [age], [name] FROM [' + @temp + '].[Person] WHERE [' + @temp + '].[Person].[age] NOT IN (SELECT [age] from [dbo].[Person])' exec sp_executesql @sql ``` **Why your where clause is not working? Schema scope resolution always starts at the user’s default schema and revert to the dbo schema if the referenced object is not scope-qualified.** In the where clause you have not specified schema name for first table. So it's taken as DB1 the source table itself. Just try replacing it with [dbo] schema and whole statement will give you syntax error. Hope this helps!!!
try this as the select statement: ``` INSERT INTO [dbo].[Person] ([age], [name]) SELECT [age], [name] FROM [' + @temp + ']..[Person] WHERE [' + @temp + ']..[Person].[age] not in (select distinct age from [dbo].[Person]) ```
132,184
I have a few thousand binary files that have corresponding structs in them, followed by any number of bytes (this exact number of bytes is given in one of the fields in the structs). I read in data from the binary files to a struct, and assign variables from certain fields in those structs. I was wondering if there is any significant improvement I could make to speed things up, specifically regarding the binary file reading? Note: I'm reading in 256 bytes at a time to a struct, and in that struct is a number that says how many bytes follow until the next struct. So there isn't a static pattern to the data that I can follow. ``` const int STRUCT_HEADER_SIZE = 256; //256 bytes const int FILE_HEADER_SIZE = 1024; //1024 bytes [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct STRUCTHEADER { //Sample fields public ushort MagicNumber; public byte SubChannelNumber; public ushort NumChansToFollow; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public ushort[] Reserved1; public int NumBytesThisRecord; //This value says how many bytes there are total in the current 'packet' which includes this struct header. public ushort Year; public byte Month; public byte Day; public byte Hour; } FileStream stream1; STRUCTHEADER testStruct = new STRUCTHEADER(); List<string> filePaths = new List<string>(); foreach (string filePath in filePaths) //for each binary file { ReadBinaryFile(filePath); //Read the binary file } public void ReadBinaryFile(string filePath) { try { stream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None); } catch(Exception ex) { } try { stream1.Position = FILE_HEADER_SIZE; //Start stream after the file header while (stream1.Position < stream1.Length) //While not at the end of the stream { testStruct = ReadRecFromStream<STRUCTHEADER>(stream1); //read data from binary file into STRUCTHEADER type struct //assigning fields here //ex: int year = testStruct.year; stream1.Position += Math.Abs(testStruct.NumBytesThisRecord - STRUCT_HEADER_SIZE); //Advance to the end of current packet } stream1.Close(); //Adding field values to a textbox //ex: textbox1.Text += year; } catch { stream1.Close(); } } //Used to read in data in binary file to a struct private T ReadRecFromStream<T>(Stream stream) where T : struct { byte[] buffer = new byte[Marshal.SizeOf(typeof(T))]; stream.Read(buffer, 0, STRUCT_HEADER_SIZE); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } } ``` Here's a link to two sample .xtf binary files (they are the same type I'm reading in): <https://sourceforge.net/projects/imagejforxtf/files/?source=navbar>
2016/06/16
[ "https://codereview.stackexchange.com/questions/132184", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/102883/" ]
An alternative solution could be a binary reader (see also: [this code project article](http://www.codeproject.com/Articles/10750/Fast-Binary-File-Reading-with-C)) **Implementation:** (I just replaced the 2 try catch blocks with one using): ``` public static void ReadBinaryReader(string filePath) { using (var stream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { stream1.Position = FILE_HEADER_SIZE; //Start stream after the file header using (var reader = new BinaryReader(stream1)) { while (stream1.Position < stream1.Length) //While not at the end of the stream { var testStruct = FromReader(reader); //read data from binary file into STRUCTHEADER type struct stream1.Position += Math.Abs(testStruct.NumBytesThisRecord - STRUCT_HEADER_SIZE); //Advance to the end of current packet } } } } private static STRUCTHEADER FromReader(BinaryReader reader) { STRUCTHEADER result = new STRUCTHEADER(); result.MagicNumber = reader.ReadUInt16(); result.SubChannelNumber = reader.ReadByte(); result.NumChansToFollow = reader.ReadUInt16(); result.Reserved1 = new [] { reader.ReadUInt16(), reader.ReadUInt16(), }; result.NumBytesThisRecord = reader.ReadInt32(); result.Year = reader.ReadUInt16(); result.Month = reader.ReadByte(); result.Day = reader.ReadByte(); result.Hour = reader.ReadByte(); return result; } ``` It is a little bis faster, but not significat... However, if you have to use a binary reader for reading the other content, maybe it is a reasonable alternative to PtrToStructure. Reading the 6 mb file 60.000 times takes: > > **PtrToStructure** > > > 1) 3791 ms > > > 2) 3807 ms > > > 3) 3794 ms > > > **BinaryReader** > > > 1) 3650 ms > > > 2) 3645 ms > > > 3) 3668 ms > > >
~~Your problem isn't the struct reading but the reading of small junks from disc. Consider to load the whole file into a memorystream first and then use either your aproach or use the `BinaryReader` like @JanDotNet suggested.~~ --- As a side note, you really should name your things better. E.g `stream1` implies that there is at least another stream around. --- Swallowing exceptions is the way to hell. Unless you have a very good reason, you should never ever do this. If you have a valid good reason then make sure to place a comment stating **why** you are swallowing that exception. --- Don't call the `Close ()` method of the stream in the `catch`. Call it in the `finally` which makes the call in the `try` superflous. But much better use a `using` block like @JanDotNet suggested.
37,691,552
I have the following code that is leveraging multiprocessing to iterate through a large list and find a match. How can I get all processes to stop once a match is found in any one processes? I have seen examples but I none of them seem to fit into what I am doing here. ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts def do_job(first_bits): for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): # CHECK FOR MATCH HERE print(''.join(x)) # EXIT ALL PROCESSES IF MATCH FOUND if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) results = [] for i in range(num_parts): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] pool.apply_async(do_job, (first_bit,)) pool.close() pool.join() ``` Thanks for your time. **UPDATE 1:** I have implemented the changes suggested in the great approach by @ShadowRanger and it is nearly working the way I want it to. So I have added some logging to give an indication of progress and put a 'test' key in there to match. I want to be able to increase/decrease the iNumberOfProcessors independently of the num\_parts. At this stage when I have them both at 4 everything works as expected, 4 processes spin up (one extra for the console). When I change the iNumberOfProcessors = 6, 6 processes spin up but only for of them have any CPU usage. So it appears 2 are idle. Where as my previous solution above, I was able to set the number of cores higher without increasing the num\_parts, and all of the processes would get used. [![enter image description here](https://i.stack.imgur.com/YjNj4.png)](https://i.stack.imgur.com/YjNj4.png) I am not sure about how to refactor this new approach to give me the same functionality. Can you have a look and give me some direction with the refactoring needed to be able to set iNumberOfProcessors and num\_parts independently from each other and still have all processes used? Here is the updated code: ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts iProgressInterval = 10000 iNumberOfProcessors = 6 def do_job(first_bits): iAttemptNumber = 0 iLastProgressUpdate = 0 for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): sKey = ''.join(x) iAttemptNumber = iAttemptNumber + 1 if iLastProgressUpdate + iProgressInterval <= iAttemptNumber: iLastProgressUpdate = iLastProgressUpdate + iProgressInterval print("Attempt#:", iAttemptNumber, "Key:", sKey) if sKey == 'test': print("KEY FOUND!! Attempt#:", iAttemptNumber, "Key:", sKey) return True def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] return first_bit if __name__ == '__main__': # with statement with Py3 multiprocessing.Pool terminates when block exits with multiprocessing.Pool(processes = iNumberOfProcessors) as pool: # Don't need special case for final block; slices can for gotmatch in pool.imap_unordered(do_job, map(get_part, range(num_parts))): if gotmatch: break else: print("No matches found") ``` **UPDATE 2:** Ok here is my attempt at trying @noxdafox suggestion. I have put together the following based on the link he provided with his suggestion. Unfortunately when I run it I get the error: ... line 322, in apply\_async raise ValueError("Pool not running") ValueError: Pool not running Can anyone give me some direction on how to get this working. Basically the issue is that my first attempt did multiprocessing but did not support canceling all processes once a match was found. My second attempt (based on @ShadowRanger suggestion) solved that problem, but broke the functionality of being able to scale the number of processes and num\_parts size independently, which is something my first attempt could do. My third attempt (based on @noxdafox suggestion), throws the error outlined above. If anyone can give me some direction on how to maintain the functionality of my first attempt (being able to scale the number of processes and num\_parts size independently), and add the functionality of canceling all processes once a match was found it would be much appreciated. Thank you for your time. Here is the code from my third attempt based on @noxdafox suggestion: ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts iProgressInterval = 10000 iNumberOfProcessors = 4 def find_match(first_bits): iAttemptNumber = 0 iLastProgressUpdate = 0 for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): sKey = ''.join(x) iAttemptNumber = iAttemptNumber + 1 if iLastProgressUpdate + iProgressInterval <= iAttemptNumber: iLastProgressUpdate = iLastProgressUpdate + iProgressInterval print("Attempt#:", iAttemptNumber, "Key:", sKey) if sKey == 'test': print("KEY FOUND!! Attempt#:", iAttemptNumber, "Key:", sKey) return True def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] return first_bit def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue=fillvalue) class Worker(): def __init__(self, workers): self.workers = workers def callback(self, result): if result: self.pool.terminate() def do_job(self): print(self.workers) pool = multiprocessing.Pool(processes=self.workers) for part in grouper(alphabet, part_size): pool.apply_async(do_job, (part,), callback=self.callback) pool.close() pool.join() print("All Jobs Queued") if __name__ == '__main__': w = Worker(4) w.do_job() ```
2016/06/08
[ "https://Stackoverflow.com/questions/37691552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109254/" ]
You can check [this question](https://stackoverflow.com/questions/33447055/python-multiprocess-pool-how-to-exit-the-script-when-one-of-the-worker-process/33450972#33450972) to see an implementation example solving your problem. This works also with concurrent.futures pool. Just replace the `map` method with `apply_async` and iterated over your list from the caller. Something like this. ``` for part in grouper(alphabet, part_size): pool.apply_async(do_job, part, callback=self.callback) ``` [grouper recipe](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks)
`multiprocessing` isn't really designed to cancel tasks, but you can simulate it for your particular case by using `pool.imap_unordered` and terminating the pool when you get a hit: ``` def do_job(first_bits): for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): # CHECK FOR MATCH HERE print(''.join(x)) if match: return True # If we exit loop without a match, function implicitly returns falsy None for us # Factor out part getting to simplify imap_unordered use def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] if __name__ == '__main__': # with statement with Py3 multiprocessing.Pool terminates when block exits with multiprocessing.Pool(processes=4) as pool: # Don't need special case for final block; slices can for gotmatch in pool.imap_unordered(do_job, map(get_part, range(num_parts))): if gotmatch: break else: print("No matches found") ``` This will run `do_job` for each part, returning results as fast as it can get them. When a worker returns `True`, the loop breaks, and the `with` statement for the `Pool` is exited, `terminate`-ing the `Pool` (dropping all work in progress). Note that while this works, it's kind of abusing `multiprocessing`; it won't handle canceling individual tasks without terminating the whole `Pool`. If you need more fine grained task cancellation, you'll want to look at [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel), but even there, it can only cancel undispatched tasks; once they're running, they can't be cancelled without terminating the `Executor` or using a side-band means of termination (having the task poll some interprocess object intermittently to determine if it should continue running).
10,823,878
It seems on XCode I need to use std::size\_t instead of just size\_t on Visual C++. But this is a pain as I don't really want to have to `#include <cstddef>` and change every `size_t` to `std::size_t` in my code... in my Windows code `size_t` just works without including any additional files. Is there a way to make my existing code work in XCode, (maybe through the .pch file?) or are GCC/MSVC++ fundamentally different in this regard and my code needs to use `std::size_t` in order to be cross-platform?
2012/05/30
[ "https://Stackoverflow.com/questions/10823878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
Perhaps saying this somewhere near the top ? ``` using std::size_t; ```
Use `#include <stddef.h>`. So, what's the difference between `#include <stddef.h>` and `#include <cstddef>`? `<cstddef>` is a C++ header and is guaranteed to define all symbols in the `std` namespace and also *may* define things in the global namespace. `<stddef.h>`is a C header and is guaranteed to define all symbols in the global namespace and *may* also define things in the `std` namespace. So, as you said on Visual Studio, `size_t` can be used because it injects `size_t` into the global namespace for you (possibly by already including "stddef.h"). If you want that to work on any compiler include `stddef.h`. (However, as a pure C++ fan, I personally prefer `std::size_t`).
10,823,878
It seems on XCode I need to use std::size\_t instead of just size\_t on Visual C++. But this is a pain as I don't really want to have to `#include <cstddef>` and change every `size_t` to `std::size_t` in my code... in my Windows code `size_t` just works without including any additional files. Is there a way to make my existing code work in XCode, (maybe through the .pch file?) or are GCC/MSVC++ fundamentally different in this regard and my code needs to use `std::size_t` in order to be cross-platform?
2012/05/30
[ "https://Stackoverflow.com/questions/10823878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
According to the C++03 standard, 17.4.1.2.4: > > Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std. > > > In other words, by choosing to use `<cstddef>` instead of `<stddef.h>`, you're specifically asking for the type size\_t to be within the namespace std. So, here are the choices: 1. Use `<stddef.h>` instead, so `size_t` is in the top-level namespace, as suggested by Jesse Good. 2. Use `<cstddef>` and use `std::size_t`. 3. Use `<cstddef>` and use a using declaration to pull `size_t` into the top-level namespace, as suggested by cnicutar. Of course you could rely on the fact that one particular version of one compiler/library/platform lets you get away with it, or write different code for each platform, or wrap the whole thing up with autoconf, or write a code generator or sed-based preprocessor, or whatever… but why?
Perhaps saying this somewhere near the top ? ``` using std::size_t; ```
10,823,878
It seems on XCode I need to use std::size\_t instead of just size\_t on Visual C++. But this is a pain as I don't really want to have to `#include <cstddef>` and change every `size_t` to `std::size_t` in my code... in my Windows code `size_t` just works without including any additional files. Is there a way to make my existing code work in XCode, (maybe through the .pch file?) or are GCC/MSVC++ fundamentally different in this regard and my code needs to use `std::size_t` in order to be cross-platform?
2012/05/30
[ "https://Stackoverflow.com/questions/10823878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
According to the C++03 standard, 17.4.1.2.4: > > Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std. > > > In other words, by choosing to use `<cstddef>` instead of `<stddef.h>`, you're specifically asking for the type size\_t to be within the namespace std. So, here are the choices: 1. Use `<stddef.h>` instead, so `size_t` is in the top-level namespace, as suggested by Jesse Good. 2. Use `<cstddef>` and use `std::size_t`. 3. Use `<cstddef>` and use a using declaration to pull `size_t` into the top-level namespace, as suggested by cnicutar. Of course you could rely on the fact that one particular version of one compiler/library/platform lets you get away with it, or write different code for each platform, or wrap the whole thing up with autoconf, or write a code generator or sed-based preprocessor, or whatever… but why?
Use `#include <stddef.h>`. So, what's the difference between `#include <stddef.h>` and `#include <cstddef>`? `<cstddef>` is a C++ header and is guaranteed to define all symbols in the `std` namespace and also *may* define things in the global namespace. `<stddef.h>`is a C header and is guaranteed to define all symbols in the global namespace and *may* also define things in the `std` namespace. So, as you said on Visual Studio, `size_t` can be used because it injects `size_t` into the global namespace for you (possibly by already including "stddef.h"). If you want that to work on any compiler include `stddef.h`. (However, as a pure C++ fan, I personally prefer `std::size_t`).
144,075
So from the [docs](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_testvisible.htm) I understand that `@TestVisible` is used to allow Unit Tests access to `private` and `protected` methods. What I was wondering is, when is it appropriate to use this annotation? For example, I have a list generated in a wrapper class that allows selection and processing of Users as below: ``` public class uUser { public User user { get; set; } public Boolean selected { get; set; } public uUser(User u) { user = u; selected = false; } } ``` I then used the following Apex to select all or deselect all these Users: ``` private Boolean isAllUsersSelected { get { if (isAllUsersSelected == null) { isAllUsersSelected = false; } return isAllUsersSelected; } set; } public PageReference selectAllUsers() { if (isAllUsersSelected == false) { isAllUsersSelected = true; for (uUser user : userList) { user.selected = true; } } else { isAllUsersSelected = false; for (uUser user : userList) { user.selected = false; } } return null; } ``` Because this depends a lot on whether the `isAllUsersSelected` variable is true or false, I wondered whether or not it is a good idea and appropriate to use a `@TestVisible` method, given its access modifier is `private`?
2016/10/12
[ "https://salesforce.stackexchange.com/questions/144075", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/22232/" ]
I think the question in your title is too broad and opinion based to touch on here. I have worked with many developers who feel the `@TestVisible` annotation should never be used, but regardless, I have found some instances where it felt like the best option. For me, it boils down to using it only when I need to be able to control application behavior but want to avoid checking `Test.isRunningTest()`. For your use case, let's take a moment to think about the behavior you actually care about. You want the function to toggle the selection of all of your users (I would rename it from *select* to *toggle* to reflect that purpose). So what you really care about is not this `Boolean` flag at all, but rather your collection of wrapper instances. That is what you should be asserting against. Make sure its size hasn't changed, and that the individual selections are correct. Then again, if you take a step back and look at what you are trying to accomplish, do you really need to involve the server at all for this mechanism? It may be worth looking at how you can move the functionality wholesale to the client side, since it is not exactly complex logic where unit tests offer significant advantages over acceptance tests run by end users. --- (Just an aside to show the one time I do find `@TestVisible` perfectly acceptable) When writing trigger handlers, it is useful to use a static flag to turn the functionality off when running certain tests to reduce the cost of `DML Operations` on that object. Granted, there are other strategies you can employ to reduce or remove the need to perform `DML` in the first place. But sometimes you can't, and making trigger execution cheaper to run can dramatically simplify/quicken your test suite. ``` public with sharing class MyTriggerHandler { @TestVisible static Boolean bypassTrigger = false; // constructor logic public void beforeInsert() { if (bypassTrigger) return; // implementation logic } // other events } ``` Then, in some test where you don't actually care about the trigger, but need your records to exist in the database: ``` static testMethod void testSomeFunctionality() { MyTriggerHandler.bypassTrigger = true; insert myRecords; MyTriggerHandler.bypassTrigger = false; // other stuff } ```
Generally, you'd use @TestVisible when you need to control the internal state of an object, *or* you need to observe the internal state of an object that can't be deduced from the outside. Generally speaking, this is only for particularly esoteric designs. I've personally never had a use for this annotation, but it can make writing some kinds of tests easier to perform. In this case, I'd argue that since userList is observable from the outside, calling the method and observing the checked state of the users in the list would more desirable than making sure the internal state variable was correct; the state variable isn't directly tied to the users' selected state, and so testing it independently has no real value. As an aside, your method is unnecessarily verbose. You could have written the code like this: ``` public void toggleAllUsers() { isAllUserSelected = !isAllUserSelected; for(uUser user: userList) { user.selected = isAllUserSelected; } } ```
144,075
So from the [docs](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_testvisible.htm) I understand that `@TestVisible` is used to allow Unit Tests access to `private` and `protected` methods. What I was wondering is, when is it appropriate to use this annotation? For example, I have a list generated in a wrapper class that allows selection and processing of Users as below: ``` public class uUser { public User user { get; set; } public Boolean selected { get; set; } public uUser(User u) { user = u; selected = false; } } ``` I then used the following Apex to select all or deselect all these Users: ``` private Boolean isAllUsersSelected { get { if (isAllUsersSelected == null) { isAllUsersSelected = false; } return isAllUsersSelected; } set; } public PageReference selectAllUsers() { if (isAllUsersSelected == false) { isAllUsersSelected = true; for (uUser user : userList) { user.selected = true; } } else { isAllUsersSelected = false; for (uUser user : userList) { user.selected = false; } } return null; } ``` Because this depends a lot on whether the `isAllUsersSelected` variable is true or false, I wondered whether or not it is a good idea and appropriate to use a `@TestVisible` method, given its access modifier is `private`?
2016/10/12
[ "https://salesforce.stackexchange.com/questions/144075", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/22232/" ]
I think the question in your title is too broad and opinion based to touch on here. I have worked with many developers who feel the `@TestVisible` annotation should never be used, but regardless, I have found some instances where it felt like the best option. For me, it boils down to using it only when I need to be able to control application behavior but want to avoid checking `Test.isRunningTest()`. For your use case, let's take a moment to think about the behavior you actually care about. You want the function to toggle the selection of all of your users (I would rename it from *select* to *toggle* to reflect that purpose). So what you really care about is not this `Boolean` flag at all, but rather your collection of wrapper instances. That is what you should be asserting against. Make sure its size hasn't changed, and that the individual selections are correct. Then again, if you take a step back and look at what you are trying to accomplish, do you really need to involve the server at all for this mechanism? It may be worth looking at how you can move the functionality wholesale to the client side, since it is not exactly complex logic where unit tests offer significant advantages over acceptance tests run by end users. --- (Just an aside to show the one time I do find `@TestVisible` perfectly acceptable) When writing trigger handlers, it is useful to use a static flag to turn the functionality off when running certain tests to reduce the cost of `DML Operations` on that object. Granted, there are other strategies you can employ to reduce or remove the need to perform `DML` in the first place. But sometimes you can't, and making trigger execution cheaper to run can dramatically simplify/quicken your test suite. ``` public with sharing class MyTriggerHandler { @TestVisible static Boolean bypassTrigger = false; // constructor logic public void beforeInsert() { if (bypassTrigger) return; // implementation logic } // other events } ``` Then, in some test where you don't actually care about the trigger, but need your records to exist in the database: ``` static testMethod void testSomeFunctionality() { MyTriggerHandler.bypassTrigger = true; insert myRecords; MyTriggerHandler.bypassTrigger = false; // other stuff } ```
As an addendum to Adrian's answer: I use a lot of custom messaging assigned to final strings and they have an access of private ``` @TestVisible private static final string REQERROR = 'There was an error processing your request'; ``` Adding the @TestVisible annotation allows me to use this property in my test classes to assert the appropriate messages are displayed while allowing me to change the message and not break the test classes. The alternative would be to make the access public but i like to only make things public when they need to be public. You can find use cases for this in many places. The one thing I would says is if you have a method that is private you should generally not need to use @TestVisible because the method itself is private and thus if a test does not cover it without the @TestVisible then either there is something wrong with your code, test, or the method is unused. The exception to the above is a helper method that you make private. If you want to use the results of that method in your assertions then you would need to use the @TestVisible
7,330,395
I have a jquery plugin for my website which converts textareas / Inputs to Urdu Keyboard but that plugin doesn't work with ckeditor, because ckeditor takes some time to load. Request you to please let me know if there is a way to load my jquery plugin after some delay or when ckeditor is completely loaded? I have added jquery code in {head} of my website: ``` <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/UrduEditor.css" /> <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/keyboard.css" /> <script src="{vb:raw vboptions.bburl}/clientscript/VirtualKeyboard/vk_loader.js?vk_layout=PK%20Urdu%20CRULP%20Phonetic&vk_skin=flat_gray" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script src="{vb:raw vboptions.bburl}/clientscript/jquery.UrduEditor.js" type="text/javascript"></script> <script src="{vb:raw vboptions.bburl}/clientscript/keyboard.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> jqcc = jQuery.noConflict(true); jqcc.fn.UrduEditor.defaults.EditorFont = 'Jameel Noori Nastaleeq'; //jQ = jQuery.noConflict(true); jqcc(document).ready(function () { jqcc(this).UrduEditor.writeKeyboard(jqcc('.cke_source')); jqcc('.cke_source').UrduEditor("18px"); }); </script> ``` Request you to please help me to correct the above code...
2011/09/07
[ "https://Stackoverflow.com/questions/7330395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932187/" ]
Solution (without altering the indexes on my tables): ``` SELECT df.*, ( SELECT dfa.file_archive_id FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_id, ( SELECT dfa.file_archive_version FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_version FROM dca_file df ``` Both tables having ~16k rows, this statement takes 0.9 seconds to perform, which is 120x faster than the first join solution. I know this is not the finest you can do with SQL
Try this (i named your tables `table1` and `table2`): ``` SELECT t1.fild_id, t1.file_name, t2A.file_archive_id, t2A.file_archive_version FROM table1 t1 JOIN table2 t2A ON (t1.fild_id = t2A.file_id) WHERE NOT EXISTS ( SELECT * FROM table2 t2B WHERE t2A.file_id = t2B.file_id AND t2B.file_archive_id > t2A.file_archive_id ) ORDER BY t1.fild_id ```
7,330,395
I have a jquery plugin for my website which converts textareas / Inputs to Urdu Keyboard but that plugin doesn't work with ckeditor, because ckeditor takes some time to load. Request you to please let me know if there is a way to load my jquery plugin after some delay or when ckeditor is completely loaded? I have added jquery code in {head} of my website: ``` <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/UrduEditor.css" /> <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/keyboard.css" /> <script src="{vb:raw vboptions.bburl}/clientscript/VirtualKeyboard/vk_loader.js?vk_layout=PK%20Urdu%20CRULP%20Phonetic&vk_skin=flat_gray" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script src="{vb:raw vboptions.bburl}/clientscript/jquery.UrduEditor.js" type="text/javascript"></script> <script src="{vb:raw vboptions.bburl}/clientscript/keyboard.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> jqcc = jQuery.noConflict(true); jqcc.fn.UrduEditor.defaults.EditorFont = 'Jameel Noori Nastaleeq'; //jQ = jQuery.noConflict(true); jqcc(document).ready(function () { jqcc(this).UrduEditor.writeKeyboard(jqcc('.cke_source')); jqcc('.cke_source').UrduEditor("18px"); }); </script> ``` Request you to please help me to correct the above code...
2011/09/07
[ "https://Stackoverflow.com/questions/7330395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932187/" ]
Solution (without altering the indexes on my tables): ``` SELECT df.*, ( SELECT dfa.file_archive_id FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_id, ( SELECT dfa.file_archive_version FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_version FROM dca_file df ``` Both tables having ~16k rows, this statement takes 0.9 seconds to perform, which is 120x faster than the first join solution. I know this is not the finest you can do with SQL
Try this one - ``` SELECT f.*, a1.file_archive_id, a1.file_archive_version FROM files f JOIN file_archives a1 ON f.file_id = a1.file_id JOIN ( SELECT file_id, MAX(file_archive_version) max_file_archive_version FROM file_archives GROUP BY file_id ) a2 ON a1.file_id = a2.file_id AND a1.file_archive_version = a2.max_file_archive_version; ```
7,330,395
I have a jquery plugin for my website which converts textareas / Inputs to Urdu Keyboard but that plugin doesn't work with ckeditor, because ckeditor takes some time to load. Request you to please let me know if there is a way to load my jquery plugin after some delay or when ckeditor is completely loaded? I have added jquery code in {head} of my website: ``` <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/UrduEditor.css" /> <link rel="stylesheet" type="text/css" href="{vb:raw vboptions.bburl}/clientscript/keyboard.css" /> <script src="{vb:raw vboptions.bburl}/clientscript/VirtualKeyboard/vk_loader.js?vk_layout=PK%20Urdu%20CRULP%20Phonetic&vk_skin=flat_gray" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script src="{vb:raw vboptions.bburl}/clientscript/jquery.UrduEditor.js" type="text/javascript"></script> <script src="{vb:raw vboptions.bburl}/clientscript/keyboard.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> jqcc = jQuery.noConflict(true); jqcc.fn.UrduEditor.defaults.EditorFont = 'Jameel Noori Nastaleeq'; //jQ = jQuery.noConflict(true); jqcc(document).ready(function () { jqcc(this).UrduEditor.writeKeyboard(jqcc('.cke_source')); jqcc('.cke_source').UrduEditor("18px"); }); </script> ``` Request you to please help me to correct the above code...
2011/09/07
[ "https://Stackoverflow.com/questions/7330395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932187/" ]
Solution (without altering the indexes on my tables): ``` SELECT df.*, ( SELECT dfa.file_archive_id FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_id, ( SELECT dfa.file_archive_version FROM dca_file_archive dfa WHERE df.file_id = dfa.file_id ORDER BY dfa.file_archive_version desc LIMIT 1 ) as file_archive_version FROM dca_file df ``` Both tables having ~16k rows, this statement takes 0.9 seconds to perform, which is 120x faster than the first join solution. I know this is not the finest you can do with SQL
t1 as first table, t2 as second table ``` SELECT t1.file_id as tx_id,t1.file_name,tx.file_archive_id,tx.file_archive_version FROM maindb.t1 t1,maindb.t2 tx WHERE t1.file_id = tx.file_id GROUP BY t1.file_id HAVING max(tx.file_archive_version) >= all ( SELECT max(t2.file_archive_version) FROM maindb.t2 WHERE t2.file_id = tx_id ) ``` hope it may help.
27,682,842
I am trying to make the text the user types of the search view white. "android:searchViewTextField" give an error. I can't find the right name for a global style: ``` <style name="AppTheme" parent="@style/_AppTheme"/> <style name="_AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:searchViewTextField">@color/white_color</item> </style> ``` Is there a global style which will **only affect** the text of the Searchview and not all text boxes?
2014/12/29
[ "https://Stackoverflow.com/questions/27682842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
Define the theme "SearchTextViewTheme" ``` <style name="SearchTextViewTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:textColor">@color/white_color</item> </style> ``` Then inside the TextView ``` <TextView style="@style/SearchTextViewTheme" android:layout_width="wrap_content" android:layout_height="wrap_content"/> ``` In fact applying theme must be explicitly defined in the layout XML. Therefore you do not have to worry about the theme affecting other text boxes
Here's how it's done ins `Xamarin` (I based the idea from **Patrick's** answer): ``` [assembly: ExportRenderer(typeof (CustomSearchBar), typeof (CustomSearchBarRenderer))] namespace Bahai.Android.Renderers { public class CustomSearchBarRenderer : SearchBarRenderer { protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e) { base.OnElementChanged(e); if (e.OldElement == null) { SearchBar element = (SearchBar) this.Element; var native = (global::Android.Widget.SearchView) Control; // do whatever you want to the controls here! //-------------------------------------------- // element.BackgroundColor = Color.Transparent; // native.SetBackgroundColor(element.BackgroundColor.ToAndroid()); // native.SetBackgroundColor(Color.White.ToAndroid()); //The text color of the SearchBar / SearchView AutoCompleteTextView textField = (AutoCompleteTextView) (((Control.GetChildAt(0) as ViewGroup) .GetChildAt(2) as ViewGroup) .GetChildAt(1) as ViewGroup) .GetChildAt(0); if (textField != null) textField.SetTextColor(Color.White.ToAndroid()); } } } } ```
27,682,842
I am trying to make the text the user types of the search view white. "android:searchViewTextField" give an error. I can't find the right name for a global style: ``` <style name="AppTheme" parent="@style/_AppTheme"/> <style name="_AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:searchViewTextField">@color/white_color</item> </style> ``` Is there a global style which will **only affect** the text of the Searchview and not all text boxes?
2014/12/29
[ "https://Stackoverflow.com/questions/27682842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
Define the theme "SearchTextViewTheme" ``` <style name="SearchTextViewTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:textColor">@color/white_color</item> </style> ``` Then inside the TextView ``` <TextView style="@style/SearchTextViewTheme" android:layout_width="wrap_content" android:layout_height="wrap_content"/> ``` In fact applying theme must be explicitly defined in the layout XML. Therefore you do not have to worry about the theme affecting other text boxes
If your targed SDK is 20 or less, the attributes Goolge uses to style the `SearchView` are hidden and you’ll end up with compilation errors if you try overriding them in your theme. You can use the AppCompat v20 `SearchView` instead of the the native `SearchView` following this [tutorial](http://www.jayway.com/2014/06/02/android-theming-the-actionbar/). AppCompat exposes attributes like `searchViewTextField` and `searchViewAutoCompleteTextView` to change the style of the `AutoCompleteTextView`.
27,682,842
I am trying to make the text the user types of the search view white. "android:searchViewTextField" give an error. I can't find the right name for a global style: ``` <style name="AppTheme" parent="@style/_AppTheme"/> <style name="_AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:searchViewTextField">@color/white_color</item> </style> ``` Is there a global style which will **only affect** the text of the Searchview and not all text boxes?
2014/12/29
[ "https://Stackoverflow.com/questions/27682842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
Define the theme "SearchTextViewTheme" ``` <style name="SearchTextViewTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:textColor">@color/white_color</item> </style> ``` Then inside the TextView ``` <TextView style="@style/SearchTextViewTheme" android:layout_width="wrap_content" android:layout_height="wrap_content"/> ``` In fact applying theme must be explicitly defined in the layout XML. Therefore you do not have to worry about the theme affecting other text boxes
this did the trick ``` <style name="myTheme" parent="@style/Theme.AppCompat.Light"> <item name="android:editTextColor">#fffff</item> </style> ``` The above solutions might work in java but they don't work in xamarin and i guess this solution will work in java.
27,682,842
I am trying to make the text the user types of the search view white. "android:searchViewTextField" give an error. I can't find the right name for a global style: ``` <style name="AppTheme" parent="@style/_AppTheme"/> <style name="_AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:searchViewTextField">@color/white_color</item> </style> ``` Is there a global style which will **only affect** the text of the Searchview and not all text boxes?
2014/12/29
[ "https://Stackoverflow.com/questions/27682842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
If your targed SDK is 20 or less, the attributes Goolge uses to style the `SearchView` are hidden and you’ll end up with compilation errors if you try overriding them in your theme. You can use the AppCompat v20 `SearchView` instead of the the native `SearchView` following this [tutorial](http://www.jayway.com/2014/06/02/android-theming-the-actionbar/). AppCompat exposes attributes like `searchViewTextField` and `searchViewAutoCompleteTextView` to change the style of the `AutoCompleteTextView`.
Here's how it's done ins `Xamarin` (I based the idea from **Patrick's** answer): ``` [assembly: ExportRenderer(typeof (CustomSearchBar), typeof (CustomSearchBarRenderer))] namespace Bahai.Android.Renderers { public class CustomSearchBarRenderer : SearchBarRenderer { protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e) { base.OnElementChanged(e); if (e.OldElement == null) { SearchBar element = (SearchBar) this.Element; var native = (global::Android.Widget.SearchView) Control; // do whatever you want to the controls here! //-------------------------------------------- // element.BackgroundColor = Color.Transparent; // native.SetBackgroundColor(element.BackgroundColor.ToAndroid()); // native.SetBackgroundColor(Color.White.ToAndroid()); //The text color of the SearchBar / SearchView AutoCompleteTextView textField = (AutoCompleteTextView) (((Control.GetChildAt(0) as ViewGroup) .GetChildAt(2) as ViewGroup) .GetChildAt(1) as ViewGroup) .GetChildAt(0); if (textField != null) textField.SetTextColor(Color.White.ToAndroid()); } } } } ```
27,682,842
I am trying to make the text the user types of the search view white. "android:searchViewTextField" give an error. I can't find the right name for a global style: ``` <style name="AppTheme" parent="@style/_AppTheme"/> <style name="_AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:searchViewTextField">@color/white_color</item> </style> ``` Is there a global style which will **only affect** the text of the Searchview and not all text boxes?
2014/12/29
[ "https://Stackoverflow.com/questions/27682842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172861/" ]
If your targed SDK is 20 or less, the attributes Goolge uses to style the `SearchView` are hidden and you’ll end up with compilation errors if you try overriding them in your theme. You can use the AppCompat v20 `SearchView` instead of the the native `SearchView` following this [tutorial](http://www.jayway.com/2014/06/02/android-theming-the-actionbar/). AppCompat exposes attributes like `searchViewTextField` and `searchViewAutoCompleteTextView` to change the style of the `AutoCompleteTextView`.
this did the trick ``` <style name="myTheme" parent="@style/Theme.AppCompat.Light"> <item name="android:editTextColor">#fffff</item> </style> ``` The above solutions might work in java but they don't work in xamarin and i guess this solution will work in java.
33,542,959
If I don't know how many arguments a function will be passed, I *could* write the function using argument packing: ``` def add(factor, *nums): """Add numbers and multiply by factor.""" return sum(nums) * factor ``` Alternatively, I could avoid argument packing by passing a list of numbers as the argument: ``` def add(factor, nums): """Add numbers and multiply by factor. :type factor: int :type nums: list of int """ return sum(nums) * factor ``` Is there an advantage to using argument packing `*args` over passing a list of numbers? Or are there situations where one is more appropriate?
2015/11/05
[ "https://Stackoverflow.com/questions/33542959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797744/" ]
`*args`/`**kwargs` has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones. Python 3's `print()` is a good example. ``` print('hi') print('you have', num, 'potatoes') print(*mylist) ``` Contrast that with what it would be like if `print()` only took a packed structure and then expanded it within the function: ``` print(('hi',)) print(('you have', num, 'potatoes')) print(mylist) ``` In this case, `*args`/`**kwargs` comes in really handy. Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as `sum()` and `str.join()` do, it might make more sense to leave out the `*` syntax.
It's about the API: \*args provides a better interface, as it states that the method accepts an arbitrary number of arguments AND that's it - no further assumptions. You know for sure that the method itself will not do anything else with the data structure containing the various arguments AND that no special data structure is necessary. In theory, you could also accept a dictionary with values set to None. Why not? It's overhead and unnecessary. To me, accepting a list when you can accept varargs is adding overhead. (as one of the comments pointed out) Furthermore, varargs are a good way to guarantee consistency and a good contract between the caller and the called function. No assumptions can be made. When and if you need a list, then you know that you need a list! Ah, note that f(\*args) is not the same as f(list): the second *wants* a list, the first takes an arbitrary number of parameters (0 included). Ok, so let's define the second as an optional argument: ``` def f(l = []): pass ``` Cool, now you have two issues, because you must make sure that you don't modify the argument l: [default parameter values](http://effbot.org/zone/default-values.htm). For what reason? Because you don't like \*args. :) PS: I think this is one of the biggest disadvantages of dynamic languages: you don't see anymore the interface, but yes! there is an interface!
33,542,959
If I don't know how many arguments a function will be passed, I *could* write the function using argument packing: ``` def add(factor, *nums): """Add numbers and multiply by factor.""" return sum(nums) * factor ``` Alternatively, I could avoid argument packing by passing a list of numbers as the argument: ``` def add(factor, nums): """Add numbers and multiply by factor. :type factor: int :type nums: list of int """ return sum(nums) * factor ``` Is there an advantage to using argument packing `*args` over passing a list of numbers? Or are there situations where one is more appropriate?
2015/11/05
[ "https://Stackoverflow.com/questions/33542959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797744/" ]
`*args`/`**kwargs` has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones. Python 3's `print()` is a good example. ``` print('hi') print('you have', num, 'potatoes') print(*mylist) ``` Contrast that with what it would be like if `print()` only took a packed structure and then expanded it within the function: ``` print(('hi',)) print(('you have', num, 'potatoes')) print(mylist) ``` In this case, `*args`/`**kwargs` comes in really handy. Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as `sum()` and `str.join()` do, it might make more sense to leave out the `*` syntax.
This is kind of an old one, but to answer @DBrenko's queries about when \*args and \*\*kwargs would be required, the clearest example I have found is when you want a function that runs another function as part of its execution. As a simple example: ``` import datetime def timeFunction(function, *args, **kwargs): start = datetime.datetime.now() output = function(*args, **kwargs) executionTime = datetime.datetime.now() - start return executionTime, output ``` timeFunction takes a function and the arguments for that function as its arguments. By using the \*args, \*\*kwargs syntax it isn't limited to specific functions.
53,392,726
I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while operating with my editable text fields, even following Google's advice on implementation... This is my code for pasting: ``` onPressed: () async { await getMyData('text'); _encodingController.text = clipData; Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( "Pasted from Clipboard"), ), ); }, ``` what doesnt work is my paste functionality... While debugging the result of this following function is null, wth????????? ``` static Future<ClipboardData> getMyData(String format) async { final Map<String, dynamic> result = await SystemChannels.platform.invokeMethod( 'Clipboard.getData', format, ); if (result == null) { return null; } else { clipData = ClipboardData(text: result['text']).text; return ClipboardData(text: result['text'].text); } } ``` I am probably using the Futures and async await wrong, would love some guidance!!! Copying is working using the Clipboard Manager plugin! Thanks very much!
2018/11/20
[ "https://Stackoverflow.com/questions/53392726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845653/" ]
You can simply re-use Flutter's existing library code to `getData` from Clipboard. ``` ClipboardData data = await Clipboard.getData('text/plain'); ```
It's works for me: ```dart _getFromClipboard() async { Map<String, dynamic> result = await SystemChannels.platform.invokeMethod('Clipboard.getData'); if (result != null) { return result['text'].toString(); } return ''; } ```
53,392,726
I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while operating with my editable text fields, even following Google's advice on implementation... This is my code for pasting: ``` onPressed: () async { await getMyData('text'); _encodingController.text = clipData; Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( "Pasted from Clipboard"), ), ); }, ``` what doesnt work is my paste functionality... While debugging the result of this following function is null, wth????????? ``` static Future<ClipboardData> getMyData(String format) async { final Map<String, dynamic> result = await SystemChannels.platform.invokeMethod( 'Clipboard.getData', format, ); if (result == null) { return null; } else { clipData = ClipboardData(text: result['text']).text; return ClipboardData(text: result['text'].text); } } ``` I am probably using the Futures and async await wrong, would love some guidance!!! Copying is working using the Clipboard Manager plugin! Thanks very much!
2018/11/20
[ "https://Stackoverflow.com/questions/53392726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845653/" ]
First create a method ``` Future<String> getClipBoardData() async { ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); return data.text; } ``` Then in build method ``` FutureBuilder( future: getClipBoardData(), initialData: 'nothing', builder: (context, snapShot){ return Text(snapShot.data.toString()); }, ), ```
It's works for me: ```dart _getFromClipboard() async { Map<String, dynamic> result = await SystemChannels.platform.invokeMethod('Clipboard.getData'); if (result != null) { return result['text'].toString(); } return ''; } ```
53,392,726
I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while operating with my editable text fields, even following Google's advice on implementation... This is my code for pasting: ``` onPressed: () async { await getMyData('text'); _encodingController.text = clipData; Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( "Pasted from Clipboard"), ), ); }, ``` what doesnt work is my paste functionality... While debugging the result of this following function is null, wth????????? ``` static Future<ClipboardData> getMyData(String format) async { final Map<String, dynamic> result = await SystemChannels.platform.invokeMethod( 'Clipboard.getData', format, ); if (result == null) { return null; } else { clipData = ClipboardData(text: result['text']).text; return ClipboardData(text: result['text'].text); } } ``` I am probably using the Futures and async await wrong, would love some guidance!!! Copying is working using the Clipboard Manager plugin! Thanks very much!
2018/11/20
[ "https://Stackoverflow.com/questions/53392726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845653/" ]
You can simply re-use Flutter's existing library code to `getData` from Clipboard. ``` ClipboardData data = await Clipboard.getData('text/plain'); ```
Also can be useful if you want to listen for periodic updates from the system clipboard. [Originally I replied here](https://stackoverflow.com/questions/50647727/how-do-i-monitor-the-clipboard-in-flutter/55596589#55596589), just re-posting the solution: ``` #creating a listening Stream: final clipboardContentStream = StreamController<String>.broadcast(); #creating a timer for updates: Timer clipboardTriggerTime; clipboardTriggerTime = Timer.periodic( # you can specify any duration you want, roughly every 20 read from the system const Duration(seconds: 5), (timer) { Clipboard.getData('text/plain').then((clipboarContent) { print('Clipboard content ${clipboarContent.text}'); # post to a Stream you're subscribed to clipboardContentStream.add(clipboarContent.text); }); }, ); # subscribe your view with Stream get clipboardText => clipboardController.stream # and don't forget to clean up on your widget @override void dispose() { clipboardContentStream.close(); clipboardTriggerTime.cancel(); } ```
53,392,726
I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while operating with my editable text fields, even following Google's advice on implementation... This is my code for pasting: ``` onPressed: () async { await getMyData('text'); _encodingController.text = clipData; Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( "Pasted from Clipboard"), ), ); }, ``` what doesnt work is my paste functionality... While debugging the result of this following function is null, wth????????? ``` static Future<ClipboardData> getMyData(String format) async { final Map<String, dynamic> result = await SystemChannels.platform.invokeMethod( 'Clipboard.getData', format, ); if (result == null) { return null; } else { clipData = ClipboardData(text: result['text']).text; return ClipboardData(text: result['text'].text); } } ``` I am probably using the Futures and async await wrong, would love some guidance!!! Copying is working using the Clipboard Manager plugin! Thanks very much!
2018/11/20
[ "https://Stackoverflow.com/questions/53392726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845653/" ]
You can simply re-use Flutter's existing library code to `getData` from Clipboard. ``` ClipboardData data = await Clipboard.getData('text/plain'); ```
First create a method ``` Future<String> getClipBoardData() async { ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); return data.text; } ``` Then in build method ``` FutureBuilder( future: getClipBoardData(), initialData: 'nothing', builder: (context, snapShot){ return Text(snapShot.data.toString()); }, ), ```
53,392,726
I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while operating with my editable text fields, even following Google's advice on implementation... This is my code for pasting: ``` onPressed: () async { await getMyData('text'); _encodingController.text = clipData; Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( "Pasted from Clipboard"), ), ); }, ``` what doesnt work is my paste functionality... While debugging the result of this following function is null, wth????????? ``` static Future<ClipboardData> getMyData(String format) async { final Map<String, dynamic> result = await SystemChannels.platform.invokeMethod( 'Clipboard.getData', format, ); if (result == null) { return null; } else { clipData = ClipboardData(text: result['text']).text; return ClipboardData(text: result['text'].text); } } ``` I am probably using the Futures and async await wrong, would love some guidance!!! Copying is working using the Clipboard Manager plugin! Thanks very much!
2018/11/20
[ "https://Stackoverflow.com/questions/53392726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8845653/" ]
First create a method ``` Future<String> getClipBoardData() async { ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); return data.text; } ``` Then in build method ``` FutureBuilder( future: getClipBoardData(), initialData: 'nothing', builder: (context, snapShot){ return Text(snapShot.data.toString()); }, ), ```
Also can be useful if you want to listen for periodic updates from the system clipboard. [Originally I replied here](https://stackoverflow.com/questions/50647727/how-do-i-monitor-the-clipboard-in-flutter/55596589#55596589), just re-posting the solution: ``` #creating a listening Stream: final clipboardContentStream = StreamController<String>.broadcast(); #creating a timer for updates: Timer clipboardTriggerTime; clipboardTriggerTime = Timer.periodic( # you can specify any duration you want, roughly every 20 read from the system const Duration(seconds: 5), (timer) { Clipboard.getData('text/plain').then((clipboarContent) { print('Clipboard content ${clipboarContent.text}'); # post to a Stream you're subscribed to clipboardContentStream.add(clipboarContent.text); }); }, ); # subscribe your view with Stream get clipboardText => clipboardController.stream # and don't forget to clean up on your widget @override void dispose() { clipboardContentStream.close(); clipboardTriggerTime.cancel(); } ```
11,677
Darussalam publishes a copy of [Riyad-us-Saliheen](https://www.goodreads.com/book/show/507739.Riyad_us_Saliheen) which, in addition to the actual ahadith compiled by Al-Nawawi, includes commentary by one Hafiz Salahuddin Yusuf. The introduction to the collection provides no information on the commentator except that he had originally provided commentary on the Urdu collection. It doesn't go into any details as to his credentials or education. In other words, it doesn't give any indication that this commentary is any more or less useful than the commentary of any random user on the street. Google searching provides next to nothing except that he's from Pakistan (no surprise, given that he's contributed to the Urdu collection), that he's involved with the Darussalam Research Division (no surprise, given that this is a Darussalam-published collection), and that he was also involved with Tafsir Ahsanul Bayan (also published by Darussalam). Which really doesn't help except to suggest that the commentary was an in-house job (which doesn't necessarily impugn credibility, but in no way bolsters it either). Who exactly is Hafiz Salahuddin Yusuf? What experience/education/expertise does he have that equips him to provide a commentary on such a classic collection? What, if anything, makes *his* commentary in any way valuable and/or useful?
2014/03/06
[ "https://islam.stackexchange.com/questions/11677", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/22/" ]
Asalam o Alikum brothers and sister, Hafiz Salahuddin Yusuf is a great scholar and had some appearance/lectures/interview on PeaceTV which is famous for it's spreading of Islam only based on Quran and Sahih Hadit (Hadees). I also bought a book from my friends book shop (Ahsan ul Bayan). He recommended that it is authentic one. But as my own curiosity, I also tried to find out some more about this person. I actually found his interview relating Zakat on youtube.com which PeaceTV on-aired as well. <http://www.youtube.com/watch?v=f5KDmW_ibMg> So, we can trust on his research and efforts... May Allah helps understand the religion and guide us and keep us stead fast on the right of those on whom HE showered his blessings. AMEEN
He focussed pretty much to prove several ahadees Daeef included in the text of Riyadhussaliheen that suggest practice against the practices of Salafiyah, from which I concluded that he is trying to say that Imaam UL Nawawi had less understanding of which Hadeeth to include and which to not include in his book. I think he is a Salafiyah based Alim. Wallahu alam
11,677
Darussalam publishes a copy of [Riyad-us-Saliheen](https://www.goodreads.com/book/show/507739.Riyad_us_Saliheen) which, in addition to the actual ahadith compiled by Al-Nawawi, includes commentary by one Hafiz Salahuddin Yusuf. The introduction to the collection provides no information on the commentator except that he had originally provided commentary on the Urdu collection. It doesn't go into any details as to his credentials or education. In other words, it doesn't give any indication that this commentary is any more or less useful than the commentary of any random user on the street. Google searching provides next to nothing except that he's from Pakistan (no surprise, given that he's contributed to the Urdu collection), that he's involved with the Darussalam Research Division (no surprise, given that this is a Darussalam-published collection), and that he was also involved with Tafsir Ahsanul Bayan (also published by Darussalam). Which really doesn't help except to suggest that the commentary was an in-house job (which doesn't necessarily impugn credibility, but in no way bolsters it either). Who exactly is Hafiz Salahuddin Yusuf? What experience/education/expertise does he have that equips him to provide a commentary on such a classic collection? What, if anything, makes *his* commentary in any way valuable and/or useful?
2014/03/06
[ "https://islam.stackexchange.com/questions/11677", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/22/" ]
Haafiz Salaah-ud-Deen Yoosuf is Head of Darussalam's Research Division in Lahore. He was formerly: - Islamic Legal Consultant to the Federal Shariat Court of Pakistan, and - Editor-in-Chief of al-I'tisaam magazine.
Asalam o Alikum brothers and sister, Hafiz Salahuddin Yusuf is a great scholar and had some appearance/lectures/interview on PeaceTV which is famous for it's spreading of Islam only based on Quran and Sahih Hadit (Hadees). I also bought a book from my friends book shop (Ahsan ul Bayan). He recommended that it is authentic one. But as my own curiosity, I also tried to find out some more about this person. I actually found his interview relating Zakat on youtube.com which PeaceTV on-aired as well. <http://www.youtube.com/watch?v=f5KDmW_ibMg> So, we can trust on his research and efforts... May Allah helps understand the religion and guide us and keep us stead fast on the right of those on whom HE showered his blessings. AMEEN
11,677
Darussalam publishes a copy of [Riyad-us-Saliheen](https://www.goodreads.com/book/show/507739.Riyad_us_Saliheen) which, in addition to the actual ahadith compiled by Al-Nawawi, includes commentary by one Hafiz Salahuddin Yusuf. The introduction to the collection provides no information on the commentator except that he had originally provided commentary on the Urdu collection. It doesn't go into any details as to his credentials or education. In other words, it doesn't give any indication that this commentary is any more or less useful than the commentary of any random user on the street. Google searching provides next to nothing except that he's from Pakistan (no surprise, given that he's contributed to the Urdu collection), that he's involved with the Darussalam Research Division (no surprise, given that this is a Darussalam-published collection), and that he was also involved with Tafsir Ahsanul Bayan (also published by Darussalam). Which really doesn't help except to suggest that the commentary was an in-house job (which doesn't necessarily impugn credibility, but in no way bolsters it either). Who exactly is Hafiz Salahuddin Yusuf? What experience/education/expertise does he have that equips him to provide a commentary on such a classic collection? What, if anything, makes *his* commentary in any way valuable and/or useful?
2014/03/06
[ "https://islam.stackexchange.com/questions/11677", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/22/" ]
Haafiz Salaah-ud-Deen Yoosuf is Head of Darussalam's Research Division in Lahore. He was formerly: - Islamic Legal Consultant to the Federal Shariat Court of Pakistan, and - Editor-in-Chief of al-I'tisaam magazine.
He focussed pretty much to prove several ahadees Daeef included in the text of Riyadhussaliheen that suggest practice against the practices of Salafiyah, from which I concluded that he is trying to say that Imaam UL Nawawi had less understanding of which Hadeeth to include and which to not include in his book. I think he is a Salafiyah based Alim. Wallahu alam
7,219
First, a bit of background. I've been training kungfu for nearly a decade now. During all these years, I had the nagging feeling something essential was missing. Shifu sometimes told me to follow tai chi classes as well, as it would make my movements more fluid. An opportunity to train tai chi with a good, proper trainer came up, and I took it. I learned alot from that, which I incorporated into my main training as well, but that nagging feeling of something essential missing, never went away. During one class, the tai chi teacher lost his patience and told students off. He told me off by saying that I've trained for nearly a decade, but to him, I didn't train for even one day, cause I always leaned out of axis. What this means, is I pretty much move like the Tower of Pisa. Ie: my entire upper body leans over, while top of my head down to the hips (and actually to the bottom of the foot I'm standing on), should be in one line, straight down. To illustrate, here are some examples: I can do squats just fine. Cat stance and the likes are no problem. When moving from one stance to another where I have to do those, then stretch my leg out, I lean over. Same with doing kicks. When I do a front kick, my hips twist forward. That's how it should go. My back (lower and upper) should remain upwards, yet I lean backwards. This results in too much time lost getting back into position, taking most usefulness out of the kick. That got me thinking... Shifu occasionally alluded to that as well, but was always very soft-worded about it. Because of that, I stupidly enough didn't pay much attention to it. When looking at the mechanics of every movement, keeping your back in axis is what makes or breaks it. As such, the tai chi teacher was right when saying it was as if I didn't train even one day. Now the problem is: How to fix it? I've trained with this flaw for such a long time, removing it has become a real challenge. Shifu told me to practice in front of a mirror, and during class he now pays extra attention to it and sends me close to a mirror when necessary. This works for static movements. Get into stance A. Check the mirror. Correct where necessary. Move into stance B. Check the mirror. Correct where necessary. This works fine for those static movements, but not for other movements, nor during more active movement (eg. sparring) This is where you guys come in. I'm hoping you guys can help me with some exercises that'll help me with this issue during active movement, and any movement in general. Especially useful are exercises I can do during daily life (eg. when walking to the grocery store), as those aren't limited to designated training time.
2017/02/14
[ "https://martialarts.stackexchange.com/questions/7219", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/7414/" ]
"Leaning out of axis" is, in my mind, a combination of three separate ideas. It's not clear to me how your idea relates to mine, so here are all of the elements as I understand them: 1. **Balance** Your center of mass is supported by your base. 2. **Alignment** The relative positions of your body parts are conducive to applying/resisting force. 3. **Verticality** Your back is perpendicular to the ground plane. The simplest example of being both balanced and aligned is standing with your back straight up, which means you are also vertical. Styles disagree about alignments and verticality. You can be balanced and vertical but not aligned if you have a hunched posture. Some styles think it is necessary to fix this, while others do not. Some styles think the shoulders should twist relative to the hips, while others insist these should move together. Some styles require verticality. Other styles allow the back to be inclined to the ground, so long as it remains balanced (due to the placement of the feet) and aligned. Some of these disagreements cannot be reconciled. It seems like you are trying to fit a round peg in a square hole. Some cross-system training is simply incompatible. Kicking high while maintaining a taiji posture is VERY HARD; only a small minority of practitioners can expect to achieve this in their lifetime. Kicking high is not a goal in taiji and fighting does not rely upon it. There are reasons why taiji practice is done slowly. While moving slowly, it is much easier to detect whether you are on balance because if you have to move quickly to catch your balance, then you are not on balance. It is also easier to tell when you are losing alignments. One simple training approach is simply to practice the taiji you have learned. Moving balance is quite a bit different from static balance because you can be balanced before and after stepping, but not while stepping. The slow [sliding step](https://martialarts.stackexchange.com/a/7196/5961) is one way to train moving with better balance without leaning. When first learning, you can use push a heavy book prop with your foot to learn to apply force rather than falling with each step. Once you get this idea, you should be able to remove the book.
I don't know about the axis part of your question, but a good way to self-check is to use your smartphone or tablet with the video camera. I do this a lot.
7,219
First, a bit of background. I've been training kungfu for nearly a decade now. During all these years, I had the nagging feeling something essential was missing. Shifu sometimes told me to follow tai chi classes as well, as it would make my movements more fluid. An opportunity to train tai chi with a good, proper trainer came up, and I took it. I learned alot from that, which I incorporated into my main training as well, but that nagging feeling of something essential missing, never went away. During one class, the tai chi teacher lost his patience and told students off. He told me off by saying that I've trained for nearly a decade, but to him, I didn't train for even one day, cause I always leaned out of axis. What this means, is I pretty much move like the Tower of Pisa. Ie: my entire upper body leans over, while top of my head down to the hips (and actually to the bottom of the foot I'm standing on), should be in one line, straight down. To illustrate, here are some examples: I can do squats just fine. Cat stance and the likes are no problem. When moving from one stance to another where I have to do those, then stretch my leg out, I lean over. Same with doing kicks. When I do a front kick, my hips twist forward. That's how it should go. My back (lower and upper) should remain upwards, yet I lean backwards. This results in too much time lost getting back into position, taking most usefulness out of the kick. That got me thinking... Shifu occasionally alluded to that as well, but was always very soft-worded about it. Because of that, I stupidly enough didn't pay much attention to it. When looking at the mechanics of every movement, keeping your back in axis is what makes or breaks it. As such, the tai chi teacher was right when saying it was as if I didn't train even one day. Now the problem is: How to fix it? I've trained with this flaw for such a long time, removing it has become a real challenge. Shifu told me to practice in front of a mirror, and during class he now pays extra attention to it and sends me close to a mirror when necessary. This works for static movements. Get into stance A. Check the mirror. Correct where necessary. Move into stance B. Check the mirror. Correct where necessary. This works fine for those static movements, but not for other movements, nor during more active movement (eg. sparring) This is where you guys come in. I'm hoping you guys can help me with some exercises that'll help me with this issue during active movement, and any movement in general. Especially useful are exercises I can do during daily life (eg. when walking to the grocery store), as those aren't limited to designated training time.
2017/02/14
[ "https://martialarts.stackexchange.com/questions/7219", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/7414/" ]
"Leaning out of axis" is, in my mind, a combination of three separate ideas. It's not clear to me how your idea relates to mine, so here are all of the elements as I understand them: 1. **Balance** Your center of mass is supported by your base. 2. **Alignment** The relative positions of your body parts are conducive to applying/resisting force. 3. **Verticality** Your back is perpendicular to the ground plane. The simplest example of being both balanced and aligned is standing with your back straight up, which means you are also vertical. Styles disagree about alignments and verticality. You can be balanced and vertical but not aligned if you have a hunched posture. Some styles think it is necessary to fix this, while others do not. Some styles think the shoulders should twist relative to the hips, while others insist these should move together. Some styles require verticality. Other styles allow the back to be inclined to the ground, so long as it remains balanced (due to the placement of the feet) and aligned. Some of these disagreements cannot be reconciled. It seems like you are trying to fit a round peg in a square hole. Some cross-system training is simply incompatible. Kicking high while maintaining a taiji posture is VERY HARD; only a small minority of practitioners can expect to achieve this in their lifetime. Kicking high is not a goal in taiji and fighting does not rely upon it. There are reasons why taiji practice is done slowly. While moving slowly, it is much easier to detect whether you are on balance because if you have to move quickly to catch your balance, then you are not on balance. It is also easier to tell when you are losing alignments. One simple training approach is simply to practice the taiji you have learned. Moving balance is quite a bit different from static balance because you can be balanced before and after stepping, but not while stepping. The slow [sliding step](https://martialarts.stackexchange.com/a/7196/5961) is one way to train moving with better balance without leaning. When first learning, you can use push a heavy book prop with your foot to learn to apply force rather than falling with each step. Once you get this idea, you should be able to remove the book.
Answering my own question... Oh geez... The past few days I've noticed some things during day to day office life, which can be helpful, and is very, very simple. When walking, I tend to walk fast. When taking stairs, I tend to take two steps at a time. If I'm carrying a coffee or a glass of water, the liquid swashes around in the cup / glass. What I'm doing now, is trying to keep the liquid calm while not slowing my pace. If the liquid stays calm, my posture should be good.
7,219
First, a bit of background. I've been training kungfu for nearly a decade now. During all these years, I had the nagging feeling something essential was missing. Shifu sometimes told me to follow tai chi classes as well, as it would make my movements more fluid. An opportunity to train tai chi with a good, proper trainer came up, and I took it. I learned alot from that, which I incorporated into my main training as well, but that nagging feeling of something essential missing, never went away. During one class, the tai chi teacher lost his patience and told students off. He told me off by saying that I've trained for nearly a decade, but to him, I didn't train for even one day, cause I always leaned out of axis. What this means, is I pretty much move like the Tower of Pisa. Ie: my entire upper body leans over, while top of my head down to the hips (and actually to the bottom of the foot I'm standing on), should be in one line, straight down. To illustrate, here are some examples: I can do squats just fine. Cat stance and the likes are no problem. When moving from one stance to another where I have to do those, then stretch my leg out, I lean over. Same with doing kicks. When I do a front kick, my hips twist forward. That's how it should go. My back (lower and upper) should remain upwards, yet I lean backwards. This results in too much time lost getting back into position, taking most usefulness out of the kick. That got me thinking... Shifu occasionally alluded to that as well, but was always very soft-worded about it. Because of that, I stupidly enough didn't pay much attention to it. When looking at the mechanics of every movement, keeping your back in axis is what makes or breaks it. As such, the tai chi teacher was right when saying it was as if I didn't train even one day. Now the problem is: How to fix it? I've trained with this flaw for such a long time, removing it has become a real challenge. Shifu told me to practice in front of a mirror, and during class he now pays extra attention to it and sends me close to a mirror when necessary. This works for static movements. Get into stance A. Check the mirror. Correct where necessary. Move into stance B. Check the mirror. Correct where necessary. This works fine for those static movements, but not for other movements, nor during more active movement (eg. sparring) This is where you guys come in. I'm hoping you guys can help me with some exercises that'll help me with this issue during active movement, and any movement in general. Especially useful are exercises I can do during daily life (eg. when walking to the grocery store), as those aren't limited to designated training time.
2017/02/14
[ "https://martialarts.stackexchange.com/questions/7219", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/7414/" ]
"Leaning out of axis" is, in my mind, a combination of three separate ideas. It's not clear to me how your idea relates to mine, so here are all of the elements as I understand them: 1. **Balance** Your center of mass is supported by your base. 2. **Alignment** The relative positions of your body parts are conducive to applying/resisting force. 3. **Verticality** Your back is perpendicular to the ground plane. The simplest example of being both balanced and aligned is standing with your back straight up, which means you are also vertical. Styles disagree about alignments and verticality. You can be balanced and vertical but not aligned if you have a hunched posture. Some styles think it is necessary to fix this, while others do not. Some styles think the shoulders should twist relative to the hips, while others insist these should move together. Some styles require verticality. Other styles allow the back to be inclined to the ground, so long as it remains balanced (due to the placement of the feet) and aligned. Some of these disagreements cannot be reconciled. It seems like you are trying to fit a round peg in a square hole. Some cross-system training is simply incompatible. Kicking high while maintaining a taiji posture is VERY HARD; only a small minority of practitioners can expect to achieve this in their lifetime. Kicking high is not a goal in taiji and fighting does not rely upon it. There are reasons why taiji practice is done slowly. While moving slowly, it is much easier to detect whether you are on balance because if you have to move quickly to catch your balance, then you are not on balance. It is also easier to tell when you are losing alignments. One simple training approach is simply to practice the taiji you have learned. Moving balance is quite a bit different from static balance because you can be balanced before and after stepping, but not while stepping. The slow [sliding step](https://martialarts.stackexchange.com/a/7196/5961) is one way to train moving with better balance without leaning. When first learning, you can use push a heavy book prop with your foot to learn to apply force rather than falling with each step. Once you get this idea, you should be able to remove the book.
I would recommend trying chi kung - in the book by Lam Kam Chuen, the simple standing 'pose' of wu chi is introduced. Nothing could be simpler to learn, but over the months and years, this simple stance teaches you everything. It's enhanced my martial arts practice beyond measure. It may or may not correct your leaning off axis, but will help you develop proprioception and a sense of your position through your own senses. With the help of a mirror and/or a partner, you can learn to bring together your 'actual' position with what you are sensing. It takes time, and the simplicity of this simple standing exercise will have most people gloss over it quickly and dismiss it. But PRACTICE it and its value will yield great rewards.
7,219
First, a bit of background. I've been training kungfu for nearly a decade now. During all these years, I had the nagging feeling something essential was missing. Shifu sometimes told me to follow tai chi classes as well, as it would make my movements more fluid. An opportunity to train tai chi with a good, proper trainer came up, and I took it. I learned alot from that, which I incorporated into my main training as well, but that nagging feeling of something essential missing, never went away. During one class, the tai chi teacher lost his patience and told students off. He told me off by saying that I've trained for nearly a decade, but to him, I didn't train for even one day, cause I always leaned out of axis. What this means, is I pretty much move like the Tower of Pisa. Ie: my entire upper body leans over, while top of my head down to the hips (and actually to the bottom of the foot I'm standing on), should be in one line, straight down. To illustrate, here are some examples: I can do squats just fine. Cat stance and the likes are no problem. When moving from one stance to another where I have to do those, then stretch my leg out, I lean over. Same with doing kicks. When I do a front kick, my hips twist forward. That's how it should go. My back (lower and upper) should remain upwards, yet I lean backwards. This results in too much time lost getting back into position, taking most usefulness out of the kick. That got me thinking... Shifu occasionally alluded to that as well, but was always very soft-worded about it. Because of that, I stupidly enough didn't pay much attention to it. When looking at the mechanics of every movement, keeping your back in axis is what makes or breaks it. As such, the tai chi teacher was right when saying it was as if I didn't train even one day. Now the problem is: How to fix it? I've trained with this flaw for such a long time, removing it has become a real challenge. Shifu told me to practice in front of a mirror, and during class he now pays extra attention to it and sends me close to a mirror when necessary. This works for static movements. Get into stance A. Check the mirror. Correct where necessary. Move into stance B. Check the mirror. Correct where necessary. This works fine for those static movements, but not for other movements, nor during more active movement (eg. sparring) This is where you guys come in. I'm hoping you guys can help me with some exercises that'll help me with this issue during active movement, and any movement in general. Especially useful are exercises I can do during daily life (eg. when walking to the grocery store), as those aren't limited to designated training time.
2017/02/14
[ "https://martialarts.stackexchange.com/questions/7219", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/7414/" ]
I don't know about the axis part of your question, but a good way to self-check is to use your smartphone or tablet with the video camera. I do this a lot.
Answering my own question... Oh geez... The past few days I've noticed some things during day to day office life, which can be helpful, and is very, very simple. When walking, I tend to walk fast. When taking stairs, I tend to take two steps at a time. If I'm carrying a coffee or a glass of water, the liquid swashes around in the cup / glass. What I'm doing now, is trying to keep the liquid calm while not slowing my pace. If the liquid stays calm, my posture should be good.
7,219
First, a bit of background. I've been training kungfu for nearly a decade now. During all these years, I had the nagging feeling something essential was missing. Shifu sometimes told me to follow tai chi classes as well, as it would make my movements more fluid. An opportunity to train tai chi with a good, proper trainer came up, and I took it. I learned alot from that, which I incorporated into my main training as well, but that nagging feeling of something essential missing, never went away. During one class, the tai chi teacher lost his patience and told students off. He told me off by saying that I've trained for nearly a decade, but to him, I didn't train for even one day, cause I always leaned out of axis. What this means, is I pretty much move like the Tower of Pisa. Ie: my entire upper body leans over, while top of my head down to the hips (and actually to the bottom of the foot I'm standing on), should be in one line, straight down. To illustrate, here are some examples: I can do squats just fine. Cat stance and the likes are no problem. When moving from one stance to another where I have to do those, then stretch my leg out, I lean over. Same with doing kicks. When I do a front kick, my hips twist forward. That's how it should go. My back (lower and upper) should remain upwards, yet I lean backwards. This results in too much time lost getting back into position, taking most usefulness out of the kick. That got me thinking... Shifu occasionally alluded to that as well, but was always very soft-worded about it. Because of that, I stupidly enough didn't pay much attention to it. When looking at the mechanics of every movement, keeping your back in axis is what makes or breaks it. As such, the tai chi teacher was right when saying it was as if I didn't train even one day. Now the problem is: How to fix it? I've trained with this flaw for such a long time, removing it has become a real challenge. Shifu told me to practice in front of a mirror, and during class he now pays extra attention to it and sends me close to a mirror when necessary. This works for static movements. Get into stance A. Check the mirror. Correct where necessary. Move into stance B. Check the mirror. Correct where necessary. This works fine for those static movements, but not for other movements, nor during more active movement (eg. sparring) This is where you guys come in. I'm hoping you guys can help me with some exercises that'll help me with this issue during active movement, and any movement in general. Especially useful are exercises I can do during daily life (eg. when walking to the grocery store), as those aren't limited to designated training time.
2017/02/14
[ "https://martialarts.stackexchange.com/questions/7219", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/7414/" ]
I would recommend trying chi kung - in the book by Lam Kam Chuen, the simple standing 'pose' of wu chi is introduced. Nothing could be simpler to learn, but over the months and years, this simple stance teaches you everything. It's enhanced my martial arts practice beyond measure. It may or may not correct your leaning off axis, but will help you develop proprioception and a sense of your position through your own senses. With the help of a mirror and/or a partner, you can learn to bring together your 'actual' position with what you are sensing. It takes time, and the simplicity of this simple standing exercise will have most people gloss over it quickly and dismiss it. But PRACTICE it and its value will yield great rewards.
Answering my own question... Oh geez... The past few days I've noticed some things during day to day office life, which can be helpful, and is very, very simple. When walking, I tend to walk fast. When taking stairs, I tend to take two steps at a time. If I'm carrying a coffee or a glass of water, the liquid swashes around in the cup / glass. What I'm doing now, is trying to keep the liquid calm while not slowing my pace. If the liquid stays calm, my posture should be good.
454,917
I do not understand how this voltage multiplier circuit works: [![enter image description here](https://i.stack.imgur.com/9ghpa.png)](https://i.stack.imgur.com/9ghpa.png) wherever I have read (also Wikipedia), I have not found a step by step explanation. I do not understand if the voltage drop across the diodes in conduction is negligible or not, and in general I need to understand the temporal trends of the voltages at the ends of the capacitances. Moreover, I do not understand what happens when the input AC voltage is different from its maximum value. Can you give me a detailed explanation on what happens?
2019/08/27
[ "https://electronics.stackexchange.com/questions/454917", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/214898/" ]
As Bimpelrekkie explained, whether or not the voltage drop of the diodes is significant or not depends on what voltage you are working with. Since I've been playing with these things for the last few days, I'll post some of the diagrams and measurements I've made. I think the voltage traces explain fairly what happens to the output when the AC is not at its peak value. Just FYI: The voltage I'm using (30 volts peak to peak) is kind of on the edge of making the forward voltage of the diodes I'm using not matter much. The forward voltage is about 3% of the available voltage, so noticeable but small enough to squint and and say "eh, close enough" most of the time. For starters, the [Cockcroft-Walton](https://en.wikipedia.org/wiki/Cockcroft%E2%80%93Walton_generator) half wave multiplier you showed is built of a bunch [Greinacher voltage doublers.](https://en.wikipedia.org/wiki/Voltage_doubler#Greinacher_circuit) The Greinacher is composed of a [Villard doubler followed by a rectifier and a filter.](https://en.wikipedia.org/wiki/Voltage_doubler#Villard_circuit) This is a Villard doubler: [![enter image description here](https://i.stack.imgur.com/6Jn6Y.png)](https://i.stack.imgur.com/6Jn6Y.png) It takes AC, and adds half the peak to peak voltage to the AC as DC. My transformer was putting out about 30 volts peak to peak AC. The Villard circuit added about 14V to that. I ended up with a peak voltage at about 30V. It isn't really DC. It is "fluctuating DC" with all of the voltage above 0. The gray line across the middle of the image is 0 volts. As you can see, the AC was moved upwards and resulted in the "DC." The flat spots at the bottom of the DC come from the diodes. The diodes have a forward voltage of around 1 volt, so that's missing from the bottom of the curve. [![enter image description here](https://i.stack.imgur.com/AUI7u.png)](https://i.stack.imgur.com/AUI7u.png) Now here's the circuit for a Greinacher doubler: [![enter image description here](https://i.stack.imgur.com/ckhhJ.png)](https://i.stack.imgur.com/ckhhJ.png) This circuit is the basis of the Cockcroft-Walton multiplier. Look at your Cockcroft-Walton diagram, and kind of tilt your head to one side. I'm sure you'll recognize its "cells" as nothing more than a bunch of Greinacher doublers strung together. This is what the output of a Greinacher doubler looks like: [![enter image description here](https://i.stack.imgur.com/nNXW0.png)](https://i.stack.imgur.com/nNXW0.png) It is a little bit lower than the Villard output, but it is much closer to DC. If I had used larger capacitors, then it would look exactly like DC. Now, you string a bunch of Greinachers together, and you get a higher voltage. It would look a lot like that last picture, just with higher output voltage. I'm getting about 24V out of a single Greinacher. If I put a bunch of them together to get a Cockcroft-Walton multiplier, then I get 24V for every stage I add to it. 1 stage 24 V 2 stages 48 V 3 stages 72 V and so on. You take the peak to peak voltage of your AC (30 V in my case,) subtract the diode forward voltage, and that's approximately the voltage you can expect in DC for a single stage. Multiply by the number of stages, and you have your (approximate) DC output voltage. The next trick is figuring out the size of the capacitors to use. I used 100nF capacitors for my experiments (that was **way** too small when working with 50 hertz.) That makes my doubler have a very high resistance. A "load" of 1 megaohm noticeably drops the output voltage. I've been trying to figure out how to express the impedance of a Cockcroft-Walton multiplier as a function of the capacitance. I'm playing hooky from that right now. My plan was to build a couple of more multipliers with different capacitors and see how they respond to loading.
> > I do not understand if the voltage drop across the diodes in conduction is negligible or not > > > It is not a case of "negligible or not", as with many things in electronics: **it depends**. The diodes have a certain forward voltage, typically between 0.5 V to 1.0 V depending on how much current flows though the diode (more current => more voltage drop). If I multiply an AC input voltage of 5 V then a drop of 0.5 V per diode is significant, 0.5 V is 10% of 5 V. If I multiply an AC input voltage of 50 V then a drop of 0.5 V per diode is less significant, 0.5 V is 1% of 50 V. If I multiply an AC input voltage of 500 V then a drop of 0.5 V per diode is practically insignificant, 0.5 V is only 0.1% of 500 V. Do you see what I'm doing here? The diode drop voltage remains constant but **relative** to the voltages at which the circuit is working, that constant drop become less significant as that voltage increases. So: it depends, on the voltages at which the multiplier operates. > > Moreover, I do not understand what happens when the input AC voltage is different from its maximum value > > > An AC voltage has a peak value which is its maximum value. We generally don't talk about an AC voltage's maximum value, we say peak value. An AC voltage is generally described using an RMS value and/or peak value and/or peak-to-peak value. It depends on your application what is most convenient. These voltage multiplier work on the peak value of the signal as they are rectifiers.
454,917
I do not understand how this voltage multiplier circuit works: [![enter image description here](https://i.stack.imgur.com/9ghpa.png)](https://i.stack.imgur.com/9ghpa.png) wherever I have read (also Wikipedia), I have not found a step by step explanation. I do not understand if the voltage drop across the diodes in conduction is negligible or not, and in general I need to understand the temporal trends of the voltages at the ends of the capacitances. Moreover, I do not understand what happens when the input AC voltage is different from its maximum value. Can you give me a detailed explanation on what happens?
2019/08/27
[ "https://electronics.stackexchange.com/questions/454917", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/214898/" ]
The Vf drop of the diode does have a significant, cumulative effect. Each stage reduces the output voltage by one Vf drop. In the example below, there are two stages. With a 10Vp-p input, the output voltage is 18.66V instead of 20. The difference is two Vf diode drops of 0.66V each (1.33V total.) ![schematic](https://i.stack.imgur.com/IAE3h.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fIAE3h.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) You can reduce this drop by using Schottky diodes, but you will still have some drop. To analyze this in detail, the key is to understand the current flow and how the diodes are steering it. Building a simulation helps with this immensely. I built this sim with the CircuitLab tool (available as an option on the edit toolbar); or use a free Spice sim like LT-Spice.
> > I do not understand if the voltage drop across the diodes in conduction is negligible or not > > > It is not a case of "negligible or not", as with many things in electronics: **it depends**. The diodes have a certain forward voltage, typically between 0.5 V to 1.0 V depending on how much current flows though the diode (more current => more voltage drop). If I multiply an AC input voltage of 5 V then a drop of 0.5 V per diode is significant, 0.5 V is 10% of 5 V. If I multiply an AC input voltage of 50 V then a drop of 0.5 V per diode is less significant, 0.5 V is 1% of 50 V. If I multiply an AC input voltage of 500 V then a drop of 0.5 V per diode is practically insignificant, 0.5 V is only 0.1% of 500 V. Do you see what I'm doing here? The diode drop voltage remains constant but **relative** to the voltages at which the circuit is working, that constant drop become less significant as that voltage increases. So: it depends, on the voltages at which the multiplier operates. > > Moreover, I do not understand what happens when the input AC voltage is different from its maximum value > > > An AC voltage has a peak value which is its maximum value. We generally don't talk about an AC voltage's maximum value, we say peak value. An AC voltage is generally described using an RMS value and/or peak value and/or peak-to-peak value. It depends on your application what is most convenient. These voltage multiplier work on the peak value of the signal as they are rectifiers.
454,917
I do not understand how this voltage multiplier circuit works: [![enter image description here](https://i.stack.imgur.com/9ghpa.png)](https://i.stack.imgur.com/9ghpa.png) wherever I have read (also Wikipedia), I have not found a step by step explanation. I do not understand if the voltage drop across the diodes in conduction is negligible or not, and in general I need to understand the temporal trends of the voltages at the ends of the capacitances. Moreover, I do not understand what happens when the input AC voltage is different from its maximum value. Can you give me a detailed explanation on what happens?
2019/08/27
[ "https://electronics.stackexchange.com/questions/454917", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/214898/" ]
As Bimpelrekkie explained, whether or not the voltage drop of the diodes is significant or not depends on what voltage you are working with. Since I've been playing with these things for the last few days, I'll post some of the diagrams and measurements I've made. I think the voltage traces explain fairly what happens to the output when the AC is not at its peak value. Just FYI: The voltage I'm using (30 volts peak to peak) is kind of on the edge of making the forward voltage of the diodes I'm using not matter much. The forward voltage is about 3% of the available voltage, so noticeable but small enough to squint and and say "eh, close enough" most of the time. For starters, the [Cockcroft-Walton](https://en.wikipedia.org/wiki/Cockcroft%E2%80%93Walton_generator) half wave multiplier you showed is built of a bunch [Greinacher voltage doublers.](https://en.wikipedia.org/wiki/Voltage_doubler#Greinacher_circuit) The Greinacher is composed of a [Villard doubler followed by a rectifier and a filter.](https://en.wikipedia.org/wiki/Voltage_doubler#Villard_circuit) This is a Villard doubler: [![enter image description here](https://i.stack.imgur.com/6Jn6Y.png)](https://i.stack.imgur.com/6Jn6Y.png) It takes AC, and adds half the peak to peak voltage to the AC as DC. My transformer was putting out about 30 volts peak to peak AC. The Villard circuit added about 14V to that. I ended up with a peak voltage at about 30V. It isn't really DC. It is "fluctuating DC" with all of the voltage above 0. The gray line across the middle of the image is 0 volts. As you can see, the AC was moved upwards and resulted in the "DC." The flat spots at the bottom of the DC come from the diodes. The diodes have a forward voltage of around 1 volt, so that's missing from the bottom of the curve. [![enter image description here](https://i.stack.imgur.com/AUI7u.png)](https://i.stack.imgur.com/AUI7u.png) Now here's the circuit for a Greinacher doubler: [![enter image description here](https://i.stack.imgur.com/ckhhJ.png)](https://i.stack.imgur.com/ckhhJ.png) This circuit is the basis of the Cockcroft-Walton multiplier. Look at your Cockcroft-Walton diagram, and kind of tilt your head to one side. I'm sure you'll recognize its "cells" as nothing more than a bunch of Greinacher doublers strung together. This is what the output of a Greinacher doubler looks like: [![enter image description here](https://i.stack.imgur.com/nNXW0.png)](https://i.stack.imgur.com/nNXW0.png) It is a little bit lower than the Villard output, but it is much closer to DC. If I had used larger capacitors, then it would look exactly like DC. Now, you string a bunch of Greinachers together, and you get a higher voltage. It would look a lot like that last picture, just with higher output voltage. I'm getting about 24V out of a single Greinacher. If I put a bunch of them together to get a Cockcroft-Walton multiplier, then I get 24V for every stage I add to it. 1 stage 24 V 2 stages 48 V 3 stages 72 V and so on. You take the peak to peak voltage of your AC (30 V in my case,) subtract the diode forward voltage, and that's approximately the voltage you can expect in DC for a single stage. Multiply by the number of stages, and you have your (approximate) DC output voltage. The next trick is figuring out the size of the capacitors to use. I used 100nF capacitors for my experiments (that was **way** too small when working with 50 hertz.) That makes my doubler have a very high resistance. A "load" of 1 megaohm noticeably drops the output voltage. I've been trying to figure out how to express the impedance of a Cockcroft-Walton multiplier as a function of the capacitance. I'm playing hooky from that right now. My plan was to build a couple of more multipliers with different capacitors and see how they respond to loading.
The Vf drop of the diode does have a significant, cumulative effect. Each stage reduces the output voltage by one Vf drop. In the example below, there are two stages. With a 10Vp-p input, the output voltage is 18.66V instead of 20. The difference is two Vf diode drops of 0.66V each (1.33V total.) ![schematic](https://i.stack.imgur.com/IAE3h.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fIAE3h.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) You can reduce this drop by using Schottky diodes, but you will still have some drop. To analyze this in detail, the key is to understand the current flow and how the diodes are steering it. Building a simulation helps with this immensely. I built this sim with the CircuitLab tool (available as an option on the edit toolbar); or use a free Spice sim like LT-Spice.
454,917
I do not understand how this voltage multiplier circuit works: [![enter image description here](https://i.stack.imgur.com/9ghpa.png)](https://i.stack.imgur.com/9ghpa.png) wherever I have read (also Wikipedia), I have not found a step by step explanation. I do not understand if the voltage drop across the diodes in conduction is negligible or not, and in general I need to understand the temporal trends of the voltages at the ends of the capacitances. Moreover, I do not understand what happens when the input AC voltage is different from its maximum value. Can you give me a detailed explanation on what happens?
2019/08/27
[ "https://electronics.stackexchange.com/questions/454917", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/214898/" ]
As Bimpelrekkie explained, whether or not the voltage drop of the diodes is significant or not depends on what voltage you are working with. Since I've been playing with these things for the last few days, I'll post some of the diagrams and measurements I've made. I think the voltage traces explain fairly what happens to the output when the AC is not at its peak value. Just FYI: The voltage I'm using (30 volts peak to peak) is kind of on the edge of making the forward voltage of the diodes I'm using not matter much. The forward voltage is about 3% of the available voltage, so noticeable but small enough to squint and and say "eh, close enough" most of the time. For starters, the [Cockcroft-Walton](https://en.wikipedia.org/wiki/Cockcroft%E2%80%93Walton_generator) half wave multiplier you showed is built of a bunch [Greinacher voltage doublers.](https://en.wikipedia.org/wiki/Voltage_doubler#Greinacher_circuit) The Greinacher is composed of a [Villard doubler followed by a rectifier and a filter.](https://en.wikipedia.org/wiki/Voltage_doubler#Villard_circuit) This is a Villard doubler: [![enter image description here](https://i.stack.imgur.com/6Jn6Y.png)](https://i.stack.imgur.com/6Jn6Y.png) It takes AC, and adds half the peak to peak voltage to the AC as DC. My transformer was putting out about 30 volts peak to peak AC. The Villard circuit added about 14V to that. I ended up with a peak voltage at about 30V. It isn't really DC. It is "fluctuating DC" with all of the voltage above 0. The gray line across the middle of the image is 0 volts. As you can see, the AC was moved upwards and resulted in the "DC." The flat spots at the bottom of the DC come from the diodes. The diodes have a forward voltage of around 1 volt, so that's missing from the bottom of the curve. [![enter image description here](https://i.stack.imgur.com/AUI7u.png)](https://i.stack.imgur.com/AUI7u.png) Now here's the circuit for a Greinacher doubler: [![enter image description here](https://i.stack.imgur.com/ckhhJ.png)](https://i.stack.imgur.com/ckhhJ.png) This circuit is the basis of the Cockcroft-Walton multiplier. Look at your Cockcroft-Walton diagram, and kind of tilt your head to one side. I'm sure you'll recognize its "cells" as nothing more than a bunch of Greinacher doublers strung together. This is what the output of a Greinacher doubler looks like: [![enter image description here](https://i.stack.imgur.com/nNXW0.png)](https://i.stack.imgur.com/nNXW0.png) It is a little bit lower than the Villard output, but it is much closer to DC. If I had used larger capacitors, then it would look exactly like DC. Now, you string a bunch of Greinachers together, and you get a higher voltage. It would look a lot like that last picture, just with higher output voltage. I'm getting about 24V out of a single Greinacher. If I put a bunch of them together to get a Cockcroft-Walton multiplier, then I get 24V for every stage I add to it. 1 stage 24 V 2 stages 48 V 3 stages 72 V and so on. You take the peak to peak voltage of your AC (30 V in my case,) subtract the diode forward voltage, and that's approximately the voltage you can expect in DC for a single stage. Multiply by the number of stages, and you have your (approximate) DC output voltage. The next trick is figuring out the size of the capacitors to use. I used 100nF capacitors for my experiments (that was **way** too small when working with 50 hertz.) That makes my doubler have a very high resistance. A "load" of 1 megaohm noticeably drops the output voltage. I've been trying to figure out how to express the impedance of a Cockcroft-Walton multiplier as a function of the capacitance. I'm playing hooky from that right now. My plan was to build a couple of more multipliers with different capacitors and see how they respond to loading.
Remove all components except for D1 and C1. Analyse the circuit behaviour. Now add in D2 and C2. What's different? What's the same? Now add D3 and C3. What's the same and what's different? Do you notice a pattern? Generalise to adding an arbitrary number of Ds and Cs in the same pattern.
454,917
I do not understand how this voltage multiplier circuit works: [![enter image description here](https://i.stack.imgur.com/9ghpa.png)](https://i.stack.imgur.com/9ghpa.png) wherever I have read (also Wikipedia), I have not found a step by step explanation. I do not understand if the voltage drop across the diodes in conduction is negligible or not, and in general I need to understand the temporal trends of the voltages at the ends of the capacitances. Moreover, I do not understand what happens when the input AC voltage is different from its maximum value. Can you give me a detailed explanation on what happens?
2019/08/27
[ "https://electronics.stackexchange.com/questions/454917", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/214898/" ]
The Vf drop of the diode does have a significant, cumulative effect. Each stage reduces the output voltage by one Vf drop. In the example below, there are two stages. With a 10Vp-p input, the output voltage is 18.66V instead of 20. The difference is two Vf diode drops of 0.66V each (1.33V total.) ![schematic](https://i.stack.imgur.com/IAE3h.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fIAE3h.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) You can reduce this drop by using Schottky diodes, but you will still have some drop. To analyze this in detail, the key is to understand the current flow and how the diodes are steering it. Building a simulation helps with this immensely. I built this sim with the CircuitLab tool (available as an option on the edit toolbar); or use a free Spice sim like LT-Spice.
Remove all components except for D1 and C1. Analyse the circuit behaviour. Now add in D2 and C2. What's different? What's the same? Now add D3 and C3. What's the same and what's different? Do you notice a pattern? Generalise to adding an arbitrary number of Ds and Cs in the same pattern.
59,762,078
To my current understanding, the pattern below should work (expected `['bar', 'FOO', 'bar']`), but only the first alternative is found (zero-width matches after FOO, but not before). ```vim echo split('barFOObar', '\v(FOO\zs|\zeFOO)') " --> ['barFOO', 'bar'] ``` Netiher could I solve it with lookahead/lookbehind. ```vim echo split('barFOObar', '\v((FOO)\@<=|(FOO)\@=)') " --> ['bar', 'bar'] ``` Compare this with e.g. Python: ```vim echo py3eval("re.split('(?=FOO)|(?<=FOO)', 'barFOObar')") " --> ['bar', 'FOO', 'bar'] ``` (Note: in Python, a paren-enclosed `'(FOO)'` would also work for this.) Why don't the above examples in Vim's regex work the way I thought they should? (And also, is there a more or less straightforward way to do this in pure Vimscript then?)
2020/01/16
[ "https://Stackoverflow.com/questions/59762078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11020321/" ]
There doesn't seem to be a way to accomplish that direct result using a single `split()`. In fact, the docs for `split()` mention this particular situation of preserving the delimiter, with: > > If you want to keep the separator you can also use `\zs` at the end of the pattern: > > > > ``` > :echo split('abc:def:ghi', ':\zs') > ['abc:', 'def:', 'ghi'] > > ``` > > Having said that, using both a lookahead and a lookbehind *does* actually work. In your example, you have a syntax error. Since you're using verymagic mode, you shouldn't escape `@`, since it's already special. (Thanks [@user938271](https://stackoverflow.com/users/9780968/user938271) for pointing that out!) This works: ``` :echo split('barFOObar', '\v((FOO)@<=|(FOO)@=)') " --> ['bar', 'FOO', 'bar'] ``` --- Regarding using the markers for `\zs` and `\ze`: ``` :echo split('barFOObar', '\v(FOO\zs|\zeFOO)') " --> ['barFOO', 'bar'] ``` So the first trouble you have here is that both expressions on each side of the `|` are matching the same text "FOO", so since they're identical, the first wins and you get it on the left side. Change order and you get it on the right side: ``` :echo split('barFOObar', '\v(\zeFOO|FOO\zs)') " --> ['bar', 'FOObar'] ``` Now the question is why the second token "FOObar" isn't being split since it's matching again (the lookbehind case splits this one, right?) Well, the answer is that it's actually being split again, but it matches on the first case of `\zeFOO` one more time and produces a split with the empty string. You can see that by passing a keepempty argument: ``` :echo split('barFOObar', '\v(\zeFOO|FOO\zs)', 1) " --> ['bar', '', 'FOObar'] ``` --- One question still unanswered here is why the lookahead/lookbehind *does* work, while the `\zs` and `\ze` doesn't. I think I addressed that somehow in [this answer](https://vi.stackexchange.com/a/22431/18609) to regex usage in syntax groups. This won't work because Vim won't scan the same text twice trying to match a different regex. Even though the `\zs` makes the resulting match only include `bar`, Vim needs to consume `FOO` to be able to match that regex and it won't do so if it already matched it with the other half of the pattern. A lookbehind with `\@<=` is different. The reason it works is that Vim will first search for `bar` (or whatever text it's considering) and then look behind to see if `FOO` also matches. So the pattern gets anchored on `bar` rather than `FOO` and doesn't suffer from the issue of trying to start a match on a region that already matched another expression. You can easily visualize that difference by performing a search with Vim. Try this one: ``` /\v(\zeFOO|FOO\zs) ``` And compare it with this one: ``` /\v((FOO)@<=|(FOO)@=) ``` You'll notice the latter one will match both before *and* after FOO, while the former won't. --- > > Compare this with e.g. Python [`re.split`] ... > in Python, a paren-enclosed `'(FOO)'` would also work for this. > > > Vim's and Python's regex engines are different beasts... Many of the limitations in Vim's engine come from its ancestry from vi. One particular limitation is capture groups, where you're limited to 9 of them and there's no way around that. Given that limitation, you'll find that capture groups are typically used less often (and, when used, they're less powerful) than in Python. One option to consider is to use Python in Vim instead of Vimscript. Although typically that impacts portability, so personally I wouldn't switch for this feature alone. --- > > is there a more or less straightforward way to do this in pure Vimscript then? > > > One option is to reimplement a version of `split()` that preserves delimiters, using `matchstrpos()`. For example: ``` function! SplitDelim(expr, pat) let result = [] let expr = a:expr while 1 let [w, s, e] = matchstrpos(expr, a:pat) if s == -1 break endif call add(result, s ? expr[:s-1] : '') call add(result, w) let expr = expr[e:] endwhile call add(result, expr) return result endfunction ```
You could first replace `FOO` with `-FOO-`, then split the string. For example: ``` :echo split(substitute('barFOObarFOObaz', 'FOO','-&-','g'),'-') ['bar', 'FOO', 'bar', 'FOO', 'baz'] ```
58,394,061
I want to remove elements from a numpy vector that are closer than a distance d. (I don't want any pair in the array or list that have a smaller distance between them than d but don't want to remove the pair completely otherwise. for example if my array is: > > > ``` > array([[0. ], > [0.9486833], > [1.8973666], > [2.8460498], > [0.9486833]], dtype=float32) > > ``` > > All I need is to remove either the element with the index 1 or 4 not both of them. I also need the indices of the elements from the original array that remain in the latent one. Since the original array is in tensorflow 2.0, I will be happier if conversion to numpy is not needed like above. Because of speed also I prefer not to use another package and stay with numpy or scipy. Thanks.
2019/10/15
[ "https://Stackoverflow.com/questions/58394061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392393/" ]
Here's a solution, using only a list. Note that this modifies the original list, so if you want to keep the original, copy.deepcopy it. ``` THRESHOLD = 0.1 def wrangle(l): for i in range(len(l)): for j in range(len(l)-1, i, -1): if abs(l[i] - l[j]) < THRESHOLD: l.pop(j) ```
If your array is really only 1-d you can flatten it and do something like this: ``` a=tf.constant(np.array([[0. ], [0.9486833], [1.8973666], [2.8460498], [0.9486833]], dtype=np.float32)) d = 0.1 flat_a = tf.reshape(a,[-1]) # flatten a1 = tf.expand_dims(flat_a, 1) a2 = tf.expand_dims(flat_a, 0) distance_map = tf.math.abs(a1-a2) too_small = tf.cast(tf.math.less(dist_map, d), tf.int32) # 1 at indices i,j if the distance between elements at i and j is less than d, 0 otherwise upper_triangular_part = tf.linalg.band_part(too_small, 0, -1) - tf.linalg.band_part(too_small, 0,0) remove = tf.reduce_sum(upper_triangular_part, axis=0) remove = tf.cast(tf.math.greater(remove, 0), tf.float32) # 1. at indices where the element should be removed, 0. otherwise output = flat_a - remove * flat_a ``` You can access the indices through the remove tensor. If you need the extra dimension you can just use tf.expand\_dims at the end of this.
58,394,061
I want to remove elements from a numpy vector that are closer than a distance d. (I don't want any pair in the array or list that have a smaller distance between them than d but don't want to remove the pair completely otherwise. for example if my array is: > > > ``` > array([[0. ], > [0.9486833], > [1.8973666], > [2.8460498], > [0.9486833]], dtype=float32) > > ``` > > All I need is to remove either the element with the index 1 or 4 not both of them. I also need the indices of the elements from the original array that remain in the latent one. Since the original array is in tensorflow 2.0, I will be happier if conversion to numpy is not needed like above. Because of speed also I prefer not to use another package and stay with numpy or scipy. Thanks.
2019/10/15
[ "https://Stackoverflow.com/questions/58394061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392393/" ]
using `numpy`: ```py import numpy as np a = np.array([[0. ], [0.9486833], [1.8973666], [2.8460498], [0.9486833]]) threshold = 1.0 # The indices of the items smaller than a certain threshold, but larger than 0. smaller_than = np.flatnonzero(np.logical_and(a < threshold, a > 0)) # Get the first index smaller than threshold first_index = smaller_than[0] # Recreate array without this index (bit cumbersome) new_array = a[np.arange(len(a)) != first_index] ``` I'm pretty sure this is really easy to recreate in `tensorflow`, but I don't know how.
If your array is really only 1-d you can flatten it and do something like this: ``` a=tf.constant(np.array([[0. ], [0.9486833], [1.8973666], [2.8460498], [0.9486833]], dtype=np.float32)) d = 0.1 flat_a = tf.reshape(a,[-1]) # flatten a1 = tf.expand_dims(flat_a, 1) a2 = tf.expand_dims(flat_a, 0) distance_map = tf.math.abs(a1-a2) too_small = tf.cast(tf.math.less(dist_map, d), tf.int32) # 1 at indices i,j if the distance between elements at i and j is less than d, 0 otherwise upper_triangular_part = tf.linalg.band_part(too_small, 0, -1) - tf.linalg.band_part(too_small, 0,0) remove = tf.reduce_sum(upper_triangular_part, axis=0) remove = tf.cast(tf.math.greater(remove, 0), tf.float32) # 1. at indices where the element should be removed, 0. otherwise output = flat_a - remove * flat_a ``` You can access the indices through the remove tensor. If you need the extra dimension you can just use tf.expand\_dims at the end of this.
2,206,281
I have to show this: Let $A = \{ x \in \mathbb{Z} : 3|x \}$ and $f : A \rightarrow \mathbb{N}$. Show that $A$ and $\mathbb{N}$ have the same cardinality. I know that when $a \in A \geq 0$, every element in $A$ maps to a unique element in $\mathbb{N}$. For example, $(0,0),(3,1),(6,2),(9,3)$, etc. Which means when $a \in A \geq 0$ it's a bijection from $A \rightarrow \mathbb{N}$ (right?). But I'm not sure how to show that the negative values in $A$ map to unique values in $\mathbb{N}$ or just in general how cardinality of an infinite set can be the same as a finite set.
2017/03/28
[ "https://math.stackexchange.com/questions/2206281", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It is enough to understand if the integrand function is integrable in a right neighbourhood of the origin and in a left neighbourhood of $+\infty$. $\sin(x)^2$ behaves like $x^2$ in a right neighbourhood of the origin and it is a non-negative function with mean value $\frac{1}{2}$, hence $$ \int\_{0}^{+\infty}\frac{\sin^2(x)}{x^\alpha}\,dx $$ converges as soon as $1<\alpha<3$. In such a case it equals $$-\frac{\pi\, 2^{\alpha-3}}{\Gamma(\alpha)\cos\left(\frac{\pi\alpha}{2}\right)}$$ by Euler's Beta function and the reflection formula for the $\Gamma$ function.
Note that $$\begin{align} \int\_1^L \frac{\sin^2(x)}{x}\,dx&=\frac12\int\_1^L \frac{1-\cos(2x)}{x}\,dx\\\\ &=\frac12\log(L)-\frac12\int\_2^{2L}\frac{\cos(x)}{x}\,dx\tag 1 \end{align}$$ From [Abel's (Dirichlet's) Test](https://en.wikipedia.org/wiki/Dirichlet%27s_test#Improper_integrals) for improper integrals, the integral on the right-hand side of $(1)$ converges. To show this, simply note that $\left|\int\_0^L\cos(x)\,dx\right|\le 2$ and $\frac1x$ monotonically decreases. Inasmuch as $\log(L)\to \infty$, the integral on the right-hand side cannot converge. And that is that. --- **RELATED PROBLEMS:** In [THIS ANSWER](https://math.stackexchange.com/questions/2203085/convergence-absolute-convergence-of-an-integral/2203109#2203109), I analyzed convergence (conditional) of the integral $\int\_0^\infty \frac{\sin^3(x)}{x}\,dx$ from which it is trivial to analyze the convergence of $\int\_0^\infty \frac{\sin^3(x)}{x^2}\,dx$ And in [THIS ANSWER](https://math.stackexchange.com/questions/2203939/determining-whether-int-0-infty-fracx-sinx1x2dx-converges-and/2203944#2203944), I analyzed the convergence (conditional) of $\int\_0^\int \frac{\sin(x)}{x}\,dx$
2,206,281
I have to show this: Let $A = \{ x \in \mathbb{Z} : 3|x \}$ and $f : A \rightarrow \mathbb{N}$. Show that $A$ and $\mathbb{N}$ have the same cardinality. I know that when $a \in A \geq 0$, every element in $A$ maps to a unique element in $\mathbb{N}$. For example, $(0,0),(3,1),(6,2),(9,3)$, etc. Which means when $a \in A \geq 0$ it's a bijection from $A \rightarrow \mathbb{N}$ (right?). But I'm not sure how to show that the negative values in $A$ map to unique values in $\mathbb{N}$ or just in general how cardinality of an infinite set can be the same as a finite set.
2017/03/28
[ "https://math.stackexchange.com/questions/2206281", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
For $(\sin^2{x})/x$: Divide the integration range up into intervals $[n\pi,(n+1)\pi]$ for $n=0,1,2,\dotsc$. Then on such an interval, $$ \frac{\sin^2{x}}{x} \geq \frac{\sin^2{x}}{(n+1)\pi}, $$ since $1/x$ is decreasing. Then $\int\_{n\pi}^{(n+1)\pi} \sin^2{x} \, dx = \pi/2$, so integrating both sides of the inequality over $[n\pi,(n+1)\pi]$, $$ \int\_{n\pi}^{(n+1)\pi} \frac{\sin^2{x}}{x} \, dx \geq \frac{1}{2(n+1)}, $$ and summing up, we find that the integral is bounded below by the harmonic series, which diverges. For $(\sin^2{x})/x^2$, first check that the integrand is bounded as $ x \downarrow 0 $ (you know $\sin{x}/x \to 1$, right?), and then use the same idea as the first example to bound the integrand above on intervals. The last one diverges for a different reason: $(\sin^2{x})/x^3 \approx 1/x$ as $x \downarrow 0$, and the integral of $1/x$ diverges.
Note that $$\begin{align} \int\_1^L \frac{\sin^2(x)}{x}\,dx&=\frac12\int\_1^L \frac{1-\cos(2x)}{x}\,dx\\\\ &=\frac12\log(L)-\frac12\int\_2^{2L}\frac{\cos(x)}{x}\,dx\tag 1 \end{align}$$ From [Abel's (Dirichlet's) Test](https://en.wikipedia.org/wiki/Dirichlet%27s_test#Improper_integrals) for improper integrals, the integral on the right-hand side of $(1)$ converges. To show this, simply note that $\left|\int\_0^L\cos(x)\,dx\right|\le 2$ and $\frac1x$ monotonically decreases. Inasmuch as $\log(L)\to \infty$, the integral on the right-hand side cannot converge. And that is that. --- **RELATED PROBLEMS:** In [THIS ANSWER](https://math.stackexchange.com/questions/2203085/convergence-absolute-convergence-of-an-integral/2203109#2203109), I analyzed convergence (conditional) of the integral $\int\_0^\infty \frac{\sin^3(x)}{x}\,dx$ from which it is trivial to analyze the convergence of $\int\_0^\infty \frac{\sin^3(x)}{x^2}\,dx$ And in [THIS ANSWER](https://math.stackexchange.com/questions/2203939/determining-whether-int-0-infty-fracx-sinx1x2dx-converges-and/2203944#2203944), I analyzed the convergence (conditional) of $\int\_0^\int \frac{\sin(x)}{x}\,dx$
35,805,804
Hi I was wondering if it's possible to leverage Spring annotated Caching within Scala. I have tried but am receiving the error below. I am running the application from a java package that depends on the scala package. ``` No cache could be resolved for 'CacheableOperation[public scala.collection.immutable.List MerchantDataGateway.getAllMerchants()] ``` My Configuration Class ``` @Configuration @EnableCaching @ComponentScan(basePackages = "xxx.xxx.xxx.xxx") public class EnvironmentHelperConfig { @Bean public CacheManager getCacheManager() { final int ttl = 12; final int maxCacheSize = 1012; GuavaCacheManager result = new GuavaCacheManager(); result.setCacheBuilder(CacheBuilder .newBuilder() .expireAfterWrite(ttl, TimeUnit.HOURS) .maximumSize(maxCacheSize)); return result; } } ``` My Scala Class ``` @Component class MerchantDataGateway { @Autowired var fmcsProxy: MerchantResource = null; @Cacheable def getAllMerchants(): List[MerchantViewModel] = { val merchants = getAllMerchantsFromFMCS() merchants.map(merchant => MerchantViewModel.getLightWeightInstance(merchant)) } } ```
2016/03/04
[ "https://Stackoverflow.com/questions/35805804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6020194/" ]
Add a name to the @Cacheable annotation: ``` @Cacheable(Array("MerchantDataGateway.getAllMerchants")) ```
It needed a name, or an entry for the value ``` @Cacheable(value = Array("MerchantDataGateway.getAllMerchants") ```
235,791
I am considering buying a Game Boy Advance. I like the 1st generation model, but I don't know if the screen is bright enough for normal indoor use or not. Is screen brightness likely to be an issue, and if so, what can I do to help with the problem?
2015/09/08
[ "https://gaming.stackexchange.com/questions/235791", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/124363/" ]
It can be seen indoors, but there's no backlighting so it's tough (if not impossible) to see in the dark. There were several [peripherals](http://rads.stackoverflow.com/amzn/click/B004910A8I) released to solve this problem, so if you're dead-set on the original model you do have options. If the model isn't that important, the [Game Boy Advance SP](http://rads.stackoverflow.com/amzn/click/B0000A9Y11) plays the same games, takes up less space, and has a backlit screen.
I can't recommend the SP enough if you're going to play any version of the Game Boy Advance. Slickest design, more durable than it looks too, and of course the backlit screen is a must. I can't envision liking the 1st generation model enough to offset the annoyance by not having a backlit screen. It is playable indoors if you turn on some lighting, however -- I used to use a desk lamp as a kid. That kind of limits the whole portability part to some extent though.
3,501,222
To find the area of segment of a circle, I used the following formula: $\frac{r^2}{2} (\theta$ - $\sin \theta$) But if the area is given and I want to find the angle $\theta$ how can I do that. $\theta$ - $\sin \theta$ = $\frac{2A}{r^2}$ where A and r are the given values of area and radius of the circle respectively. Please answer this question as soon as possible any help would be appreciated.
2020/01/08
[ "https://math.stackexchange.com/questions/3501222", "https://math.stackexchange.com", "https://math.stackexchange.com/users/634349/" ]
It is enough to solve for $\theta\in[0,\pi]$, other ranges can be handled by symmetry. For small angles, the Taylor expansion to the third order is $$r:=\theta-\sin\theta\approx\frac{\theta^3}{6}$$ and can be used to find a simple approximation $$\theta\approx \sqrt[3]{6r}.$$ And you get an even better approximation with $$r\approx\frac{\theta^3}{\pi^2},\ \theta\approx \color{green}{\sqrt[3]{\pi^2r}}$$ which is exact at both ends of the range. In blue the true curve, in green Taylor ($r$ as a function of $\theta$). [![enter image description here](https://i.stack.imgur.com/Zv9P1.png)](https://i.stack.imgur.com/Zv9P1.png) From this initial value, you can improve by Newton's iterations, $$\theta'=\theta-\frac{\theta-\sin\theta-r}{1-\cos\theta}=\color{green}{\frac{\sin\theta-\theta\cos\theta+r}{1-\cos\theta}}$$ applied two or three times. Below in magenta the first approximation and in green the first Newton's iterate overlaid on the exact curve ($\theta$ as a function of $r$). [![enter image description here](https://i.stack.imgur.com/K72ur.png)](https://i.stack.imgur.com/K72ur.png)
As Lord Shark pointed out there is no closed form expression to calculate $\theta$. I am not aware of any series expansion either. What I can give you is a formula that can be used to determine an approximate value for $\theta$. The values obtained are good only for small $\theta$ (i.e. $\lt \frac{\pi}{2})$. $$\theta\approx\frac{x^3 + 6\sin x - 6x\cos x}{6\left(1-\cos x\right)},\space\space \rm{where} \space\space\space \it{x}\rm{=\sqrt[3]{\frac{12\it{A}}{\it{r}^2}}}\space\space and\space\space \theta\space\space is\space\space given\space\space in\space\space radians$$ It is up to you to take this formula or leave it depending on your requirements. Now I will give the iteration formula based on Newton-Raphson method that can be used to improve $\theta$ in radians to a desired accuracy. $$\theta\_{i+1} = \theta\_{i} - \frac{\theta\_{i} - \sin \theta\_{i} - \frac{2A}{r^2}}{1 - \cos \theta\_{i}},\space\space \rm{where} \space\space\space \it{\theta}\rm{\_1=}\space\space\it{\theta}$$ I am adding the text given below at the request of Tanmay Gajapati. First of all, you don't seem foolish to me. I omitted this part from my answer assuming that you are already familiar with this type of calculations. Now I know that you are not, so here it is. To use the $1^{st}$ formula, calculate the value of $x$ using the given area $A$ and radius $r$, e.g. if $r=10\space \rm{cm}\space$ and $\space A=1.18\space \rm{cm^2}$ $$x=\sqrt[3]{\frac{12\times 1.18}{10^2}}=0.52122$$ Then substitute this value of $x$ in the expression given for $\theta$ to obtain its value, e.g. $$\theta\approx \frac{0.52122^3+6\times \sin\left(0.52122\right)-6\times 0.52122\times\cos\left(0.52122\right)}{6\times\left(1-\cos\left(0.52122\right)\right)}=0.5236186\space\rm{rad}.$$ If you think the value obtained from the $1^{st}$ formula for $\theta$ is not accurate enough, you can use the $2^{nd}$ formula to improve it, e.g. $$\theta\_2 = 0.5236186 - \frac{0.5236186 - \sin\left(0.5236186\right) - \frac{2\times 1.18}{10^2}}{1 - \cos\left(0.5236186\right)}=0.5236079\space\rm{rad}, $$ $$\theta\_3 = 0.5236079 - \frac{0.5236079 - \sin\left(0.5236079\right) - \frac{2\times 1.18}{10^2}}{1 - \cos\left(0.5236079\right)}=0.5236079\space\rm{rad}. $$ As you can see from the last two values of $\theta$, it is no longer improving. Therefore, this is the value of the subtended angle $\theta$ at the center of the circle for the given values of $A$ and $r$.
3,501,222
To find the area of segment of a circle, I used the following formula: $\frac{r^2}{2} (\theta$ - $\sin \theta$) But if the area is given and I want to find the angle $\theta$ how can I do that. $\theta$ - $\sin \theta$ = $\frac{2A}{r^2}$ where A and r are the given values of area and radius of the circle respectively. Please answer this question as soon as possible any help would be appreciated.
2020/01/08
[ "https://math.stackexchange.com/questions/3501222", "https://math.stackexchange.com", "https://math.stackexchange.com/users/634349/" ]
Considering that you want to work with $\theta -\sin (\theta )$, use Taylor series to get $$\theta -\sin (\theta )=\frac{\theta ^3}{6}-\frac{\theta ^5}{120}+\frac{\theta ^7}{5040}-\frac{\theta ^9}{362880}+O\left(\theta ^{11}\right)$$ If you look at the plots of the lhs and rhs, you will not see any difference for $0 \leq \theta \leq \pi$. Taking that into account, letting $k=\frac{2A}{r^2}$, use series reversion to get $$\theta=t+\frac{t^3}{60}+\frac{t^5}{1400}+\frac{t^7}{25200}+\cdots \qquad \text{where} \qquad t=\sqrt[3]{6k}$$ Using, as @YNK did, $r=10$ and $A=1.18$ (that is to say $k=0.0236$) the above expansion will give $\theta=0.5236079073$ while the "exact" solution, obtained using Newton method, would be $0.5236079142$.
As Lord Shark pointed out there is no closed form expression to calculate $\theta$. I am not aware of any series expansion either. What I can give you is a formula that can be used to determine an approximate value for $\theta$. The values obtained are good only for small $\theta$ (i.e. $\lt \frac{\pi}{2})$. $$\theta\approx\frac{x^3 + 6\sin x - 6x\cos x}{6\left(1-\cos x\right)},\space\space \rm{where} \space\space\space \it{x}\rm{=\sqrt[3]{\frac{12\it{A}}{\it{r}^2}}}\space\space and\space\space \theta\space\space is\space\space given\space\space in\space\space radians$$ It is up to you to take this formula or leave it depending on your requirements. Now I will give the iteration formula based on Newton-Raphson method that can be used to improve $\theta$ in radians to a desired accuracy. $$\theta\_{i+1} = \theta\_{i} - \frac{\theta\_{i} - \sin \theta\_{i} - \frac{2A}{r^2}}{1 - \cos \theta\_{i}},\space\space \rm{where} \space\space\space \it{\theta}\rm{\_1=}\space\space\it{\theta}$$ I am adding the text given below at the request of Tanmay Gajapati. First of all, you don't seem foolish to me. I omitted this part from my answer assuming that you are already familiar with this type of calculations. Now I know that you are not, so here it is. To use the $1^{st}$ formula, calculate the value of $x$ using the given area $A$ and radius $r$, e.g. if $r=10\space \rm{cm}\space$ and $\space A=1.18\space \rm{cm^2}$ $$x=\sqrt[3]{\frac{12\times 1.18}{10^2}}=0.52122$$ Then substitute this value of $x$ in the expression given for $\theta$ to obtain its value, e.g. $$\theta\approx \frac{0.52122^3+6\times \sin\left(0.52122\right)-6\times 0.52122\times\cos\left(0.52122\right)}{6\times\left(1-\cos\left(0.52122\right)\right)}=0.5236186\space\rm{rad}.$$ If you think the value obtained from the $1^{st}$ formula for $\theta$ is not accurate enough, you can use the $2^{nd}$ formula to improve it, e.g. $$\theta\_2 = 0.5236186 - \frac{0.5236186 - \sin\left(0.5236186\right) - \frac{2\times 1.18}{10^2}}{1 - \cos\left(0.5236186\right)}=0.5236079\space\rm{rad}, $$ $$\theta\_3 = 0.5236079 - \frac{0.5236079 - \sin\left(0.5236079\right) - \frac{2\times 1.18}{10^2}}{1 - \cos\left(0.5236079\right)}=0.5236079\space\rm{rad}. $$ As you can see from the last two values of $\theta$, it is no longer improving. Therefore, this is the value of the subtended angle $\theta$ at the center of the circle for the given values of $A$ and $r$.
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Apache POI is a good librairy to read xsl and xslx format. To read a file just instanciate a new `XSSFWorkbook` by passing a new FileInputStream with the path of the Excel file: ``` XSSFWorkbook workbook = new XSSFWorkbook(OPCPackage.open(new File("foo.xslx"))); ``` Or with an input stream (takes a little more memory than a file): ``` XSSFWorkbook workbook = new XSSFWorkbook(myInputStream); ``` After having a `XSSFWorkbook`, use it to iterate through all the cell ([example](http://www.luv2code.com/2011/11/09/reading-ms-excel-files-xslx-in-java/)). Download Apache POI 3.9 [here](http://poi.apache.org/download.html#POI-3.9)
Using POI 3.8 and poi-ooxml-3.8, I've had success with something like this (i've not tried older versions): ``` InputStream is = //Open file, and get inputstream Workbook workBook = WorkbookFactory.create(is); int totalSheets = workBook.getNumberOfSheets(); for (int i = 0; i <= totalSheets - 1; i++) { Sheet sheet = workBook.getSheetAt(i); // Do something with the sheet } ``` `WorkbookFactory` will automatically determine whether the file is the old XLS, or newer XLSX and return the correct version of `Workbook`. The rest of the code is just a sample of iterating through the sheets contained within.
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Apache POI is a good librairy to read xsl and xslx format. To read a file just instanciate a new `XSSFWorkbook` by passing a new FileInputStream with the path of the Excel file: ``` XSSFWorkbook workbook = new XSSFWorkbook(OPCPackage.open(new File("foo.xslx"))); ``` Or with an input stream (takes a little more memory than a file): ``` XSSFWorkbook workbook = new XSSFWorkbook(myInputStream); ``` After having a `XSSFWorkbook`, use it to iterate through all the cell ([example](http://www.luv2code.com/2011/11/09/reading-ms-excel-files-xslx-in-java/)). Download Apache POI 3.9 [here](http://poi.apache.org/download.html#POI-3.9)
I ended up using this modification of AbstractExcelView <https://github.com/hmkcode/Spring-Framework/blob/master/spring-mvc-json-pdf-xls-excel/src/main/java/com/hmkcode/view/abstractview/AbstractExcelView.java>
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Apache POI is a good librairy to read xsl and xslx format. To read a file just instanciate a new `XSSFWorkbook` by passing a new FileInputStream with the path of the Excel file: ``` XSSFWorkbook workbook = new XSSFWorkbook(OPCPackage.open(new File("foo.xslx"))); ``` Or with an input stream (takes a little more memory than a file): ``` XSSFWorkbook workbook = new XSSFWorkbook(myInputStream); ``` After having a `XSSFWorkbook`, use it to iterate through all the cell ([example](http://www.luv2code.com/2011/11/09/reading-ms-excel-files-xslx-in-java/)). Download Apache POI 3.9 [here](http://poi.apache.org/download.html#POI-3.9)
Add following dependencies in your code. ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> ``` Also to read excel file use the following code, it will work for both .xls as well as .xlsx file. ``` Workbook workbook = WorkbookFactory.create(inputStream); ```
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Apache POI is a good librairy to read xsl and xslx format. To read a file just instanciate a new `XSSFWorkbook` by passing a new FileInputStream with the path of the Excel file: ``` XSSFWorkbook workbook = new XSSFWorkbook(OPCPackage.open(new File("foo.xslx"))); ``` Or with an input stream (takes a little more memory than a file): ``` XSSFWorkbook workbook = new XSSFWorkbook(myInputStream); ``` After having a `XSSFWorkbook`, use it to iterate through all the cell ([example](http://www.luv2code.com/2011/11/09/reading-ms-excel-files-xslx-in-java/)). Download Apache POI 3.9 [here](http://poi.apache.org/download.html#POI-3.9)
Add dependencies in pom.xml - ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>ooxml-schemas</artifactId> <version>1.3</version> </dependency> ``` Excel 2007 or later (.xlsx) - sample code - ``` //reading data from byte array OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(data)); Workbook wb = new XSSFWorkbook(pkg); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` 2) ``` //reading from a file File file = new File(pathxlsx); FileInputStream fis = new FileInputStream(file); Workbook wb = new XSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` Excel 1998-2003 file (.xls) - you may use HSSF library. just use : Workbook wb = new HSSFWorkbook(pkg);
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Using POI 3.8 and poi-ooxml-3.8, I've had success with something like this (i've not tried older versions): ``` InputStream is = //Open file, and get inputstream Workbook workBook = WorkbookFactory.create(is); int totalSheets = workBook.getNumberOfSheets(); for (int i = 0; i <= totalSheets - 1; i++) { Sheet sheet = workBook.getSheetAt(i); // Do something with the sheet } ``` `WorkbookFactory` will automatically determine whether the file is the old XLS, or newer XLSX and return the correct version of `Workbook`. The rest of the code is just a sample of iterating through the sheets contained within.
I ended up using this modification of AbstractExcelView <https://github.com/hmkcode/Spring-Framework/blob/master/spring-mvc-json-pdf-xls-excel/src/main/java/com/hmkcode/view/abstractview/AbstractExcelView.java>
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Using POI 3.8 and poi-ooxml-3.8, I've had success with something like this (i've not tried older versions): ``` InputStream is = //Open file, and get inputstream Workbook workBook = WorkbookFactory.create(is); int totalSheets = workBook.getNumberOfSheets(); for (int i = 0; i <= totalSheets - 1; i++) { Sheet sheet = workBook.getSheetAt(i); // Do something with the sheet } ``` `WorkbookFactory` will automatically determine whether the file is the old XLS, or newer XLSX and return the correct version of `Workbook`. The rest of the code is just a sample of iterating through the sheets contained within.
Add following dependencies in your code. ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> ``` Also to read excel file use the following code, it will work for both .xls as well as .xlsx file. ``` Workbook workbook = WorkbookFactory.create(inputStream); ```
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Using POI 3.8 and poi-ooxml-3.8, I've had success with something like this (i've not tried older versions): ``` InputStream is = //Open file, and get inputstream Workbook workBook = WorkbookFactory.create(is); int totalSheets = workBook.getNumberOfSheets(); for (int i = 0; i <= totalSheets - 1; i++) { Sheet sheet = workBook.getSheetAt(i); // Do something with the sheet } ``` `WorkbookFactory` will automatically determine whether the file is the old XLS, or newer XLSX and return the correct version of `Workbook`. The rest of the code is just a sample of iterating through the sheets contained within.
Add dependencies in pom.xml - ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>ooxml-schemas</artifactId> <version>1.3</version> </dependency> ``` Excel 2007 or later (.xlsx) - sample code - ``` //reading data from byte array OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(data)); Workbook wb = new XSSFWorkbook(pkg); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` 2) ``` //reading from a file File file = new File(pathxlsx); FileInputStream fis = new FileInputStream(file); Workbook wb = new XSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` Excel 1998-2003 file (.xls) - you may use HSSF library. just use : Workbook wb = new HSSFWorkbook(pkg);
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Add following dependencies in your code. ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> ``` Also to read excel file use the following code, it will work for both .xls as well as .xlsx file. ``` Workbook workbook = WorkbookFactory.create(inputStream); ```
I ended up using this modification of AbstractExcelView <https://github.com/hmkcode/Spring-Framework/blob/master/spring-mvc-json-pdf-xls-excel/src/main/java/com/hmkcode/view/abstractview/AbstractExcelView.java>
13,996,965
I need to create a custom class that extends `MapFragment`. I am not sure how to instantiatemy new class, so that MapFragment will be instantiated in the correct way. MapFragment are suppose to be created by doing ``` MapFragment.newInstance(options) ``` If I have my own class, that extends MapFragment ``` public class MyMapFragment extends MapFragment { } ``` How do I go about to instantiate `MyMapFragment`, or is this approach all together wrong?
2012/12/21
[ "https://Stackoverflow.com/questions/13996965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995350/" ]
Add following dependencies in your code. ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> ``` Also to read excel file use the following code, it will work for both .xls as well as .xlsx file. ``` Workbook workbook = WorkbookFactory.create(inputStream); ```
Add dependencies in pom.xml - ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>ooxml-schemas</artifactId> <version>1.3</version> </dependency> ``` Excel 2007 or later (.xlsx) - sample code - ``` //reading data from byte array OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(data)); Workbook wb = new XSSFWorkbook(pkg); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` 2) ``` //reading from a file File file = new File(pathxlsx); FileInputStream fis = new FileInputStream(file); Workbook wb = new XSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { int j = 5; Person person= new Person (); Row row = rows.next(); if (row.getRowNum() > 0) { person.setPersonId((int)(row.getCell(0).getNumericCellValue())); person.setFirstName(row.getCell(1).getStringCellValue()); person.setLastName(row.getCell(2).getStringCellValue()); person.setGroupId((int)(row.getCell(3).getNumericCellValue())); person.setUserName(row.getCell(4).getStringCellValue()); person.setCreditId((int)(row.getCell(5).getNumericCellValue())); } } ``` Excel 1998-2003 file (.xls) - you may use HSSF library. just use : Workbook wb = new HSSFWorkbook(pkg);
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
All you need is specify in celery conf witch task you want to run periodically and with which interval. Example: Run the tasks.add task every 30 seconds ``` from datetime import timedelta CELERYBEAT_SCHEDULE = { "runs-every-30-seconds": { "task": "tasks.add", "schedule": timedelta(seconds=30), "args": (16, 16) }, } ``` Remember that you have to run celery in beat mode with the -B option ``` manage celeryd -B ``` You can also use the crontab style instead of time interval, checkout this: <http://ask.github.com/celery/userguide/periodic-tasks.html> If you are using django-celery remember that you can also use tha django db as scheduler for periodic tasks, in this way you can easily add trough the django-celery admin panel new periodic tasks. For do that you need to set the celerybeat scheduler in settings.py in this way ``` CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" ```
Because of celery.decorators deprecated, you can use periodic\_task decorator like that: ``` from celery.task.base import periodic_task from django.utils.timezone import timedelta @periodic_task(run_every=timedelta(seconds=5)) def my_background_process(): # insert code ```
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
All you need is specify in celery conf witch task you want to run periodically and with which interval. Example: Run the tasks.add task every 30 seconds ``` from datetime import timedelta CELERYBEAT_SCHEDULE = { "runs-every-30-seconds": { "task": "tasks.add", "schedule": timedelta(seconds=30), "args": (16, 16) }, } ``` Remember that you have to run celery in beat mode with the -B option ``` manage celeryd -B ``` You can also use the crontab style instead of time interval, checkout this: <http://ask.github.com/celery/userguide/periodic-tasks.html> If you are using django-celery remember that you can also use tha django db as scheduler for periodic tasks, in this way you can easily add trough the django-celery admin panel new periodic tasks. For do that you need to set the celerybeat scheduler in settings.py in this way ``` CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" ```
Add that task to a separate queue, and then use a separate worker for that queue with the concurrency option set to 1.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
Because of celery.decorators deprecated, you can use periodic\_task decorator like that: ``` from celery.task.base import periodic_task from django.utils.timezone import timedelta @periodic_task(run_every=timedelta(seconds=5)) def my_background_process(): # insert code ```
Add that task to a separate queue, and then use a separate worker for that queue with the concurrency option set to 1.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
You may be interested in this simpler method that requires no changes to a celery conf. ``` @celery.decorators.periodic_task(run_every=datetime.timedelta(minutes=5)) def my_task(): # Insert fun-stuff here ```
Because of celery.decorators deprecated, you can use periodic\_task decorator like that: ``` from celery.task.base import periodic_task from django.utils.timezone import timedelta @periodic_task(run_every=timedelta(seconds=5)) def my_background_process(): # insert code ```
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
All you need is specify in celery conf witch task you want to run periodically and with which interval. Example: Run the tasks.add task every 30 seconds ``` from datetime import timedelta CELERYBEAT_SCHEDULE = { "runs-every-30-seconds": { "task": "tasks.add", "schedule": timedelta(seconds=30), "args": (16, 16) }, } ``` Remember that you have to run celery in beat mode with the -B option ``` manage celeryd -B ``` You can also use the crontab style instead of time interval, checkout this: <http://ask.github.com/celery/userguide/periodic-tasks.html> If you are using django-celery remember that you can also use tha django db as scheduler for periodic tasks, in this way you can easily add trough the django-celery admin panel new periodic tasks. For do that you need to set the celerybeat scheduler in settings.py in this way ``` CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" ```
To expand on @MauroRocco's post, from <http://docs.celeryproject.org/en/v2.2.4/userguide/periodic-tasks.html> > > Using a timedelta for the schedule means the task will be executed 30 seconds after celerybeat starts, and then every 30 seconds after the last run. A crontab like schedule also exists, see the section on Crontab schedules. > > > So this will indeed achieve the goal you want.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
You may be interested in this simpler method that requires no changes to a celery conf. ``` @celery.decorators.periodic_task(run_every=datetime.timedelta(minutes=5)) def my_task(): # Insert fun-stuff here ```
Add that task to a separate queue, and then use a separate worker for that queue with the concurrency option set to 1.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
Wow it's amazing how no one understands this person's question. They are asking not about running tasks periodically, but how to ensure that Celery does not run two instances of the same task simultaneously. I don't think there's a way to do this with Celery directly, but what you can do is have one of the tasks acquire a lock right when it begins, and if it fails, to try again in a few seconds (using retry). The task would release the lock right before it returns; you can make the lock auto-expire after a few minutes if it ever crashes or times out. For the lock you can probably just use your database or something like Redis.
Because of celery.decorators deprecated, you can use periodic\_task decorator like that: ``` from celery.task.base import periodic_task from django.utils.timezone import timedelta @periodic_task(run_every=timedelta(seconds=5)) def my_background_process(): # insert code ```
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
You may be interested in this simpler method that requires no changes to a celery conf. ``` @celery.decorators.periodic_task(run_every=datetime.timedelta(minutes=5)) def my_task(): # Insert fun-stuff here ```
To expand on @MauroRocco's post, from <http://docs.celeryproject.org/en/v2.2.4/userguide/periodic-tasks.html> > > Using a timedelta for the schedule means the task will be executed 30 seconds after celerybeat starts, and then every 30 seconds after the last run. A crontab like schedule also exists, see the section on Crontab schedules. > > > So this will indeed achieve the goal you want.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
To expand on @MauroRocco's post, from <http://docs.celeryproject.org/en/v2.2.4/userguide/periodic-tasks.html> > > Using a timedelta for the schedule means the task will be executed 30 seconds after celerybeat starts, and then every 30 seconds after the last run. A crontab like schedule also exists, see the section on Crontab schedules. > > > So this will indeed achieve the goal you want.
Add that task to a separate queue, and then use a separate worker for that queue with the concurrency option set to 1.
5,361,521
I want to have a task that will execute every 5 minutes, but it will wait for last execution to finish and then start to count this 5 minutes. (This way I can also be sure that there is only one task running) The easiest way I found is to run django application manage.py shell and run this: ``` while True: result = task.delay() result.wait() sleep(5) ``` but for each task that I want to execute this way I have to run it's own shell, is there an easy way to do it? May be some king custom ot django celery scheduler?
2011/03/19
[ "https://Stackoverflow.com/questions/5361521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44537/" ]
All you need is specify in celery conf witch task you want to run periodically and with which interval. Example: Run the tasks.add task every 30 seconds ``` from datetime import timedelta CELERYBEAT_SCHEDULE = { "runs-every-30-seconds": { "task": "tasks.add", "schedule": timedelta(seconds=30), "args": (16, 16) }, } ``` Remember that you have to run celery in beat mode with the -B option ``` manage celeryd -B ``` You can also use the crontab style instead of time interval, checkout this: <http://ask.github.com/celery/userguide/periodic-tasks.html> If you are using django-celery remember that you can also use tha django db as scheduler for periodic tasks, in this way you can easily add trough the django-celery admin panel new periodic tasks. For do that you need to set the celerybeat scheduler in settings.py in this way ``` CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" ```
Wow it's amazing how no one understands this person's question. They are asking not about running tasks periodically, but how to ensure that Celery does not run two instances of the same task simultaneously. I don't think there's a way to do this with Celery directly, but what you can do is have one of the tasks acquire a lock right when it begins, and if it fails, to try again in a few seconds (using retry). The task would release the lock right before it returns; you can make the lock auto-expire after a few minutes if it ever crashes or times out. For the lock you can probably just use your database or something like Redis.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
Here are some FAQ type of information to the question in the original post. [Cilk Plus vs. TBB vs. Intel OpenMP](http://www.cilkplus.org/faq/24) In short it depends what type of parallelization you are trying to implement and how your application is coded.
So, as a request from the OP: I have used `TBB` before and I'm happy with it. It has good docs and the forum is active. It's not rare to see the library developers answering the questions. Give it a try. (I never used `cilkplus` so I can't talk about it). I worked with it both in Ubuntu and Windows. You can download the packages via the package manager in Ubuntu or you can build the sources yourself. In that case, it shouldn't be a problem. In Windows I built `TBB` with `MinGW` under the `cygwin` environment. As for the compatibility issues, there shouldn't be none. `TBB` works fine with `Boost.Thread` or `OpenMP`, for example; it was designed so it could be mixed with other threading solutions.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
Is there a reason you can't use the pre-built GCC binaries we make available at <https://www.cilkplus.org/download#gcc-development-branch> ? It's built from the cilkplus\_4-8\_branch, and should be reasonably current. Which solution you choose is up to you. Cilk provides a very natural way to express recursive algorithms, and its child-stealing scheduler can be very cache friendly if you use cache-oblivious algorithms. If you have questions about Cilk Plus, you'll get the best response to them in the Intel Cilk Plus forum at <http://software.intel.com/en-us/forums/intel-cilk-plus/>. Cilk Plus and TBB are aware of each other, so they should play well together if you mix them. Instead of getting a combinatorial explosion of threads you'll get at most the number of threads in the TBB thread pool plus the number of Cilk worker threads. Which usually means you'll get 2P threads (where P is the number of cores) unless you change the defaults with library calls or environment variables. You can use the vectorization features of Cilk Plus with either threading library. ``` - Barry Tannenbaum Intel Cilk Plus developer ```
So, as a request from the OP: I have used `TBB` before and I'm happy with it. It has good docs and the forum is active. It's not rare to see the library developers answering the questions. Give it a try. (I never used `cilkplus` so I can't talk about it). I worked with it both in Ubuntu and Windows. You can download the packages via the package manager in Ubuntu or you can build the sources yourself. In that case, it shouldn't be a problem. In Windows I built `TBB` with `MinGW` under the `cygwin` environment. As for the compatibility issues, there shouldn't be none. `TBB` works fine with `Boost.Thread` or `OpenMP`, for example; it was designed so it could be mixed with other threading solutions.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
They can be used in complement to each other (CILK and TBB). Usually, thats the best. But from my experience you will use TBB the most. TBB and CILK will scale automatically with the number of cores. (by creating a tree of tasks, and then using recursion at run-time). * **TBB** is a runtime library for C++, that uses programmer defined Task Patterns, instead of threads. TBB will decide - at run-time - on the optimal number of threads, tasks granularity and performance oriented scheduling (Automatic load balancing through tasks stealing, Cache efficiency and memory reusing). Create tasks recursively (for a tree this is logarithmic in number of tasks). * **CILK(plus)** is a C/C++ language extension requires compiler support. Code may not be portable to different compilers and operating systems. It supports fork-join parallelism. Also, it is extremely easy to parallelize recursive algorithms. Lastly, it has a few tools (spawn, sync), with which you can parallelize a code very easily. (not a lot of rewrite is needed!). **Other differences, that might be interesting:** a) CILK's random work stealing schedule for countering "waiting" processes. a) TBB steals from the most heavily loaded process.
So, as a request from the OP: I have used `TBB` before and I'm happy with it. It has good docs and the forum is active. It's not rare to see the library developers answering the questions. Give it a try. (I never used `cilkplus` so I can't talk about it). I worked with it both in Ubuntu and Windows. You can download the packages via the package manager in Ubuntu or you can build the sources yourself. In that case, it shouldn't be a problem. In Windows I built `TBB` with `MinGW` under the `cygwin` environment. As for the compatibility issues, there shouldn't be none. `TBB` works fine with `Boost.Thread` or `OpenMP`, for example; it was designed so it could be mixed with other threading solutions.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
I can answer this question in context to TBB. The pros of using TBB are: * No compiler support needed to run the code. * Generic C++ algorithms of TBB lets user create their own objects and map them to thread as task. * User doesn't need to worry about thread management. The built in task scheduler automatically detects the number of possible hardware threads. However user can chose to fix the number of threads for performance studies. * Flow graphs for creating tasks that respect dependencies easily lets user exploit functional as well as data parallelism. * TBB is naturally scalable obviating the need for code modification when migrating to larger systems. * Active forum and documentation being continually updated. * with intel compilers, latest version of tbb performs really well. The cons can be * Low user base in the open source community making it difficult to find examples * examples in documentations are very basic and in older versions they are even wrong. However the Intel forum is always ready to extend support to resolve issues. * the abstraction in the template classes are very high making the learning curve very steep. * the overhead of creating tasks is high. User has to make sure that the problem size is large enough for the partitioner to create tasks of optimal grain size. I have not worked with cilk either, but it's apparent that if at all there are users in the two domain, the majority is that of TBB. It's likely if Intel pushes for TBB by it's updated document and free support, the user community in TBB grows
So, as a request from the OP: I have used `TBB` before and I'm happy with it. It has good docs and the forum is active. It's not rare to see the library developers answering the questions. Give it a try. (I never used `cilkplus` so I can't talk about it). I worked with it both in Ubuntu and Windows. You can download the packages via the package manager in Ubuntu or you can build the sources yourself. In that case, it shouldn't be a problem. In Windows I built `TBB` with `MinGW` under the `cygwin` environment. As for the compatibility issues, there shouldn't be none. `TBB` works fine with `Boost.Thread` or `OpenMP`, for example; it was designed so it could be mixed with other threading solutions.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
Here are some FAQ type of information to the question in the original post. [Cilk Plus vs. TBB vs. Intel OpenMP](http://www.cilkplus.org/faq/24) In short it depends what type of parallelization you are trying to implement and how your application is coded.
Is there a reason you can't use the pre-built GCC binaries we make available at <https://www.cilkplus.org/download#gcc-development-branch> ? It's built from the cilkplus\_4-8\_branch, and should be reasonably current. Which solution you choose is up to you. Cilk provides a very natural way to express recursive algorithms, and its child-stealing scheduler can be very cache friendly if you use cache-oblivious algorithms. If you have questions about Cilk Plus, you'll get the best response to them in the Intel Cilk Plus forum at <http://software.intel.com/en-us/forums/intel-cilk-plus/>. Cilk Plus and TBB are aware of each other, so they should play well together if you mix them. Instead of getting a combinatorial explosion of threads you'll get at most the number of threads in the TBB thread pool plus the number of Cilk worker threads. Which usually means you'll get 2P threads (where P is the number of cores) unless you change the defaults with library calls or environment variables. You can use the vectorization features of Cilk Plus with either threading library. ``` - Barry Tannenbaum Intel Cilk Plus developer ```
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
Here are some FAQ type of information to the question in the original post. [Cilk Plus vs. TBB vs. Intel OpenMP](http://www.cilkplus.org/faq/24) In short it depends what type of parallelization you are trying to implement and how your application is coded.
They can be used in complement to each other (CILK and TBB). Usually, thats the best. But from my experience you will use TBB the most. TBB and CILK will scale automatically with the number of cores. (by creating a tree of tasks, and then using recursion at run-time). * **TBB** is a runtime library for C++, that uses programmer defined Task Patterns, instead of threads. TBB will decide - at run-time - on the optimal number of threads, tasks granularity and performance oriented scheduling (Automatic load balancing through tasks stealing, Cache efficiency and memory reusing). Create tasks recursively (for a tree this is logarithmic in number of tasks). * **CILK(plus)** is a C/C++ language extension requires compiler support. Code may not be portable to different compilers and operating systems. It supports fork-join parallelism. Also, it is extremely easy to parallelize recursive algorithms. Lastly, it has a few tools (spawn, sync), with which you can parallelize a code very easily. (not a lot of rewrite is needed!). **Other differences, that might be interesting:** a) CILK's random work stealing schedule for countering "waiting" processes. a) TBB steals from the most heavily loaded process.
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
Here are some FAQ type of information to the question in the original post. [Cilk Plus vs. TBB vs. Intel OpenMP](http://www.cilkplus.org/faq/24) In short it depends what type of parallelization you are trying to implement and how your application is coded.
I can answer this question in context to TBB. The pros of using TBB are: * No compiler support needed to run the code. * Generic C++ algorithms of TBB lets user create their own objects and map them to thread as task. * User doesn't need to worry about thread management. The built in task scheduler automatically detects the number of possible hardware threads. However user can chose to fix the number of threads for performance studies. * Flow graphs for creating tasks that respect dependencies easily lets user exploit functional as well as data parallelism. * TBB is naturally scalable obviating the need for code modification when migrating to larger systems. * Active forum and documentation being continually updated. * with intel compilers, latest version of tbb performs really well. The cons can be * Low user base in the open source community making it difficult to find examples * examples in documentations are very basic and in older versions they are even wrong. However the Intel forum is always ready to extend support to resolve issues. * the abstraction in the template classes are very high making the learning curve very steep. * the overhead of creating tasks is high. User has to make sure that the problem size is large enough for the partitioner to create tasks of optimal grain size. I have not worked with cilk either, but it's apparent that if at all there are users in the two domain, the majority is that of TBB. It's likely if Intel pushes for TBB by it's updated document and free support, the user community in TBB grows
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
They can be used in complement to each other (CILK and TBB). Usually, thats the best. But from my experience you will use TBB the most. TBB and CILK will scale automatically with the number of cores. (by creating a tree of tasks, and then using recursion at run-time). * **TBB** is a runtime library for C++, that uses programmer defined Task Patterns, instead of threads. TBB will decide - at run-time - on the optimal number of threads, tasks granularity and performance oriented scheduling (Automatic load balancing through tasks stealing, Cache efficiency and memory reusing). Create tasks recursively (for a tree this is logarithmic in number of tasks). * **CILK(plus)** is a C/C++ language extension requires compiler support. Code may not be portable to different compilers and operating systems. It supports fork-join parallelism. Also, it is extremely easy to parallelize recursive algorithms. Lastly, it has a few tools (spawn, sync), with which you can parallelize a code very easily. (not a lot of rewrite is needed!). **Other differences, that might be interesting:** a) CILK's random work stealing schedule for countering "waiting" processes. a) TBB steals from the most heavily loaded process.
Is there a reason you can't use the pre-built GCC binaries we make available at <https://www.cilkplus.org/download#gcc-development-branch> ? It's built from the cilkplus\_4-8\_branch, and should be reasonably current. Which solution you choose is up to you. Cilk provides a very natural way to express recursive algorithms, and its child-stealing scheduler can be very cache friendly if you use cache-oblivious algorithms. If you have questions about Cilk Plus, you'll get the best response to them in the Intel Cilk Plus forum at <http://software.intel.com/en-us/forums/intel-cilk-plus/>. Cilk Plus and TBB are aware of each other, so they should play well together if you mix them. Instead of getting a combinatorial explosion of threads you'll get at most the number of threads in the TBB thread pool plus the number of Cilk worker threads. Which usually means you'll get 2P threads (where P is the number of cores) unless you change the defaults with library calls or environment variables. You can use the vectorization features of Cilk Plus with either threading library. ``` - Barry Tannenbaum Intel Cilk Plus developer ```
19,242,348
I am creating a theme for my wordpress blog, I am struct on the code to display custom menus in my functions.php I have wrote: ``` function register_my_menus(){ register_nav_menus( array('menu-1' => __('Primary Menu'), ) ); } add_action('init', 'register_my_menus'); ``` this is my header.php ``` if ( has_nav_menu( $location ) ) { wp_nav_menu(array( 'theme_location' => 'menu-1')); } ``` the problem is that when I am setting a menu from wordpress to Primary Menu, no menu is displaying and also the content after menu is not displaying, please help me where I am wrong
2013/10/08
[ "https://Stackoverflow.com/questions/19242348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756124/" ]
I can answer this question in context to TBB. The pros of using TBB are: * No compiler support needed to run the code. * Generic C++ algorithms of TBB lets user create their own objects and map them to thread as task. * User doesn't need to worry about thread management. The built in task scheduler automatically detects the number of possible hardware threads. However user can chose to fix the number of threads for performance studies. * Flow graphs for creating tasks that respect dependencies easily lets user exploit functional as well as data parallelism. * TBB is naturally scalable obviating the need for code modification when migrating to larger systems. * Active forum and documentation being continually updated. * with intel compilers, latest version of tbb performs really well. The cons can be * Low user base in the open source community making it difficult to find examples * examples in documentations are very basic and in older versions they are even wrong. However the Intel forum is always ready to extend support to resolve issues. * the abstraction in the template classes are very high making the learning curve very steep. * the overhead of creating tasks is high. User has to make sure that the problem size is large enough for the partitioner to create tasks of optimal grain size. I have not worked with cilk either, but it's apparent that if at all there are users in the two domain, the majority is that of TBB. It's likely if Intel pushes for TBB by it's updated document and free support, the user community in TBB grows
Is there a reason you can't use the pre-built GCC binaries we make available at <https://www.cilkplus.org/download#gcc-development-branch> ? It's built from the cilkplus\_4-8\_branch, and should be reasonably current. Which solution you choose is up to you. Cilk provides a very natural way to express recursive algorithms, and its child-stealing scheduler can be very cache friendly if you use cache-oblivious algorithms. If you have questions about Cilk Plus, you'll get the best response to them in the Intel Cilk Plus forum at <http://software.intel.com/en-us/forums/intel-cilk-plus/>. Cilk Plus and TBB are aware of each other, so they should play well together if you mix them. Instead of getting a combinatorial explosion of threads you'll get at most the number of threads in the TBB thread pool plus the number of Cilk worker threads. Which usually means you'll get 2P threads (where P is the number of cores) unless you change the defaults with library calls or environment variables. You can use the vectorization features of Cilk Plus with either threading library. ``` - Barry Tannenbaum Intel Cilk Plus developer ```
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
Use reflection: ``` TestImpl ti = (TestImpl) Class.forName("test.test.impl.TestImpl").newInstance(); ```
``` Class<?> clazz = .... Object o = clazz.newInstance(); // o will be a valid instance of you impl class ``` It will call the default constructor (you must have one!).
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
[Use](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getConstructor%28java.lang.Class...%29) `impl = (IMyInterface) i.getConstructor().newInstance();`
``` Class<?> clazz = .... Object o = clazz.newInstance(); // o will be a valid instance of you impl class ``` It will call the default constructor (you must have one!).
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
With [Class.newInstance](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29). The drawback of this approach is, though, that it suppresses checked exceptions (and introduces new reflection related exceptions) and always no-arg. Alternatively you can use [Class.getConstructor](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getConstructor%28java.lang.Class...%29) (then `Constructor.newInstance`), this way you can provide the arguments, but the exception problem is still there.
``` Class<?> clazz = .... Object o = clazz.newInstance(); // o will be a valid instance of you impl class ``` It will call the default constructor (you must have one!).
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
``` Class<?> clazz = .... Object o = clazz.newInstance(); // o will be a valid instance of you impl class ``` It will call the default constructor (you must have one!).
``` IMyInterface impl = null; Class testImpl = Class.forName("test.test.impl.TestImpl"); if(testImpl != null && IMyInterface.class.isAssignableFrom(testImpl.getClass()) { impl = testImpl.getConstructor().newInstance(); } ``` Also, check: 1) [Using Java Reflection - java.sun.com](http://java.sun.com/developer/technicalArticles/ALT/Reflection/) 2) [Java instantiate class from string - Stackoverflow](https://stackoverflow.com/questions/5178205/java-instantiate-class-from-string)
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
Use reflection: ``` TestImpl ti = (TestImpl) Class.forName("test.test.impl.TestImpl").newInstance(); ```
``` IMyInterface impl = null; Class testImpl = Class.forName("test.test.impl.TestImpl"); if(testImpl != null && IMyInterface.class.isAssignableFrom(testImpl.getClass()) { impl = testImpl.getConstructor().newInstance(); } ``` Also, check: 1) [Using Java Reflection - java.sun.com](http://java.sun.com/developer/technicalArticles/ALT/Reflection/) 2) [Java instantiate class from string - Stackoverflow](https://stackoverflow.com/questions/5178205/java-instantiate-class-from-string)
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
[Use](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getConstructor%28java.lang.Class...%29) `impl = (IMyInterface) i.getConstructor().newInstance();`
``` IMyInterface impl = null; Class testImpl = Class.forName("test.test.impl.TestImpl"); if(testImpl != null && IMyInterface.class.isAssignableFrom(testImpl.getClass()) { impl = testImpl.getConstructor().newInstance(); } ``` Also, check: 1) [Using Java Reflection - java.sun.com](http://java.sun.com/developer/technicalArticles/ALT/Reflection/) 2) [Java instantiate class from string - Stackoverflow](https://stackoverflow.com/questions/5178205/java-instantiate-class-from-string)
8,848,806
I have the following interface ``` package test.test; public interface IMyInterface { public String hello(); } ``` and an implementation ``` package test.test.impl; public class TestImpl implements IMyInterface { public String hello() { return "Hello"; } } ``` So I have only the full String "test.test.impl.TestImpl". How can I load the Class and create a Object from the Implementation? I will use the current Classloader but I have no idea to create a Object. ``` Class<?> i = getClass().getClassLoader().loadClass("test.test.impl.TestImpl"); IMyInterface impl = null; ``` Thanks for help!
2012/01/13
[ "https://Stackoverflow.com/questions/8848806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007099/" ]
With [Class.newInstance](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29). The drawback of this approach is, though, that it suppresses checked exceptions (and introduces new reflection related exceptions) and always no-arg. Alternatively you can use [Class.getConstructor](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getConstructor%28java.lang.Class...%29) (then `Constructor.newInstance`), this way you can provide the arguments, but the exception problem is still there.
``` IMyInterface impl = null; Class testImpl = Class.forName("test.test.impl.TestImpl"); if(testImpl != null && IMyInterface.class.isAssignableFrom(testImpl.getClass()) { impl = testImpl.getConstructor().newInstance(); } ``` Also, check: 1) [Using Java Reflection - java.sun.com](http://java.sun.com/developer/technicalArticles/ALT/Reflection/) 2) [Java instantiate class from string - Stackoverflow](https://stackoverflow.com/questions/5178205/java-instantiate-class-from-string)
7,397,626
I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself. I use `System.exit(0);` when this cancel button is pressed. The launcher program does this in `actionPerformed`: ``` if (source==carMenuItem) { ta.append("Car launched\n"); TestCar.main(par); } if (source==DialogboxMenuItem) { ta.append("Dialogbox launched\n"); DialogBox.main(par); } if (source==LengthConversionMenuItem) { ta.append("LengthConversion launched\n"); LengthConversion.main(par); } ``` When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?
2011/09/13
[ "https://Stackoverflow.com/questions/7397626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925552/" ]
[System.exit()](http://download.oracle.com/javase/6/docs/api/java/lang/System.html) terminates the VM therefore your initial thread is terminated also, simply return from your main() method. After reviewing you code: Not all classes are supposed to have a main() method (If not also used standalone). You should consider to call a constructor to create an instance of a class and call a method not named main().
With System.exit you can't. This will terminate the whole JVM and all processes inside it.
7,397,626
I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself. I use `System.exit(0);` when this cancel button is pressed. The launcher program does this in `actionPerformed`: ``` if (source==carMenuItem) { ta.append("Car launched\n"); TestCar.main(par); } if (source==DialogboxMenuItem) { ta.append("Dialogbox launched\n"); DialogBox.main(par); } if (source==LengthConversionMenuItem) { ta.append("LengthConversion launched\n"); LengthConversion.main(par); } ``` When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?
2011/09/13
[ "https://Stackoverflow.com/questions/7397626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925552/" ]
[System.exit()](http://download.oracle.com/javase/6/docs/api/java/lang/System.html) terminates the VM therefore your initial thread is terminated also, simply return from your main() method. After reviewing you code: Not all classes are supposed to have a main() method (If not also used standalone). You should consider to call a constructor to create an instance of a class and call a method not named main().
Or you can use `dispose()` method in stead of `System.exit()` :-because `System.exit()` will terminate the total application it self. or you can use `setVisible()` as false.
7,397,626
I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself. I use `System.exit(0);` when this cancel button is pressed. The launcher program does this in `actionPerformed`: ``` if (source==carMenuItem) { ta.append("Car launched\n"); TestCar.main(par); } if (source==DialogboxMenuItem) { ta.append("Dialogbox launched\n"); DialogBox.main(par); } if (source==LengthConversionMenuItem) { ta.append("LengthConversion launched\n"); LengthConversion.main(par); } ``` When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?
2011/09/13
[ "https://Stackoverflow.com/questions/7397626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925552/" ]
[System.exit()](http://download.oracle.com/javase/6/docs/api/java/lang/System.html) terminates the VM therefore your initial thread is terminated also, simply return from your main() method. After reviewing you code: Not all classes are supposed to have a main() method (If not also used standalone). You should consider to call a constructor to create an instance of a class and call a method not named main().
you have to implements [WindowListener](http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html) and its `WindowEvents`, example [here](https://stackoverflow.com/questions/7080638/basic-java-swing-how-to-exit-and-dispose-of-your-application-jframe/7082054#7082054) another option is [setDefaultCloseOperation](http://download.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29) properly
7,397,626
I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself. I use `System.exit(0);` when this cancel button is pressed. The launcher program does this in `actionPerformed`: ``` if (source==carMenuItem) { ta.append("Car launched\n"); TestCar.main(par); } if (source==DialogboxMenuItem) { ta.append("Dialogbox launched\n"); DialogBox.main(par); } if (source==LengthConversionMenuItem) { ta.append("LengthConversion launched\n"); LengthConversion.main(par); } ``` When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?
2011/09/13
[ "https://Stackoverflow.com/questions/7397626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925552/" ]
Or you can use `dispose()` method in stead of `System.exit()` :-because `System.exit()` will terminate the total application it self. or you can use `setVisible()` as false.
With System.exit you can't. This will terminate the whole JVM and all processes inside it.
7,397,626
I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself. I use `System.exit(0);` when this cancel button is pressed. The launcher program does this in `actionPerformed`: ``` if (source==carMenuItem) { ta.append("Car launched\n"); TestCar.main(par); } if (source==DialogboxMenuItem) { ta.append("Dialogbox launched\n"); DialogBox.main(par); } if (source==LengthConversionMenuItem) { ta.append("LengthConversion launched\n"); LengthConversion.main(par); } ``` When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?
2011/09/13
[ "https://Stackoverflow.com/questions/7397626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925552/" ]
you have to implements [WindowListener](http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html) and its `WindowEvents`, example [here](https://stackoverflow.com/questions/7080638/basic-java-swing-how-to-exit-and-dispose-of-your-application-jframe/7082054#7082054) another option is [setDefaultCloseOperation](http://download.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29) properly
With System.exit you can't. This will terminate the whole JVM and all processes inside it.
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
The `()` is an empty argument list. You're defining an anonymous function that takes no arguments and returns `x.Something`. Edit: It differs from `x => x.Something` in that the latter requires an argument and Something is called on that argument. With the former version `x` has to exist somewhere outside the function and Something is called on that outside `x`. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.
I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty ``` delegate{ return x.someproperty; } ``` that is the same as: ``` () => x.someproperty ```
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
It's a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx). That is, it's a way to create an anonymous function or delegate. The general form is: ``` (input parameters) => expression ``` If you have ``` () => expression ``` then you have created a function that takes no arguments, and returns the result of the expression. C# uses [type inference](http://en.wikipedia.org/wiki/Type_inference) to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a [lexical closure](http://en.wikipedia.org/wiki/Closure_(computer_science)).
the () mean that this method doesn't take any parameters. for example, if you assign a normal event handler using a lambda expression, it would look like this: ``` someButton.Click += (s, e) => DoSomething(); ```
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
The `()` is an empty argument list. You're defining an anonymous function that takes no arguments and returns `x.Something`. Edit: It differs from `x => x.Something` in that the latter requires an argument and Something is called on that argument. With the former version `x` has to exist somewhere outside the function and Something is called on that outside `x`. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.
To get the name of the property you need SomeMethod to have an argument of the type of `System.Linq.Expressions.Expression<System.Func<object>>`. You can then go through the expression to determine the property name.
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
> > What do the first brackets mean in the expression? > > > It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be: ``` SomeMethod(x => x.Something); ``` If it took n + 1 arguments, then it'd be: ``` SomeMethod((x, y, ...) => x.Something); ``` > > I'm also curious how you can get the property name from argument that is being passed in. Is this possible? > > > If your `SomeMethod` takes an `Expression<Func<T>>`, then yes: ``` void SomeMethod<T>(Expression<Func<T>> e) { MemberExpression op = (MemberExpression)e.Body; Console.WriteLine(op.Member.Name); } ```
I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty ``` delegate{ return x.someproperty; } ``` that is the same as: ``` () => x.someproperty ```
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
See also the following two blog posts that discuss exactly your second question and provide alternative approaches: [How to Find Out Variable or Parameter Name in C#?](http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html) [How to Get Parameter Name and Argument Value From C# Lambda via IL?](http://abdullin.com/journal/2008/12/19/how-to-get-parameter-name-and-argument-value-from-c-lambda-v.html) (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")
To get the name of the property you need SomeMethod to have an argument of the type of `System.Linq.Expressions.Expression<System.Func<object>>`. You can then go through the expression to determine the property name.
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
the () mean that this method doesn't take any parameters. for example, if you assign a normal event handler using a lambda expression, it would look like this: ``` someButton.Click += (s, e) => DoSomething(); ```
To get the name of the property you need SomeMethod to have an argument of the type of `System.Linq.Expressions.Expression<System.Func<object>>`. You can then go through the expression to determine the property name.
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
The `()` is an empty argument list. You're defining an anonymous function that takes no arguments and returns `x.Something`. Edit: It differs from `x => x.Something` in that the latter requires an argument and Something is called on that argument. With the former version `x` has to exist somewhere outside the function and Something is called on that outside `x`. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.
It's a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx). That is, it's a way to create an anonymous function or delegate. The general form is: ``` (input parameters) => expression ``` If you have ``` () => expression ``` then you have created a function that takes no arguments, and returns the result of the expression. C# uses [type inference](http://en.wikipedia.org/wiki/Type_inference) to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a [lexical closure](http://en.wikipedia.org/wiki/Closure_(computer_science)).
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty ``` delegate{ return x.someproperty; } ``` that is the same as: ``` () => x.someproperty ```
See also the following two blog posts that discuss exactly your second question and provide alternative approaches: [How to Find Out Variable or Parameter Name in C#?](http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html) [How to Get Parameter Name and Argument Value From C# Lambda via IL?](http://abdullin.com/journal/2008/12/19/how-to-get-parameter-name-and-argument-value-from-c-lambda-v.html) (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
> > What do the first brackets mean in the expression? > > > It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be: ``` SomeMethod(x => x.Something); ``` If it took n + 1 arguments, then it'd be: ``` SomeMethod((x, y, ...) => x.Something); ``` > > I'm also curious how you can get the property name from argument that is being passed in. Is this possible? > > > If your `SomeMethod` takes an `Expression<Func<T>>`, then yes: ``` void SomeMethod<T>(Expression<Func<T>> e) { MemberExpression op = (MemberExpression)e.Body; Console.WriteLine(op.Member.Name); } ```
the () mean that this method doesn't take any parameters. for example, if you assign a normal event handler using a lambda expression, it would look like this: ``` someButton.Click += (s, e) => DoSomething(); ```
1,370,236
*(Note the code is an example)* I have the following syntax: ``` SomeMethod(() => x.Something) ``` What do the first brackets mean in the expression? I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
2009/09/02
[ "https://Stackoverflow.com/questions/1370236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59711/" ]
It's a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx). That is, it's a way to create an anonymous function or delegate. The general form is: ``` (input parameters) => expression ``` If you have ``` () => expression ``` then you have created a function that takes no arguments, and returns the result of the expression. C# uses [type inference](http://en.wikipedia.org/wiki/Type_inference) to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a [lexical closure](http://en.wikipedia.org/wiki/Closure_(computer_science)).
To get the name of the property you need SomeMethod to have an argument of the type of `System.Linq.Expressions.Expression<System.Func<object>>`. You can then go through the expression to determine the property name.
676,370
I want to store the value of os-version from the command `cat /etc/os-release`. The output of cat /etc/os-release is ``` VERSION="4.4" ID="someId" ID_LIKE="someIdLike" ``` I want a shell command to store the version "4.4" into a variable without apostrophes or the text "VERSION". So far what I have done is ``` variable==`grep 'VERSION' /etc/os-release ``` which gives me variable=" VERSION="4.4"" and I just want the numerical value of the version which would be just 4.4.
2021/11/05
[ "https://unix.stackexchange.com/questions/676370", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/500076/" ]
The `os-release` manual on Ubuntu states that the `/etc/os-release` file should contain simple variable assignments compatible with the shell and that one should be able to source the file: > > The basic file format of `os-release` is a newline-separated list of > environment-like shell-compatible variable assignments. It is possible to source > the configuration from shell scripts [...] > > > ```bsh $ ( . /etc/os-release && printf '%s\n' "$VERSION" ) 20.04.3 LTS (Focal Fossa) ``` Above, I'm sourcing the file in a subshell to avoid polluting my interactive environment. In a shell script, you might not care too much about that. After sourcing the file, I print the value of the `VERSION` variable. The bare version number, without the patch release number, is available in the `VERSION_ID` variable on my system. Still, you could get it with the patch release included from the `VERSION` variable by removing everything after the first space with a standard variable expansion. ```bsh $ ( . /etc/os-release && printf '%s\n' "${VERSION%% *}" "$VERSION_ID" ) 20.04.3 20.04 ``` On your system, since the `VERSION` variable seems to contain the string `4.4` and nothing else, you could source the file and use `"$VERSION"` without further processing.
Using `lsb_release` to get the release number: ``` variable=$(lsb_release -rs) ``` `man lsb_release`: ``` -r, --release displays release number of distribution. -s, --short displays all of the above information in short output format. ```
676,370
I want to store the value of os-version from the command `cat /etc/os-release`. The output of cat /etc/os-release is ``` VERSION="4.4" ID="someId" ID_LIKE="someIdLike" ``` I want a shell command to store the version "4.4" into a variable without apostrophes or the text "VERSION". So far what I have done is ``` variable==`grep 'VERSION' /etc/os-release ``` which gives me variable=" VERSION="4.4"" and I just want the numerical value of the version which would be just 4.4.
2021/11/05
[ "https://unix.stackexchange.com/questions/676370", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/500076/" ]
Using `lsb_release` to get the release number: ``` variable=$(lsb_release -rs) ``` `man lsb_release`: ``` -r, --release displays release number of distribution. -s, --short displays all of the above information in short output format. ```
Thanks for the above answers as they were really helpful, but I found another solution from <https://unix.stackexchange.com/a/498788> which states that we can store the value from `os-release` as ``` VERSION=$(grep -oP '(?<=^VERSION_ID=).+' /etc/os-release | tr -d '"') echo $VERSION ```
676,370
I want to store the value of os-version from the command `cat /etc/os-release`. The output of cat /etc/os-release is ``` VERSION="4.4" ID="someId" ID_LIKE="someIdLike" ``` I want a shell command to store the version "4.4" into a variable without apostrophes or the text "VERSION". So far what I have done is ``` variable==`grep 'VERSION' /etc/os-release ``` which gives me variable=" VERSION="4.4"" and I just want the numerical value of the version which would be just 4.4.
2021/11/05
[ "https://unix.stackexchange.com/questions/676370", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/500076/" ]
The `os-release` manual on Ubuntu states that the `/etc/os-release` file should contain simple variable assignments compatible with the shell and that one should be able to source the file: > > The basic file format of `os-release` is a newline-separated list of > environment-like shell-compatible variable assignments. It is possible to source > the configuration from shell scripts [...] > > > ```bsh $ ( . /etc/os-release && printf '%s\n' "$VERSION" ) 20.04.3 LTS (Focal Fossa) ``` Above, I'm sourcing the file in a subshell to avoid polluting my interactive environment. In a shell script, you might not care too much about that. After sourcing the file, I print the value of the `VERSION` variable. The bare version number, without the patch release number, is available in the `VERSION_ID` variable on my system. Still, you could get it with the patch release included from the `VERSION` variable by removing everything after the first space with a standard variable expansion. ```bsh $ ( . /etc/os-release && printf '%s\n' "${VERSION%% *}" "$VERSION_ID" ) 20.04.3 20.04 ``` On your system, since the `VERSION` variable seems to contain the string `4.4` and nothing else, you could source the file and use `"$VERSION"` without further processing.
Thanks for the above answers as they were really helpful, but I found another solution from <https://unix.stackexchange.com/a/498788> which states that we can store the value from `os-release` as ``` VERSION=$(grep -oP '(?<=^VERSION_ID=).+' /etc/os-release | tr -d '"') echo $VERSION ```
64,923,873
So to give a little context im using expo-firebase-analytics (latest version) on Expo (27) and im trying to activate setDebugModeEnabled so that i can use the debugView on firebase analytics. The problem is that when running it i get the following warning > > The method or property expo-firebase-analytics.setDebugModeEnabled is not available on ios, are you sure you've linked all the native dependencies properly?] > > > I havent found any information about it on the web
2020/11/20
[ "https://Stackoverflow.com/questions/64923873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710240/" ]
Have you tried installing the latest version of expo-firebase-analytics since expo install brings an older one
if you check on the exports is the function there?