text
stringlengths
64
81.1k
meta
dict
Q: Setting the page title from a usercontrol in Umbraco I am having this problem on a site built with Umbraco v3.0.3. The master page is, as far as I know, stored by the CMS in the database. Thus when I do the following in my master page, it's not being processed and in fact the head isn't runat server. So the following comes through to the page in the browser: <head runat="server"> Consequently, I'm having problems using the following from within my usercontrol protected void Page_Load(object sender, EventArgs e) { this.Page.Title = "Lorem Ipsum"; } Which gives the following server error Using the Title property of Page requires a header control on the page. (e.g. runat="server" />) I just want a simple and clean way of setting the page title from a usercontrol! A: Did you also embellish the title tag with runat="server" like <head runat="server"> <title runat="server"></title> </head> Off the tangent, why would you need to set the page title from a user control? You would be better of having a page item or umbraco macro(possibly an asp.net user control) sitting inside the <title></title> tag that sets the page title for you.
{ "pile_set_name": "StackExchange" }
Q: alternating Fibonacci and prime series The task is to print the following series 1 2 1 3 2 5 3 7... The elements at odd positions are Fibonacci series terms and the elements at even positions are prime numbers. Given an input 'n' the element at the nth position in the series has to be printed. eg. when n = 4, output will be 3. n = 7, output will be 3 I've tried to solve the problem by returning nth prime number or nth fibonacci term. I am looking for any improvements that can be made to the code to optimize it further. #include <bits/stdc++.h> using namespace std; int retPrime(int n) { //Using sieve of Eratosthenes to generate primes int size = n + 1; bool Primes[100]; int count = 0; memset(Primes, true, sizeof(Primes)); for (int i = 2; i<sqrt(100); ++i) { if (Primes[i] == true) { for (int j = i * 2; j <= 100; j = j + i) { Primes[j] = false; } } } int primeIndex=0; int i = 2; while (count != n) { if (Primes[i] == true) { count++; primeIndex = i; } ++i; } return primeIndex; } int retFib(int n) { if(n<=1){ return n; } return retFib(n-1)+retFib(n-2); } int main() { int n; cin >> n; if(n%2==0) cout << retPrime(n/2)<<" "; else cout << retFib((n/2)+1)<<" "; return 0; } A: <bits/stdc++.h> is non-standard and likely far more than you actually need. Unless coupled with use of precompiled headers, it will slow down compilation at least. Replace it with the standard includes. See "How does #include <bits/stdc++.h> work in C++?". Never import wholesale any namespace which isn't designed for it. Doing so leads to conflicts, silent changes of behaviour, and generally brittle code. See "Why is “using namespace std” considered bad practice?". Crank up the warning-level for your compiler. You will see it complain that size in retPrime() is unused. There are only two good reason to give a variable a bigger scope than needed: Restricting the scope would be more verbose, or constructing it anew repeatedly would be more expensive. Otherwise, it's needless extra-stress put on each reader to understand things. Avoid magic numbers. Instead, use some well-named constant, or simply eliminate them. std::sqrt() may be required by the IEEE Standard to be exact. But does your implementation guarantee IEEE-conformance? Anyway, why not start with the square-roots? Try to use fewer variables. Instead of incrementing a new variable up to a target, decrement the target if you don't need it any longer. If you detect an error, like running beyond the bounds of your sieve, throw an exception, return an obviously impossible value (0 is a good candidate), or abort the program. But don't return a value which looks legitimate but is wrong. Take a bit more care with formatting. An empty line before each function is a good idea, but please neither more (before the first) nor less (before the last). retFib() and retPrime() are curious names. getFibonacci() and getPrime() seem better. You really should add a function for your own series, abstracting the details away. Comparing booleans against true or false is just pointless verbosity. Use the value directly, or after Negation with !. There is no guarantee that a bool is a byte big. Nor that memsetting every byte to 1 will result in a valid bool, let alone that it's true. Use std::fill, or reverse the logic and use aggregate-initialization to start with all-false instead. Even better, consider that the only even prime is 2, and change the code accordingly. Calculating fibonacci naively needs \$O(n)\$ space and \$O(2^n)\$ time. Consider being slightly more clever and calculate it iteratively in \$O(1)\$ space and \$O(n)\$ time. The conditional operator condition ? true_exp : false_exp is excellent for selecting one of two expressions. Use it where appropriate. You should end each line of output with \n, it's expected. A single space instead is surprising. If you want to stream a single character, use a character-literal, not a length-one string-literal. It might be slightly more efficient. return 0; is implicit for main(). Use noexcept where appropriate. Don't make things external for no reason. It increases the chance for collisions, and decreases the chance for inlining. Input can fail. Deal with it. As a final point, it might be better to just pre-compute the full sequence and be done with it. That might even save space. Modified code: #include <iostream> static int getPrime(int n) noexcept { //Using sieve of Eratosthenes to generate primes constexpr auto sqrt_size = 10; constexpr auto size = sqrt_size * sqrt_size; if (!n) return 2; bool prime[size] = {false, false, true}; for (int i = 3; i < size; i += 2) prime[i] = true; for (int i = 3; i < sqrt_size; i += 2) { if (!prime[i]) continue; if (!--n) return i; for (int j = i + i; j < size; j += i) prime[i] = false; } for (int i = (sqrt_size & ~1) + 1; i < size; i += 2) if (prime[i] && !--n) return i; return 0; } static int getFibonacci(int n) noexcept { int last = 0, r = 1; while (n-- > 0) { int temp = last + r; last = r; r = temp; } return r; } static int mySeries(int n) noexcept { return n % 2 ? getFibonacci(n / 2 + 1) : getPrime(n / 2); } int main() { int n; if (std::cin >> n) std::cout << mySeries(n) << '\n'; else std::cerr << "Could not understand your input. Expected a number.\n"; } A: Don't use #include <bits/stdc++.h>. This include is not portable to every compiler and it's non-standard. Also, it includes every standard header which just bloats up the size of your executable. See this relevant Stack Overflow post. Also, using namespace std; is considered bad practice, since you import the whole namespace. See this other relevant Stack Overflow post. Consider using std::array <bool,100> instead of a plain C arraybool Primes[100]; It also eliminates the use of memset(Primes, true, sizeof(Primes));. You can just initialise all 100 elements in the array to true. Instead of if (Primes[i] == true), you can just say if (Primes[i]) for bool types.
{ "pile_set_name": "StackExchange" }
Q: UIToolbar on each page of UINavigationController I have an application which runs on a UINavigationController. Now I would like to add a UIToolbar element to the bottom of each screen. The Toolbar on the bottom should the be customizable for the ViewController that is currently being displayed. My first idea was to simply add the toolbar to the navigationController view and tag it, in the viewController I thought I would then be able to retrieve the UIToolbar element. I have the following code: In my AppDelegate: // Get instance of Toolbar (navController is an instance of UINavigationController and TOOLBAR_TAG a constant) UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 440, 320, 40)]; toolbar.tag = TOOLBAR_TAG; [navController.view addSubview:toolbar]; In my viewController I tried this: UIToolbar *toolbar = [self.navigationController.view viewWithTag:TOOLBAR_TAG]; toolbar.barStyle = UIBarStyleBlack; Yet this gives me an error saying that toolbar in my case is a "UILayoutContainerView" object, not an UIToolbar object. Hence this idea seems to be a dead end. How did others solve this issue? A: UINavigationController already has a toolbar. Just use [self.navigationController setToolbarHidden:NO]; in the topmost view controller and [self setToolbarItems:items]; in all your view controllers, where items is an NSArray of that view controller's toolbar items. EDIT: As for why your solution isn't working: your TOOLBAR_TAG is probably not unique, that's why you're getting another subview. But as I said, you should use the included toolbar anyway.
{ "pile_set_name": "StackExchange" }
Q: Spring security autoauthentication not working I am using spring security in my application. When user wants to access /privatePages/* a login screen shows up for authentication. This works fine. I want to have something as a guest access so in my controller I did something like this: Authentication authentication = new UsernamePasswordAuthenticationToken("SAMPLE", "SAMPLE", getAuthority()); //authentication.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authentication); public Collection<GrantedAuthority> getAuthority() { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); GrantedAuthority grantedAuthority = new GrantedAuthority() { public String getAuthority() { return "ROLE_RequiredRole"; } }; grantedAuthorities.add(grantedAuthority); return grantedAuthorities; } I can see that authentication is now performed as this expression gives true: SecurityContextHolder.getContext().getAuthentication().isAuthenticated() However I am not able to access /privatePages/somePage.jsp. It still redirects me to the login page. Am I missing something ? UPDATE <http pattern="/privatePages/**" auto-config="true" use-expressions="true" authentication-manager-ref="myManager" create-session="never"> <session-management invalid-session-url="/privatePages/login" /> <intercept-url pattern="/privatePages" access="hasRole('RequiredRole')"/> <intercept-url pattern="/privatePages/" access="hasRole('RequiredRole')"/> <form-login login-page="/privatePages/login" . . . . A: You're making a rule on /privatePages/** which means that, the rule will be applied on all URLs with the prefix localhost:8080/privatePages/..., and if in that rule you're enforcing some sort of authentication required then it wold ask you regardless of what you do in the Controller because your requests go through the security filter before they reach to that stage. In your SecurityConfig try doing the following: <http auto-config="true"> <intercept-url pattern="/privatePages" access="ROLE_RequredRole" /> <intercept-url pattern="/privatePages/somePage.jsp" access="ROLE_ANONYMOUS" /> </http> Here we are making use of ROLE_ANONYMOUS which means that it the role doesn't require any authentication. See here for more info.
{ "pile_set_name": "StackExchange" }
Q: pre-loading images using Javascript I'm using Javascript to make a simple image viewer bar for my site (ASP.NET), I have 3 pictures displayed at each time and user can go to next or previous images using two buttons, also when users mouse overs on each picture, a larger version of the selected image is displayed on a separate DIV. The only problem is that when users overs the images for the selected time, there is a delay before displaying the large image (as the big image is being loaded for the first time). how can I solve this problem? is there any way that I can initially load all large images (of course they should not be visible) what are my options? Is there any way I can do it purely with javascript? I don't want to use jQuery A: Create an element neer the end of the body like this <div id="preload"> set this div to display:none and place the images inside of it. Now when you use your gallery there shouldn't be a delay. A: Another way using pure javascript is this one: var img = new Image(); img.src = "url to image"; That's it! That will make the request to the server. You can do this for the rest of the images. If you want to know when it is finally loaded you could add the load event. For example: img.onload = function(){ alert("image ready"); }
{ "pile_set_name": "StackExchange" }
Q: How to reference external set of permissions in an XACML policy? Originally, I asked "How do you write a policy that requires a subject be granted access to a requested permission, where the set of allowed permissions is in an external attribute store. Can you reference an external set of permissions in a policy?" The second question has been answered in the affirmative, so I'm revising the question a bit to focus on the "how". Can someone provide a xacml policy snippet (or even pseudo-xacml) that requires a role attribute id (will be provided by the request) to be within a set of roles which are identified by another attribute id (managed by external attribute store). For the sake of providing a starting point, the following is an example from http://docs.oasis-open.org/xacml/2.0/XACML-2.0-OS-ALL.zip. In this case, the role is inline. <Subject> <SubjectMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">administrator</AttributeValue> <SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:example:attribute:role" DataType="http://www.w3.org/2001/XMLSchema#string"/> </SubjectMatch> </Subject> A: Yes, policies can be written to reference attributes that come from an external attribute store. However, where the attributes actually come from is usually not specified in the policy itself, other than perhaps by a naming pattern in the attribute ID. In the XACML PDP reference architecture, it's the responsibility of the request context handler to resolve attribute IDs and produce values for the PDP. It goes something like this: While evaluating a request against a set of policies, the PDP encounters an attributeID in a policy rule that it needs to form a decision about the request. The PDP asks the request context handler to get the value of that attributeID "from whereever" - the PDP doesn't care where it comes from. The request context handler may look for the attribute in the attributes provided with the request, or in any number of external attribute providers, such as LDAP or AD or SAML or plain old databases. The request handler might recognize naming patterns (like, namespace prefixes) in the attributeID to know where to obtain it. You want your attributeIDs to be specific enough to know what they are and what they mean, but not so specific that all of your policies break when you move your attribute provider to a different machine. Policies should be configuration independent. Ultimately, where the request handler looks for attributes is a matter of configuration of the request handler / PDP server, and will vary by product vendor. Update: To answer the 2nd revision to this question You would write your policy to perform a comparison between the attribute value(s) provided in the request and a list of values provided by an external source. Keep in mind that an attribute designator returns a list of values, since the request could contain multiple attribute values for the same attributeID. You can accommodate that by either by wrapping the attribute designator in a "one-and-only" reduction function, or by using a many-to-many cross product match function that will test every member of list1 for a match in list2. Unless you have a specific design requirement that the request is only allowed to contain one role attribute, it's best to avoid the "one-and-only" reduction since it really limits your options. Your Xacml 2.0 policy could look something like this: (forgive syntax errors, my Xacml 2.0 is a little rusty) <Policy [...] RuleCombiningAlgorithm="deny-unless-permit"> <Rule [...]> <Effect>Permit</Effect> <Condition> <Apply FunctionId=”urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of”> <SubjectAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:example:attribute:role" DataType="http://www.w3.org/2001/XMLSchema#string"/> <SubjectAttributeDesignator AttributeId="list-of-acceptable-roles-from-external-provider-attribute-id" DataType="http://www.w3.org/2001/XMLSchema#string"/> </Apply> </Condition> </Rule> </Policy> The Xacml function "at-least-one-member-of" takes two lists as parameters. For every item in the first list, it tests to see if that item exists in the second list. It returns true as soon as it finds at least one match. The attribute "...example:attribute:role" from your example is the attribute you're expecting to be provided in the request. If you want to enforce that the attribute must be provided in the request, you can set MustBePresent="true" in the attribute designator. The "list-of-acceptable-roles..." attribute is an attribute id that your PDP context handler recognizes and retrieves from some external provider. What prefix or pattern the context handler looks for and which provider it fetches from is a matter of PDP configuration. Ideally, the naming pattern on the attribute id indicates a conceptual domain or namespace the id is associated with, but the id does not explicitly indicate the physical location or provider of the attribute value(s). For longer app lifetime with lower maintenance costs, you want to be able to change your provider implementation details without having to rewrite all of your policies. You can have vendor-specific attribute ids that will probably only come from a single provider, you can have application-specific attribute ids that could be supplied by multiple providers but only make sense for a particular application, and you can have generic or standardized attribute ids that could come from multiple providers and be used in multiple applications. The Oasis standards body and domain-specific profiles are a good starting point for finding standardized attribute ids and their semantics or getting ideas on how to organize your own app specific ids. Depending on your PDP and context handler implementation, it may also possible to use the "Issuer" field as a way to constrain the list of providers for an attribute. The Xacml spec doesn't say much about use of the Issuer field, but the same goals of decoupling policy from provider implementation details still holds.
{ "pile_set_name": "StackExchange" }
Q: antcontrib foreach executed in parallel does not raise errors I have the following ant script that I can't seem to find a way to make fail when parallel is set to true for antcontrib's foreach task. Any ideas? <project name="asdf" > <taskdef resource="net/sf/antcontrib/antcontrib.properties"> <classpath> <pathelement location="../lib/ant/ant-contrib-1.0b3.jar" /> </classpath> </taskdef> <target name="build"> <foreach target="exex-subant" param="foreach.dir" parallel="true" maxthreads="4" inheritall="true" list="1,2,3"> <param name="target" value="build" /> </foreach> </target> <target name="exex-subant"> <fail>test</fail> </target> </project> A: This occurs because when executed in parallel, <foreach> uses the <parallel> task, but does not set the "failonany" property, or give any way to say that the task should fail if any iteration failed. Fortunately, there is a relatively easy workaround, which is to use <for> instead of <foreach>. In your example, that would look like this: <target name="build"> <for param="foreach.dir" parallel="true" list="1,2,3"> <sequential> <antcall target="exex-subant" inheritall="true"> <param name="target" value="build" /> <param name="foreach.dir" value="@{foreach.dir}" /> </antcall> </sequential> </for> </target> Note that you have to explicitly pass in the foreach.dir property, which will then be accessible in the exex-subant target as ${foreach.dir}. This will execute all iterations in parallel, but the script will fail if any one of them fails (it will not execute anything beyond the for task). Note that in order to use the for task, you'll need ant 1.6 or higher, and will need to change your taskdef to: <taskdef resource="net/sf/antcontrib/antlib.xml"> <classpath> <pathelement location="../lib/ant/ant-contrib-1.0b3.jar" /> </classpath> </taskdef> If for some reason you need to support older versions of ant, then you would have to change the exex-subant target slightly, so that it changed something when it failed. For example, you could wrap the current logic in exex-subant within a try/catch, and in the catch block it could create a file. Then after the foreach terminates you can check to see if that file exists, and fail the build if it does. That way, if any execution of the foreach fails, the ant script will fail after the foreach finishes. Note that you can't just set a property in exex-subant on failure, since the property won't propagate back to the foreach loop (which is why I suggested creating a file). But I'd strongly recommend just using the for task and requiring ant 1.6 or higher.
{ "pile_set_name": "StackExchange" }
Q: SQL Count(*) Not working in Formula with Group By I can't seem to have my code take the [Actual Closed Loans] variable and divide it by the [Loan Count] variable. I tried doing this step in the [Actual Closing Ratio] variable. However I get a zero result. Even when I add a new variable to this code and do 1 / count(*) SQL doesn't seem to like it. I know I must be using the Count(*) incorrectly in this context. But I can't figure it out. My query: Select [PORT_DATE], Count (*) as [Loan Count], --this works fine sum(Case when [Closed or Fallen Out] ='c' then 1 else 0 end) as [Actual Closed Loans],--this works fine sum(Case when [Closed or Fallen Out] ='C' then 1 else 0 end)/count(*) as [Actual Closing Ratio], --although code works doesnt produce correct result, output for this variable is all zeros From dbo.XYZ Group by [PORT_DATE] order by [PORT_DATE] A: This happens due to integer division, add multiplication by 1.0 to get numeric result. sum(Case when [Closed or Fallen Out] ='C' then 1 else 0 end)*1.0/count(*)
{ "pile_set_name": "StackExchange" }
Q: MySQL 5.6.13 not executing create table properly I have the following SQL to create a table on a MySQL 5.6.13 instance: CREATE TABLE 'exchange' ( 'id' int NOT NULL AUTO_INCREMENT, 'abbrev' varchar(32) NOT NULL, 'name' varchar(255) NOT NULL, 'city' varchar(255) NULL, 'country' varchar(255) NULL, 'currency' varchar(128) NULL, 'time_zone_offset' time NULL, 'created_date' datetime NOT NULL, 'last_updated_date' datetime NOT NULL, PRIMARY KEY ('id') ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; However, I keep getting the following unhelpful error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''exchange' ( 'id' int NOT NULL AUTO_INCREMENT, 'abbrev' varchar(32) NOT NULL, 'n' at line 1 I must be missing something glaringly obvious... Any ideas where I'm going wrong? A: Try : CREATE TABLE exchange ( Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
{ "pile_set_name": "StackExchange" }
Q: NLTK PunktSequenceTokenizer return type or a way to use it faster in an iterative function? Within my PHP function, I am calling a Python script like this: $foo = exec("python tokenize.py $bar"); The problem is, now I have built a function that executes the command above iteratively and it takes more than five minutes to finish, because of the code I use below: train_text = state_union.raw("1963-Johnson.txt") custom_sent_tokenizer = PunktSentenceTokenizer(train_text) The operation of training my PST takes some time even for one of the shortest corpora in the state_union package. I tried to store the output in a plain txt file but I cannot find the return type in the documentation here. I guess it is an iterator like everything else in the package, but I've tried to convert the iterator to the list and failed miserably. The questions are: 1. What is the return type of the PunktSentenceTokenizer and can I store it? 2. Will reading it from the .txt file or any other source be faster than training it over and over when executing my PHP program? 3. Do you have any other idea how to use PST so it remains trained over the same portion of text so I can use it with my script faster? A: Why not pickle it? import pickle ... # other imports and stuff custom_sent_tokenizer = PunktSentenceTokenizer(train_text) pickle.dump(custom_sent_tokenizer, open( "save.p", "wb" )) Now you can easily load the trained tokenizer in another call or script: >>> import pickle >>> pickle.load(open( "save.p", "rb" ) ) <nltk.tokenize.punkt.PunktSentenceTokenizer object at 0x00000000023B9EB8>
{ "pile_set_name": "StackExchange" }
Q: Enhanced for loop compiling fine for JDK 8 but not 7 Consider the following code snippet, I stumpled upon after some refactoring, when checkin why the build server reported a broken build but it was fine in my IDE: List<String> text; ... for (String text : text) {...} So, the same name is used for the String and the List within the for-each. This is of course not very wise to do, but after following my nosiness before renaming it, I saw that the above code compiles fine with JDK 8, but gives the below error with JDK 7: error: for-each not applicable to expression type for (String text : text) { ^ required: array or java.lang.Iterable found: String 1 error I know that changes were made to several parts in this area within the JDK - but can someone enlighten me on why exactly this behaviour occurs? Update: Since I got some comments about different behaviour, here's a full sample class: import java.util.Arrays; import java.util.List; public class Strange { List<String> text = Arrays.asList("Max", "Alex", "Maria"); public static void main(String[] args) { new Strange().doSomething("Alex"); } public void doSomething(String name) { for (String text : text) { System.out.println(text.equals("Alex")); } } } And here's the compile process and output (Windows 7 64bit): C:\copy>c:\Projects\java\jdk1.7.0_79\bin\javac.exe Strange.java Strange.java:13: error: for-each not applicable to expression type for (String text : text) { ^ required: array or java.lang.Iterable found: String 1 error C:\copy>c:\Projects\java\jdk1.8.0_60\bin\javac.exe Strange.java C:\copy> Conclusion: I was so puzzled why my IDE (which uses 8) didn't complain about twice the same name in one statement - but now it is clear that it is not one statement. I really wonder why this point has so long been in place if the JLS states otherwise. But anyway, thanks for the insights I have received and the great answers (which made it hard for me to pick the best one). A: This should actually compile fine for JDK 7 and 8. Quoting JLS section 14.14.2 (which is the same for the Java 7 specification): The enhanced for statement is equivalent to a basic for statement of the form: for (I #i = Expression.iterator(); #i.hasNext(); ) { {VariableModifier} TargetType Identifier = (TargetType) #i.next(); Statement } Rewriting the enhanched for loop with Iterator for (String text : text) {...} becomes for (Iterator<String> it = text.iterator(); it.hasNext(); ) { String text = it.next(); } Then, quoting example 6.4.1 of the JLS: A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. As such, there is no compile-time error here because no restriction is made when shadowing a member variable by a local variable, which is the case here: the local variable String text is shadowing the member variable List<String> text. A: While the reasoning, using the specified translation from the enhanced for loop to the traditional for loop, used by other answers is correct, there is an explicit specification about the scopes: §6.3. Scope of a Declaration … The scope of a local variable declared in the FormalParameter part of an enhanced for statement (§14.14.2) is the contained Statement. (direct link) Thus, the scope of the variable does not include the Expression of the enhanced for loop… You can verify that this hasn’t changed, compared to Java 7 and Java 6, though both (I tried Java 6 javac) exhibit the contradicting behavior. So this change in the compiler behavior is the fix of an old bug… A: I would say it is a compiler bug in the particular version of the Java 7 compiler that you are using. The earlier text is a field, and it is legal for the text local declared in the for statement to shadow a field. Then we look at what the for loop means. According to the JLS, for (String text : text) {...} is equivalent to for (Iterator<String> #i = text.iterator(); #i.hasNext(); ) { String text = (String) #i.next(); ... } As you can see the inner text is not in-scope for the text.iterator() expression. I tried searching the Oracle Java Bugs Database, but couldn't find anything that matched this scenario.
{ "pile_set_name": "StackExchange" }
Q: Why am I not seeing what I expect when I use Python 2.7's decimal function? I'm just beginning to use Python 2.7 and am trying to build a simple credit payment calculator as a test. From what I've been able to find, the decimal function should force the program to calculate to a specific number of decimal places. From the documentation pages: >>> from decimal import * >>> getcontext().prec = 6 >>> Decimal(1) / Decimal(7) Decimal('0.142857') >>> getcontext().prec = 28 >>> Decimal(1) / Decimal(7) Decimal('0.1428571428571428571428571429') So my understanding is if I type the following: from decimal import * getcontext().prec=2 total =5 print Decimal(total) I should get the following 5.00 However, it keeps printing 5. If I type Decimal (5) or Decimal (total) I get the output Decimal ('5'). Can anyone tell me what I'm doing wrong? A: The precision you're setting is the mathematical precision of calculations. It has nothing to do with the number of decimal places printed. A Decimal instance will print the shortest textual representation of itself by default. To print otherwise, use Python string interpolation (% operator) or the format() method of strings. A: why dont you just do format strings? >>> print "{0:0.2f}".format(5) 5.00 sorry I dont know anything about the decimal package so I really cant help you there...ive never really understood the need, or niche for the decimal package http://www.shocksolution.com/2011/11/python-string-format-examples/ http://docs.python.org/library/string.html#formatspec
{ "pile_set_name": "StackExchange" }
Q: Directx control in browser plugin I have to insert a directx control to a firebreath plug in for a browser. Can anyone post a sample how to do it? I have no knowledge in plugins... 10x A: I don't have an example that I can give you, but I can tell you roughly what you need to do. First, read this: http://colonelpanic.net/2010/11/firebreath-tips-drawing-on-windows/ That will give you an overview of how drawing works in FireBreath. First, you set everything up when handling AttachedEvent. Create a new thread to handle drawing (your DirectX drawing must not be on the main thread) Get the HWND from the PluginWindowWin object (cast the FB::PluginWindow* to FB::PluginWindowWin and call getHWND()) Initialize DirectX on the secondary thread with the provided HWND. Set up some form of render loop and make sure you can send it commands from the main thread. Handle the RefreshEvent (comes from WM_PAINT) by posting a message somehow to your render thread so it redraws when that event is fired. Make sure that on DetachedEvent you shut down your thread. You need to do all initialization, drawing, and shutdown of the DirectX stuff on the same thread. This needs to all happen on a thread that is not just the main thread (don't just use timers) because otherwise it'll mess up the browser rendering context on some versions of Firefox -- not sure why. Anyway, hope this helps. Edit: To pass parameters into the start of a boost::thread, should that be the threading abstraction you decide to use, simply pass it in as a parameter. boost::thread t(&MyClass::someFunction, this, theHWND); That will start the thread. In actuality, you probably want to make the thread a class variable or something so that you can access it later -- remember that you'll want the thread to have stopped during the handling of DetachedEvent. For messages I'd probably use FB::SafeQueue, which is a threadsafe queue that is part of FireBreath. Look at the sources for how to use it; it's pretty straightforward (stolen from a codeproject article, I think). // Inside MyClass void someFunction(HWND theHWND) { ... }
{ "pile_set_name": "StackExchange" }
Q: Unable to position infobox to its previous position when loaded again using ajax It seems like reloading infobox inside ajax success function is trying to position infobox somewhere else, in firebug I can see it changes its top to something else. If earlier its top: -12.4635px; then when I use lastInfoWindow.setOptions({"content":"its content here"}); then it becomes -4.46351px; when I click on next or previous button on infobox, next and previous buttons calls ajax to change its content dynamically where previously intialised lastInfoWindow is like this: > var myOptions = { > boxClass: "popup infoBox", > content:boxText, > disableAutoPan:true, > maxWidth:0, > pixelOffset: new google.maps.Size(-(ib_width/2), 0), > zIndex: null, > boxStyle: { > background: "none", > opacity: 1, > width: ib_width+"px" > }, > closeBoxMargin: "0px 0px 0px 0px", > closeBoxURL: "/" + version_link + "/images/popup_close.png", > infoBoxClearance: new google.maps.Size(1, 1), > isHidden: false, > pane: "floatPane", > enableEventPropagation: false, > marginBottom:mb, > marginLeft:ml, > grouped:group > }; > var infoWindow = new InfoBox(myOptions); > lastInfoWindow = infoWindow; I tried fetching current top position in some variable and then after ajax done function i tried changing its top to already saved position, but it didn't work, I used setTimeout to delay it but still it isn't working. What else I can do now. A: Modified Infobox js file InfoBox.prototype.rePosition = function () { if(cM_contentCurrentPos){ this.div_.style.top = cM_contentCurrentPos; } } where cM_contentCurrentPos contains previous top position. I called it like this infoWindow.rePosition();
{ "pile_set_name": "StackExchange" }
Q: Problems with inline-block in IE8 I just tested my code. It works fine on Chrome and Mozilla. But not in IE 8. Problems with inline-block display: The 3th block: the content is not vertically align The 5th box: No hover submenu appeared. see here: http://jsfiddle.net/evNjH/ <style type="text/css"> html, body { margin: 0; padding: 0; } #navcontainer { padding: 0 5 20px 10px; } ul#navlist { font-family: sans-serif; margin-left: 0; padding: 0; } ul#navlist li { padding: 10px 5px 10px 5px; background-color: #EF634A; } ul#navlist > li { height:38px; line-height:38px; } ul#navlist li:hover { color: #ffff00; background-color: #3E748A; } ul#navlist a { font-weight: bold; text-decoration: none; display: inline-block; line-height:1.1; vertical-align: middle; } ul#navlist ul, ul#navlist li { padding: 0 8px; margin: 0 8px; list-style-type: none; box-shadow: 8px 8px 12px #aaa; } ul#navlist > li:first-child { margin-left: 0; } ul#navlist li { float: left; } ul#navlist li a { color: #ffffff; //padding:10px; /*border: 1px #ffffff outset; height: 40px;*/ } ul#navlist li:active { color: #cccccc; background-color: #3E748A; border: 1px #ffffff inset; box-shadow: none; } ul#subnavlist { display: none; } ul#subnavlist li { float: none;line-height:normal; } ul#subnavlist li a { padding: 0px; margin: 0px; height: 14px; } ul#navlist li:hover ul#subnavlist { display: block; //display: inline-block; //display: table-cell; position: absolute; font-size: 8pt; padding-top: 5px; box-shadow: none; } ul#navlist li:hover ul#subnavlist li a { display: block; width : 360; height : 100; border: none; padding: 2px; } ul#navlist li:hover ul#subnavlist li a:before { content: " >> "; } a.white:link {color: #fff;} a.white:active {color: #fff;} a.white:visited {color: #fff;} a.white:hover {color: #fff;} </style> and the html <div id="navcontainer"> <ul id="navlist"> <li><a href="obs-geostrategique-sport1.php?cat=2">ACTUALITÉS</a></li> <li><a href="obs-geostrategique-sport1.php?cat=5">ANALYSE</a></li> <li><a href="obs-geostrategique-sport1.php?cat=1">PROGRAMME EUROPÉEN DE LUTTE <br>CONTRE LE TRUCAGE DE MATCHS</a></li> <li><a href="obs-geostrategique-sport1.php?cat=3">COMMUNIQUÉ</a></li> <li><a href="#">THEMATIQUES</a> <ul id="subnavlist"> <li id="subactive"> <a href="obs-geostrategique-sport1.php?cat=4&id=1">Lutte contre la corruption</a></li> <li><a href="obs-geostrategique-sport1.php?cat=4&id=2">Evènements sportifs </a></li> <li><a href="obs-geostrategique-sport1.php?cat=4&id=3">Bonne gouvernance du sport</a></li> <li><a href="obs-geostrategique-sport1.php?cat=4&id=4">Economie du sport</a></li> <li><a href="obs-geostrategique-sport1.php?cat=4&id=5">Lutte contre le dopage</a></li> <li><a href="obs-geostrategique-sport1.php?cat=4&id=7">Lutte pour l'intégrité dans le sport</a></li> </ul> </li> </ul> </div> A: You have some errors in css, try html, body { margin: 0; padding: 0; } #navcontainer { padding: 0 5px 20px 10px; } ul#navlist { font-family: sans-serif; margin-left: 0; padding: 0; } ul#navlist li { padding: 10px 5px 10px 5px; background-color: #EF634A; } ul#navlist > li { height:38px; line-height:38px; } ul#navlist li:hover { color: #ffff00; background-color: #3E748A; } ul#navlist a { font-weight: bold; text-decoration: none; display: inline-block; line-height:1.1; vertical-align: middle; } ul#navlist ul, ul#navlist li { padding: 0 8px; margin: 0 8px; list-style-type: none; box-shadow: 8px 8px 12px #aaa; } ul#navlist > li:first-child { margin-left: 0; } ul#navlist li { float: left; } ul#navlist li a { color: #ffffff; } ul#navlist li:active { color: #cccccc; background-color: #3E748A; border: 1px #ffffff inset; box-shadow: none; } ul#subnavlist { display: none; } ul#subnavlist li { float: none; line-height:normal; } ul#subnavlist li a { padding: 0px; margin: 0px; height: 14px; } ul#navlist li:hover ul#subnavlist { display: block; position: absolute; font-size: 8pt; padding-top: 5px; box-shadow: none; } ul#navlist li:hover ul#subnavlist li a { display: block; width : 360; height : 100; border: none; padding: 2px; } ul#navlist li:hover ul#subnavlist li a:before { content:" >> "; } a.white:link { color: #fff; } a.white:active { color: #fff; } a.white:visited { color: #fff; } a.white:hover { color: #fff; } Errors 6 #navcontainer padding only 0 can be a length. You must put a unit after your number : 0 5 20px 10px 46 ul#navlist li a Parse Error //padding:10px; 70 ul#navlist li:hover ul#subnavlist Parse Error //display: inline-block; 71 ul#navlist li:hover ul#subnavlist Parse Error //display: table-cell;
{ "pile_set_name": "StackExchange" }
Q: Can a Community be included in a Trialforce template? I think (but am not sure) I could not include a Site in a Trialforce template a few years ago. One problem was the need for a unique domain name. We are now using Communities that are layered on top of Sites. Can a Community be included in a Trialforce template? PS This may be relevant Can we enable "My Domains" within "Trialforce Source Org"? A: I took Jayant's advice and this https://partners.salesforce.com/0D53A00003jZcp3 is a great link on the subject for anyone who has a Partner Community login. That thread is quite long and there are quite a few "if this then that" factors (particularly for Sites) but the basic answer is "yes".
{ "pile_set_name": "StackExchange" }
Q: Not understanding help files, case automatic deleted q/post I had a question. The title was: ReGina - 5.5.3 Scoping at work: the classic accumulator test - Perl example [closed] I can see that it is automated closed. There was the message: deleted by Community Jun 29 at 3:00 (RemoveAbandonedClosed) This question was automatically deleted. Please see the help center for more information. I did follow the link and read. I do not understand why my question was deleted. Can someone please explain to me? What I have seen is that my q had -6. But I do not understand, what should be wrong with a question about a not working example in a Groovy book. I would like to learn the reason why my question was deleted as I see the possibility to step in this trap again and I want to avoid this. A: But I do not understand, what should be wrong with a question about a not working example in a Groovy book. Me neither. If that was the question, then it might be boring, but it should be on-topic. However, you are misrepresenting the question that you actually asked. The body consisted solely of the following text: in ReGina (Groovy in Action, Second Edition) in chapter 5.5.3 Scoping at work: the classic accumulator test - there is a Perl example. This example seems to not work. Has anybody ever made this Perl-snippet to run? Would be thankful for hints. Thanks in advance, Thomas Even putting aside the grammar mistakes, the lack of formatting, and the unnecessary signature, there is a larger problem: you forgot to include the code from the example that didn't work! In fact, this is precisely why your question got closed by community members: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. That is, as usual, a very apt description of the problems with your question, so it was rightfully closed. Then, after the question was closed, you essentially abandoned it. You did not bother to go back and update the question (edit it) to include the missing information. So the system automatically deleted it to clean up clutter. This is a process that we affectionately call the "Roomba", after the autonomous vacuum cleaner. In particular, the rule that caused your question to be deleted was "RemoveAbandonedClosed", which that Help Center page describes as follows: If the question was closed more than 9 days ago, and ... not closed as a duplicate has a score of 0 or less is not locked has no answers with a score > 0 has no accepted answer has no pending reopen votes has not been edited in the past 9 days ... it will be automatically deleted. These are "abandoned closed", and are termed as RemoveAbandonedClosed.
{ "pile_set_name": "StackExchange" }
Q: How to go to next iteration Here is what I want to do: In the loop, if the program finds an error, it will print out "Nothing" and go to the next loop (skips print out ""Service discovered at port: " + px + "\n" for(int px=PORT1; px <=PORT2; px++) { //search try{ Socket s = new Socket(IPaddress,px); } catch(Exception e) { System.out.print("Nothing\n"); // I want to go to next iteration } System.out.print("Service discovered at port: " + px + "\n"); } What code should I put in the catch? "break" or "next" or ??? (This is java) A: Use the continue keyword: continue; It'll break the current iteration and continue from the top of the loop. Here's some further reading: continue Keyword in Java A: If you want to only print out a message (or execute some code) if an exception isn't thrown at a particular point, then put that code after the line that might throw the exception: try { Socket s = new Socket(IPaddress,px); System.out.print("Service discovered at port: " + px + "\n"); } catch(Exception e) { System.out.print("Nothing\n"); } This causes the print not to execute if an exception is thrown, since the try statement will be aborted. Alternatively, you can have a continue statement from inside the catch: try { Socket s = new Socket(IPaddress,px); } catch(Exception e) { System.out.print("Nothing\n"); continue; } System.out.print("Service discovered at port: " + px + "\n"); This causes all of the code after the try/catch not to execute if an exception is thrown, since the loop is explicitly told to go to the next iteration. A: The keyword you're looking for is continue. By putting continue after your print statement in the catch block, the remaining lines after the end of the catch block will be skipped the next iteration will begin.
{ "pile_set_name": "StackExchange" }
Q: onclick event not applying border around checkbox in my Spring web Flow, while click on Confirm button it should highlight the checkbox if it is uncheck and form should not be submitted. if it is checked form should be submitted <form:form> <input type="checkbox" id="check-box" name="<c:out value="${status.expression}"/>" value=" <c:out value="${status.value}"/>"> <input type="hidden" name="_<c:out value="${status.value}"/>"> <span onclick="submitForm('confirm')">Confirm</span> <span onclick="submitForm('cancel')">Cancel</span> </form:form> <script type="text/javascript"> function submitForm(event){ if(document.getElementId('check-box').checked){ doc.form[0]._eventId_value=event; doc.form[0].submit(); } else { document.getElementId('check-box').style="border-style:solid,border-width:5px;" } } </script> A: I think you should use border:5px solid #ccc; or any color for that matter
{ "pile_set_name": "StackExchange" }
Q: Please explain closures, or binding the loop counter to the function scope I've seen programmers assign events listeners inside loops, using the counter. I believe this is the syntax: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); } Could someone please explain the logic behind this, and this weird syntax, I've never seen this: (function(i))(i); Many thanks for your time and patience. A: The (function(i))(i) syntax creates an anonymous function and then immediately executes it. Usually you'll do this to create a new function every time through the loop, that has its own copy of the variable instead of every event handler sharing the same variable. So for example: for(int i = 0; i < 10; i++) buttons[i].click = function() { doFoo(i); }; Often catches people out, because no matter what button you click on, doFoo(10) is called. Whereas: for(int i = 0; i < 10; i++) buttons[i].click = (function(i){ return function() { doFoo(i); };)(i); Creates a new instance of the inner function (with its own value of i) for each iteration, and works as expected. A: This is done because JavaScript only has function scope, not block scope. Hence, every variable you declare in a loop is in the function's scope and every closure you create has access to the very same variable. So the only way to create a new scope is to call a function and that is what (function(i){/* Some code using i */}(i)) is doing. Note that your example misses an important part: The immediate function has to return another function which will be the click handler: someArray[i].onclick = (function(i){ return function() { /* Some code using i */ } }(i)); The immediate function is nothing special. It is somehow inlining function definition and function call. You can replace it by a normal function call: function getClickHandler(i) { return function() { /* Some code using i */ } } for(var i=0; i < someArray.length; i++){ someArray[i].onclick = getClickHandler(i); }
{ "pile_set_name": "StackExchange" }
Q: Masking phone number using TextBoxFor I want to mask a phone number using html helpers (TextBoxFor) there is my code Model : [Required(ErrorMessageResourceType = typeof(ProcRec.Ressources.Candidat.ErreurValidation), ErrorMessageResourceName = "num_tel_obligatoire")] [RegularExpression(@"[0][6]\-\d{2}\-\d{2}\-\d{2}\-\d{2}$", ErrorMessageResourceType = typeof(ProcRec.Ressources.Candidat.ErreurValidation), ErrorMessageResourceName = "num_tel_faux")] public string num_tel { set; get; } View : <script type="text/javascript"> jQuery(function($){ $("#date").mask("99/99/9999"); $("#num_tel").mask("(999) 999-9999"); $("#tin").mask("99-9999999"); $("#ssn").mask("999-99-9999"); }); </script> <td>@Html.LabelFor(model => model.num_tel)</td> <td>@Html.TextBoxFor(model => model.num_tel)</td> the validation is working but when it comes to mask i get nothing their is the result i get . . . . . . . A: I found a solution the broblem was that i have not instaled jQuery.MaskedInput plugin To install jQuery.MaskedInput, run the following command in the Package Manager Console PM> Install-Package jQuery.MaskedInput -Version 1.3.1 thinks
{ "pile_set_name": "StackExchange" }
Q: Fading text in and out using jquery I am trying to fadein some text 2 seconds after the page loads and after 5 seconds i want it to fade out. Fiddle here I have tried using the following code: <div id="intro-wrap"> <div id="intro-text"> <h1 style="font-size: 20px; letter-spacing: 0.1em; font-family: serif; color: rgb(253, 236, 204); font-weight: 100;">Creating the world's most exceptional homes</h1> </div> </div> $(window).on("load", function () { $('#intro-wrap').fadeIn('4000', function () { // First Animation complete $(this).fadeOut('4000', function () { // Second Animation complete }); }); }); The issue is the text quickly appears and disappears. How can I make it appear after sometime, make it visible for some time and then make it fade away? A: setTimeoutI changed the color of the Text so you can better see the animation, this yellow stuff was just disgusting, sorry about that. Fiddle Link: http://jsfiddle.net/zbbv4z9n/9/ You first need to hide your div to make it fadein otherwise it is already their. $(window).on("load", function () { $('#intro-wrap').hide(); $('#intro-wrap').fadeIn(4000, function () { // First Animation complete setTimeout(function(){$('#intro-wrap').fadeOut(4000, function () { // Second Animation complete }); },4000);// Wait for 4 Seconds before starting }); });
{ "pile_set_name": "StackExchange" }
Q: Question potentially off-topic, judment and possible migration needed In regards to this question. I am an IT Professional and I am doing sysadmin work on a network appliance and server on what is my primary business network. However, I do not use it to provide services to clients. None the less, I'm beginning to think the reason I'm getting neither downvotes or answers is that the question rides the line between on-topic and off-topic. I wanted to request a judgement on whether it should be migrated to another site, which site, and (if needed) request a moderator to do so. So, should the linked question be moved? If so, to where? Unix/Linux? A: I read through the question but I don't see anything that would make it obviously off topic, nor did I see anything that suggested any other site in the network would be a better place to ask. You originally posted it on the weekend, when we have fewer people overall reading the site. It looks like you edited it today, which does bring it back to the homepage. But there just aren't a lot of people following questions about snort so it may take a while before someone who can answer it sees it. In such circumstances the usual advice is to continue to add details to the question and offer a bounty. You don't have much reputation yet, so I've put a 500 reputation bounty on the question. Do your part by continuing to add any possibly relevant details to the question. (BTW, you shouldn't add things like "UPDATE:" to the question. The edit history is visible to everyone.)
{ "pile_set_name": "StackExchange" }
Q: How to pass array to rdlc report? I provided a radcombobox to let user select one or more than one department to generate a report (developed by asp.net report (RDLC)). I had developeded the following dataset: SELECT c.DeptID, c.Department, b.Course_Name, b.Course_ID, b.Type, b.Ref_Code, b.Exam FROM dbo.db_Competency_List AS a INNER JOIN dbo.db_Course AS b ON a.Course_ID = b.Course_ID INNER JOIN dbo.db_Department AS c ON a.Dept_ID = c.DeptID where a.Dept_ID in (@Para_DID) It works if user select one department only. but if user select more than one department, it seems that the dataset cannot get the parameter. e.g. 12,33,65,78... Code: <telerik:RadComboBox ID="rcb_select_dept" runat="server" DataSourceID="LDS_ddl_dept" DataTextField="Department" AutoPostBack="True" DefaultMessage="Please Select" DataValueField="DeptID" Width="300" CheckBoxes="true" AllowCustomText="true" > </telerik:RadComboBox> <asp:LinqDataSource ID="LDS_ddl_dept" runat="server" ContextTypeName="dcLRDBDataContext" EntityTypeName="" TableName="db_Departments" OrderBy="Department"> </asp:LinqDataSource> </td> </tr> </table> <br /> <rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="1200px" Height="800px" Font-Names="Verdana" Font-Size="8pt" InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt"> <LocalReport ReportPath="Reports\template\RequiredByDepartment.rdlc"> <DataSources> <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DS_Content" /> </DataSources> </LocalReport> </rsweb:ReportViewer> <br /> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="LRDBDataSetTableAdapters.vReqByDeptTableAdapter"> <SelectParameters> <asp:Parameter DefaultValue="0" Name="Para_DID" Type="String" /> </SelectParameters> </asp:ObjectDataSource> Code behind: Protected Sub rtbMenu_ButtonClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadToolBarEventArgs) Handles rtbMenu.ButtonClick If e.Item.Value = "Generate" Then 'Get DID Dim strCOM_cmb As String = "" For i = 0 To rcb_select_dept.CheckedItems.Count - 1 If rcb_select_dept.CheckedItems(i).Checked = True Then strCOM_cmb += rcb_select_dept.CheckedItems(i).Value.ToString & "," End If Next If Left(strCOM_cmb, 1) = "," Then strCOM_cmb = Right(strCOM_cmb, Len(strCOM_cmb) - 1) End If If Right(strCOM_cmb, 1) = "," Then strCOM_cmb = Left(strCOM_cmb, Len(strCOM_cmb) - 1) End If strCOM_cmb = TrimList(strCOM_cmb) Dim params(0) As Microsoft.Reporting.WebForms.ReportParameter params(0) = New Microsoft.Reporting.WebForms.ReportParameter("Para_DID", strCOM_cmb) ReportViewer1.LocalReport.SetParameters(params) ObjectDataSource1.SelectParameters("Para_DID").DefaultValue = strCOM_cmb ObjectDataSource1.DataBind() Preview() End If End Sub Sub Preview() ReportViewer1.Visible = True ReportViewer1.LocalReport.Refresh() End Sub How can i pass the department ID array (parameter) to the report ? thanks. A: I would suggest you to handle this issue in SQL implementation. Just the optional. To pass text parameter and hope it works as a list, you should represent them in table, after then join your query result to that list in the table. See code below: Create new table variable and insert each member in the list into the table: DECLARE @SelectedDeptIds table ( DeptID int ) DECLARE @deptIdTemp varchar(10), @Pos int SET @Para_DID = LTRIM(RTRIM(@Para_DID))+ ',' SET @Pos = CHARINDEX(',', @Para_DID, 1) IF REPLACE(@Para_DID, ',', '') <> '' BEGIN WHILE @Pos > 0 BEGIN SET @deptIdTemp = LTRIM(RTRIM(LEFT(@Para_DID, @Pos - 1))) IF @deptIdTemp <> '' BEGIN INSERT INTO @SelectedDeptIds (DeptID) VALUES (CAST(@deptIdTemp AS int)) END SET @Para_DID = RIGHT(@Para_DID, LEN(@Para_DID) - @Pos) SET @Pos = CHARINDEX(',', @Para_DID, 1) END END Next code is to join table to the list: SELECT c.DeptID, c.Department, b.Course_Name, b.Course_ID, b.Type, b.Ref_Code, b.Exam FROM dbo.db_Competency_List AS a INNER JOIN dbo.db_Course AS b ON a.Course_ID = b.Course_ID INNER JOIN dbo.db_Department AS c ON a.Dept_ID = c.DeptID INNER JOIN @SelectedDeptIds d ON a.Dept_ID = d.DeptID
{ "pile_set_name": "StackExchange" }
Q: Задача на нахождение в числе подчисла 33 Не получается сделать задачу на C++ Дано число N. Требуется определить, есть ли в данном числе две тройки, идущие подряд. c++ A: while(N) { if (N%100 == 33) return true; N /= 10; } return false; Вариант: return to_string(N).find("33") != string::npos;
{ "pile_set_name": "StackExchange" }
Q: I have 23andme text files and would like to convert to SAM/BAM format I would like to convert 23andme text file to NextGen to BAM file for Yfull.com to read. It is difficult to get answers on how to convert to SAM/BAM file for the 23andme text file to be converted to SAM/BAM tools A: Having done 23andme myself I can tell you that your variant file, which contains SNP genotypes, cannot be converted to a bam file. It does not contain the same information as a bam file. It may be helpful to familiarize yourself with those filetypes and the technologies used to obtain them. A SAM/BAM file contains alignments of reads obtained by sequencing. Your standard* 23andme analysis doesn't have reads, as it uses a SNP array for determining the alleles at predefined positions. Markers which are not included in your 23andme file cannot be added by other means because those were not genotyped by the array. Therefore also Y-DNA cannot use your 23andme file or add additional markers. *For the sake of completeness: I am aware that under rare circumstances 23andme can perform WGS for additional variant typing, but I do not assume this is the case for OP. A: If you just want to get the markers which were not reported/genotyped by 23andMe (as you mentioned in the comment), you don´t want to convert your 23andMe data to SAM/BAM (which is most probably really difficult or impossible, as explained by @Wouter De Coster), but rather to perform imputation on your data file. This will give you a genotype file with genotype or allele probabilities for all the markers. While it will not give you a 100% certainty for the lacking variants, it can certainly give you more information on many of them. NB: you can imputate the Y-chromosome variants only if your 23andMe file contain data from Y-chromosome. If you want to know about that option, let me know. A: I think the closest approximation for a SNP chip would be the intensity values. When I asked 23andMe about obtaining these, the answer was that they don't plan on adding this feature. Some programs use the .vcf file format instead of the 23andMe format, but I think the 23andMe format is compatible with relatively more 3rd party software than some other vendors. If I remember correctly, I think DNA.land even has an intermediate .vcf file, which you can download. I actually think it is important that 23andMe doesn't impute the variants in your genotype table. However, if you are trying to dig deeper into some SNP chip data, I believe you can still get genotyping for free from Genes for Good. They provide a few different "raw data" formats (such as .vcf files, with and without imputation, as well as a "23andMe format" file) and I got the impression that they would consider providing an even more raw form of data (to test the effect of generating genotypes on your own, even thought I don't think most sites will change). However, to be clear, they also do not currently provide intensity values (or some other even more raw form of data).
{ "pile_set_name": "StackExchange" }
Q: wxWidgets mac clipboard on 3.1.3 broken? I am not sure if I am doing something exceedingly stupid but my calls to the clipboard have ceased working since 3.1.3. I stepped into the code and it all works at the lower levels (wxClipboard::AddData returns true). This worked under 3.1.2, which I built on macOS 10.12.6 Sierra with the following configure: configure --disable-shared --enable-unicode --prefix="$(pwd)" --enable-ipc --enable-base64 --enable-exceptions --enable-fontenum --enable-fs_archive --enable-stdpaths --enable-sysoptions --enable-threads --enable-url --enable-aui --enable-graphics_ctx --enable-printarch --enable-timer --enable-ribbon --enable-webview --enable-display --enable-splash --enable-snglinst --enable-printfposparam --with-opengl --with-osx_cocoa --with-expat=builtin --with-cxx=11 --enable-cxx11 --enable-stl --enable-std_iostreams --enable-std_string --enable-ftp --enable-http --enable-fileproto --enable-sockets --enable-ipv6 --enable-dataobj --enable-ipc --enable-any --enable-arcstream --enable-backtrace --enable-cmdline --enable-datetime --enable-debugreport --enable-dynamicloader --enable-exceptions --enable-ffile --enable-file --enable-filehistory --enable-filesystem --enable-fontmap --enable-fs_inet --enable-fs_zip --enable-fsvolume --enable-fswatcher --enable-geometry --enable-sound --enable-stopwatch --enable-streams --enable-tarstream --enable-textbuf --enable-textfile --enable-variant --enable-zipstream --enable-protocol --enable-protocol-http --enable-protocol-ftp --enable-protocol-file --enable-html --enable-htmlhelp --enable-propgrid --enable-svg --enable-clipboard --enable-dnd --enable-accel --with-osx_cocoa --disable-debug_flag --with-libpng=builtin --with-libjpeg=builtin --with-zlib=builtin I know that the base SDK has moved from what it used to be (10.4?) to (10.9) and I do not explicitly specify it so I am going along with the defaults for 3.1.3. For wxWidgets 3.1.3 under the same system I built with the following configure options: configure --disable-shared --enable-unicode --prefix="$(pwd)" --enable-stc --enable-ipc --enable-base64 --enable-exceptions --enable-fontenum --enable-fs_archive --enable-stdpaths --enable-sysoptions --enable-threads --enable-url --enable-aui --enable-graphics_ctx --enable-printarch --enable-timer --enable-ribbon --enable-webview --enable-display --enable-splash --enable-snglinst --enable-printfposparam --with-opengl --with-osx_cocoa --with-expat=builtin --with-cxx=11 --enable-cxx11 --enable-stl --enable-std_iostreams --enable-std_string --enable-ftp --enable-http --enable-fileproto --enable-sockets --enable-ipv6 --enable-dataobj --enable-ipc --enable-any --enable-arcstream --enable-backtrace --enable-cmdline --enable-datetime --enable-debugreport --enable-dynamicloader --enable-exceptions --enable-ffile --enable-file --enable-filehistory --enable-filesystem --enable-fontmap --enable-fs_inet --enable-fs_zip --enable-fsvolume --enable-fswatcher --enable-geometry --enable-sound --enable-stopwatch --enable-streams --enable-tarstream --enable-textbuf --enable-textfile --enable-variant --enable-zipstream --enable-protocol --enable-protocol-http --enable-protocol-ftp --enable-protocol-file --enable-html --enable-htmlhelp --enable-propgrid --enable-svg --enable-clipboard --enable-dnd --enable-accel --with-osx_cocoa --disable-debug_flag --with-libpng=builtin --with-libjpeg=builtin --with-zlib=builtin --with-libtiff=builtin I have written a sample test application to test this and the clipboard seems defunct. If I use the clipboard sample the paste button is disabled. Here's a test application: #include <wx/wx.h> #include <wx/app.h> #include <wx/clipbrd.h> class MainFrame : public wxFrame { protected: wxStaticText* label; public: MainFrame( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 500,300 ), long style = wxDEFAULT_FRAME_STYLE|wxTAB_TRAVERSAL ) : wxFrame(parent, id, title, pos, size, style) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); label = new wxStaticText( this, wxID_ANY, wxT("<pasted text should go here>"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT|wxST_NO_AUTORESIZE ); label->Wrap( -1 ); bSizer1->Add( label, 1, wxALIGN_CENTER_HORIZONTAL|wxALL, 5 ); this->SetSizer( bSizer1 ); this->Layout(); this->Centre( wxBOTH ); if (wxTheClipboard->Open()) { wxTheClipboard->SetData(new wxTextDataObject("Hello this is pasted text")); wxTheClipboard->Close(); } if (wxTheClipboard->Open()) { if (wxTheClipboard->IsSupported( wxDF_TEXT )) { wxTextDataObject data; wxTheClipboard->GetData(data); label->SetLabel(data.GetText()); } wxTheClipboard->Close(); } } virtual ~MainFrame() { } }; class demoApp: public wxApp { MainFrame *frame = nullptr; public: demoApp(); virtual ~demoApp() { } virtual bool OnInit() override; }; IMPLEMENT_APP(demoApp) //#include <ApplicationServices/ApplicationServices.h> demoApp::demoApp() { //ProcessSerialNumber PSN; //GetCurrentProcess(&PSN); //TransformProcessType(&PSN,kProcessTransformToForegroundApplication); } bool demoApp::OnInit() { frame = new MainFrame(nullptr); frame->Show(); SetTopWindow(frame); SetExitOnFrameDelete(true); return true; } You can build that with something like g++ clipboard.cpp -o clipboard -std=gnu++11 -I/DeveloperLibs/wxWidgets-3.1.3/build-debug/lib/wx/include/osx_cocoa-unicode-static-3.1/ -I/DeveloperLibs/wxWidgets-3.1.3/include -D_FILE_OFFSET_BITS=64 -DWXUSINGDLL -D__WXMAC__ -D__WXOSX__ -D__WXOSX_COCOA__ -D_DEBUG=1-stdlib=libc++ -L/DeveloperLibs/wxWidgets-3.1.3/build-debug/lib/ -framework IOKit -framework Carbon -framework Cocoa -framework AudioToolbox -framework System -lwx_baseu-3.1 -lwx_osx_cocoau_adv-3.1 -lwx_osx_cocoau_core-3.1 -liconv -lz -headerpad_max_install_names -lwxregexu-3.1 -lwx_osx_cocoau_qa-3.1 -framework Quartz -lwx_baseu_xml-3.1 -lwxjpeg-3.1 -lwxpng-3.1 -lwxzlib-3.1 -lwxexpat-3.1 -lwxtiff-3.1 -llzma I can't see anything wrong with it at all?? I should note that the same application fails to work under Mojave (with the binary from the Sierra system, or even with the binary built under Mojave using the wxWidgets on my Mojave system). A: Yes, unfortunately copying to clipboard got broken shortly before 3.1.3 release. It was fixed soon after it in this commit that you should be able to cherry-pick locally -- or you could just update to the latest master.
{ "pile_set_name": "StackExchange" }
Q: how to make a text boxes text move back and forth? hello atm I have this code private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { x = 0; timer1.Enabled = true; timer1.Start(); } else { timer1.Enabled = false; } } private int x = 0; private int y = 0; private void timer1_Tick(object sender, EventArgs e) { if (x <= 10) { x++; string ping = new string(' ', x) + "hello"; label1.Text = ping; if (x == 10) { y = 10; } } else if (y > 0) { y--; string pong = new string(' ', y) + "hello"; label1.Text = pong; if (y == 0) { x = 0; } } } at the moment the label has a maximum length of 15 characters and i want it to stay that way. but i want it to instead of using "hello" to take the text i input into a textbox and do it. however it has to take 15 and subtract the length of the textboxes text in order to keep the labels max length of 15 intact while displaying the entire word in the textbox aswell but i cant figure out how to do it i have tried plenty of things but i cannot figure it out any help would be greatly appreciated. :D A: Your use of the words "ping" and "pong", plus your title saying "move back and forth" leads me to believe the result you want can be achieved by changing the TextAlign property of the label upon each tick. If this is the result you want, you won't have to add spaces at all. The text will appear to go from left to right edges in the label. You might consider trimming the text property with TRIM() to ensure no spaces exist on either side that would make it appear aligned incorrectly.
{ "pile_set_name": "StackExchange" }
Q: How can I paint a layer in front, but make it select-able in back? Think Google Chrome's "Inspect Element." When a user mouses over a line in Developer Tools, the element is "highlighted" on the screen. I am trying to replicate the same functionality, except that an element may be highlighted when a user mouses over that element instead of from a list. My problem is this: When I highlight the element (by creating a div with a translucent background color with the same dimensions as the original element and positioned in the same location as the original element), the div has to be painted higher than that element (in order to be visible.) However, in some cases where there are sub elements that should be highlight-able, the "highlight" div is on top, preventing them from being select-able. Some of the elements will have background images or colors, preventing the highlighting from showing up. Also, the markup may contain any number of elements with variating z-index values. I'll update my question to reflect these constraints. I'm looking for any suggestions for work-arounds or alternatives if this is not possible. Here's a fiddle to show what I mean. Thanks in advance! A: You can use CSS3 pointer-events:none;: http://jsfiddle.net/Shmiddty/BU27J/9/ Alternatively, you can use z-index:-1;, but if your "highlighted" elements have a background of their own, you won't see the highlighting div.
{ "pile_set_name": "StackExchange" }
Q: We decided to post a new factorial challenge. Should we close the old one as dupe? The existing factorial challenge has some restrictions on the domain, performance, and banning built-ins. I opened a meta question about it a week ago, and as per the meta consensus, we decided to post a new vanilla factorial challenge. The sandboxed challenge is here. Now the problem is: Should we close the old factorial challenge as a dupe of the new one? Relevant existing meta discussion: 1, 2, 3 A: No, leave both challenges open As Luis Mendo requested in the comment, here is a copy of my statement for voting. I believe it is not a dupe because the solutions to the existing challenge are not likely to be competitive here, and solutions to this one are not likely to be valid on the other. Using Mego's post as the guideline, in my opinion: Is the "meat" of the challenges the same? Not really. The restriction imposed on the old challenge is so hard for languages without infinite-precision integer support, making the "restriction" the core part of the challenge, rather than the factorial-calculating part. Could answers from one be posted to the other, with trivial modifications at most, and be competitive? No, based on the quote above. Which challenge is better? This part is irrelevant since it is about which to leave open assuming they are dupes of each other, and I don't think they are dupes.
{ "pile_set_name": "StackExchange" }
Q: Why is the Euler characteristic for the circle $0$? The Euler characteristic of an edge is $-1$, so what makes the circle different? A: Actually, the Euler characteristic of an edge is $+1$ according to the most common definition. In terms of "triangulations", you can describe the circle as the union of two edges which meet at two vertices so the Euler characteristic is $2 - 2 = 0$. In terms of homology groups, we have $\dim H_0(S^1) = \dim H_1(S^1) = 1$ and $\dim H_i(S^1) = 0$ for $i \geq 2$ so the Euler characteristic is $1 - 1 = 0$. A: You can think of an (open) edge as one $1$-dimensional cell, while a circle as a disjoint union of one $0$-dimensional cell (that is, a point) and one $1$-dimensional cell. Since a common definition of the Euler characteristic is $k_0-k_1+k_2-\cdots$, where $k_i$ denotes the number of $i$-dimensional cells in a cell decomposition of the underlying topological space, we get the answers $-1$ and $0$ for the edge and circle respectively.
{ "pile_set_name": "StackExchange" }
Q: how to implement an email to post system in php I would like to know how to setup a system in php that I could send emails to and the email content would poblish on my blog as a new post and the email subject would be the new post title. Am not using word press or any of those blogging platforms am running my own blogging script and a php 5.x version. I don't even know how to get started on this kind of programming challenge please any one with any ideas is welcomed. Joe A: You would need to create a script that is able to read from your email account. Php has the IMAP library that enables you to read email messages. Check this link to see how you could use the library. You would need to schedule the script to be run at a periodic interval of time (eg. every 5 minutes). In Linux you would setup a cron job to do it. So, I mean the script should be invoked periodically. If it finds a new message, it would then update your blog by taking the body of the email.
{ "pile_set_name": "StackExchange" }
Q: Why we add a value to initialize the stack pointer (R7) in assembly? I'm currently new into assembly. I know that we first need to allocate the dimension of the stack (in the example below is 1000). However I struggle to understand why we should add a value (in this case #999) to initialize the stack pointer. Here's the pseudo-assembly: STACK: .RES 1000 MOV #STACK, SP ADD #999, SP A: To allocate space on the stack, the stack pointer is decremented (i.e. the stack grows down). Thus, in order to use the buffer STACK for the stack, the stack pointer has to initially point to the end of STACK so decrementing the stack pointer makes it point to new parts of STACK.
{ "pile_set_name": "StackExchange" }
Q: Token based authentication and multiple sessions I've a token based authentication system (REST) that I inherited for an iOS app (can't change), and I've to re-use the same authentication web api system (that I can change to adapt for the web requests while still accommodating iOS app). Here's how the authentication system works. username, password -> if valid a token is returned to the user and also saved to the database getNewToken -> passes the old authToken, web api verifies from the table, issues a new token, updates the database table 1 is triggered by user login while 2 is automated interval based call every 15 minutes by the iOS app (I guess to keep the session alive, like heart beat) Now when user is on the web and logs in, I call #1 to get the token but then if user is already on the device, the old token at device won't work because it got updated on the server as a result of user signing on the web. This makes me wonder and in the light of above scenario my question is how multiple sessions are handled using authentication token system out there in real life, for instance I could open gmail or Facebook in two different browsers and both sessions are maintained (I'm not sure if they are using token based system or some other but let's say they are for an example). Please advise. A: Yes if id is id of the device cause you need to store device id in some place. If you can install programs on the server better to store login tokens not in database but in some external key value storage like redis or memcached, if you can do it of course.
{ "pile_set_name": "StackExchange" }
Q: MPAndroidChart fill color gradient Is it possible with MPAndroidChart (or any other Android chart library) to fill the chart under the draw line with a gradient color? Something like this: set1.setFillColor(getResources().getColor(R.drawable.chart_fill)); then in chart_fill.xml: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="90" android:endColor="#FF207a54" android:startColor="#FFffffff" /> </shape> A: You can use the following two methods: LineRadarDataSet#setDrawFilled(boolean isFilled); LineRadarDataSet#setFillDrawable(Drawable d); Here's a link to the javadoc for that class. This is the example from the MPAndroidChart sample project: set1.setDrawFilled(true); if (Utils.getSDKInt() >= 18) { // fill drawable only supported on api level 18 and above Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red); set1.setFillDrawable(drawable); } else { set1.setFillColor(Color.BLACK); } In fade_red.xml: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="90" android:startColor="#00ff0000" android:endColor="#ffff0000" /> </shape> Here's a sample of what it looks like on a LineChart: A: Okay i have found a solution: William Chart and i am using this method: int[] colors = { getResources().getColor(R.color.menu_text), getResources().getColor(android.R.color.white) }; float[] index = { 0, 1 }; dataset.setGradientFill(colors, index);
{ "pile_set_name": "StackExchange" }
Q: When installing the software that was developed using NSIS, how should I throw a pop-up message if installing in server operating systems When installing the software that was developed using NSIS, how should I throw a pop-up message if installing in server operating systems. Below are the unsupported operating systems. In those when installing the software i should show the popup message. Windows Server 2003 Windows Server 2003 R2 Windows Server 2008 Windows Server 2008 R2 Windows Server 2012 Windows Server 2012 R2 I am facing difficulty to implement this. Could any one please guide me on this? A: You can use WinVer.nsh to detect Windows versions !include "LogicLib.nsh" !include "WinVer.nsh" Function .onInit ${If} ${IsServerOS} MessageBox MB_OK "Running on Windows Server." Quit ${EndIf} FunctionEnd If you need to be more specific, you can combine this with at AtLeastWin* / AtMostWin*, where * is the version you're targeting (e.g. AtLeastWin2003 / AtLeastWin2012R2)
{ "pile_set_name": "StackExchange" }
Q: Como evitar que el boton dropdown de bootstrap se oculte al hacer click dentro de el? Tengo el siguiente boton: es un dropdown, no pongo el codigo completo por que no es necesario. <button type="button" onclick="dropdownEvent(this);" class="btn btn-link text-default btn-herramienta" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Color de fondo </button> El dropdown funciona bien, lo que quiero es evitar que se cierra automaticamente cuando le doy click dentro de el y cuando se de click fuera de el pues que se cierre, como haria eso? gracias. A: Cogí el código de ejemplo de dropdown de bootstrap de la siguiente pagina $('.dropdown-menu').on('click', function (e) { e.stopPropagation(); console.log(`${e.target.textContent} clicado!`); }); <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Ejemplo dropdown <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">Primera opcion</a></li> <li><a href="#">Segunda opcion</a></li> <li><a href="#">Tercera opcion</a></li> </ul> </div> La idea es que debes "capturar" cuando haces click y cancelar la desaparición del elemento, sustituyendolo por lo que quieras.
{ "pile_set_name": "StackExchange" }
Q: Como ocultar numa URL o texto que aparece após o meu domínio? Tenho uma aplicação Java utilizando Spring MVC. Suponhamos que a minha aplicação tenho o domínio www.meusistema.com.br Conforme o usuário navega, outras urls são geradas, exemplo: www.meusistema.com.br/acessarConta www.meusistema.com.br/cadastros/recuperarSenha www.meusistema.com.br/cadastrar?tipo=1 Gostaria de saber se existe alguma forma de ocultar o que aparece depois da barra (/), e portanto o meu usuário sempre navegar apenas vendo www.meusistema.com.br Existe alguma forma de ocultar esse restante da url? A aplicação utiliza Spring MVC mas a solução pra isso não necessariamente precisa usar esse framework... Minhas telas são em JSP, então posso usar javascript, ajax, jquery etc. A: Solucionei o problema mudando todos os forms do html para POST, definindo então no Controller o que aparece na URL.
{ "pile_set_name": "StackExchange" }
Q: Adding sub command sqlall to manage.py I am a beginner in web development using Django framework. While trying to work on mysql database . python manage.py sqlall appname It gives out the following error Unknown command: '--sqlall' Type 'manage.py help' for usage. How to add a sub command sqlall to manage.py.(i'm not trying to implement it)? A: The sqlall management command was removed in Django 1.9, along with syncdb. Since Django 1.7, you shouldn't use syncdb. Instead, you should create migrations with makemigrations and perform the migrations with migrate. If you work through the polls tutorial, it explains how to use migrations. There is now an sqlmigrate command that displays the sql commands for a specific migration, without performing the migration.
{ "pile_set_name": "StackExchange" }
Q: Gzip use short path for files and directories I am creating gz of all static files in build directory dist. gzip -fkqr ./dist/*.html ./dist/*.css ./dist/*.js ./dist/css/*.css ./dist/js/*.js 2>/dev/null Here f is --force, k is --keep, q is --quiet and r is --recursive. It is possible to make the path shorter? I tried this but not working. gzip -fkqr ./dist/*.{html,css,js} ./dist/{css,js}/*.{css,js} 2>/dev/null Update #1 The output for shopt | grep glob is dotglob off extglob off failglob off globasciiranges off globstar off nocaseglob off nullglob off Update #2 The output for echo $- is himBHs A: Your solution generates more entries then you want. $ echo gzip -fkqr ./dist/*.html ./dist/*.css ./dist/*.js ./dist/css/*.css ./dist/js/*.js 2>/dev/null gzip -fkqr ./dist/*.html ./dist/*.css ./dist/*.js ./dist/css/*.css ./dist/js/*.js $ echo gzip -fkqr ./dist/*.{html,css,js} ./dist/{css,js}/*.{css,js} 2>/dev/null gzip -fkqr ./dist/*.html ./dist/*.css ./dist/*.js ./dist/css/*.css ./dist/css/*.js ./dist/js/*.css ./dist/js/*.js ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I guess the gzip fails with no such file or directory kind-of message, which you don't see, because you deliberately 2>/dev/null. I guess you want: gzip -fkqr ./dist/*.{html,css,js} ./dist/{css/*.css,js/*.js} or maybe: gzip -fkqr ./dist/{*.{html,css,js},css/*.css,js/*.js}
{ "pile_set_name": "StackExchange" }
Q: Replacing std::async with own version but where should std::promise live? I'm using vc2011 and it turns out the std::async(std::launch::async, ... ) is a bit buggy (sometimes it does not spawn new threads and runs them in parallel, but instead reuses threads and runs task one after another). This is too slow when I'm doing expensive network calls. So I figured I'd write my own async function. I'm getting stuck though, where should std::promise live? In the 1) thread function, 2) async function, or 3) caller function. Code: #include <future> #include <thread> #include <iostream> #include <string> #include <vector> std::string thFun() { throw std::exception("bang!"); return "val"; } std::future<std::string> myasync(std::promise<std::string>& prms) { //std::future<std::string> myasync() { //std::promise<std::string> prms; //needs to outlive thread. How? std::future<std::string> fut = prms.get_future(); std::thread th([&](){ //std::promise<std::string> prms; //need to return a future before... try { std::string val = thFun(); prms.set_value(val); } catch(...) { prms.set_exception(std::current_exception()); } }); th.detach(); return fut; } int main() { std::promise<std::string> prms; //I really want the promise hidden iway in the myasync func and not live here in caller code but the promise needs to outlive myasync and live as long as the thread. How do I do this? auto fut = myasync(prms); //auto fut = myasync(); //Exception: future already retrieved try { auto res = fut.get(); std::cout << "Result: " << res << std::endl; } catch(const std::exception& exc) { std::cout << "Exception: " << exc.what() << std::endl; } } I cant seem to get past the fact that the std::promise needs to outlive the async function (and live as long as the thread), so the promise cant live as a local variable in the async func. But the std::promise shouldn’t live in in the caller code either, as the caller only need to know about futures. And i dont know how to make the promise live in the thread function as async needs to return a future before it even calls the thread func. I’m scratching my head on this one. Anyone got any ideas? Edit: I'm highlighting this here as the top comment is a bit misinformed. While the default for std::asycn is allowed to be the dererred mode, when a launch policy of std::launch::async is explicitly set it must behave "as if" threads are spawned and run at once (see wording in en.cppreference.com/w/cpp/thread/async). See the example in pastebin.com/5dWCjjNY for one case where this is not the behavioured seen in vs20011. The solution works great and sped up my real world application by a factor of 10. Edit 2: MS fixed the bug. More info here: https://connect.microsoft.com/VisualStudio/feedback/details/735731/std-async-std-launch-async-does-not-behave-as-std-thread A: Here is one solution: future<string> myasync() { auto prms = make_shared<promise<string>> (); future<string> fut = prms->get_future(); thread th([=](){ try { string val = thFun(); // ... prms->set_value(val); } catch(...) { prms->set_exception(current_exception()); } }); th.detach(); return fut; } Allocate promise on the heap, and then pass-by-value [=] a shared_ptr to it through to the lambda. A: You need to move the promise into the new thread. Andrew Tomazos's answer does it by creating a std::promise with shared ownership, so that both threads can own the promise, and when the current one returns from the current scope only the new thread owns the promise, i.e. the ownership has been transferred. But std::promise is movable so it should be possible to move it directly into the new thread, except that the "obvious" solution of capturing it doesn't work because lambda's can't capture by move, only by copy (or by reference, which wouldn't work as you'd get a dangling reference.) However, std::thread supports passing rvalue objects to the new thread's start function. so you can declare the lambda to take a std::promise argument by value, i.e. pass the promise to the lambda rather than capturing it, and then move the promise into one of the arguments of the std::thread e.g std::future<std::string> myasync() { std::promise<std::string> prms; std::future<std::string> fut = prms.get_future(); std::thread th([&](std::promise<std::string> p){ try { std::string val = thFun(); p.set_value(val); } catch(...) { p.set_exception(std::current_exception()); } }, std::move(prms)); th.detach(); return fut; } This move the promise into the std::thread object, which then moves it (in the context of the new thread) into the lambda's parameter p.
{ "pile_set_name": "StackExchange" }
Q: Delete .xlsx or .pdf after closing file I'm trying to delete .xlsx or .pdf files after using them. When files are created I display them, but then users want automatic file deletion after closing them. I've tried couple of things, but none of them seem to work properly. Issue: When opened multiple files (.xlsx or .pdf) I can't terminate a single process, like just a single file. Instead what happens is that file get's deleted only when I close all same processes (Excel or PDF files). As I investigated this happens because Excel or PDF works as one instance only. However code works as expected when I have only one file opened... This is what I have so far: var process= Process.Start(file_path); //file_path is global variable Set_event(process); private void Set_event(Process process) { process.EnableRaisingEvents = true; process.Exited += new EventHandler(Delete_File); } public void Delete_File(object sender, EventArgs e) { //Delete file on close File.Delete(file_path); } I've also tried with DeleteOnClose method of FileOptions, but unfortunally that doesn't display file to user and doesn't quite delete file immediately after using them, only after my win app is closed. That isn't my desired output, but at least files are deleted, so If I could fix that I would be partially satisfied too. Here is my line for that: var open_file = new FileStream(file_path,FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite, 512, FileOptions.DeleteOnClose); With all that said, are there any other options I missed ? Thanks for help in advance. A: I've tried almost everything I could find (different variations of Exited_Event for Process, monitoring with FileSystemWatcher, creating files with DeleteOnClose - even API), but none of them worked as expected. Everything ends or fails with issue I described in first place - some apps, like Microsoft Excel or Adobe Acrobat uses one instance to open a file (.pdf or .xls/.xlsx), so you can't just reference a single file as object while you have opened more files. That means you either end up with an error when trying to assign Exited_event to single file, or no error but file gets deleted only when you close all files with same type... BUT fortunate enough I figured out one thing: WHEN you have opened more than one file in question (.pdf or .xlsx) something happens in background of OS: If you loop through processes of same type at that time, you'll get a list of particular instance that is in use. In other words, while you have 2 Excel files opened, loop through processes is showing you only a file which is currently active for "EXCEL" process. So, that leaded me to a completely new approach that might solve this issue. In order to have a complete solution for this you have to: 1. Create a method to check whether file is no longer in use. 2. Set a Timer with a delay of 2 seconds, to make sure process really ends. Maybe this should be incremented for different purposes... 3. Set a Timer_tick event, where you loop processes to see whether particular file is listed as active, and If user has already closed this file. As described by other users this method isn't quite accurate, but with setting delay for Timer I think there shouldn't be any problems anymore. Here is a complete code for this (for .pdf and .xlsx - that is what I needed): //as global variable System.Windows.Forms.Timer delete_file = new System.Windows.Forms.Timer(); Process.Start(file_path); //file_path is global variable delete_file.Tick += new EventHandler(timer_Tick); delete_file.Interval = (2000); delete_file.Enabled = true; delete_file.Start(); private void timer_Tick(object sender, EventArgs e) { Boolean file_is_opened = false; // Loop processes and list active files in use foreach (var process in Process.GetProcesses()) { if (process.MainWindowTitle.Contains(Path.GetFileName(file_path))) { file_is_opened = true; } } //If our file is not listed under active processes we check //whether user has already closed file - If so, we finally delete It if (file_is_opened==false) { if (!File_In_Use(new FileInfo(file_path))) { File.Delete(file_path); delete_file.Enabled = false; delete_file.Stop(); return; } } } private bool File_In_Use(FileInfo file) { //Method to check whether file is in use FileStream stream = null; try { //If file doesn't exist if (!file.Exists) { return false; } stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //File is unavailable: //because someone writes to It, or It's being processed return true; } finally { if (stream!=null) { stream.Close(); } } //File not locked return false; } This is how I did It. It might not be a perfect solution, but that works for me on Win 10 with no errors so far. If someone has a suggestion to fix upper code, please let me know. Otherwise I hope this will help someone in future as I noticed there were already some questions about this in past, with no proper answer.
{ "pile_set_name": "StackExchange" }
Q: getting error when trying to use jquery fileUpload I'm letting the user select files and then trying to programmatically uploading them after they click the upload button using the jquery fileupload script The HTML looks like this: <input name="my_image[]" id="my_file" type="file" multiple="multiple"> The jquery call looks like this: $('#start-upload').click(function(e) { var filesList = $('#my_file')[0].files; //var filesList = $('#my_file').prop("files"); var url = 'photos/index.php'; $('#my_file').fileupload('send', { files: filesList, url: url, dataType: 'json', start: function(e, data) { console.log("Upload started"); }, done: function (e, data) { console.log("Upload complete"); } }); }); This is the error I get: Uncaught Error: cannot call methods on fileupload prior to initialization; attempted to call method 'send' Any idea what I'm doing? A: It wasn't initialized. Ensure you first have something like: $(document).ready(function(){ $('#my_file').fileupload({ url: 'your_url' ...} ); }); Cheers
{ "pile_set_name": "StackExchange" }
Q: Not able to create equal gap between two div's because of image element inside one of the div Looking at this image might make things clear.. FIDDLE The main container is a div in which there are 5 more div's each of them holding some data. If the count for that data is 0 then , just display the text . If the count is greater than 0 , then shown count and image nested inside a span and the image and number are clickable... The second image is to show how the text inside the div is being rendered.. Because of the image in the 3rd and the 5th div's the gap between the div's is not being consistent . Even after setting the image to position:relative and position:absolute , setting the left and top property seems to have no affect .. Can someone help me out in this context .. HTML <div id="prop"> <div id="lvl1" class="alrt"> Missing reads within 1 week : <span data-tr="1">0</span> </div> <div id="lvl2" class="alrt"> Latest reads 1 Week or older : <span data-tr="2">0</span> </div> <div id="lvl3" class="alrt"> Occupied Zero Consumption : <span data-tr="3"><a>39 <img src="../icon1.png" title="" /></a></span> </div> <div id="lvl4" class="alrt"> Negative Consumption : <span data-tr="4">0</span> </div> <div id="lvl5" class="alrt"> Vacant Consumption: <span data-tr="5"><a>5 <img src="../icon2.png" title="" /></a></span> </div> <div class="msg"> *all alerts are based on yesterdays reads </div> </div> CSS #prop { height:55%; padding-top:10px; border:solid 2px #B2CD48; border-radius:10px; margin:10px 0 10px 15px; } #prop > .alrt { width:80%; float:right; height:12%; font-weight:700; font-size:1em; color:#42456B; padding:3px; } .alrt a { cursor:pointer; position:relative; } .alrt > span > a > img { width:20px; height:20px; position:relative; top:3px; } A: Try using this for .alrt > span > a > img .alrt > span > a > img { width: 20px; height: 20px; position: absolute; top: -3px; }
{ "pile_set_name": "StackExchange" }
Q: Can is_lock_free() return true for some data types and false for another one? I know that is_lock_free depends on the hardware but when I used it on an ADT it returned false but true with int type. How this can be? #include <iostream> #include <atomic> struct myType { size_t ID{}; size_t to{}; }; int main() { std::atomic<myType> i{ }; std::cout << "\n" << i.is_lock_free(); std::atomic j { 1}; std::cout << "\n" << j.is_lock_free(); } A: Can is_lock_free() return true for some data types and false for another one? Yes, it can. It is possible for the shown program to output 0 1. In fact, if this wasn't the case, then there would be no point for the function to be a member of a template.
{ "pile_set_name": "StackExchange" }
Q: showAsAction="always" does not work when in two-pane mode I tried setting the menu items in my app as actions with app:showAsAction="always". This works on a phone and also on the tablet when I use the same layout. But when I use a two-pane layout, the items don't show up in the action bar but in the overflow menu even though there is plenty of room. Here is the menu xml: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/menu_item_maps" android:icon="@drawable/ic_action_place" android:orderInCategory="20" android:title="@string/maps_menu_item" app:showAsAction="always"> </item> <item android:id="@+id/menu_item_event" android:icon="@drawable/ic_action_event" android:orderInCategory="30" android:title="@string/menu_item_event" app:showAsAction="always"> </item> <item android:id="@+id/menu_item_share_gig" android:orderInCategory="100" android:title="@string/menu_item_share" app:actionProviderClass="android.support.v7.widget.ShareActionProvider" app:showAsAction="always"> </item> </menu> Here is the two-pane layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:baselineAligned="false" android:divider="?android:attr/dividerHorizontal" android:orientation="horizontal" android:showDividers="middle" > <fragment android:id="@+id/gig_list" android:name="de.nobodyknows.app.GigListFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/> <FrameLayout android:id="@+id/gig_detail_container" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" /> </LinearLayout> In my code I use the callback method to replace the FrameLayout with a detail fragment: /** * Callback method from {@link GigListFragment.Callbacks} indicating that * the item with the given ID was selected. */ @Override public void onItemSelected(Long id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle arguments = new Bundle(); arguments.putLong(GigDetailFragment.GIG_ID, id); GigDetailFragment fragment = new GigDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.gig_detail_container, fragment).commit(); } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, GigDetailActivity.class); detailIntent.putExtra(GigDetailFragment.GIG_ID, id); startActivity(detailIntent); } } The detail Fragment inflates the options menu that was shown above: @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.detail, menu); } Now these menu items show up fine in the phone layout when a new acticity is started. But when the fragment replaces the FrameLayout in the first activity, the menu items just show up in the overflow menu. I can't figure out why that happens, though. Has it something to do with the support library? Or is it something special about how fragments work? Thanks for your help. A: Okay, I found the solution. My Activity did not extend theActionBarActivityand therefore was not correctly set up to work with MenuItemCompat. The reason why it still worked on the phone was because that was in a different Activity that correctly extended ActionBarActivity. To correct this I just replaced the superclass of the Activity that acts as the two-pane Activity to be ActionBarActivity.
{ "pile_set_name": "StackExchange" }
Q: OpenGL Question about scaling 3D Object I got some scaled cubes (1, 2.5, 1) in a 3D Space with a grounded floor with position (0, 0, 0) and scale (100, 0, 100) like in the picture. But why are the cubes scaled out from the center. I want to level them on top of the ground. This is my matrix manipulation code: Matrix4f.scale(scale, mMatrix, mMatrix); Matrix4f.translate(position, mMatrix, mMatrix); So how is OpenGL scaling my cube, How can I level it? A: You need to translate them before scaling them. Otherwise, the entire coordinate space is scaled. For example: // Scale the coordinate space by two. Matrix4f.scale( 2, 2, 2 ); // Now because of the scale this is the same as translating by 2 in every axis. Matrix4f.translate( 1, 1, 1 ); // Actually means Matrix4f.translate( 2, 2, 2 ) here. When you transform you are transforming the coordinate space, not the object. If you translate, scale then rotate, the transformations should have no effect on each other. That's one of your problems, potentially. Your cubes are scaling from the center because that is where the origin is in model space. Each vertex of your cube is placed relative to the center( 0, 0, 0 ) of the cube. To change this either make your model origin the bottom center( I don't recommend this ) or translate up by half the cubes height after scaling. EDIT: To go more in depth about why your cubes are scaled from ( 0, 0, 0 ), you should understand how vectors work. All vectors have an origin and a distance from that origin( unlike a point, which just has a location ), this origin is zero. To scale a matrix, we can simply multiply it by a scalar: Vector3( 1, 1, 1 ) * 2 = Vector3( 2, 2, 2 ) This doubles each component of the vector. Similarly, if we scale the up vector by, say, 5, we get: Vector3( 0, 1, 0 ) * 5 = Vector3( 0, 5, 0 ) This is just simple arithmetic. This vector is scaled up to 5 units. It is now 5 times higher than it was before, however the x and z components remain unchanged, because they are 0. So, each of the vertices that make up your cubes have a vector to describe where they are. They are all relative to some origin( ( 0, 0, 0 ) in this case ). So, if we have a cube made up of the following vectors: Top ( -0.5, 0.5, -0.5 ), ( 0.5, 0.5, -0.5 ), ( -0.5, 0.5, 0.5 ), ( 0.5, 0.5, 0.5 ) Bottom ( -0.5, -0.5, -0.5 ), ( 0.5, -0.5, -0.5 ), ( -0.5, -0.5, 0.5 ), ( 0.5, -0.5, 0.5 ) We can see how these are scaled. Let's take one of the top vectors and scale it by the up vector * 5: New Vector = ( -0.5, 0.5, -0.5 ) * ( 0, 5, 0 ) New Vector = ( -0.5, 2.5, -0.5 ) So, this vector has been scaled upwards. Great, just like you were expecting( although only half as much ). Now let's try one of the bottom vectors: New Vector = ( -0.5, -0.5, -0.5 ) * ( 0, 5, 0 ) New Vector = ( -0.5, -2.5, -0.5 ) This vector scaled downwards instead because it was negative to begin with. So, if we scale by a positive number, it's just going to get further away from the origin, the same with the top vectors. They just have different directions. You might wonder why the cube is constructed like this. The cube's origin is 0, 0, 0( this is chosen to simplify things like placing the object, and scaling. Like I said, the origin doesn't have to be 0, 0, 0, but it's a good idea ) so, to get a cube of area 1, we want the total length between vectors in each component to be 1. So, you can see how it works mathematically. Technically the origin is as arbitrary as the bottom center of the cube. Having weird origins can be a pain when scaling though.
{ "pile_set_name": "StackExchange" }
Q: solaris svm and raid5 : a way for expand on fly? I know two methods for expand raid5 on solaris svm using UFS one is this another is to replace disk by disk,suppose i want to remove old small disk and replace with bigger disk using this procedure devfsadm cfgadm -c configure sata2/0 format -d c0t5d0 metadb -a -f c0t5d0s2 metareplace -e myraid c0t4d0s2 c0t5d0s2 metadb -d c0t4d0s2 cfgadm -c unconfigure c0t4d0s2 I have replaced all disks with the method above and my raid5 is online and ok as metastat said But after give metadevadm -vr and growfs -M /raid /dev/md/rdsk/d44 The SIZE is the same as raid with old disks and this is wrong because i replaced disks with bigger disks. On linux is really easy to replace raid5 disk on fly and grow the raid5 (mdadm fail,add,grow,then pvresize..) on fly,i miss something on solaris svm? The first method is also good(concatenate+growfs) but i want to replace disks old(small) with new(big). Please don't answer zfs,for "study" reason i'm on ufs+svm A: It's been awhile since I've had to touch SVM, but I'm inclined to agree with BitsOfNix that it's not possible to do what you are trying to do. Memory is that you can only do what you're trying to do with RAID 1 on SVM. Did you verify that metastat sees that the blocksizes have changed for the larger disks and the "RAID device?" I think you're also missing a step prior to your growfs. Memory is that you need to expand the slice of "RAID device" prior to the growfs. And with RAID1 on SVM, then a metasync for the mirroring? You might need to do something similar for RAID5 on SVM. You mention doing this for a "study," but I'm not sure it's fair to ding SVM compared to mdadm since SVM was created and used in a different time to meet a different need.
{ "pile_set_name": "StackExchange" }
Q: Is the voice casting done before or after computer graphics? In animated motion films, is the voice casting done before or after computer graphics animations? A: Normally it is done before the animation. The voice acting is done and then the animators will match the animation of the characters to the voice. They will sometimes use the movement of the actors too. In Aladdin a lot of the genies movements and behaviours can be seen in footage of Robin Williams delivering the lines. It also allows the actors to ad-lib lines that are the put into the movie. You can see some of what I mentioned here although I’m sure there are better videos...
{ "pile_set_name": "StackExchange" }
Q: Why isn't my for loop using the updated global variable? I am writing a script that places markers on a map. To decode the zip code into latitude and longitude I use the Geocoder function. This function updates the global variable. But I can't get the loop to use the updated variable. I've struggled for a while, but can't figure out why the for loop is not using the updated variable. Can someone take a look? Thx in advance. AndereKlant1 = { title: '<strong>Naam</strong><br>\ Dienst', lat: 51.986847, long: 5.955350, adres: "1011AC", geocodeLat: "", geocodeLong: "", }; /* AndereKlant2 = { title: '<strong>Naam</strong><br>\ Dienst', lat: 51.986846, long: 5.955350, adres: "", geocodeLat: "" , geocodeLong: "" , }; */ locations = [ [AndereKlant1.title, AndereKlant1.geocodeLat, AndereKlant1.geocodeLong, 0], // [AndereKlant2.title, AndereKlant2.lat, AndereKlant2.long, 0], ]; function initMap() { geocoder = new google.maps.Geocoder(); var iconAanvraag = { url: 'link to icon', }; var iconDienstverlener = { url: 'http://icons.iconarchive.com/icons/paomedia/small-n-flat/32/map-marker-icon.png', }; var iconBestaandeklanten = { url: 'http://icons.iconarchive.com/icons/double-j-design/origami-colored-pencil/32/yellow-home-icon.png', }; geocoder.geocode({ 'address': AndereKlant1.adres }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { // no need to define it in outer function now AndereKlant1.geocodeLat = results[0].geometry.location.lat(); AndereKlant1.geocodeLong = results[0].geometry.location.lng(); /* alert(AndereKlant1.geocodeLat); alert(AndereKlant1.geocodeLong); */ } else { alert("Geocode was not successful for the following reason: " + status); } }); var map = new google.maps.Map(document.getElementById('map'), { disableDefaultUI: true, zoomControl: true, scaleControl: false, rotateControl: true, fullscreenControl: true, gestureHandling: 'cooperative' }); var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, polylineOptions: { strokeColor: "#036396", strokeOpacity: 0.6, strokeWeight: 6, }, suppressMarkers: true, }); var infowindow = new google.maps.InfoWindow({}); var marker, i; for (i = 0; i < locations.length; i++) { // alert(locations[0][1]); marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map, icon: iconBestaandeklanten, }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } A: Accessing the Geocoding service with geocoder.geocode(...) is asynchronous. This means that the request to the service is made in the background and it takes some time to finish. The callback function (function(results, status) {...}) that you pass to the geocode method gets executed when the Geocoding service responds with the result of the request. In the meantime, while the request is being processed in the background, your code continues to run and the for-loop gets executed before the Geocoding service has responded with the updated coordinates. So if you want to update the position of your markers with data from the Geocoding request, you should put your for loop inside the callback function that you pass to geocoder.geocode method. Example: geocoder.geocode({ 'address': AndereKlant1.adres }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { locations[0][1] = results[0].geometry.location.lat(); locations[0][2] = results[0].geometry.location.lng(); for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map, icon: iconBestaandeklanten, }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } else { alert("Geocode was not successful for the following reason: " + status); } }); Also, keep in mind that changing the values AndereKlant1.geocodeLat and AndereKlant1.geocodeLong does not update the values in the locations array. The locations array has copies of the values from AndereKlant1. Reference: Google Docs
{ "pile_set_name": "StackExchange" }
Q: create symbolic links in windows How to create symbolic links in magento2 folder for pwa studio installation. In linux using by ln command But in windows, How to do?can anyone brief about this A: You can use the command as follows: ln [-fs] [-L|-P] source_path target_path Where, -f Force existing destination pathnames to be removed to allow the link. -L For each source_file operand that names a file that is a symbolic link, create a hard link to the file referenced by the symbolic link. -P For each source_file operand that names a file that is a symbolic link, create a (hard) link to the symbolic link itself. Hope this will help you
{ "pile_set_name": "StackExchange" }
Q: Integration Problem Through Parts or u-substitution? I have this integral I need to solve, and I am not sure if I did this correctly, or how to do it even if this way isn't correct. $$ \int \frac{x}{\sqrt{x+5}} dx $$ I've tried to do it through integration by parts, but it doesn't seem to make it much easier. I am not very good with the math notation on here so I can't really show you what I tried but I've tried setting $u = \frac{1}{\sqrt{x+5}}$ and $dv = x dx$. A: $$\int \frac{x}{\sqrt{x+5}}dx=\int \frac{x+5}{\sqrt{x+5}}dx-\int \frac{5}{\sqrt{x+5}}dx$$ $$=\int \sqrt{x+5}dx-\int \frac{5}{\sqrt{x+5}}dx$$ $$=\frac23(x+5)^\frac32-10\sqrt{x+5}$$
{ "pile_set_name": "StackExchange" }
Q: WPF DataGrid - Creating a new custom Column I am trying to create my own checkbox column (replacing the default one), in order to move to more complex data columns later-on, and I have the following code: public class MyCheckBoxColumn : DataGridBoundColumn { protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var cb = new CheckBox(); var bb = this.Binding as Binding; var b = new Binding { Path = bb.Path, Source = cell.DataContext }; cb.SetBinding(ToggleButton.IsCheckedProperty, b); return cb; } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { var cb = new CheckBox(); var bb = this.Binding as Binding; var b = new Binding { Path = bb.Path, Source = ToggleButton.IsCheckedProperty }; cb.SetBinding(ToggleButton.IsCheckedProperty, b); return cb; } protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { var cb = editingElement as CheckBox; return cb.IsChecked; } protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { var cb = editingElement as CheckBox; if (cb != null) cb.IsChecked = (bool)uneditedValue; } protected override bool CommitCellEdit(FrameworkElement editingElement) { var cb = editingElement as CheckBox; BindingExpression binding = editingElement.GetBindingExpression(ToggleButton.IsCheckedProperty); if (binding != null) binding.UpdateSource(); return true;// base.CommitCellEdit(editingElement); } } And my custom DataGrid: public class MyDataGrid : DataGrid { protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e) { try { var type = e.PropertyType; if (type == typeof(bool)) { var col = new MyCheckBoxColumn(); col.Binding = new Binding(e.PropertyName) {Mode = BindingMode.TwoWay}; e.Column = col; } else { base.OnAutoGeneratingColumn(e); } var propDescr = e.PropertyDescriptor as System.ComponentModel.PropertyDescriptor; e.Column.Header = propDescr.Description; } catch (Exception ex) { Utils.ReportException(ex); } } } Now, everything seems nice except for two things: It seems that the only used method in in MyCheckBoxColumn is the GenerateElement(). All the other methods are not used. I have put breakpoints in them and they never get hit... I use an ObservableCollection as a data source and, while the rest of the columns notify me when they get changed, this one doesn't. The odd thing is that the bool value gets changed when you check/uncheck the checkbox, but without notification and without passing through CommitCellEdit(). Does anyone know what is going wrong here? EDIT : It seems that if I return a TextBlock from inside GenerateElement() it makes the other methods to be called (the notification problem doesn't get fixed though). But why doesn't this work with with CheckBoxes? How does the default check box column work??? A: OK. Here is the complete code for a custom CheckBox column. It seems that, in order to have a control like a checkbox as a display (not editing) element in a DataGrid you have to make it hit-test-invisible. Or you can simply use a TextBlock to display some character that resembles a checkmark: public class MyCheckBoxColumn : DataGridBoundColumn { protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var cb = new CheckBox() { IsHitTestVisible = false, HorizontalAlignment = HorizontalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Center }; var bb = this.Binding as Binding; var b = new Binding { Path = bb.Path, Source = dataItem, Mode = BindingMode.TwoWay }; cb.SetBinding(ToggleButton.IsCheckedProperty, b); return cb; // var cb = new TextBlock() { TextAlignment = TextAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; // var bb = this.Binding as Binding; // var b = new Binding { Path = bb.Path, Source = dataItem, Mode = BindingMode.TwoWay, Converter = new MyBoolToMarkConverter() }; // cb.SetBinding(TextBlock.TextProperty, b); // return cb; } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { var cb = new CheckBox() { HorizontalAlignment = HorizontalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Center }; var bb = this.Binding as Binding; var b = new Binding { Path = bb.Path, Source = dataItem, Mode = BindingMode.TwoWay }; cb.SetBinding(ToggleButton.IsCheckedProperty, b); return cb; } protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { var cb = editingElement as CheckBox; if (cb != null) return cb.IsChecked; return false; } protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { var cb = editingElement as CheckBox; if (cb != null) cb.IsChecked = (bool)uneditedValue; } protected override bool CommitCellEdit(FrameworkElement editingElement) { // The following 2 lines seem to help when sometimes the commit doesn't happen (for unknown to me reasons). //var cb = editingElement as CheckBox; //cb.IsChecked = cb.IsChecked; BindingExpression binding = editingElement.GetBindingExpression(ToggleButton.IsCheckedProperty); if (binding != null) binding.UpdateSource(); return true;// base.CommitCellEdit(editingElement); } } //-------------------------------------------------------------------------------------------- public class MyBoolToMarkConverter : IValueConverter { const string cTick = "■"; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value.GetType() != typeof(bool)) return ""; bool val = (bool)value; return val ? cTick : ""; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value.GetType() != typeof(string)) return false; string val = (string)value; return val == cTick; } } //--------------------------------------------------------------------------------------------
{ "pile_set_name": "StackExchange" }
Q: Visual Studio Code terminal freezes when asking to overwrite file for Ember.js VS Code just installed update 1.34.0 I have created a new project in Ember. When I attempt to create a new route ember g route application, I am asked if I want to overwrite app\templates\application.hbs. When I press Y and then Enter, the terminal freezes. I have to close it and open a new one. Unfortunately, the route is not created. Is anyone else getting this? Am I doing something wrong? A: I solved the problem by deleting the Application template and re-running the command. Though, I should not have to do this.
{ "pile_set_name": "StackExchange" }
Q: How does the VPS provider decide which process to kill? Almost all of them promise me x-MB RAM and y-MB dynamically. I'm a programmer but I don't understand how they decide which process needs to be killed if I alloc memory and keep it for such a long time that they need to. I mean let's say a php-fcgi server instance is running up to 500MB, I don't have a problem killing it but they shouldn't kill my mysqld or lighttpd which is only started during boot time. I couldn't find anything in the FAQ or support form of a handful of providers I checked. A: Processes consuming too much RAM under Linux are typically killed by the kernel's oom-killer process. OOM standing for "Out Of Memory". You can read a description of the decision process that it makes here and how to influence it's behaviour here.
{ "pile_set_name": "StackExchange" }
Q: Google Sheets ImportXML - Insert dynamic query if cell is filled I'm using Google Sheets as a scraper for youtube videos. I would like to make the sheet even more dynamic, but it doesn't seem to work. For example, I would like to write "How to get my baby to sleep" as a search query, therefore I would write this query into H6. If H6 is filled now, I would like to dynamically insert this query into the importXML function. This is what I've already had, but I can't get this to work. =ARRAYFORMULA("https://www.youtube.com"&QUERY(QUERY(UNIQUE( IMPORTXML("https://www.youtube.com/results?search_query=**{{dynamicInsertion}}**","//a/@href")), "where Col1 contains '/watch?v='"),"limit 50")) A: try: =ARRAYFORMULA("https://www.youtube.com/"&QUERY(IMPORTXML( "https://www.youtube.com/results?search_query="&H6, "//a/@href"), "where Col1 matches '/channel.+|/watch.+|/user.+|/results.+' order by Col1 desc")) UPDATE: =ARRAYFORMULA("https://www.youtube.com/"&QUERY(UNIQUE(IMPORTXML( "https://www.youtube.com/results?search_query="&H6, "//a/@href")), "where Col1 matches '/channel.+|/watch.+|/user.+|/results.+' order by Col1 desc limit 50"))
{ "pile_set_name": "StackExchange" }
Q: If we were able to control the Earth's spin with magic, could we defeat the Rocket Equation? Yesterday, I read the NASA post The Tyranny of the Rocket Equation. Very interesting read. In there, it states: The rocket equation contains three variables. Given any two of these, the third becomes cast in stone. ... They are the energy expenditure against gravity (often called delta V or the change in rocket velocity) the energy available in your rocket propellant (often called exhaust velocity or specific impulse) and the propellant mass fraction (how much propellant you need compared to the total rocket mass). This led me to think: the first factor, $\Delta$V, is the main obstacle in being able to leave Earth. So, if we had a means to alter the rate of spin of the Earth using magic, could we defeat it? Or would we just get thrown out in a chaotic manner, to our eventual death due to loss of control? Note: Assume the magic is specific to the spin of the Earth and nothing else; i.e. we don't have generalized energy/magic of levels required to alter planets. A: If the Earth were a rigid sphere, and we spun it up to: $$ a_c = r \omega^2 \\ a_c \approx g \\ \omega = \sqrt{\frac{1~g}{R_\text{E}}} = 1.2\times 10^{-3}~\text{rad}\cdot\text{s}^{-1}= \frac{1~\text{revolution}}{1.4~\text{hours}} $$ Then the centrifugal acceleration would roughly balance out gravity, and objects on the equator would appear weightless: essentially, they would be in orbit! This is a problem. The Earth contains a lot of things that are not nailed down (like the atmosphere) that are normally held down by gravity[citation needed]. On the super-spinning Earth, centrifugal force balances gravity and these things are no longer held down. You can probably already see where this is going. However, it turns out that it's even worse! Rocks seem pretty rigid to us, so we might be tempted to think of the Earth like a rigid object. However, on a planetary scale materials like rock behave like fluids (not to mention that parts of the inside are actually molten). This means that centrifugal force causes the equator to bulge outward. To first order, we can approximate the flattening of a rotating, self-gravitating body composed of incompressible fluid by: $$ \frac{15\pi}{4GT^2\rho} $$ In real life this formula gives a value of about $1/230$ for the Earth (the true value is closer to $1/300$ due to the fact that the core of the Earth is denser than the surface). For the super-spinning Earth this formula gives a value of $1.25$. For such an extreme value this formula no longer applies and the actual value is much worse. The Earth would probably look more like a pancake. A useful comparison is to look at the amount of energy we've added to the Earth by spinning it up this fast. $$ E = \frac{1}{2}I\omega^2 = \frac{2MR^2 \omega^2}{2\cdot 5} = \frac{g M R}{5} = \frac{G M^2}{5R} < \frac{3GM^2}{5R} $$ The term on the right is the gravitational binding energy. The fact that we have only added about a third of the gravitational binding energy means that the pieces of the Earth are likely to stay gravitationally bound: that is, they won't all fly off into space. Basically, we've turned the Earth back into a protoplanetary disk. Eventually, after they've dissipated enough energy (probably only 100 million years or so), the pieces will collapse back into a planet a little smaller than the Earth. Of course, it will take another one or two billion years for the molten mass to cool enough for oceans to form. So in summary, if the Earth was spinning fast enough, then yes, we would all be flung into space, and this is pretty much as bad an idea as it sounds.
{ "pile_set_name": "StackExchange" }
Q: Sidekiq PG::UndefinedColumn: ERROR: does not exist I made a migration changing branch to branch_name for my phone_contact model. I then changed my code to this: class ContactWorker include Sidekiq::Worker def perform(record, service_type = 'test', list_type = 'test') phone_contact = PhoneContact.create( client_id: record['ClientID'], client_name: record['ClientName'], branch_id: record['branchID'], branch_name: record['branch'], unit_id: record['UnitID'], member_id: record['MemberID'], first_name: record['FirstName'], last_name: record['LastName'], date_of_birth: record['DateofBirth'], most_recent_join_date: record['ChangeDate'], old_membership_type: record['OldMembershipType'], membership_type: record['NewMembershipType'], phone_number: record['HomePhone'], email: record['EMailAddress'], visits: record['ID__Visits'], primary_language: record['PrimaryLanguage'], call_type: record['CallType'], list_id: "#{Time.new.strftime("%Y_%m_%d")}_#{service_type}_#{list_type}" ) end end As you can see, branch is no longer listed. It clearly states branch_name:. So I pass in a record, which is a hash with all of the above attributes to this worker. Regardless of what that hash looks like, this is the error I receive: "error_message"=>"PG::UndefinedColumn: ERROR: column \"branch\" of relation \"phone_contacts\" does not exist\nLINE 1: INSERT INTO \"phone_contacts\" (\"branch\", \"branch_id\", \"call_t...\n ^\n: INSERT INTO \"phone_contacts\" (\"branch\", \"branch_id\", \"call_type\", \"client_id\", \"client_name\", \"created_at\", \"date_of_birth\", \"email\", \"first_name\", \"last_name\", \"list_id\", \"member_id\", \"membership_type\", \"most_recent_join_date\", \"old_membership_type\", \"phone_number\", \"primary_language\", \"unit_id\", \"updated_at\", \"visits\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) RETURNING \"id\"", "error_class"=>"ActiveRecord::StatementInvalid" The error changed to this with no code changes - I was just getting an unknown attribute: branch_name error. What could be causing this? My migration ran fine, when I look in my database i see branch_name, and if I use the Rails Console and manually go through the steps that my code is going through, one by one, it works fine. It only fails when I use Sidekiq. I am using Ruby 2.0.0 and Rails 4.0.0. A: My opinion is that the schema is cached. Have you tried restarting all of your workers?
{ "pile_set_name": "StackExchange" }
Q: Make an animated GIF with PHP's ImageMagick API I can do it easily in my OS convert -delay 1/1 -loop 0 *.gif animated.gif But I can't find how to do this in the PHP API. No resizing or anything needed, I've just got a set of frames that need animating. A: While I'm not a PHP expert, I know that this issue isn't a too difficult one. What you want to do is create an Imagick object that you can append your frames to. With each frame you can change parameters like timing etc. Assuming you're working with images that are uploaded from a basic web form, I've written a basic example that loops through images that were uploaded with a name of "image0", where "0" goes up to however many files are included. You could naturally just add images by using the same methods on fixed file names or whatever. $GIF = new Imagick(); $GIF->setFormat("gif"); for ($i = 0; $i < sizeof($_FILES); ++$i) { $frame = new Imagick(); $frame->readImage($_FILES["image$i"]["tmp_name"]); $frame->setImageDelay(10); $GIF->addImage($frame); } header("Content-Type: image/gif"); echo $GIF->getImagesBlob(); This example creates an Imagick object that is what will become our GIF. The files that were uploaded to the server are then looped through and each one is firstly read (remember however that this technique relies on that the images are named as I described above), secondly it gets a delay value, and thirdly, it's appended to the GIF-to-be. That's the basic idea, and it will produce what you're after (I hope). But there's lot to tamper with, and your configuration may look different. I always found the php.net Imagick API reference to kind of suck, but it's still nice to have and I use it every now and then to reference things from the standard ImageMagick. Hope this somewhat matches what you were after.
{ "pile_set_name": "StackExchange" }
Q: Реализация корзины для интернет-магазина Всем привет. Делаю интернет-магазин, возник вопрос с реализацией корзины. В голове лишь 1 вариант, как это сделать, но хочется все-таки услышать мнение со стороны. Идея реализации: хранить все данные в массиве в $_COOKIE, т.е. каждое действие с корзиной делает AJAX-запрос к серверу с id товара и действием (удаление, добавление). Сразу скажу, реализация фронт-энда на jQuery идет, ничего сложного нет, чтобы юзать vue/react и т.д.. Корзина будет доступна на каждой странице, также будет возможность изменять количество товара и удалять товар из корзины, с этим больше всего трудностей. Также хочется поинтересоваться, как правильно изменять общую цену товаров в корзине? Добавлять к каждому товару атрибут data-price, а затем делать подсчет через цикл по каждому товару, считая сумму? Или же лучше делать запрос к серверу после каждого изменения? A: Намного проще в Cookies хранить только номер сессии пользователя и токен (для проверки), а сами данные о заказе хранить в БД. В этом случае мы обращаемся к БД по номеру сессии и запрашиваем список заказанных товаров с их ценами (например, из таблицы cart_products). Общее количество товаров и сумму к оплате также считаем в цикле на сервере. В этом случае изменение содержимого корзины осуществляется через AJAX-запросы к серверу, где при добавлении нового товара мы указываем добавляемый product_id (в базе ищется соответствующий продукт, а в таблицу с заказанными товарами добавляются нужные поля - id, название, цена и т.д.), а при удалении - соответственно удаляемый product_id (то же самое делается с артикулами, если под одним product_id у вас несколько позиций). При выводе краткой информации о содержимом корзины (для всех страниц сайта) можно при сборке страницы запрашивать саму таблицу cart_products, либо хранить краткую информацию в самой таблице с сессиями пользователей. P.S. Также желательно добавить код, который периодически будет очищать старые данные из таблицы с сессиями и заказанными товарами (например, те, которые старше 1 недели).
{ "pile_set_name": "StackExchange" }
Q: Android how to detect if outgoing call is answered I'm developing an app that will only be used in house for testing purpose. I have searched a lot and tried different suggestions as suggested in different post but none seems to be working for me. I'm open to any suggestions like Reflections, Accessibility Service, root or any other hack. Please help. Regards A: TRY THIS Set all required permission in manifest.xml file. Call this class in Service public class PhoneListener extends PhoneStateListener { private static PhoneListener instance = null; /** * Must be called once on app startup * * @param context - application context * @return */ public static PhoneListener getInstance(Context context) { if (instance == null) { instance = new PhoneListener(context); } return instance; } public static boolean hasInstance() { return null != instance; } private final Context context; private CallLog phoneCall; private PhoneListener(Context context) { this.context = context; } AtomicBoolean isRecording = new AtomicBoolean(); AtomicBoolean isWhitelisted = new AtomicBoolean(); /** * Set the outgoing phone number * <p/> * Called by {@link MyCallReceiver} since that is where the phone number is available in a outgoing call * * @param phoneNumber */ public void setOutgoing(String phoneNumber) { if (null == phoneCall) phoneCall = new CallLog(); phoneCall.setPhoneNumber(phoneNumber); phoneCall.setOutgoing(); // called here so as not to miss recording part of the conversation in TelephonyManager.CALL_STATE_OFFHOOK isWhitelisted.set(Database.isWhitelisted(context, phoneCall.getPhoneNumber())); } @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); switch (state) { case TelephonyManager.CALL_STATE_IDLE: // Idle... no call if (isRecording.get()) { RecordCallService.stopRecording(context); phoneCall = null; isRecording.set(false); } break; case TelephonyManager.CALL_STATE_OFFHOOK: // Call answered if (isWhitelisted.get()) { isWhitelisted.set(false); return; } if (!isRecording.get()) { isRecording.set(true); // start: Probably not ever usefull if (null == phoneCall) phoneCall = new CallLog(); if (!incomingNumber.isEmpty()) { phoneCall.setPhoneNumber(incomingNumber); } // end: Probably not ever usefull RecordCallService.sartRecording(context, phoneCall); } break; case TelephonyManager.CALL_STATE_RINGING: // Phone ringing // DO NOT try RECORDING here! Leads to VERY poor quality recordings // I think something is not fully settled with the Incoming phone call when we get CALL_STATE_RINGING // a "SystemClock.sleep(1000);" in the code will allow the incoming call to stabilize and produce a good recording...(as proof of above) if (null == phoneCall) phoneCall = new CallLog(); if (!incomingNumber.isEmpty()) { phoneCall.setPhoneNumber(incomingNumber); // called here so as not to miss recording part of the conversation in TelephonyManager.CALL_STATE_OFFHOOK isWhitelisted.set(Database.isWhitelisted(context, phoneCall.getPhoneNumber())); } break; } } } And use Broadcast Receiver public class MyCallReceiver extends BroadcastReceiver { public MyCallReceiver() { } static TelephonyManager manager; @Override public void onReceive(Context context, Intent intent) { Log.i("JLCreativeCallRecorder", "MyCallReceiver.onReceive "); if (!AppPreferences.getInstance(context).isRecordingEnabled()) { removeListener(); return; } if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) { if (!AppPreferences.getInstance(context).isRecordingOutgoingEnabled()) { removeListener(); return; } PhoneListener.getInstance(context).setOutgoing(intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)); } else { if (!AppPreferences.getInstance(context).isRecordingIncomingEnabled()) { removeListener(); return; } } // Start Listening to the call.... if (null == manager) { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } if (null != manager) manager.listen(PhoneListener.getInstance(context), PhoneStateListener.LISTEN_CALL_STATE); } private void removeListener() { if (null != manager) { if (PhoneListener.hasInstance()) manager.listen(PhoneListener.getInstance(null), PhoneStateListener.LISTEN_NONE); } } } I hope you get some help from this code. Thanks
{ "pile_set_name": "StackExchange" }
Q: Remove a character from the end of a variable Bash auto completion appends a / at the end of a directory name. How I can strip this off from a positional parameter? #!/bin/sh target=$1 function backup(){ date=`date "+%y%m%d_%H%M%S"` PWD=`pwd` path=$PWD/$target tar czf /tmp/$date$target.tar.gz $path } backup A: Use target=${1%/} A reference. A: Use target=${1%/} See this the parameter substitution of this bash scripting guide for more. A: I think better solution to canonize paths is realpath $path or with -m option if it doesn't exist. This solution automaticaly removes unnecessary slashes and adds pwd
{ "pile_set_name": "StackExchange" }
Q: 7 way light bulb combinations I am having trouble with this question as I am not sure I am approaching it in the correct manor. A so-called 7-way lamp has three 60-watt bulbs which may be turned on one or two or all three at a time, and a large bulb which may be turned to 100 watts, 200 watts or 300 watts. How many different light intensities can the lamp be set to give if the completely off position is not included? Firstly I am not too sure what the ref to a seven way light bulb is from what I have google I have assumed it means that the intensity of the bulb can be varied with 7 different intensity's and I am assuming that as the bulbs can be turned on separately then the intensity for each can be varied individually. So my working are as follows If I think of a single bulb on it own, the I am going to have $^7C_1=7$ different intensities. Now if I switch on another bulb so now I would have $^7C_1*^7C_1=49$ a brief reasoning for this is as follows: $B_n=n^{th}$ Bulb $I_n=n^{th}$ Intensity If I set $B_1$ to an intensity of $I_1$ then turned on $B_2$ and adjust the intensity of $B_2$ from $I_1$ to $I_7$ then I would form the following combinations $I_1,I_1$ $I_1,I_2$ . . . . $I_1,I_7$ So if I apply this to all for 2 bulbs I would get $49$ different intensities. Applying same logic again to all three $60W$ bulbs then I would have 343 different intensities. Now if I then add the $100W$ bulb to this I would get $343+7=350$ different intensities. If I then apply this to varying the bulb power for $200W$ and $300W$ then the number of intensity's I would get now would be: $$No.intensity=343+7*3=364$$ Iv tried to think of it as I would be operating the switch myself, but am just not 100% that this is correct, is there a flaw with my working or how I have approached this? A: Ok, so if there are n devices with k positions, there are $k^n$ possibilities. The possible intensities for the first three bulbs are $0$, $60$, $120$ and $180$ (4 possibilities). The three-way bulb has 3 positions and a off position, so 4 positions in total. So there are $4\cdot 4 = 16$ possibilities. You remove the position completely off and you get $15$ positions.
{ "pile_set_name": "StackExchange" }
Q: How to run multiple Unix commands in one shot I am trying to execute multiple commands in one shot but to my surprise only the first command is getting executed and the rest are skipped. And the command is cleartool setview view1234 ; cleartool setactivity activity456 ; cd /vobs/app/src/epw/WEB-INF/scripts ; pwd And the output of the above command is You can now run 'clearquest' to start Rational ClearQuest. But instead I'm expecting to see the following 3 lines of output: You can now run 'clearquest' to start Rational ClearQuest. Set activity "activity456" in view "view1234". /vobs/app/src/epw/WEB-INF/scripts My search efforts yielded few more variations for the same command by replacing semicolon(;) with ampersand (&) or pipe (|) but nothing seems to be working. Any suggestions/ideas on how to run multiple commands like above? A: Don't use cleartool setview: it forks the current shell in a subshell, which is why the rest is skipped when executed in a single line. And which is why it works when executed one by one (the last two are executed in the subshell) Always work with the full path of the dynamic view: /view/aview/vobs/avob/..., instead of setview (which you don't need). If you must use cleartool setview, then use it with the -exec option (as in this answer): cleartool setview -login -exec "command 1; command 2; command 3" view_tag In your case: cleartool setview -exec 'cleartool setactivity activity456 ; cd /vobs/app/src/epw/WEB-INF/scripts ; pwd' view1234 Without setview: The OP asks: Say my view named humanbeing is in universe/planet/earth/humanbeing.vws How do I use the startview command? Is it something like cleartool startview universe/planet/earth/humanbeing or cleartool startview cd universe/planet/earth/humanbeing In both the cases it says the Error: Couldn't set view tag universe/planet/earth/humanbeing To be sure, do a cleartool lsview -s | grep humanbeing: that will give you the view tag. That should be: cleartool startview humanbeing cd /view/humanbeing/vobs/<avob> universe/planet/earth/humanbeing.vws is the view storage, not a view tag. Make sure that is mounted (cleartool mount /vobs/avob) myapp/WEB-INF/scripts is present in /view/humanbeing/vobs/<avob> Don't try to do any symlink in /vobs: /vobs is a special MVFS (Multi-Version FileSystem) mounting point, not a regular folder. Make sure your webapp search for apps in another path than /vobs.
{ "pile_set_name": "StackExchange" }
Q: boto3 list_services() with order I made aws auto deployment code with boto3 library. In my code, get all service list and use it. I have to get lastest service. But I think there is no order option. (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecs.html#ECS.Client.list_services) Sometimes, first element is latest service. But sometimes, old service is placed in first element. Is there any option or way to get latest service? Thanks. A: The list_services method does not return details of individual services. It simply lists the services, and returns you a list of identifiers (ARNs) for those services. To get more details of a given service, you can use describe_services. This allows you to get details of up to 10 services at a time. So, take the list of service identifiers that you get back from list_services, and pass it to describe_services (with at most 10 service identifiers). Something like this (untested): list_response = client.list_services( cluster='xyz', launchType='EC2' ) desc_response = client.describe_services( cluster='xyz', services=list_response['serviceArns'] ) Note that you will have to do pagination using maxResults / nextToken if there are a lot of results.
{ "pile_set_name": "StackExchange" }
Q: How to get the source or id from youtube player onstatechange callback This is a question similar to how to pass arguments to addeventlistner But the scenario is a bit different by using Youtube player's api. So I have multiple youtube player on the same page, using swfobject: swfobject.embedSWF("http://www.youtube.com/v/"+video_id+"?enablejsapi=1&version=3&modestbranding=1&theme=light&color=white&autohide=1&controls=1&showinfo=0&iv_load_policy=3&autoplay=0&playerapiid=<%= "ytPlayer#{index}" %>", "<%= "ytPlayer#{index}" %>", "500", "280", "8", null, null, params); Where I'm using ruby to generate the ytplayer object id. And I'm listening the event onStateChange in another function. ytplayer.addEventListener("onStateChange", "onytplayerStateChanged"); function onytplayerStateChanged(newState) { if(newState == -1){ //unstarted }else{ debugger; } } But the problem is I cannot know which ytPlayer this event comes from. (find the source of the caller in the onytplayerStateChanged function) Since I'm only able to catch this event by following the exact implementation of this structure. I tried the implementation on This one but it won't catch the event anymore. A: I think you can embed an Id and then add the listener to a dynamic function as is propose here: How to display multiple YouTube videos without overlapping audio window["dynamicYouTubeEventHandler" + embedid] = function(state) { onytplayerStateChange(state, embedid); } ytplayer.addEventListener("onStateChange", "dynamicYouTubeEventHandler"+embedid); (...) function onytplayerStateChange(newState, playerId)
{ "pile_set_name": "StackExchange" }
Q: Matlab Plotting with Variable Subscripts So I need to plot a function, let's say it's: y = sin( xk ) But I can only write the matlab code like: x = -pi : .1 : pi; y = sin(x); plot(x,y); If I try to do xk, then it cries about not knowing what k is. Any idea how I can plot functions with variables that contain subscripts (the subscripts are just descriptive, they don't hold any value)? Thanks A: Variables cannot have subscripts. You don't have to reproduce the formula exactly in a MATLAB statement. This is fine to name variable just x, or xk, or x_k, etc. On the other hand, if you have multiple vectors that you want to associate with the same name, you can put them into a cell array and get each vector as x{k}. You can use subscripts in axes labels, title and text annotations using Tex (default) or Latex interpretor. Use underscore character followed by subscript in a text string. title('y = sin(x_k)') or title('y = sin(x_{several chars})')
{ "pile_set_name": "StackExchange" }
Q: Vue.js progress bar I'm using vue.js 2.0 I've got this method: calculatePercentage(option) { let totalVotes = 0; this.poll.options.forEach((option) => { totalVotes+= option.votes.length; }); return option.votes.length / totalVotes * 100; } This is my bootstrap progress bar: <div class="span6"> <div v-for="option in poll.options"> <strong>{{ option.name }}</strong><span class="pull-right">{{ calculatePercentage(option) }}%</span> <div class="progress progress-danger active" aria-valuenow="12"> <div class="bar" style="width: 15%;"></div> </div> </div> </div> So the calculatePercentage(option); is working properly. But how do I bind this to the style (style="width: 15%;") ? Thanks a lot A: You can bind inline style to vue data as explained here. All you need to do is return values from calculatePercentage and use it in style like following: <div class="span6"> <div v-for="option in poll.options"> <strong>{{ option.name }}</strong><span class="pull-right">{{ calculatePercentage(option) }}%</span> <div class="progress progress-danger active" aria-valuenow="12"> <div class="bar" v-bind:style="{width: calculatePercentage(option) + '%'}"></div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Is a Nikkor 70-300mm lens compatible with a Nikon D3300? I have just bought my first DSLR, a Nikon D3300 with an 18-55mm lens. I want to enhance my reach and purchase a higher lens. My choice is a Nikkor 70-300mm but one of my friends said that as my camera is currently working at 55mm, I have to go for 55-200mm or 55-300mm lense only. Is it true? Can I not use 70-300mm lenses on my D3300? My major purpose is to shoot landscape images. A: Your friend is wrong. You don't have to get a 55-something telephoto zoom, unless you don't want a gap in focal length coverage. A lot of us would say that the 55-75mm range probably doesn't matter, while the additional length of a 300mm lens over 200mm lens is probably worth it. If you do care about range coverage without a gap, then getting an 18-300 supertelephoto might be a better alternative, but with more image quality compromises at the ends of the range. You can use FX lenses on a DX body with no issues. And, as long as it's got AF-S, it will autofocus on a D3x00 entry-level body. However. You do need to be aware that using a telephoto zoom lens can be more difficult than using a simple 18-55 walkaround. Most reasonable-cost 70-300ish telephoto lenses tend to be slow (i.e., have a maximum aperture in the f/4.5-5.6 range) to keep their size small and the cost low; and like any lenses, will typically perform better stopped down from wide open (i.e., f/8-f/11). 300mm is a lot of a reach, and a lot of magnification which will effectively increase blur from camera shake while handholding. Know the 1/focal_length rule (i.e., that you want to use at least 1/300s shutter speed for a 300mm lens; or 1/450s if you count the "crop factor" of a DX camera). Know good long lens techniques, and consider support gear if you need slower shutter speeds.
{ "pile_set_name": "StackExchange" }
Q: Calling lambda method defined in class scope (as a class attribute) class _GhostLink(object): toGhost = lambda filename: False class _Mod_AllowGhosting_All(_GhostLink): def _loop(self): # ... if self.__class__.toGhost(fileName) != oldGhost:... produces: Traceback (most recent call last): File "bash\basher\mod_links.py", line 592, in Execute changed = self._loop() File "bash\basher\mod_links.py", line 587, in _loop if self.__class__.toGhost(fileName) != oldGhost: TypeError: unbound method <lambda>() must be called with _Mod_AllowGhosting_All instance as first argument (got Path instance instead) while passing an instance as in if self.toGhost(fileName) != ... results in: Traceback (most recent call last): File "bash\basher\mod_links.py", line 592, in Execute changed = self._loop() File "bash\basher\mod_links.py", line 587, in _loop if self.toGhost(fileName) != oldGhost: TypeError: <lambda>() takes exactly 1 argument (2 given) How come toGhost behaves as a classmethod instance method ? EDIT: I know the difference of class,static etc methods - this is a syntactic question A: Looks like you want a static method: class _GhostLink(object): toGhost = staticmethod(lambda filename: False) or: class _GhostLink(object): @staticmethod def toGhost(filename): return False A: The reason this happens is fundamentally that lambda and def do the same thing, except that def also assigns a variable, That is, both constructs produce a function. The binding of a function (whether from lambda or def) into an instance method happens because functions are also descriptors; remember, in every single case: foo = lambda (...): (...) is identical to: def foo(...): return (...) so when you say: class _GhostLink(object): toGhost = lambda filename: False It's the same as if you had said: class _GhostLink(object): def toGhost(filename): return False So the moral of the story is that you should probably never use lambda as the right side of an assignment; it's not "better" or even different from using def. All it does is confuse.
{ "pile_set_name": "StackExchange" }
Q: Where are HERE maps docs about layer attributes? I am experimenting with HERE Maps API. I am requesting Platform Data Extension API and getting a valid response. The thing is I would like to know what do the values I get mean exactly? For example I can request ADAS_ATTRIB_FC1, is there any documentation telling me what do the slope values, curvature values etc. mean? And for other layer attributes? Please see an example response for ADAS_ATTRIB request below: { "Rows": [{ "LINK_ID": "52795003", "HPX": "88135200,3000,9200,4200,2400,900,800,1200", "HPY": "487947300,700,2400,1100,700,200,100,-100", "HPZ": "48073,-76,-236,-107,-61,-23,-20,-30", "SLOPES": "-1866,6,1,33,-26,-31,-26,3837", "HEADINGS": "70051,-2011,-2374,6159,7062,8114", "CURVATURES": "1182,-1182,0,-14170,-7255,-5046", "VERTICAL_FLAGS": "0,0,0,0,0,0", "REFNODE_LINKCURVHEADS": "19928834:2225:72335", "NREFNODE_LINKCURVHEADS": "708877367:-29444:101120", "BUA_ROAD": "1", "BUA_ROAD_VERIFIED": "Y" } } I haven't found anything like this in the online documentation (https://developer.here.com/documentation/platform-data/topics/layers-indexes-attributes.html) nor in the pdf documentation. Since the HERE support doesn't reply at all, I am posting my question here. Thanks in advance. A: Give it a try with PLATFORM EXTENSION REST API with GET request as following: http://pde.cit.api.here.com/1/doc/layer.json?region=NA&release=LATEST&layer={name}&app_id={your_id}&app_code={your_code} Try to learn more about resources and indexes in order to retrieve a response you are looking for. For example to get the whole list of attributes and corresponding layers in EU you can request as follows: http://pde.cit.api.here.com/1/doc/attributes.json?region=EU&release=LATEST&app_id={your_id}=&app_code={your_code}
{ "pile_set_name": "StackExchange" }
Q: Counts & Percentages in xTable, Sweave, R, cross tabulations Edit: Building off of aL3xa's answer below, I've modified his syntax below. Not perfect, but getting closer. I still haven't found a way to make xtable accept \multicolumn{} arguments for columns or rows. It also appears that Hmisc handles some of these type of tasks behind the scenes, but it looks like a bit of an undertaking to understand what's going on there. Does anyone have experience with the latex function in Hmisc? ctab <- function(tab, dec = 2, margin = NULL) { tab <- as.table(tab) ptab <- paste(round(prop.table(tab, margin = margin) * 100, dec), "%", sep = "") res <- matrix(NA, nrow = nrow(tab) , ncol = ncol(tab) * 2, byrow = TRUE) oddc <- 1:ncol(tab) %% 2 == 1 evenc <- 1:ncol(tab) %% 2 == 0 res[,oddc ] <- tab res[,evenc ] <- ptab res <- as.table(res) colnames(res) <- rep(colnames(tab), each = 2) rownames(res) <- rownames(tab) return(res) } I would like to create a table formatted for LaTeX output that contains both the counts and percentages for each column or variable. I have not found a ready made solution to this problem, but feel I must be recreating the wheel to some extent. I have developed a solution for straight tabulations, but am struggling with adopting something for a cross tabulation. First some sample data: #Generate sample data dow <- sample(1:7, 100, replace=TRUE) purp <- sample(1:4, 100, replace=TRUE) dow <- factor(dow, 1:7, c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")) purp <- factor(purp, 1:4, c("Business", "Commute", "Vacation", "Other")) And now the working straight tab function: customTable <- function(var, capt = NULL){ counts <- table(var) percs <- 100 * prop.table(counts) print( xtable( cbind( Count = counts , Percent = percs ) , caption = capt , digits = c(0,0,2) ) , caption.placement="top" ) } #Usage customTable(dow, capt="Day of Week") customTable(purp, capt="Trip Pupose") Does anyone have any suggestions for adopting this for cross tabulations (i.e. day of week BY trip purpose)? Here is what I've currently written, which does NOT use the xtable library and ALMOST works, but is not dynamic and is quite ugly to work with: #Create table and percentages a <- table(dow, purp) b <- round(prop.table(a, 1),2) #Column bind all of the counts & percentages together, this SHOULD become dynamic in future d <- cbind( cbind(Count = a[,1],Percent = b[,1]) , cbind(Count = a[,2], Percent = b[,2]) , cbind(Count = a[,3], Percent = b[,3]) , cbind(Count = a[,4], Percent = b[,4]) ) #Ugly function that needs help, or scrapped for something else crossTab <- function(title){ cat("\\begin{table}[ht]\n") cat("\\begin{center}\n") cat("\\caption{", title, "}\n", sep="") cat("\\begin{tabular}{rllllllll}\n") cat("\\hline\n") cat("", cat("", paste("&\\multicolumn{2}{c}{",colnames(a), "}"), sep = ""), "\\\\\n", sep="") c("&", cat("", colnames(d), "\\\\\n", sep=" & ")) cat("\\hline\n") c("&", write.table(d, sep = " & ", eol="\\\\\n", quote=FALSE, col.names=FALSE)) cat("\\hline\n") cat("\\end{tabular}\n") cat("\\end{center}\n") cat("\\end{table}\n") } crossTab(title = "Day of week BY Trip Purpose") A: In the Tables-package it is one line: # data: dow <- sample(1:7, 100, replace=TRUE) purp <- sample(1:4, 100, replace=TRUE) dow <- factor(dow, 1:7, c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")) purp <- factor(purp, 1:4, c("Business", "Commute", "Vacation", "Other")) dataframe <- data.frame( dow, purp) # The packages library(tables) library(Hmisc) # The table tabular( (Weekday=dow) ~ (Purpose=purp)*(Percent("row")+ 1) ,data=dataframe ) # The latex table latex( tabular( (Weekday=dow) ~ (Purpose=purp)*(Percent("col")+ 1) ,data=dataframe )) Using booktabs, you get this (can be further customised): A: Great question, this one's bothering me for a while (it's not that hard, it's just me being lazy as hell... as usual). However... though the question's great, your approach, I'm afraid, isn't. There's priceless package called xtable that you can (mis)use. Besides, this issue is too common - there's a great chance that there's already some ready-made solution sitting somewhere on the Internets. One of these days I'm about to work it out once and for all (I'll post the code on GitHub). The main idea goes a little bit like this: would you like frequency and/or percentage values within one cell (separated by \) or rows with absolute and relative frequencies (or %) in succession? I'd go with the 2nd one, so I'll post a "first-aid" solution for now: ctab <- function(tab, dec = 2, ...) { tab <- as.table(tab) ptab <- paste(round(prop.table(tab) * 100, dec), "%", sep = "") res <- matrix(NA, nrow = nrow(tab) * 2, ncol = ncol(tab), byrow = TRUE) oddr <- 1:nrow(tab) %% 2 == 1 evenr <- 1:nrow(tab) %% 2 == 0 res[oddr, ] <- tab res[evenr, ] <- ptab res <- as.table(res) colnames(res) <- colnames(tab) rownames(res) <- rep(rownames(tab), each = 2) return(res) } Now try something like: data(HairEyeColor) # load an appropriate dataset tb <- HairEyeColor[, , 1] # choose only male respondents ctab(tb) Brown Blue Hazel Green Black 32 11 10 3 Black 11.47% 3.94% 3.58% 1.08% Brown 53 50 25 15 Brown 19% 17.92% 8.96% 5.38% Red 10 10 7 7 Red 3.58% 3.58% 2.51% 2.51% Blond 3 30 5 8 Blond 1.08% 10.75% 1.79% 2.87% Make sure you loaded xtable package and use print (it's a generic function, so you must pass a xtable classed object). It's important that you suppress the row names. I'll optimize this one tomorrow - it should be xtable compatible. It's 3AM in my time zone, so with these lines I'll end my answer: print(xtable(ctab(tb)), include.rownames = FALSE) Cheers! A: I wasn't able to figure out how to generate a multi column header using xtable, but I did realize that i could concatenate my counts & percentages into the same column for printing purposes. Not ideal, but seems to get the job done. Here's the function I've written: ctab3 <- function(row, col, margin = 1, dec = 2, percs = FALSE, total = FALSE, tex = FALSE, caption = NULL){ tab <- as.table(table(row,col)) ptab <- signif(prop.table(tab, margin = margin), dec) if (percs){ z <- matrix(NA, nrow = nrow(tab), ncol = ncol(tab), byrow = TRUE) for (i in 1:ncol(tab)) z[,i] <- paste(tab[,i], ptab[,i], sep = " ") rownames(z) <- rownames(tab) colnames(z) <- colnames(tab) if (margin == 1 & total){ rowTot <- paste(apply(tab, 1, sum), apply(ptab, 1, sum), sep = " ") z <- cbind(z, Total = rowTot) } else if (margin == 2 & total) { colTot <- paste(apply(tab, 2, sum), apply(ptab, 2, sum), sep = " ") z <- rbind(z,Total = colTot) } } else { z <- table(row, col) } ifelse(tex, return(xtable(z, caption)), return(z)) } Probably not the final product, but does allow for some flexibility in parameters. At the most basic level, is only a wrapper of table() but can also generate LaTeX formatted output as well. Here is what I ended up using in a Sweave document: <<echo = FALSE>>= for (i in 1:ncol(df)){ print(ctab3( col = df[,1] , row = df[,i] , margin = 2 , total = TRUE , tex = TRUE , caption = paste("Dow by", colnames(df[i]), sep = " ") )) } @
{ "pile_set_name": "StackExchange" }
Q: Articles with word 'parallel' While reading an MSDN page I have noticed that whenever a word parallel is used, then there is no article 'a' used: In the past, parallelization required low-level manipulation [...]. These features simplify parallel development [...] fine-grained, and scalable parallel code. Why there is no article? I thought it should be: a parallelization a parallel development a parallel code Is it because words parallelization is abstract, development is uncountable and code is I don't know, uncountable? A: It has nothing to do with the word parallel itself, but (as you suspect) with the contexts in which it used. The parallelization sentence is not speaking of a specific instance of the process but of the process-in-general: every time you "parallelize" something it requires low-level manipulation. Again, what these features simplify is not one or more particular parallel developments but the process-in-general: every time you develop stuff in parallel it's simplified by these features. And code, likewise, isn't any particular program or app but code-in-general: every time you need code that's parallel, fine-grained and scalable, these features simplify the process of writing it.
{ "pile_set_name": "StackExchange" }
Q: Change Amount Of Columns In Table Is it possible to change the amount of columns in this table? I want to remove the blank td pair. Also, when I remove the attribute colspan="3", 2/3 of the width of the table is removed. So, what is controlling the amount of columns? <table> <tr> <td colspan="3" class="temperature">Temperature</td> </tr> <tr> <td>Temperature:</td> <td></td> <td><#temp><#tempunit></td> </tr> </table> Please let me know if you need any more information. Thanks for your help! William A: colspan="3" is stating that the td covers three columns of the table. To remove the blank set of tds in the centre of the table, change it to colspan="2". This makes the td only cover two columns, so then you can delete the <td></td> without having an empty column on the right hand side. Also, you may want to consider using th (Table Header) instead of td (Table Data) for the headings. This would mean that you would not need the "temperature" class for styling, as you could use the th selector. Doing both of these things, this would be your new code: <table> <tr> <th colspan="2">Temperature</th> </tr> <tr> <td>Temperature:</td> <td><#temp><#tempunit></td> </tr> </table>
{ "pile_set_name": "StackExchange" }
Q: Service discovery for a fixed period of time when using NsdManager.DiscoveryListener I am attempting to implement a class for service discovery using Android's NsdManager API. I am wondering how one could start the service search for a fixed amount of time from the main activity, then stop it to use the results of the search? The NsdManager API says the call should be asynchronous The API is asynchronous and responses to requests from an application are on listener callbacks on a seperate thread. I have successfully sent the class a handler which updates my UI thread with the message response but I'm not sure how I can then stop the discovery service after, say, 5 seconds without blocking the Main Thread with a timer :S I hope it is a relevant question and I have provided enough information. Br A: You don't need to use a timer, just use postDelayed(Runnable r, long millis) on your View. You can call that from any thread, so you could call it from the callback.
{ "pile_set_name": "StackExchange" }
Q: Could not load file or assembly 'tesseract.dll' or one of its dependencies I'm trying to create OCR functionality using tesseract 3.02 dll. Project building successfull but run time throwing the exception like bellow error. Could not load file or assembly 'tesseract.dll' or one of its dependencies. The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail. (Exception from HRESULT: 0x800736B1) How to fix this error? A: The solution was to download the right references from NuGet as per the example project in GitHub https://github.com/charlesw/tesseract .
{ "pile_set_name": "StackExchange" }
Q: Convert varchar to uniqueidentifier in SQL Server A table I have no control of the schema for, contains a column defined as varchar(50) which stores uniqueidentifiers in the format 'a89b1acd95016ae6b9c8aabb07da2010' (no hyphens) I want to convert these to uniqueidentifiers in SQL for passing to a .Net Guid. However, the following query lines don't work for me: select cast('a89b1acd95016ae6b9c8aabb07da2010' as uniqueidentifier) select convert(uniqueidentifier, 'a89b1acd95016ae6b9c8aabb07da2010') and result in: Msg 8169, Level 16, State 2, Line 1 Conversion failed when converting from a character string to uniqueidentifier. The same queries using a hyphenated uniqueidentifier work fine but the data is not stored in that format. Is there another (efficient) way to convert these strings to uniqueidentifiers in SQL. -- I don't want to do it in the .Net code. A: DECLARE @uuid VARCHAR(50) SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010' SELECT CAST( SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' + SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12) AS UNIQUEIDENTIFIER) A: It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING. create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin -- just in case it came in with 0x prefix or dashes... set @s = replace(replace(@s,'0x',''),'-','') -- inject dashes in the right places set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-') return cast(@s as uniqueidentifier) end A: your varchar col C: SELECT CONVERT(uniqueidentifier,LEFT(C, 8) + '-' +RIGHT(LEFT(C, 12), 4) + '-' +RIGHT(LEFT(C, 16), 4) + '-' +RIGHT(LEFT(C, 20), 4) + '-' +RIGHT(C, 12))
{ "pile_set_name": "StackExchange" }
Q: create-react-app failing with error I'm trying to create a new react project with create-react-app but it's failing with the below error Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts... yarn add v1.3.2 info No lockfile found. [1/4] Resolving packages... error Couldn't find any versions for "require-from-string" that matches "^1.1.0" info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command. Error: Received malformed response from registry for "timed-out". The registry may be down. at MessageError (C:\Program Files (x86)\Yarn\lib\cli.js:139:5) at C:\Program Files (x86)\Yarn\lib\cli.js:48907:15 at next (native) at step (C:\Program Files (x86)\Yarn\lib\cli.js:92:30) at C:\Program Files (x86)\Yarn\lib\cli.js:110:14 at new Promise (C:\Program Files (x86)\Yarn\lib\cli.js:93093:7) at C:\Program Files (x86)\Yarn\lib\cli.js:89:12 at Function.findVersionInRegistryResponse (C:\Program Files (x86)\Yarn\lib\cli.js:48946:7) at C:\Program Files (x86)\Yarn\lib\cli.js:48963:28 at next (native) Aborting installation. A: This is a temporary failure in npm registry (source)
{ "pile_set_name": "StackExchange" }
Q: Activating Network Location Provider in the Android Emulator? Is it possible to activate the network location provider on the android emulator? Maybe with a fake cellid? A: I believe that what you want to achieve is not possible at the moment. You cannot put mock location data to the emulator's network location provider. "Providing mock location data is injected as GPS location data, so you must request location updates from GPS_PROVIDER in order for mock location data to work." (Quote from Android, Documentation, Providing Mock Location Data) The closest thing I can come up with would be to to create a "Test Provider" from the Location Manager public void addTestProvider (String name, boolean requiresNetwork, boolean requiresSatellite, boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude, boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) and set the arguments requiresNetwork, requiresCell and requiresSatellite accordingly. Then you can from put fake locations to that provider: public void setTestProviderLocation (String provider, Location loc) That's close to but not exactly what you asked for. A: do you need to send location info to the emulator? if you wanna do this, yo can send location to the emulator throug the adb console and the geo command http://developer.android.com/guide/developing/tools/emulator.html#geo i don't know if its possible to send fake cellid, but its possible with gps coordinates, if your application listen to any gps provider
{ "pile_set_name": "StackExchange" }
Q: Android swipe left and right from record to record A lot of apps that I have (such as gmail) has a feature where you can swipe left and right to go from one record to another. In gmail, this navigation takes you from one email to the next (or previous, depending on which way you swipe). When you reach the end, you get this blue halo effect, and the swiping in that direction doesn't work. My question is, what is this navigation called? Is it something in the sdk, or is it written by the developer for each app? Can I use it in my app where I have data stored in the sqlite database that I would like to show one record at a time this way? Is it available in all sdk versions? I would search for it, but I don't know what it's called so I can't really think of any good search terms here. If someone just points me in the right direction, I can read the documentation and figure it out. A: The component you are looking for calls ViewPager. You'll find in under the compatibility pack jar. android viewPager implementation http://android-developers.blogspot.co.il/2011/08/horizontal-view-swiping-with-viewpager.html
{ "pile_set_name": "StackExchange" }
Q: Page Shadow Effect: Catch the Focus Out Event Here is what I am thinking: When a user browses some other page, or uses different application, or to say straight is not actively interacting with the webpage I want to catch this as a event and trigger a fadeIn() function. In this particular case only, I want to fill the page with shadow, which fades out once the user is back. The question is , How to catch this event, and execute a function? Created a demo here but I want the shadow to fade in, when the mouseout event triggers in window, but if I do so, when I come back in the body, the window start pulsating. A: It's really easy. Just use the blur and focus events on window. You can do whatever you want to show/hide your page shadow in the callbacks. Personally, I'd recommend the BlockUI plugin. $(function() { var $body = $('body'); $(window).focus(function () { $body.removeClass('fade'); }) .blur(function () { $body.addClass('fade'); }); });? Working example: http://jsbin.com/idipo5/2 (tested in Chrome) (be forewarned, it's really ugly) Edit: I'm pretty this what you're going for. Note how it doesn't unmask if the window is moused-over but doesn't have focus. If you do want it to unmask in this case, you can remove the focused flag and its checks. Tested in Chrome and FF (IE is a miserable piece of not-worth-my-time): http://jsbin.com/ufido3 Posting the JS code below, since I'm not sure how long JSBin keeps your stuff around. $(function () { var $modal = $('#modal'), masked = false, focused = true; function mask() { if (!masked) { $modal.fadeIn('fast'); masked = true; } } function unmask() { if (masked && focused) { $modal.fadeOut('fast'); masked = false; } } $('html').hover(unmask, mask).focus(function (e) { e.stopPropagation(); if ($(e.target).is('html')) unmask(); }).blur(function (e) { e.stopPropagation(); if ($(e.target).is('html')) mask(); }); $(window).focus(function () { focused = true; unmask(); }).blur(function () { focused = false; mask(); }); });
{ "pile_set_name": "StackExchange" }
Q: How to add minutes to the time part of datetime How to add minutes(INT) to the time part of datetime ? For example : If i have datetime variable like this : @shift_start_time = 2015-11-01 08:00:00.000 @increase = 30 How to get the result : 2015-11-01 08:30:00.000 A: Use DATEADD: SELECT DATEADD(mi, @increase, @shift_start_time); db<>fiddle demo A: Using dateadd: DATEADD(minute,@increase,@shift_start_time) the first argument can be chosen among: year quarter month dayofyear day week weekday hour minute second millisecond microsecond nanosecond please check https://msdn.microsoft.com/it-it/library/ms186819%28v=sql.120%29.aspx
{ "pile_set_name": "StackExchange" }
Q: How do I set up file sharing between Windows and Ubuntu I recently set up an old machine with Edubuntu 9.x (because if its nice set of educational games for my daughter). I would like to set up file sharing on my home network, which is comprised mostly of Windows boxes XP-and-up. Being a noob with Ubuntu, I don't know where to start. How do I get started with sharing files between the different computers on my home network? A: With Ubuntu is very easy: Using Nautilus (the File Explorer like applicaction) Right click on the folder you want to share, search for the Share options command, click on it, Edubuntu/Ubuntu will ask you to automatically install the Windows folder sharing libraries. Then you can adjust the parameters in System/Preferences File Sharing Options. The command names can vary, because my PC runs in Spanish and I can't see how are named in English A: SAMBA is probably the best place to start. To quote their own site - Samba is the standard Windows interoperability suite of programs for Linux and Unix. Samba is software that can be run on a platform other than Microsoft Windows, for example, UNIX, Linux, IBM System 390, OpenVMS, and other operating systems. Samba uses the TCP/IP protocol that is installed on the host server. When correctly configured, it allows that host to interact with a Microsoft Windows client or server as if it is a Windows file and print server. Here's a tutorial
{ "pile_set_name": "StackExchange" }
Q: Mockwebserver in gradle build throwing error This entry in my gradle file : androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0') is throwing error: Warning:Conflict with dependency 'com.squareup.okio:okio'. Resolved versions for app (1.8.0) and test app (1.6.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details. I tried commenting out different compile entries in my gradle file to find out which one was conflicting but I just can't find which one uses com.squareup.okio:okio. UPDATE: I was able to get the dependencies by running: gradlew.bat app:dependencies > c:\tmp\output.txt +--- com.squareup.retrofit2:retrofit:2.0.0 -> 2.1.0 | \--- com.squareup.okhttp3:okhttp:3.3.0 | \--- com.squareup.okio:okio:1.8.0 --- com.squareup.okhttp:mockwebserver:2.7.0 | +--- com.squareup.okhttp:okhttp:2.7.0 | | \--- com.squareup.okio:okio:1.6.0 So as you can see, retrofit 2.0 uses okhttp3 which uses okio:1.8.0. On the other hand mockwebserver:2.7.0 uses okhttp:2.7.0 which uses okio:1.6.0. So how can I resolve this? Here are the entries in "dependencies" section of my gradle file: compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.2.1' //retrofit compile 'com.squareup.retrofit2:retrofit:2.0.0' compile 'com.squareup.retrofit2:converter-gson:2.+' compile 'com.squareup.retrofit2:adapter-rxjava:2.+' compile 'com.squareup.retrofit2:retrofit-mock:2.+' //recycler view compile 'com.android.support:recyclerview-v7:+' //picasso image caching compile 'com.squareup.picasso:picasso:2.5.2' //jackson parser compile ( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'] ) //Dagger compile 'com.google.dagger:dagger:2.7' apt 'com.google.dagger:dagger-compiler:2.7' //constraint based layouts compile 'com.android.support:design:24.1.1' compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4' //for chrome debugging compile 'com.facebook.stetho:stetho:1.4.1' compile 'com.facebook.stetho:stetho-okhttp3:1.4.1' //for retrofit //RxJava compile 'io.reactivex:rxandroid:1.2.1' // Because RxAndroid releases are few and far between, it is recommended you also // explicitly depend on RxJava's latest version for bug fixes and new features. compile 'io.reactivex:rxjava:1.1.6' //--- For Testing --- //robolectric: testCompile "org.robolectric:robolectric:3.2.2" //mockito testCompile "org.mockito:mockito-core:2.+" testCompile('org.hamcrest:hamcrest-core:1.3') testCompile('org.hamcrest:hamcrest-library:1.3') testCompile 'junit:junit:4.12' androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) // Espresso-web for WebView support androidTestCompile( 'com.android.support.test.espresso:espresso-web:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) androidTestCompile( 'com.android.support.test:runner:0.5', { exclude group: 'com.android.support', module: 'support-annotations' }) androidTestCompile( 'com.android.support.test:rules:0.5', { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile ('org.powermock:powermock-api-mockito:1.6.2') { exclude module: 'hamcrest-core' exclude module: 'objenesis' } //mockwebserver //testCompile 'com.squareup.okhttp3:mockwebserver:3.3.0' androidTestCompile ('com.squareup.okhttp:mockwebserver:2.7.0') androidTestCompile 'com.squareup.spoon:spoon-client:1.2.0' A: I solved by using Retrofit version 2.3.0 -> com.squareup.retrofit2:retrofit:2.3.0 MockWebServer version 3.8.0 -> com.squareup.okhttp3:mockwebserver:3.8.0
{ "pile_set_name": "StackExchange" }
Q: How to create deep entity with oModel.createEntry Is there a way to create a "temporary" (or I guess it's called virtual) deep entity with using oModel.createEntity()? I have a entity called Timesheet with an association to breaks, called ToBreaks. Now I want to create a new entity in the frontend by using oModel.createEntity("/TimesheetSet"). Unfortunately in the so called virtual new entry all my associations are missing. Because I use the assications for binding tables, after creating the virtual new entry, a backend call is triggered TimesheetSet("id-04-123456789")/ToBreaks which leads to a "invalid key predicate" error. Is there a way to do this with OData V2? Update 09.08.2016: You can still try by just using the properties parameter with a nested entity set. As long as your OData service supports the corresponding deep create it should work: I've also tried something like this: oModel.createEntry("/TimesheetEntry", { Pernr: sPernr, Begda: dBegda, ToBreaks: [{ Pernr: sPernr, Begda: dBegda }] }); ToBreaks is the name of the association. In the virtual entry of the OData-Model the properties for the associations are still missing. I can create the new entry by using the code above, but afterwards there is no property called ToBreaks On the Backend-Side I followed this tutorial for implementing the deep_create method: step-by-step-development-guide-for-createdeepentity-operation. I'm able to trigger the method from within the SAP Gateway Client. A: Yes you can execute deep entity creation with oData V2. In order to do so you need to build your request body according to your metadata structure. Let's assume that your metadata model is User and each user have multiple Communication. So we have a user entity and communication entity. We also have association of fromUserToCommunications and navigation property let's call it Communications In order to execute a call to deep create a User entity you will need to do the following: // Create the oData Model var oModel = new sap.ui.model.odata.ODataModel("{YOUR_SERVICE_DOCUMENT_URL}"); // Create the user request body, please make sure that // all required fields are filled in and are according to the // user entity metadata var userRequestBody = { id: "123", firstName: "Your First Name", lastName: "Your Last Name", address: "Your Address", communications: [] // contain multiple communications }; var comm1 = { id : "1", userId : "123", // foregin key to the user entity homePhone: "+134342445435" }; var comm2 = { id : "2", userId : "123", // foregin key to the user entity homePhone: "+134342445436" }; // add the communications to the user entity userRequestBody.communications.push(comm1); userRequestBody.communications.push(comm2); oModel.create("/UserCollection",userRequestBody,{ success: function(result){ // everything is OK }, error: function(err){ // some error occuerd }, async: true, // execute async request to not stuck the main thread urlParameters: {} // send URL parameters if required }); A: From the API docs: Please note that deep creates (including data defined by navigationproperties) are not supported. You can still try by just using the properties parameter with a nested entity set. As long as your OData service supports the corresponding deep create it should work: properties could be an object which includes the desired properties and the values which should be used for the created entry.
{ "pile_set_name": "StackExchange" }
Q: cx_Oracle ignores order by clause I've created complex query builder in my project, and during tests stumbled upon strange issue: same query with the same plan produces different results on different clients: cx_Oracle ignores order by clause, while Oracle SQLDeveloper Studio process query correctly, however in both cases order by present in both plans. Query in question is: select * from ( select a.*, ROWNUM tmp__rnum from ( select base.* from ( select id from ( ( select profile_id as id, surname as sort__col from names ) /* here usually are several other subqueries chained by unions */ ) group by id order by min(sort__col) asc ) tmp left join (profiles) base on tmp.id = base.id where exists ( select t.object_id from object_rights t where t.object_id = base.id and t.subject_id = :a__subject_id and t.rights in ('r','w') ) ) a where ROWNUM < :rows_to ) where tmp__rnum >= :rows_from and plan from cx_Oracle in case I missed anything: {'operation': 'SELECT STATEMENT', 'position': 9225, 'cardinality': 2164, 'time': 1, 'cost': 9225, 'depth': 0, 'bytes': 84396, 'optimizer': 'ALL_ROWS', 'id': 0, 'cpu_cost': 1983805801}, {'operation': 'VIEW', 'position': 1, 'filter_predicates': '"TMP__RNUM">=TO_NUMBER(:ROWS_FROM)', 'parent_id': 0, 'object_instance': 1, 'cardinality': 2164SEL$1', 'projection': '"from$_subquery$_001"."ID"[NUMBER,22], "from$_subquery$_001"."CREATION_TIME"[TIMESTAMP,11], "TMP__RNUM"[NUMBER,22]', 'time': 1, 'cost': 9225, 'depth': 1, 'bytes': 84396, 'id': 1, 'cpu_cost': 1983805801}, {'operation': 'COUNT', 'position': 1, 'filter_predicates': 'ROWNUM<TO_NUMBER(:ROWS_TO)', 'parent_id': 1, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11], ROWNUM[8]', 'options': 'STOPKEY', 'depth': 2, 'id': 2, {'operation': 'HASH JOIN', 'position': 1, 'parent_id': 2, 'access_predicates': '"TMP"."ID"="BASE"."ID"', 'cardinality': 2164, 'projection': '(#keys=1) "BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'time': 1, 'cost': 9225, 'depth': 3, 'bytes': 86560, 'id': 3, 'cpu_cost': 1983805801}, {'operation': 'JOIN FILTER', 'position': 1, 'parent_id': 3, 'object_owner': 'SYS', 'cardinality': 2219, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'object_name': ':BF0000', 'time': 1, 'cost': 662, 'options': 'CREATE', 'depth': 4, 'bytes': 59913, 'id': 4, 'cpu_cost': 223290732}, {'operation': 'HASH JOIN', 'position': 1, 'parent_id': 4, 'access_predicates': '"T"."OBJECT_ID"="BASE"."ID"', 'cardinality': 2219, 'projection': '(#keys=1) "BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'time': 1, 'cost': 662, 'options': 'RIGHT SEMI', 'depth': 5, 'bytes': 59913, 'id': 5, 'cpu_cost': 223290732}, {'operation': 'TABLE ACCESS', 'position': 1, 'filter_predicates': '"T"."SUBJECT_ID"=TO_NUMBER(:A__SUBJECT_ID) AND ("T"."RIGHTS"=\'r\' OR "T"."RIGHTS"=\'w\')', 'parent_id': 5, 'object_type': 'TABLE', 'object_instance': 8, 'cardinality': 2219, 'projection': '"T"."OBJECT_ID"[NUMBER,22]', 'object_name': 'OBJECT_RIGHTS', 'time': 1, 'cost': 5, 'options': 'FULL', 'depth': 6, 'bytes': 24409, 'optimizer': 'ANALYZED', 'id': 6, 'cpu_cost': 1823386}, {'operation': 'TABLE ACCESS', 'position': 2, 'parent_id': 5, 'object_type': 'TABLE', 'object_instance': 6, 'cardinality': 753862, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'object_name': 'PROFILES', 'time': 1, 'cost': 654, 'options': 'FULL', 'depth': 6, 'bytes': 12061792, 'optimizer': 'ANALYZED', 'id': 7, 'cpu_cost': 145148296}, {'operation': 'VIEW', 'position': 2, 'parent_id': 3, 'object_instance': 3, 'cardinality': 735296, 'projection': '"TMP"."ID"[NUMBER,22]', 'time': 1, 'cost': 8559, 'depth': 4, 'bytes': 9558848, 'id': 8, 'cpu_cost': 1686052619}, {'operation': 'SORT', 'position': 1, 'parent_id': 8, 'cardinality': 735296, 'projection': '(#keys=1) MIN("SURNAME")[50], "PROFILE_ID"[NUMBER,22]', 'time': 1, 'cost': 8559, 'options': 'ORDER BY', 'temp_space': 18244000, 'depth': 5, 'bytes': 10294144, 'id': 9, 'cpu_cost': 1686052619}, {'operation': 'HASH', 'position': 1, 'parent_id': 9, 'cardinality': 735296, 'projection': '(#keys=1; rowset=200) "PROFILE_ID"[NUMBER,22], MIN("SURNAME")[50]', 'time': 1, 'cost': 8559, 'options': 'GROUP BY', 'temp_space': 18244000, 'depth': 6, 'bytes': 10294144, 'id': 10, 'cpu_cost': 1686052619}, {'operation': 'JOIN FILTER', 'position': 1, 'parent_id': 10, 'object_owner': 'SYS', 'cardinality': 756586, 'projection': '(rowset=200) "PROFILE_ID"[NUMBER,22], "SURNAME"[VARCHAR2,50]', 'object_name': ':BF0000', 'time': 1, 'cost': 1202, 'options': 'USE', 'depth': 7, 'bytes': 10592204, 'id': 11, 'cpu_cost': 190231639}, {'operation': 'TABLE ACCESS', 'position': 1, 'filter_predicates': 'SYS_OP_BLOOM_FILTER(:BF0000,"PROFILE_ID")', 'parent_id': 11, 'object_type': 'TABLE', 'object_instance': 5, 'cardinality': 756586, 'projection': '(rowset=200) "PROFILE_ID"[NUMBER,22], "SURNAME"[VARCHAR2,50]', 'object_name': 'NAMES', 'time': 1, 'cost': 1202, 'options': 'FULL', 'depth': 8, 'bytes': 10592204, 'optimizer': 'ANALYZED', 'id': 12, 'cpu_cost': 190231639} cx_Oracle output (appears to be ordered by id): ID, Created, rownum (1829, 2016-08-24, 1) (2438, 2016-08-24, 2) SQLDeveloper Output (ordered by surname, as expected): ID, Created, rownum (518926, 2016-08-28, 1) (565556, 2016-08-29, 2) A: I don't see an ORDER BY clause that would affect the ordering of the results of the query. In SQL, the only way to guarantee the ordering of a result set is to have an ORDER BY clause for the outer-most SELECT. In almost all cases, an ORDER BY in a subquery is not necessarily respected (Oracle makes an exception when there are rownum comparisons in the next level of the query -- and even that is now out of date with the support of FETCH FIRST <n> ROWS). So, there is no reason to expect that an ORDER BY in the innermost subquery would have any effect, particularly with the JOIN that then happens. Suggestions: Move the ORDER BY to the outermost query. Use FETCH FIRST syntax, if you are using Oracle 12c+. Move the ORDER BY after the JOIN. Use ROW_NUMBER() instead of rownum.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to create ERC223 token that is ERC20 backwards compatible I'm going to use ERC223 token, but worry about backward compatibility with ERC20. Here are questions that bother me: Two different Transfer events: 3 args ERC20 Transfer(address indexed _from, address indexed _to, uint256 _value) and 4 args ERC223 Transfer(address indexed from, address indexed to, uint value, bytes data) transferFrom/approve/allowance functions and Approval event are specified in ERC20 standard, but lacks in ERC223 though it is said that "ERC223 is a superset of the ERC20 token standard". Could anybody clarify this points for me? I want to avoid situation when token is already deployed and sent to people, but it is not operable at trading exchange and does not not work with services designed for ERC20. A: Problem solved, found ERC20_compatible branch in Dexaran's ERC223 repo https://github.com/Dexaran/ERC223-token-standard/tree/ERC20_compatible and with few additions from master branch implemented fully functional and ERC20 compatible token.
{ "pile_set_name": "StackExchange" }
Q: Keras how to slice output of a layer and then add it to the model I have a layer which outputs [N,100,100,2] I want to use only the [N,100,100,0], I have used slice(layer,[0,0,0,0],[-1,-1,-1,1] to get this, however I am unable to add this sliced output to a model as it is not a layer. How is it done. Can some one provide a code snippet. c3 = Convolution2D(2, (1, 1),strides=(1,1),padding='same',use_bias=True,activation='softmax') output = (c3)(output) slicedoutput = slice(output,[0,0,0,0],[-1,-1,-1,1]) classifier = Model(inputs=[image_a],outputs=[slicedoutput,outputboxes]) A: There is no inbuilt slice layer in Keras. But you can use Lambda layer for your purpose. In your case instead of using slice from keras.backend you can use Lambda layer slicedoutput = Lambda(lambda x: x[:,:,:,0])(output)
{ "pile_set_name": "StackExchange" }
Q: Proving that the derivative is unique in higher dimensions Can someone help me prove this please? I am thinking of using triangle inequality. However, I feel as if I would be doing to much and there is a better way to prove the following. $\def\h{{\mathbf h}} \def\x{{\mathbf x}} \def\f{{\mathbf f}} \def\0{{\mathbf 0}} \def\R{{\mathbb R}} \def\L{{\mathcal L}}$ Let $\f\colon D\to \R^m$ where $D\subseteq\R^n$ is open. Let $\x_0\in D$ and suppose that $\f$ is differentiable at $\x_0$. Prove $T\in\L(\R^n,\R^m)$ satisfies the definition of derivative, such that $$\lim_{\h\to\0}\frac{\|\f(\x_0+\h)-\f(\x_0)-T(\h)\|}{\|\h\|} = 0$$ is unique. Essentially, I want to conclude $\|T-S\|<\epsilon$. $\textit{Proof.}$ Suppose $T$ and $S$ are two linear transformations which satisfy our definition. By $\epsilon-\delta$ definition of limit, for any given $\epsilon >0$, there exists $\delta >0$ such that $0< \|\h\| < \delta$ then $\displaystyle{\frac{\|\f(\x_0+\h)-\f(\x_0)-T(\h)\|}{\|\h\|}<\frac{\epsilon}{2}}.$ Now, $0<\|\h\|<\delta$ implies $\displaystyle{\|\f(\x_0+\h)-\f(\x_0)-T(\h)\| < \frac{\epsilon}{2}\|\h\|}$ A: We also have for all $\epsilon>0$, there is $\delta'>0$ such that for all $0<\|h\|<\delta'$, $\|f(x_0+h)-f(x_0)-S(h)\|<\dfrac{\epsilon}{2}\|h\|$. By the triangle inequality, for $0<\|h\|<\delta'':=\min\{\delta,\delta'\}$, $$\|(T-S)h\|=\|f(x_0+h)-f(x_0)-T(h)-(f(x_0+h)-f(x_0)-S(h))\|$$ $$\le\|f(x_0+h)-f(x_0)-T(h)\|+\|f(x_0+h)-f(x_0)-S(h)\|<\epsilon\|h\|$$ Now using the definition of the operator norm, $$\|T-S\|=\sup_{\|x\|\le1}\|(T-S)(x)\|$$ and so $$\|T-S\|\cdot\delta''=\sup_{\|x\|<\delta''}\|(T-S)(x)\|<\epsilon\delta'',$$ so $\|T-S\|<\epsilon$.
{ "pile_set_name": "StackExchange" }
Q: group data into one variable from sql Not too sure if the title to this actually explains what I really need to ask, so I'm sorry about that. Basically, I have two tables (products and stock). In products, I have two products: ID: 1 || Name: Top ID: 2 || Name: Bottom In stock, I have five stock lines: ID: 1 || ProductID: 1 || Size: Medium ID: 2 || ProductID: 1 || Size: Large ID: 3 || ProductID: 2 || Size: Medium ID: 4 || ProductID: 3 || Size: 7 ID: 5 || ProductID: 3 || Size: 8 What I need to do is pull out all products with stock, therefore my code at the moment is: SELECT p.ID, p.Name, s.Size FROM products p JOIN stock s ON s.ProductID = p.ID This is then pulling the following out: ID: 1 || Name: Top || Size: Medium ID: 1 || Name: Top || Size: Large ID: 2 || Name: Bottom || Size: Medium ID: 3 || Name: Shoes || Size: 7 ID: 3 || Name: Shoes || Size: 8 What I want to do with this is put the sizes in one column (comma delimited) per ID - thus I want it to look like: ID: 1 || Name: Top || Size: Medium, Large ID: 2 || Name: Bottom || Size: Medium ID: 3 || Name: Shoes || Size: 7, 8 Do anyone know how I can do this? I should know how to do it but my mind has just gone blank! A: SELECT p.ID, p.Name, GROUP_CONCAT(s.Size) AS Size FROM products p JOIN stock s ON s.ProductID = p.ID GROUP BY p.ID That should work fine.
{ "pile_set_name": "StackExchange" }
Q: How to read columns of SQL Server tables in Visual Studio? In Microsoft Access functions like DLookup - DMax or Dcount help the programmer to read a column from a table of a SQL Server database. How do you do the same task in Visual Studio? For example how can I find the ID of a user (John) in tblUsers table. tblUsers columns: ID, Username, Password, ..... I've already added the SQL Server database to the Data Source. Any kind of advice is much appreciated. A: ow. Even in Access, that isn't proper. Go read up on DAO, ADO, and, if you're using Visual Studio to write .Net applications, the system.data namespace. in general, when accessing relational data via non-database program code, including the vba you're using in Access, you'd retrieve a reference to a Recordset object and query each record's fields as object properties.
{ "pile_set_name": "StackExchange" }
Q: Is there any website having command line environment of Linux, for practicing commands? I was wondering whether I could practice LINUX commands and shell scripting, online, over a website which could provide me an editor to practice them. And I know that probably the easiest thing to do would be to download a Linux LIVE CD and then practice shell scripting, but apart from it, I want to practice them online, anywhere I want, anytime I want and on any system, without bothering about booting from a LIVE CD. A: There is a quite a good one here: Javascript PC Emulator - http://bellard.org/jslinux/ Related: How does Linux emulator in Javascript by Fabrice Bellard work? Simulating linux terminal in browser
{ "pile_set_name": "StackExchange" }
Q: Передача массива из функции Бинарный файл составляю из 2 source-файлов, в одном основной код, в другой функции генерации ssl-сертификата. Функция формирования сертификата (дополнительные функции не привожу) из второго файла. int create_cert(unsigned char *buf, int *len) { BIO *bio_err; X509 *x509=NULL; EVP_PKEY *pkey=NULL; unsigned char *p; int i; CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); mkcert(&x509,&pkey,2048,0,1490); *len=i2d_X509(x509,NULL); buf=malloc(*len); if (buf==NULL) return -1; p=buf; i2d_X509(x509,&p); X509_free(x509); EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_ENGINE ENGINE_cleanup(); #endif CRYPTO_cleanup_all_ex_data(); CRYPTO_mem_leaks(bio_err); BIO_free(bio_err); return 1; } Тут я генерирую сертификат средствами openssl, с помощью i2d_X509 перевожу в DER-формат и записываю в память под указателем buf (а так же размер массива сертификата), который должен возвратиться туда где я вызываю эту функцию (т.е. в основной файл). А вот главная функция первого файла. int main(void) { char Cert; unsigned char *cbCertificate; int certLen; create_cert(&cbCertificate,&certLen); } Тут я принимаю указатель и размер массива сертификата с предыдущей функции. Все никак не могу понять как можно взять массив из памяти и присвоить его в переменную Cert, чтобы после передать другой функции. Я попытался записать сертификат в файл с помощью FILE *fp=fopen("cert.cer","w"); if (fp!=NULL) { fwrite(&cbCertificate,1,certLen,fp); fclose(fp); } Записывается всякая хрень. Я понимаю что cbCertificate это указатель на указатель. Я понимаю как можно взять адрес указателя, но вот к данным получить доступ не понимаю как. A: Если я правильно Вас поняла, и Вы хотите вернуть из внутренней функции наружу выделенный внутри нее массив, используя в качестве параметра этой функции двойной указатель, то, для начала, нужно описать в параметрах этой функции двойной указатель: int create_cert(unsigned char **buf, int *len){...} Далее, выделять память под массив Вам нужно с учетом, что вы используете двойной указатель (Вы аналогично уже работаете с len): *buf = (unsigned char *)malloc(*len); Тогда, после вывова функции create_cert() в cbCertificate будет лежать указатель на новый, выделенный внутри create_cert() массив. Все никак не могу понять как можно взять массив из памяти и присвоить его в переменную Cert Так, как у Вас описано, это точно не получится, так как переменная Cert у вас имеет тип char, - т.е. 1 элемент. Нельзя одному элементу типа char присвоить весь массив. Если же Вы, после того, как получили с помощью функции create_cert() данные, хотите записать их в файл, то запись будет выглядеть вот так : fwrite(cbCertificate,1,certLen,fp); так как unsigned char *cbCertificate; это не двойной, а обычный указатель. Вот когда вы берете его адрес, как здесь : create_cert(&cbCertificate,&certLen); внутри функции create_cert() получается двойной указатель. UPD: Как выглядят двойные указатели: Объявление : int **cbCertificate; Тогда инициализация такого указателя может выглядеть вот так : int a = 0; int *ptr = &a; int **cbCertificate = &ptr; И передавать такой двойной указатель в функцию можно будет вот так : void foo(int ** pptr){...} ... int main(){ int a = 0; int *ptr = &a; int **cbCertificate = &ptr; foo(cbCertificate); } Если же двойной указатель нам нужен только для того, чтобы вернуть из функции адрес выделенного внутри этой функции буффера, то можно обойтись использованием двойного указателя только на стеке функции, тогда вышеприведенный пример можно записать так : void foo(int ** pptr){...} ... int main(){ int a = 0; int *ptr = &a; foo(&ptr); } Двойной указатель является не чем иным, как адресом некоторого указателя, следовательно, работать с самим указателем и данными внутри функции foo() можно следующим образом: void foo(int **pptr){ ... *pptr = NULL; // инициализация указателя, адрес котрого хранится в pptr //(pptr все еще хранит значение, указывающее на некоторую ячейку памяти, //а вот эта самая память уже никуда не указывает) *pptr = (int *)malloc(10*sizeof(int)); // ячейка, на которую указывает // pptr, указывает на массив из 10 значений типа int (*pptr)[0] = 5; // инициализируем первый элемент выделенного массива ... }
{ "pile_set_name": "StackExchange" }
Q: Alert box in Javascript I am doing my project about scanner. So if i have finished to scan bardcode, the alert box will appear and show the ingredients of food products. But i have found the problem in alert box, it appeared but it only show native alert box. Can someone help, how to change style in alert box. My codes are below: var localJSONFile= "db/product.json"; $.getJSON(localJSONFile) .success(function(data, status, xhr){ $.each(data, function(i, product){ if(result.text == product.barcode){ alert( "name: " + product.name + "\n" + "barcode: " + product.barcode + "\n" + "status: " +product.status + "\n" + "E-code: " + product.e_code + "\n" + "Ingredients: " + product.ingredients + "\n" + "Country: " + product.country + "\n" + product.image ); } }); }) A: Unfortunately you cannot style an alert box, there are alternative projects out there however, SweetAlerts being my personal favourite, that make alert boxes look good
{ "pile_set_name": "StackExchange" }
Q: Can't telnet a server from vps i try to understand why i can't telnet this server 213.132.48.107 from any of my VPSs. Well this ip is for a mail server i don't own but our emails are not received by this server. when i checked the log i saw this error: 554 5.7.1 You are not allowed to connect. Connection closed by foreign host. I thought i'm in black list so i tried to telnet to that server from all my VPSs (7 VPSs) and always get the same error. telnet 213.132.48.107 25 Trying 213.132.48.107... Connected to 213.132.48.107. Escape character is '^]'. 554 5.7.1 You are not allowed to connect. But when i try from a dedicate server i can telnet. I have contacted the server admin but didn't get any response. I still don't see any reason for them to block my IP address. we just installed the server and it's used for regular emails only. Please help me My VPSs run debian/ubuntu/centos and all created created by proxmox A: The server is configured not to accept connections from your ip. Obviously, it blocks them even before HELO. You may check your VPS ip against some blacklists. If it's listed, try to get it unlisted. If it is not listed, you may need to contact the mail server admin, why you cannot send mail to this server or if it is even supposed to accept mail from the internet. Maybe you're connecting a system, which isn't used to accept mail from other servers?
{ "pile_set_name": "StackExchange" }
Q: Windows 7 Media Player won't add MP3 files I have a set of MP3 files that Windows Media Player just refuses to add to the library. They are placed in the standard My Music folder. I play them in media player. They just won't be listed in the library. I've tried dragging them and dropping them on the media player but they still don't appear in the library. I have an identical laptop where I've also copied the mp3 files and they appear in the library fine. Any ideas what would cause this? A: This article describes how to reset the Windows Media Player Library, you could try it. Close Microsoft Media Player for at least 30 seconds. Click Start and then Run. Type the following into the text box: %userprofile%\Local Settings\Application Data\Microsoft\Media Player Click OK and a folder showing you your library files will appear. Erase all the files that end with .wmdb. Open Microsoft Media Player. Push F3. Select the locations for your music files. WMP will reindex your music.
{ "pile_set_name": "StackExchange" }
Q: PHP excecute once it gets loaded I'm trying to get a :"var = new class" , but i need this variable to be global in the file (or superglobal) and it needs to be rememberd. <?php include 'game.php'; include 'button.php'; include 'beurt.php'; include 'scores.php'; include 'round.php'; include 'speelveld.php'; include 'player.php'; include 'cells.php'; if(isset($_POST['action']) && !empty($_POST['action'])) { $action = $_POST['action']; if (isset($_POST['Val']) && !empty($_POST['Val'])) { $Val = $_POST['Val']; } switch ($action) { case 'Start' : echo"<script>alert('new game started')</script>"; $Game = new Game; break; case 'ButtonClickStart': $Game->ButtonClickStart(); break; case 'ButtonClickStop' : $Game->ButtonClickStop(); break; case 'ClickCell' : $Game->ClickCell( $Val ); break; // ...etc... } } ?> i call this file trough $ajax and try to make it execute Functions to the Class, however what i cant seem to get past is that : "$Game = new Game();" should only be executed onces and it needs to be remeberd. I understood it could be done trough a: static $game = '' , but php didnt seem to like static in combination with a new class. At first i tried to declare $Game below the includes, however that lead to it executing that everytime upon calling the file trough Ajax, setting $Game to the construction value's. now what i want cant figure out is, is there a way to only execute $Game = new Game once while getting remeberd (so it doesnt lose the data after the function is done) And being able to use the var in the other cases Case start gets activated by the index on a onload function, but i it doesnt seem to remeber the data also as last note im very new to php in general so any info is very welcome A: Your problem is not that your Game variable lives globally throughout your execution context (which is very easy, just declare $Game at the beginning of the script, and use it as you're currently doing), but rather you must be able to save the Game object across the users' session. You need to be able to serialize the Game object somehow and store it in a database, a cookie or somewhere else, and preferrably not in session variables, because, depending on the size of the Game object and the number of users, you could run out of resources quickly.
{ "pile_set_name": "StackExchange" }
Q: Are ALL forms of 'flight' on-topic? I've recently begun following a young YouTuber whose thing is paramotors. That is a para-wing with a small two-stroke engine/blade strapped on your back. I'd like to ask some questions (and I will), but thought I'd try and get consensus about topicality. I know motored planes, gliders and (hot-air) balloons have had questions. Drones as well. What about the other forms of flying? Things like hang-gliders, Para-motors, etc. What about flying suits (I don't know their correct names, the things that look like sugar-glider suits)? Then there are the much more likely to not be on-topic forms, yet still a form a 'flying' such as kite surfing, where operators have been pulled up so high as to be severely injured upon landing. A: Are they on topic? I'd say yes! They are likely regulated by the same aviation authority that regulates other aspects of flying They are interesting, it broadens our site to more readers Some aerodynamic concepts are likely applicable We do have questions about parachuting already A: If it leaves the ground, under control of a pilot, its on-topic for aviation. A paramotor certainly qualifies as all that. The pilot doesn't have to be on/in the craft (so model aircraft and drones are included.) If the craft is destined for space then its a grey area between this site and https://space.stackexchange.com/ Depends if its related specifically to atmospheric segment of the launch/landing. If its tethered to the ground then that's another marginally grey area and would be considered off-topic unless there's a specific connection to flying ("kites near an airport" is on topic, but "kites generally" might be off topic. A: I think of the scope of the site as everything which is related to flying, that is: Gaining altitude, maintaining altitude, or controlling descent by the mean of an aerodynamic force (which to me includes air buoyancy). Cases: A rocket usually relies on the pure thrust created by its engines. It's not in scope. V2 are not in scope (or perhaps for their attitude control system). An airplane using a rocket engine to move a wing, which in turn creates lift, is in-scope. V1 are in scope. Any wing like a parachute or a steerable fabric wing is in scope.
{ "pile_set_name": "StackExchange" }
Q: What is the recommended way for sending personalized images in html emails? I know similar questions have already been asked but the answer is almost always the same: you need to share the image on a server and link to it from within the email. For my purpose I cannot do that. The image needs to be personalized for each user I send an email to (so the email will be dynamically generated for each user and will not always be the same. I cannot share the image -- since it will change but also for avoiding disclosure of users' information). Have you ever encountered this scenario? Should I go with attachments or base64 encoding of images? Thoughts/experiences? A: The HTML body must refer to the images using the content id (cid): <img src="cid:xyz">, where xyz is the value of the attachment content id (Content-ID) MIME header. If you are creating the message directly in the MIME format, make sure the attachment is added to the message and its Content-ID MIME header is properly set. If you are Outlook Object Model or MAPI, you must set the PR_ATTACH_CONTENT_ID property on the image.
{ "pile_set_name": "StackExchange" }
Q: Stop MPlayer from using float in Awesome WM I understand that MPlayer calls a "configurerequest" and for that reason, completely ignores the rules of my Window Manager in Archlinux, AwesomeWM and instead of being tiled, it floats. Is there anyway to stop this from happening? Thanks! A: You want to find the following code block, and change floating = false: awful.rules.rules = { ... { rule = { class = "MPlayer" }, properties = { floating = false } }, ... } The determine the class part, do the following in a terminal window: % xprop | grep WM_CLASS Then click on the window whose class name you are trying to determine. One of those wonderful UNIX things that you have to experience to believe.
{ "pile_set_name": "StackExchange" }