_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d19381
test
You should use ngFor instead of ng-repeat <ol> <li *ngFor="let item of testarr">{{item}}ITEM Found!</li> </ol>
unknown
d19383
test
If your images are in mydomain.com/images and you are linking to them using relative links on the page mydomain.com/sub/folder/ the browser is going to try to attempt to access the image via mydomain.com/sub/folder/images/i.gif. But if you change your links to absolute links, the browser will correctly attempt to load mydomain.com/images/i.gif. However, the RewriteRule will change it to: mydomain.com/index/php?Controller=images&View=i.gif. To avoid this you need to add a few RewriteConds: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9-_]+)\/?$ index.php?Controller=$1 RewriteRule ^([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)\/? index.php?Controller=$1&View=$2 So that when attempting at access an existing file/directory, don't rewrite to index.php.
unknown
d19385
test
This error happen because the registry value DefaultData and DefaultLog (which correspond to default data directory) are either empty or does not exists. See documentation for more information. Most of the time, these registry values does not exists because they actually need to be accessed as Admin. So, to fix this issue, simply run whatever application you are using to execute the sql as an administrator.
unknown
d19387
test
To get the values instead of percentages : * *Edit the datawindow, select the "Text" tab *Select "Pie Graph Labels" in the TextObject drop-down list *In the "Display Expression" field type "value" I'm using PB10.5, I hope it's same with 12.
unknown
d19389
test
In package.json you can use scripts or even at commandline you can use environment variable.s "scripts": { "dev": "NODE_ENV=development webpack", "production": "NODE_ENV=production webpack", "watch": "npm run dev -- --watch" }, In webpack.config.js you can use const inProduction = process.env.NODE_ENV === 'production'; const inDevelopment = process.env.NODE_ENV === "development"; if(inProduction) //do this if(inDevelopment) //do that webpack by default looks for weback.config.js however for custom config you can use webpack --config config_local.js
unknown
d19395
test
I've been down this path, and I don't recommend you actually make deep hierarchies of windows. Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts. Also, windows in Windows are relatively heavy objects, mostly for historical reasons. So if you have tons of objects, you could run into limitations, performance problems, etc. What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows. Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent. You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows. For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows. But the hierarchy has several layers of non-window objects in between that know about layout. A: A rough take on this: * *memory overhead for the window management on application- and os-side *reduced speed due to calls to external library / os which do way more for windows than needed for your application *possibly quite some overhead through long window message paths in complex layouts It probably depends on wether you want a very fast implementation and do efficient buffered drawing by yourself or want it to work more reliably and with less time invested.
unknown
d19401
test
From http://hsivonen.iki.fi/xhtml2-html5-q-and-a/ : If I can use any doctype for XHTML5, how can browsers tell XHTML 1.0 and XHTML5 apart? They can’t and they don’t need to. By design, a user agent that implements XHTML5 will process inputs authored as XHTML 1.0 appropriately. A: There is no XHTML 5. Currently there is HTML 4.01 and XHTML 1.0. There will be no XHTML 2.0. There will only be HTML 5. HTML 5 is not an XML standard (meaning an HTML 5 document is not an XML document). Perhaps you're looking at HTML 5 + XML = XHTML 5. I guess you can express HTML 5 as XML but as far as I know this is non-standard. More specifically, this is just a serialization method for the document tree rather than a standard. To clarify this issue, take a look at HTML 5 and XHTML 5 - one vocabulary, two serializations. Even from the title it says "one vocabulary, two serializations". And Conversation With X/HTML 5 Team: The XHTML 5 spec says that "generally speaking, authors are discouraged from trying to use XML on the Web". Why write an XML spec like XHTML 5 and then discourage authors from using it? Why not just drop support for XML (XHTML 5)? Some people are going to use XML with HTML 5 whatever we do. It's a simple thing to do — XML is a metalanguage for describing tree structures, HTML 5 is a tree structure, it's obvious that XML can be used to describe HTML 5. The problem is that if we don't specify it, then everyone who thinks it is obvious and goes ahead and does it will do it in a slightly different way, and we'll have an interoperability nightmare. So instead we bite the bullet and define how it must work if people do it. XHTML 1.0 was a standard. It differed to HTML 4. XHTML 5, if you can call it that, is nothing more than representing HTML 5 documents in XML form. A: Browsers won't. The elements exist in the same namespace, and have the same meaning, except where the WHATWG have decided to change them — such as the b element — where browsers are just going to have to muddle through. A: It would be possible to distinguish by DOCTYPE (which is different for HTML5 and XHTML 1.x), but its presence is specifically non-mandatory in XHTML5; and element namespace is the same. So, in general, there's no good way to distinguish them. If you want to write portable XHTML5, I guess providing DOCTYPE is your best bet.
unknown
d19407
test
It is not related to the type of the task, it's a typical << misunderstanding. When you write project.task('hello') << { println project.greeting.message } and execute gradle hello, the following happens: configuration phase * *apply custom plugin *create task hello *set greeting.message = 'Hi from Gradle' executon phase * *run task with empty body *execute << closure { println project.greeting.message } in this scenario output is Hi from Gradle When you write project.task('hello', type: Exec) { println project.greeting.message } and execute gradle hello, the following happens configuration phase * *apply custom plugin *create exec task hello *execute task init closure println project.greeting.message *set greeting.message = 'Hi from Gradle' (too late, it was printed in step 3) the rest of workflow does not matter. So, small details matter. Here's the explanation of the same topic. Solution: void apply(Project project) { project.afterEvaluate { project.task('hello', type: Exec) { println project.greeting.message } } }
unknown
d19411
test
1.Is autocommit turned on or turned off on your database connection ? 2. In DB2, there are chances of deadlock when you are firing a select query and update query within same transaction. 3. If the auto commit is turned off and you have fired a select query on the table then try committing or rollback that transaction and then fire update query. It should work. Let me know in case if you are still facing above issue.
unknown
d19415
test
Consider creating a custom filter that uses Number.prototype.toLocaleString() console.log(Number(8).toLocaleString('en',{style: 'currency', currency: 'USD'})) console.log(Number(8).toLocaleString('de',{style: 'currency', currency: 'EUR'})) A: Something like this: {{ lang == 'tr' ? '₺' + item.price : item.price + '$' }} Or write your own Custom Filter that parses your currency.
unknown
d19425
test
I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey). Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime. A: Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded. A: I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/ A: You could also use Spring's UriUtils A: It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License. A: I think that the URI class is the one that you are looking for. A: Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try. You said: For example, given an input: http://google.com/resource?key=value I expect the output: http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue So: C:\oreyes\samples\java\URL>type URLEncodeSample.java import java.net.*; public class URLEncodeSample { public static void main( String [] args ) throws Throwable { System.out.println( URLEncoder.encode( args[0], "UTF-8" )); } } C:\oreyes\samples\java\URL>javac URLEncodeSample.java C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value" http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue As expected. What would be the problem with this?
unknown
d19427
test
You shouldn't need a timeout here. function scheduleDelayedCallback() { var now = new Date(); if (now.getTime() - lastEvent.getTime() >= 750) { // minimum time has passed, go ahead and update or whatever $("#main").html('Lade...'); // reset your reference time lastEvent = now; } else { this_function_needs_to_be_delayed(); // don't know what this is. } } Your explanation of what you want to happen isn't the clearest so let me know if the flow is wrong.
unknown
d19429
test
Updated This is related to sequence A051026 : Number of primitive subsequences of {1, 2, ..., n} in OEIS, the Online Encyclopedia of Integer Sequences. I don't think there is any easy way to calculate the terms. Even the recursive computations are not trivial, except when n is prime where: a(n) = 2 * a(n-1) - 1 Both the problem here and "A051026" can be thought of subproblems of a generalization of the above sequence. "A051026" is the instance with (a,b,..) = (2,3,4,5...), e.g. "all the integers >= 2". A: I believe it will be easier to calculate the complimentary- that is the number of subsets of S that are not allowed. This is the number of subsets of S for each there is at least one pair (a,b) such that a divides b. After you calculate that number M' simply subtract it from the total number of subsets of S that is 2n. Now to calculate the number of subsets of S that are not allowed you will have to apply the inclusion-exclusion principle. The solution is not very easy to implement but I don't think there is an alternative approach.
unknown
d19433
test
The elements within the transclude directive aren't receiving the same scope. If you use the angualr $compile method and apply the scope of the transclude directive to the scope of the child directives it should work. The following should be added to your simpleTransclude directive: link: function(scope, element) { $compile( element.contents() )( scope ) } remember to pass $compile into the directive. I've forked your plnkr and applied the simpleTransclude scope to it's contents.
unknown
d19437
test
You could use np.where: >>> edge = np.array(EDGE) >>> edge[edge > 0].min() 0.5 >>> np.where(edge == edge[edge > 0].min()) (array([1, 2]), array([0, 1])) which gives the x coordinates and the y coordinates which hit the minimum value separately. If you want to combine them, there are lots of ways, e.g. >>> np.array(np.where(edge == edge[edge > 0].min())).T array([[1, 0], [2, 1]]) A few asides: from numpy import * is a bad habit because that replaces some built-in functions with numpy's versions which work differently, and in some cases have the opposite results; ALLCAPS variable names are usually only given to constants; and your EDGE = array(zeros((NUM_NODE, NUM_NODE))) line doesn't do anything, because your EDGE = [[ 0., ... etc line immediately makes a new list and binds EDGE to it instead. You made an array and threw it away. There's also no need to call array here; zeros already returns an array. A: numpy.ndenumerate will enumerate over the array(by the way, you shouldn't lose position information with reshaping). In [43]: a = array(EDGE) In [44]: a Out[44]: array([[ 0. , 0. , 0. , 0. , 0. ], [ 0.5 , 0. , 0. , 0. , 0. ], [ 1. , 0.5 , 0. , 0. , 0. ], [ 1.41421356, 1.11803399, 1. , 0. , 0. ], [ 1. , 1.11803399, 1.41421356, 1. , 0. ]]) In [45]: min((i for i in ndenumerate(a) if i[1] > 0), key=lambda i: i[1]) Out[45]: ((1, 0), 0.5) Or you can do it with the old way if you want every occurence: In [11]: m, ms = float("inf"), [] In [12]: for pos, i in ndenumerate(a): ....: if not i: continue ....: if i < m: ....: m, ms = i, [pos] ....: elif i == m: ....: ms.append(pos) ....: In [13]: ms Out[13]: [(1, 0), (2, 1)]
unknown
d19439
test
The issue here is that when you say NORTH_EAST = [x_coordinate + 1, y_coordinate - 1] You construct a list of two values, which are computed and stored at the time. They will not update based on the values of x_coordinate and y_coordinate changing. You will need to recalculate the values on each loop to get the behaviour you expect. The easiest way to do this is with a function: directions = { "north east": (+1, -1), "north west": (-1, -1), "south east": (+1, +1), "south west": (-1, +1), } def new_position(old, direction): x, y = old dx, dy = directions[direction] return x + dx, y + dy position = 100, 100 direction = "north east" while True: print(position) position = new_position(position, direction) Note that where there are linked pieces of data, it's best to store them in a data structure. Here I use a tuple to store the x and y values together, and a dictionary for the directional data. This means less repetition in your code.
unknown
d19441
test
You need to install Visual Studio Test Agent first in your remote/test machine. Then using a remote access tool such as PsExec from PsTools you use MSTest.exe or VSTest.Console.exe to run a dll. You can script this in bat file on your own machine to trigger loading of test dlls to the remote machine and automated running. However setting up a good build-test environment using Visual Studio TFS will always be a better and more integrated solution.
unknown
d19443
test
I just wanted to understand if we are creating any additional threads that is responsible for this task threads? Yes - from the documentation: Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
unknown
d19445
test
It's possible. Using Console APIs in WebView Just override WebViewClient for your WebView like this: val myWebView: WebView = findViewById(R.id.webview) myWebView.webChromeClient = object : WebChromeClient() { override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean { consoleMessage?.apply { Log.d("MyApplication", "${message()} -- From line ${lineNumber()} of ${sourceId()}") } return true } } A: @Volodymyr ans work for me. Just override onConsoleMessage on WebChromeClient (reference): webview.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.d(TAG, "onConsoleMessage: "+ consoleMessage.message()); return true; } });
unknown
d19447
test
With Postgresql 9.5 UPDATE test SET data = data - 'v' || '{"v":1}' WHERE data->>'c' = 'ACC'; OR UPDATE test SET data = jsonb_set(data, '{v}', '1'::jsonb);
unknown
d19449
test
Got the same issue with Qt5.2.0 on Mavericks... I found a work around: append a dummy file name to the directory you want to select. However, be sure not to do this on Windows because the user will see it. QString dir = "/Users/myuser/Desktop"; #if defined(__APPLE__) dir += "/MyFile.txt"; #endif fn = QFileDialog::getOpenFileName(this, "Select File", dir); Also, for those like me that instantiate a file dialog because they need more options you can also do: QFileDialog fileDialog(this, "Select File"); #if defined(__APPLE__) fileDialog.selectFile(dir + "/MyFile.txt"); #else fileDialog.setDirectory(dir); #endif ... A: This is a bug in Qt that is reportedly fixed in Qt 5.0.1 and Qt 4.8.4 (though it seems that it still reproducible in 4.8.4 by people (myself included)). This bug has been reported in JIRA as QTBUG-20771, QTBUG-28161 and finally QTBUG-35779 (which appears to have finally fully resolved the issue in Qt 5.2.1). Here is a link to the patch in Gerrit.
unknown
d19451
test
I have the same issue with eval-source-map, so I finally switch back to source-map. However, I do find two approaches to make eval-source-map work, quite dirty though. * *Insert a debugger in the JS file you are working on. Open DevTools before you visit the page, then the debugger will bring you to the right place, add your break points and they should work now. *Or insert console.log('here is it') instead of debugger. Then open DevTools -> Console, on the right end of the line, a link will bring you to the place where console.log fires. Add your break points and they should also work.
unknown
d19453
test
Use it something like this for API level 5 and greater @Override public void onBackPressed() { super.onBackPressed() if (keycode == KeyEvent.KEYCODE_BACK) { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { finish(); } } older than API 5 public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { finish(); } } return super.onKeyDown(keycode, event); } Let me know if it works for you A: Remove this.finishAffinity(); from onBackPressed() SAMPLE CODE @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); finish(); } }
unknown
d19457
test
It depends on what exactly you want to mutate. * *If you really want to reassign the field values::Vector{Int64} itself, then you have to use a mutable struct. There's no way around that, because the actual data of the struct changes when you reassign that field. *If you use an immutable struct with a values::Vector{Int64} field, it means that you cannot change which array is contained, but the array itself is mutable and can change its elements (which are not stored in the struct). In this case, you really do have to copy values to it from external arrays, like your example code (though I would point out that your code did not reset the array to an empty one). I personally think this would be cleaner: function set_values!(list::NumberedList, new_values::Vector{Int64}) empty!(list.values) # reset list.values to Int64[] append!(list.values, new_values) end *The thread you linked talks about using Base.Ref. Base.Ref is pretty much THE way to make a field of an immutable struct indirectly act like a mutable field. It works like this: the field cannot change which RefValue{Vector{Int64}} instance is contained, but the instance itself is mutable and can change its reference (again, not stored in the struct) to any Int64 array. You have to use indexing values[] to get to the array, though: struct NumberedList index::Int64 values::Ref{Vector{Int64}} NumberedList(i) = new(i, Int64[]) end function set_values!(list::NumberedList, new_values::Vector{Int64}) list.values[] = new_values # "reassign" different array to Ref end # --- mylist = NumberedList(1) set_values!(mylist, [1, 2, 3])
unknown
d19459
test
You need to create a Windows Runtime component by creating a class library from the "Visual C#" -> "Windows Metro Style" -> "Class Library" template. Then in the properties for that class library project you need to mark the output type as "WinMD File" Better instructions can be found here: http://msdn.microsoft.com/en-us/library/windows/apps/hh779077(v=vs.110).aspx This isn't stated in the documentation and is probably just a bug with the Windows 8 Consumer Preview and the Visual Studio 11 Beta but be sure not to include a period in the name of the project you're referencing. For instance, I was working on a Car application so I made an assembly named "Car.Business". The application would always crash with a blank startup screen whenever I tried to reference this. If on the other hand I just used "Business" as the name of the assembly then the application would work fine.
unknown
d19461
test
try: $('ul li').on('mouseenter mouseleave', function() { $(this).find('.overview').toggleClass('top_out'); }); A: You have to use the hovered over li as the context: $("ul li").hover(function(){ $(".overview", this).toggleClass("top_out"); }); Rather than .hover(function() ... you may want to use: .on('mouseenter mouseleave', function() ... $("ul li").on('mouseenter mouseleave', function(){ $(".overview", this).toggleClass("top_out"); }); .top_out { background-color: black; color: white; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> </ul> A: It seems like you need to toggle the class based on the context of the element you are hovering over. Use the jQuery selector $(".overview", this) to select .overview elements within the li element that is currently being moused over. I also change the hover event to mouseover/mouseout. $("ul li").on('mouseover mouseout', function () { $(".overview", this).toggleClass("top_out"); }); Which is essentially equivalent to $("ul li").on('mouseover mouseout', function () { $(this).find(".overview").toggleClass("top_out"); });
unknown
d19463
test
Due to your current indentation, coordpairs is only seeing the last value of longitudes each time it loops through y. If you would like to use loops, you could do something like this (assuming your longitudes and latitudes lists are the same length) coordpairs = [] for coord_num in range(len(longitudes)): coord_pair = [longitudes[coord_num], latitudes[coord_num]] coordpairs.append(coord_pair) If you want to combine each item in longitudes with each item in latitudes without using loops, you can use list(zip(longitudes, latitudes))
unknown
d19469
test
I copied your example into a test file, and it works fine. I also can't see how the error message in your example could be generated by the current version of noUiSlider, so I'd suggest using the latest version of noUiSlider and the latest version of jQuery. It would also be a good idea to only run this JS after the page has loaded, like this: $(function() { $("#sslider").noUiSlider({ start: 5, range: { 'min': 1, 'max': 80 } }); }); A: Ok, problem solved. I have downloaded jquery.nouislider.js from NuGet (from VisualStudio 2013) and they provided me older or broken file. I thought the file was from website, but I browsed NuGet and noticed, that I have already downloaded from there. There is no problem with code but with file. Lesson: before asking question, compare official files with those you already have installed. A: Try to follow the official docs: $("#slider").noUiSlider({ start: [5], connect: true, range: { 'min': 1, 'max': 80 } });
unknown
d19471
test
why do you wish to have an empty array as a default column values? That isn't correct to assign an empty array to value of DB column, because it must be specifically serialized. Instead define methods in model, which will return empty array for specific column: def some_field read_attribute(:some_field) || [] end def other_field read_attribute(:other_field) || [] end But better way is to define that methods not in model, but in a serializer or decorator.
unknown
d19473
test
You can assign the output of the command to a string. Use 2>&1 to redirect stderr to stdout and thus capture all the output. str = `git pull origin master 2>&1` if $?.exitstatus > 0 ... elsif str =~ /up-to-date/ ... else ... end
unknown
d19477
test
So, you are using discord.js v13 which is a lot different from the previous version which is v12. In v13, it is compulsory to add intents. You can read this for more information: here A: new Discord version V13 requires you to set the intents your bot will use. First, you can go to https://ziad87.net/intents/ where you can choose the intents you want and gives you a number, you should use that number like this: const intents = new Discord.Intents(INTENTS NUMBER); const client = new Discord.Client({ intents }); For example, if you want all the intents, you will have: const intents = new Discord.Intents(32767); const client = new Discord.Client({ intents });
unknown
d19485
test
by tag mysqli I can assume that You're using PHP. So it can be done this way: $year = '2015'; $data = []; foreach(range(1, 12) AS $month) { $data[$month] = [ 'date_year' => $year, 'date_month' => $month, 'nb_item' => 0 ]; } $q = "SELECT year(feed_date) as date_year, month(feed_date) as date_month, count(*) as nb_item FROM table WHERE year(feed_date) = '".$year."' GROUP BY date_year, date_month"; $q = mysqli_query($q); while($record = mysqli_fetch_assoc($q)) { $data[$record['date_month']]['nb_item'] = $record['nb_item']; } $data = array_values($data); print_r($data); or with mysql it will be huge query: SELECT year(table.feed_date) AS date_year, month(table.feed_date) AS date_month, COALESCE(count(*), 0) as nb_item FROM ( SELECT 1 as month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) months LEFT JOIN table ON (months.month = month(table.feed_date)) WHERE year(table.feed_date) = '2015' GROUP BY date_year, date_month; A: You need a table containing all the year-month combinations for a LEFT JOIN. You can create it on the fly by cross joining all years and months: SELECT y.date_year, m.date_month, count(*) as nb_item FROM ( SELECT 1 as date_month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) m CROSS JOIN ( SELECT 2015 as date_year ) y LEFT JOIN `table` t ON year(t.feed_date) = y.date_year AND month(t.feed_date) = m.date_month AND t.feed_title LIKE '%word%' AND t.source = '3' GROUP BY y.date_year, m.date_month If you have a helper table with sequence numbers you can shorten the query to: SELECT y.seq as date_year, m.seq as date_month, count(*) as nb_item FROM sequences y CROSS JOIN sequences m LEFT JOIN `table` t ON year(t.feed_date) = y.date_year AND month(t.feed_date) = m.date_month AND t.feed_title LIKE '%word%' AND t.source = '3' WHERE y.seq IN (2015) AND m.seq <= 12 GROUP BY y.seq, m.seq A: You can join the selected data with a subquery that gets all the existing years and months from the table. SELECT t1.date_year, t1.date_monthmonth, IFNULL(t2.nb_item, 0) AS nb_item FROM (SELECT DISTINCT YEAR(feed_date) AS date_year, MONTH(feed_date) AS date_month FROM table) AS t1 LEFT JOIN ( SELECT year(feed_date) as date_year, month(feed_date) as date_month, count(*) as nb_item FROM table WHERE year(feed_date) = '2015' AND feed_title LIKE '%word%' AND source = '3' GROUP BY date_year, date_month) AS t2 ON t1.date_year = t2.date_year AND t1.date_month = t2.date_month ORDER BY t1.date_year, t1.date_month
unknown
d19493
test
'scaled' using plt The best thing is to use: plt.axis('scaled') As Saullo Castro said. Because with equal you can't change one axis limit without changing the other so if you want to fit all non-squared figures you will have a lot of white space. Equal Scaled 'equal' using ax Alternatively, you can use the axes class. fig = plt.figure() ax = figure.add_subplot(111) ax.imshow(image) ax.axes.set_aspect('equal') A: There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick. To do it after the fact you can use the current axis and set it's aspect ratio with "set_aspect('equal')". In your example: import matplotlib.pyplot as plt plt.fill(*zip(*polygon)) plt.axes().set_aspect('equal', 'datalim') plt.show() I use this all the time and it's from the examples on the matplotlib website. A: Does it help to use: plt.axis('equal') A: Better plt.axis('scaling'), it works better if you want to modify the axes with xlim() and ylim().
unknown
d19495
test
You can manage Azure NSG configuration via ARM template, Teffaform and Ansible. * *ARM template 1,You can check out below examples to create ARM Template to manage Azure NSG. Create a Network Security Group. How to create NSGs using a template Please check the official document for more examples. 2, After the ARM template is created and pushed to your git repo. You can create azure pipeline to automate the deployment. See tutorial here. 3, Then you need to create an azure Resource Manager service connection to connect your Azure subscription to Azure devops. See this thread for an example. 4, In your azure devops pipeline. You can use ARM template deployment task to deploy the ARM template. steps: - task: AzureResourceManagerTemplateDeployment@3 displayName: 'ARM Template deployment: Resource Group scope' inputs: azureResourceManagerConnection: 'azure Resource Manager service connection' subscriptionId: '...' resourceGroupName: '...' location: 'East US' csmFile: azuredeploy.json csmParametersFile: azuredeploy.parameters.json * *Teffaform 1, Create Teffaform configuration file. See example here. Check out terraform-azurerm-network-security-group module for more information. 2, Upload Teffaform configuration file to git repo. Create Azure devops pipeline 3, Create azure Resource Manager service connection like above using ARM template. 4, Use Terraform task in the azure devops pipeline. steps: - task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0 displayName: 'Install Terraform 0.12.3' - task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0 displayName: 'Terraform : azurerm' inputs: command: apply environmentServiceNameAzureRM: 'azure Resource Manager service connection' * *Ansible 1, Create Ansible playbook with plugin azure.azcollection.azure_rm_securitygroup Please check out the example here. 2,Upload ansible playbook to git repo. Create Azure devops pipeline. Use Ansible task in your pipeline. Please check out this detailed tutorial for more information about how to run ansible playbook in azure devops pipeline. * *Azure powershell/Azure CLI commands You can using azure powershell or azure cli commands to manage azure nsg. And run the commands in Azure powershell task or azure cli task in azure devops pipeline. Please check out this document for more information.
unknown
d19499
test
Try this: SELECT $path FROM ( TRAVERSE out() FROM (select from entities where id ='A') WHILE $depth <= N ) where id ='B'
unknown
d19501
test
If fetching the entity doesn't emit a Last-Modified header, then I would say this is a bug in the client, not SDR. If none of your entities support Last-Modified, maybe create a filter that strips If-Modified-Since from the request or catches it early and responds appropriately. All of that said, I also don't think a NPE is acceptable and a SDR bug should be filed.
unknown
d19503
test
"Looking for much simple way since full query have more than 15 columns" Sorry, you can have a complex query or no query at all :) The problem is the structure of the posted table mandates a complex query. That's because it uses a so-called "generic data model", which is actually a data anti-model. The time saved in not modelling the requirement and just smashing values into the table is time you will have to spend writing horrible queries to get those values out again. I assume you need to drive off the other table you referred to, and the posted table contains attributes supplementary to the core record. select ano.id , ano.name , ano.address , ano.region , t1.value as alt_id , t2.value as birth_date , t3.value as contact_no from another_table ano left outer join ( select id, value from generic_table where key = 'alt_id' ) t1 on ano.id = t1.id left outer join ( select id, value from generic_table where key = 'birth_date' ) t2 on ano.id = t2.id left outer join ( select id, value from generic_table where key = 'contact_no' ) t3 on ano.id = t3.id Note the need to use outer joins: one of the problems with generic data models is the enforcement of integrity constraints. Weak data typing can also be an issue (say if you wanted to convert the birth_date string into an actual date). A: PIVOT concept fits well for these types of problems : SQL> create table person_info(id int, key varchar2(25), value varchar2(25)); SQL> create table person_info2(id int, name varchar2(25), address varchar2(125), region varchar2(25)); SQL> insert into person_info values(4150521,'contact_no',772289317); SQL> insert into person_info values(4150522,'alt_id','98745612V'); SQL> insert into person_info values(4150522,'birth_date',date '1990-04-21'); SQL> insert into person_info values(4150522,'contact_no',777894561); SQL> insert into person_info2 values(4150521,'ABC','AAAAAA','ASD'); SQL> insert into person_info2 values(4150522,'XYZ','BBBBB','WER'); SQL> select p1.id, name, address, region, alt_id, birth_date, contact_no from person_info pivot ( max(value) for key in ('alt_id' as alt_id,'birth_date' as birth_date,'contact_no' as contact_no) ) p1 join person_info2 p2 on (p1.id = p2.id); ID NAME ADDRESS REGION ALT_ID BIRTH_DATE CONTACT_NO ------- ------- ------- ------ --------- ---------- ---------- 4150521 ABC AAAAAA ASD 12345678V 21-APR-89 772289317 4150522 XYZ BBBBB WER 98745612V 21-APR-90 777894561
unknown
d19509
test
Pages normally have controller(s), a service can be created to share data between pages ( by injecting service in associated controllers). Like: app.factory('myService', function() { var savedData = {} function set(data) { savedData = data; } function get() { return savedData; } return { set: set, get: get } }); In your controller A: myService.set(yourSharedData); In your controller B: $scope.desiredLocation = myService.get(); Happy Helping! A: Use a service (best) https://docs.angularjs.org/guide/services Or $rootScope (bad, but simpler) https://docs.angularjs.org/api/ng/service/$rootScope
unknown
d19513
test
@published - is two way binding ( model to view and view to model) Use case for @published is ,if your model property is also attribute in a tag. Example : For a table-element you want to provide data from external source ,so you'll define attribute data,in this case data property should be @published . <polymer-element name = "table-element" attributes ="structure data"> <template> <table class="ui table segment" id="table_element"> <tr> <th template repeat="{{col in cols}}"> {{col}} </th> </tr> <tr template repeat="{{row in data}}"> etc...... </template> <script type="application/dart" src="table_element.dart"></script> </polymer-element> @CustomTag("table-element") class Table extends PolymerElement { @published List<Map<String,String>> structure; // table struture column name and value factory @published List<dynamic> data; // table data @observable - is one way binding - ( model to view) If you just want to pass data from model to view use @observable Example : To use above table element i have to provide data ,in this case data and structure will be observable in my table-test dart code. <polymer-element name = "table-test"> <template> <search-box data ="{{data}}" ></search-box> <table-element structure ="{{structure}}" data = "{{data}}" ></table-element> </template> <script type="application/dart" src="table_test.dart"></script> </polymer-element> dart code CustomTag("table-test") class Test extends PolymerElement { @observable List<People> data = toObservable([new People("chandra","<a href=\"http://google.com\" target=\"_blank\"> kode</a>"), new People("ravi","kiran"),new People("justin","mat")]); @observable List<Map<String,String>> structure = [{ "columnName" : "First Name", "fieldName" : "fname"}, {"columnName" : "Last Name", "fieldName" : "lname","cellFactory" :"html"}]; Test.created():super.created(); Examples are taken from My Repo
unknown
d19523
test
You can use different methodes $this->Connect = new mysqli( $Config['mysql']['hostname'], $Config['mysql']['username'], $Config['mysql']['password'], $Config['mysql']['database'], $Config['mysql']['dataport']) or die('The connection fails, check config.php'); or if (!$this->Connection) { die('The connection fails, check config.php'); } I should put the error in the die part too if I was you: die('Connection failed' . mysqli_connect_error());
unknown
d19529
test
I wouldn't use this approach because it makes building a project checked out from the SCM not possible without providing the build.number property. I don't think that this is a good thing. Maybe I'm missing something though. Actually, I don't get what you are trying to achieve exactly (why don't you write the build number in the manifest for example). But, according to the Maven Features on the Teamcity website: By default, it also keeps TeamCity build number in sync with the Maven version number (...). Couldn't that be helpful? There is another thread about this here. A: Try to use generateReleasePoms property of maven-realease-plugin, maybe that helps a little.
unknown
d19531
test
This worked for me in a word document. It may do the same for you... Function I used: import re def removeSpecialCharacters(cellValue): text=re.sub(r"[\r\n\t\x07\x0b]", "", cellValue) return text Afterwards, I used this for the values: character = table.Cell(Row = 1, Column = 1).Range.Text character = removeSpecialCharacters(character) You may also use a for loop for your solution as well.
unknown
d19533
test
In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions. As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private). Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals. A: If the scope of the objects is the lifetime of the class they are instantiated in, then they should be private member variables. If they do not maintain state themselves, then you should make them static classes. You should still pass them around as variables, or at least create property accessors to get at the backing field. This way you can change implementation details without blowing up your code. SOLID design principles are a good place to start when thinking about these things. A: I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. This sounds like a perfect time to use a private static readonly variable. These can be initialized in their declaration, or you can make a static constructor to initialize them. The fact that you are only referencing these objects within a single class is key point. There are other better ways to do things if these objects are ever needed outside of the single class. A: If the objects will be the same for every instance of the class then static const double PI = 3.14158; A: You should generally use accessor methods (e.g. getters and setters) and keep your internal variables private. This way the rest of your code, outside of your class, is not dependent on your actual variables. See this tutorial. A: If your class is dependent on these 2 objects then they should probably be members on the class itself. Something like this (where A is the class you are talking about and B is one of the objects you initialize: public class A { private B _b; public A(B b) { _b = b; } public void DoSomething() { //do something with _b; } private void DoSomethingElse() { //do something else with _b; } } In this example A is dependent on B (so you pass your instance of B into A's constructor or through some Dependency Injection framework). It wouldn't make a lot of sense for every method on class A to need a parameter of type B to be passed to it. A: I think in this case you should ask what makes more sense. Is there some kind of relationship between the 2 objects and the new class. Also, how often are they used in the class. Generally, If only a couple of methods use the objects, pass them around otherwise, instantiate them as class level variables (possibly using private static readonly as Jefferey suggests) and use them in the class. Making the code more readable should be your goal here.
unknown
d19539
test
Skype for Business does not support its own calendar. Instead, it gets calendar data from the Exchange account of the signed in user. You can easily add a new event to the user's calendar by using the Microsoft Graph RESTful API: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_post_events
unknown
d19541
test
You can also check out archive-tar-minitar, it is partially based on minitar that you already tested out, and it doesn't seem that it emmits calls to the command line. A: I ended up giving up with using a gem to manipulate the tar archives, and just doing it by shelling out to the commandline. `cd #{container} && tar xvfz sdk.tar.gz` `cd #{container} && tar xvfz Wizard.tar.gz` #update the framework packaged with the wizard FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.bundle") FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.framework") FileUtils.mv(container + "/resources/SDK.bundle", container + "/Wizard.app/Contents/Resources/") FileUtils.mv(container + "/resources/SDK.framework", container + "/Wizard.app/Contents/Resources/") config_plist = render_to_string({ file: 'site/_wizard_config', layout: false, locals: { app_id: @version.app.id }, formats: 'xml' }) File.open(container + "/Wizard.app/Contents/Resources/Configuration.plist", 'w') { |file| file.write( config_plist ) } `cd #{container} && rm Wizard.tar.gz` `cd #{container} && tar -cvf Wizard.tar 'Wizard.app'` `cd #{container} && gzip Wizard.tar` All these backticks make me feel like I'm writing Perl again.
unknown
d19543
test
/// <summary> /// Checks if string contains only letters a-z and A-Z and should not be more than 25 characters in length /// </summary> /// <param name="value">String to be matched</param> /// <returns>True if matches, false otherwise</returns> public static bool IsValidString(string value) { string pattern = @"^[a-zA-Z]{1,25}$"; return Regex.IsMatch(value, pattern); } A: The string can be up to 25 letters long. (I'm not sure if regex can check length of strings) Regexes ceartanly can check length of a string - as can be seen from the answers posted by others. However, when you are validating a user input (say, a username), I would advise doing that check separately. The problem is, that regex can only tell you if a string matched it or not. It won't tell why it didn't match. Was the text too long or did it contain unallowed characters - you can't tell. It's far from friendly, when a program says: "The supplied username contained invalid characters or was too long". Instead you should provide separate error messages for different situations. A: The regular expression you are using is an alternation of [^a-z] and [^A-Z]. And the expressions [^…] mean to match any character other than those described in the character set. So overall your expression means to match either any single character other than a-z or other than A-Z. But you rather need a regular expression that matches a-zA-Z only: [a-zA-Z] And to specify the length of that, anchor the expression with the start (^) and end ($) of the string and describe the length with the {n,m} quantifier, meaning at least n but not more than m repetitions: ^[a-zA-Z]{0,25}$ A: Regex lettersOnly = new Regex("^[a-zA-Z]{1,25}$"); * *^ means "begin matching at start of string" *[a-zA-Z] means "match lower case and upper case letters a-z" *{1,25} means "match the previous item (the character class, see above) 1 to 25 times" *$ means "only match if cursor is at end of string" A: I'm trying to create a regex to verify that a given string only has alpha characters a-z or A-Z. Easily done as many of the others have indicated using what are known as "character classes". Essentially, these allow us to specifiy a range of values to use for matching: (NOTE: for simplification, I am assuming implict ^ and $ anchors which are explained later in this post) [a-z] Match any single lower-case letter. ex: a matches, 8 doesn't match [A-Z] Match any single upper-case letter. ex: A matches, a doesn't match [0-9] Match any single digit zero to nine ex: 8 matches, a doesn't match [aeiou] Match only on a or e or i or o or u. ex: o matches, z doesn't match [a-zA-Z] Match any single lower-case OR upper-case letter. ex: A matches, a matches, 3 doesn't match These can, naturally, be negated as well: [^a-z] Match anything that is NOT an lower-case letter ex: 5 matches, A matches, a doesn't match [^A-Z] Match anything that is NOT an upper-case letter ex: 5 matches, A doesn't matche, a matches [^0-9] Match anything that is NOT a number ex: 5 doesn't match, A matches, a matches [^Aa69] Match anything as long as it is not A or a or 6 or 9 ex: 5 matches, A doesn't match, a doesn't match, 3 matches To see some common character classes, go to: http://www.regular-expressions.info/reference.html The string can be up to 25 letters long. (I'm not sure if regex can check length of strings) You can absolutely check "length" but not in the way you might imagine. We measure repetition, NOT length strictly speaking using {}: a{2} Match two a's together. ex: a doesn't match, aa matches, aca doesn't match 4{3} Match three 4's together. ex: 4 doesn't match, 44 doesn't match, 444 matches, 4434 doesn't match Repetition has values we can set to have lower and upper limits: a{2,} Match on two or more a's together. ex: a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa matches a{2,5} Match on two to five a's together. ex: a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa doesn't match Repetition extends to character classes, so: [a-z]{5} Match any five lower-case characters together. ex: bubba matches, Bubba doesn't match, BUBBA doesn't match, asdjo matches [A-Z]{2,5} Match two to five upper-case characters together. ex: bubba doesn't match, Bubba doesn't match, BUBBA matches, BUBBETTE doesn't match [0-9]{4,8} Match four to eight numbers together. ex: bubba doesn't match, 15835 matches, 44 doesn't match, 3456876353456 doesn't match [a3g]{2} Match an a OR 3 OR g if they show up twice together. ex: aa matches, ba doesn't match, 33 matches, 38 doesn't match, a3 DOESN'T match Now let's look at your regex: [^a-z]|[^A-Z] Translation: Match anything as long as it is NOT a lowercase letter OR an upper-case letter. To fix it so it meets your needs, we would rewrite it like this: Step 1: Remove the negation [a-z]|[A-Z] Translation: Find any lowercase letter OR uppercase letter. Step 2: While not stricly needed, let's clean up the OR logic a bit [a-zA-Z] Translation: Find any lowercase letter OR uppercase letter. Same as above but now using only a single set of []. Step 3: Now let's indicate "length" [a-zA-Z]{1,25} Translation: Find any lowercase letter OR uppercase letter repeated one to twenty-five times. This is where things get funky. You might think you were done here and you may well be depending on the technology you are using. Strictly speaking the regex [a-zA-Z]{1,25} will match one to twenty-five upper or lower-case letters ANYWHERE on a line: [a-zA-Z]{1,25} a matches, aZgD matches, BUBBA matches, 243242hello242552 MATCHES In fact, every example I have given so far will do the same. If that is what you want then you are in good shape but based on your question, I'm guessing you ONLY want one to twenty-five upper or lower-case letters on the entire line. For that we turn to anchors. Anchors allow us to specify those pesky details: ^ beginning of a line (I know, we just used this for negation earlier, don't get me started) $ end of a line We can use them like this: ^a{3} From the beginning of the line match a three times together ex: aaa matches, 123aaa doesn't match, aaa123 matches a{3}$ Match a three times together at the end of a line ex: aaa matches, 123aaa matches, aaa123 doesn't match ^a{3}$ Match a three times together for the ENTIRE line ex: aaa matches, 123aaa doesn't match, aaa123 doesn't match Notice that aaa matches in all cases because it has three a's at the beginning and end of the line technically speaking. So the final, technically correct solution, for finding a "word" that is "up to five characters long" on a line would be: ^[a-zA-Z]{1,25}$ The funky part is that some technologies implicitly put anchors in the regex for you and some don't. You just have to test your regex or read the docs to see if you have implicit anchors. A: Do I understand correctly that it can only contain either uppercase or lowercase letters? new Regex("^([a-z]{1,25}|[A-Z]{1,25})$") A regular expression seems to be the right thing to use for this case. By the way, the caret ("^") at the first place inside a character class means "not", so your "[^a-z]|[^A-Z]" would mean "not any lowercase letter, or not any uppercase letter" (disregarding that a-z are not all letters).
unknown
d19549
test
Appreciate that applying or popping a Git stash just alters the working directory and/or stage. It does not make a new commit. Therefore, simply doing a hard reset should get you back to where you were before the first stash: # from your branch git reset --hard That being said, if you wanted to retain some permutation of the changes since the first stash, that is another story and would require more work and thought to pull off. Note: Generally speaking, popping a Git stash is risky, because if something goes wrong along the way, you can't reapply the same stash as it has already been popped from the stack. Use git stash apply for best results. A: git stash list <shows all the saved stashes> git stash show 'stash{0}' <displays changes in this stash> <change index according to the one you want, 0 is the last saved stash> git stash apply 'stash{0}' <applies the stash>
unknown
d19551
test
It shows you installed all the simulators. Just Quit the Xcode and open again. It wil show you a window same as below. Also please cross check that, the downlaoded SDK's are available under Application->Xcode.app->right-click->Show Package Contents ->Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs Also cross check the Base SDK and Target devices.
unknown
d19555
test
I suggest you look at ResourceT: ResourceT is a monad transformer which creates a region of code where you can safely allocate resources. A: You can use System.Mem.Weak.addFinalizer for this. Unfortunately the semantics for weak references can be a little difficult to understand at first. The warning note is particularly important. If you can attach an IORef, MVar, or TVar to your key, and make a weak reference/finalizer associated with that, it's likely to be much more reliable. In the special case that your key is a pointer to non-managed memory (e.g. some C data structure), you should instead create a ForeignPtr and attach a finalizer to it. The semantics for these finalizers are a little different; rather than an arbitrary IO action the finalizer must be a function pointer to an external function.
unknown
d19557
test
After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html to summarise though this should help you (untested): This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width. Follow these instructions to add the code to Outlook. * *Start Outlook *Press ALT+F11 to open the Visual Basic Editor *If not already expanded, expand Microsoft Office Outlook Objects *If not already expanded, expand Modules *Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module. *Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window *Click the diskette icon on the toolbar to save the changes *Close the VB Editor Here's how to add a button to the QAT for running the macro with a single click. Outlook 2010. http://www.howto-outlook.com/howto/macrobutton.htm#qat Sub ResizeAllPicsTo75Pct() Const wdInlineShapePicture = 3 Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object Set olkMsg = Application.ActiveInspector.CurrentItem Set wrdDoc = olkMsg.GetInspector.WordEditor For Each wrdShp In wrdDoc.InlineShapes If wrdShp.Type = wdInlineShapePicture Then wrdShp.ScaleHeight = 75 wrdShp.ScaleWidth = 75 End If Next Set olkMsg = Nothing Set wrdDoc = Nothing Set wrdShp = Nothing End Sub
unknown
d19561
test
I don't believe you need Business Intelligence Development Studio for this. You should be able to link to the remote server, run an external query and then do an SELECT INTO statement to insert the table data directly into your database. A: (i am assuming that you are running SQL Server 2005+) If you have access to both SQL Servers, simply use the Data Import / Export wizard. * *Open Management Studio and connect to source database server. *Right click the source database and click Export Data. *Follow the wizard. It will ask to target database and table. You can create a new database / table at the target system with this wizard. You can also use SQL Script Generator, a free & great tool which allows you to script both database, table with it's data. See http://sqlscriptgenerator.com/ for more information about the tool. And yes, you don't need Business Intelligence Development Studio.
unknown
d19563
test
You can use broadcasted comparison to generate a mask, and index into arr accordingly: arr[np.arange(arr.shape[1]) <= idxs[:, None]] = 0 print(arr) array([[0, 2, 3, 4], [0, 0, 3, 4], [0, 0, 0, 4], [0, 2, 3, 4]]) A: This does the trick: import numpy as np arr = np.array([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]) idxs = [0,1,2,0] for i,j in zip(range(arr.shape[0]),idxs): arr[i,:j+1]=0 A: Here is a sparse solution that may be useful in cases where only a small fraction of places should be zeroed out: >>> idx = idxs+1 >>> I = idx.cumsum() >>> cidx = np.ones((I[-1],), int) >>> cidx[0] = 0 >>> cidx[I[:-1]]-=idx[:-1] >>> cidx=np.cumsum(cidx) >>> ridx = np.repeat(np.arange(idx.size), idx) >>> arr[ridx, cidx]=0 >>> arr array([[0, 2, 3, 4], [0, 0, 3, 4], [0, 0, 0, 4], [0, 2, 3, 4]]) Explanation: We need to construct the coordinates of the positions we want to put zeros in. The row indices are easy: we just need to go from 0 to 3 repeating each number to fill the corresponding slice. The column indices start at zero and most of the time are incremented by 1. So to construct them we use cumsum on mostly ones. Only at the start of each new row we have to reset. We do that by subtracting the length of the corresponding slice such as to cancel the ones we have summed in that row. A: import numpy as np arr = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) idxs = np.array([0, 1, 2, 0]) for i, idx in enumerate(idxs): arr[i,:idx+1] = 0
unknown
d19573
test
You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall If this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access. A: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit. Also, there is Microsoft Support article How to Use WinDiff to Compare Registry Files. For a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for example). A: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install) There is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote). You can also run it live from here, so though not strictly pythonic you could plug it in quite nicely. A: Taken from List installed software from the command line: If you want to list the software known to Windows Management Instrumentation (WMI) from the command line, use WMI command line (WMIC) interface. To list all products installed locally, run the following command: wmic product Caveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class
unknown
d19575
test
Take note that each row of mapMatrix must be ascending startMatrix <- t(matrix( c(2.3, 1.2, 3.6, 6.9, 5.3, 6.7), nrow = 3, ncol = 2)) mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3, 5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2)) res <- do.call(rbind,lapply(1:nrow(startMatrix), function(m) mapMatrix[m,][findInterval(startMatrix[m,],mapMatrix[m,])])) Hope this helps! > res [,1] [,2] [,3] [1,] 2.0 1 3.0 [2,] 6.2 5 6.2
unknown
d19579
test
You can use ListView component, the first row would be your header (renderHeader), others are rows (renderRow). Both row and header would be the same component containing a parent View with flexDirection: 'row' with 4 Text components. Each Text component would have a flex: 1 if you want them to be of the same widths. A: import React from "react"; import { registerComponent } from "react-native-playground"; import { StatusBar, StyleSheet, Text, View } from "react-native"; class App extends React.Component { render() { return ( <View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Jill</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Smith</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>50</Text> </View> </View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Eve</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Jackson</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>94</Text> </View> </View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>First Name</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Last Name</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Age</Text> </View> </View> </View> ); } } registerComponent(App); Here's the working code https://rnplay.org/apps/e3MZAw
unknown
d19581
test
You can either include it in the template, or place it just outside the templated div, and set its position absolutely with CSS. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" /> <div style="height: 100%; width: 100%;" data-bind="template: { name: $root.currentChildTemplate() }"></div> You could go a step further, and have it only visible when a certain observable is true. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" data-bind="visible: ajaxLoading" />
unknown
d19585
test
You have to have to define a Style for each control. This is because the visuals and visual states are defined by the internal ControlTemplate of each control. But you can significantly reduce the amount of work by reusing templates and cascading styles. To allow easy color theming and centralized customization, you should create a resource that defines all relevant colors of your theme: ColorResources.xaml <ResourceDictionary> <!-- Colors --> <Color x:Key="HighlightColor">DarkOrange</Color> <Color x:Key="DefaultControlColor">LightSeaGreen</Color> <Color x:Key="ControlDisabledTextColor">Gray</Color> <Color x:Key="BorderColor">DarkGray</Color> <Color x:Key="MouseOverColor">LightSteelBlue</Color> <!-- Brushes --> <SolidColorBrush x:Key="HighlightBrush" Color="{StaticResource HighlightColor}" /> <SolidColorBrush x:Key="ControlDisabledTextBrush" Color="{StaticResource ControlDisabledColor}" /> <SolidColorBrush x:Key="BorderBrush" Color="{StaticResource BorderColor}" /> <SolidColorBrush x:Key="MouseOverBrush" Color="{StaticResource MouseOverColor}" /> </ResourceDictionary> You may add the following styles an templates to the App.xaml file: App.xaml <Application> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/File/Path/To/ColorResources.xaml" /> </ResourceDictionary.MergedDictionaries> ... </ResourceDictionary> </Application.Resources> </Application> To override the color of the selected row in a GridView or DataGrid you simply need to override the default brush SystemColors.HighlightBrush used by these controls: <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{StaticResource HighlightColor}" /> To override the default color of controls like the column headers of e.g DatGrid you simply need to override the default brush SystemColors.ControlBrush used by these controls: <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{StaticResource DefaultControlColor}" /> For simple ContentControls like Button or ListBoxItem you can share a common ControlTemplate. This shared ControlTemplate will harmonize the visual states: <ControlTemplate x:Key="BaseContentControlTemplate" TargetType="ContentControl"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <ContentPresenter/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="{StaticResource ControlDisabledTextBrush}" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Opacity" Value="0.7" /> <Setter Property="Background" Value="{StaticResource MouseOverBrush}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> This base template will be applied using base styles. This allows simple chaining (style inheritance) and reuse of the BaseContentControlTemplate for different controls like Button or ListBoxItem: <Style x:Key="BaseContentControlStyle" TargetType="ContentControl"> <Setter Property="Template" Value="{StaticResource BaseContentControlTemplate}" /> </Style> Some ContentControl like a Button might need additional states like Pressed. You can extend additional basic visual states by creating a base style that e.g., targets ButtonBase and can be used with any control that derives from ButtonBase: <Style x:Key="BaseButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource BaseContentControlStyle}"> <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> To apply this base styles you have to target the controls explicitly. You use this styles to add more specific visual states or layout e.g., ListBoxItem.IsSelcted, ToggleButton.IsChecked or DataGridColumnHeader: <!-- Buttons --> <Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}" /> <Style TargetType="ToggleButton" BasedOn="{StaticResource BaseButtonStyle}"> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> <!- ListBox --> <Style TargetType="ListBoxItem" BasedOn="{StaticResource BaseContentControlStyle}"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> <!-- ListView --> <Style TargetType="ListViewItem" BasedOn="{StaticResource {x:Type ListBoxItem}}" /> <!-- GridView Since GridViewColumnHeader is also a ButtonBase we can extend existing style --> <Style TargetType="GridViewColumnHeader" BasedOn="{StaticResource BaseButtonStyle}" /> <Style x:Key="BaseGridViewStyle" TargetType="ListViewItem"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="{StaticResource {x:Static SystemColors.HighlightBrushKey}}" /> </Trigger> </Style.Triggers> </Style> <!-- DataGrid Since DataGridColumnHeader is also a ButtonBase we can extend existing style --> <Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource BaseButtonStyle}"> <Setter Property="BorderThickness" Value="1,0" /> <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" /> </Style> Other more complex composed controls like ComboBox, TreeView or MenuItem require to override the control's template individually. Since these controls are composed of other controls, you usually have to override the styles for this controls too. E.g., ComboBox is composed of a TextBox, ToggleButton an Popup. You can find their styles at Microsoft Docs: Control Styles and Templates. This is a very simple and basic way to add theming to your application. Knowledge of the inheritance tree of the controls helps to create reusable base styles. Reusing styles helps to reduce the effort to target and customize each control. Having all visual resources like colors or icons defined in one place makes it easy to modify them without having to know/modify each control individually. A: If you have a look at the default styles (https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/button-styles-and-templates), you will find out, that each style uses static resources for declaring the colors. So to achieve your project you would have to overwrite these static resources where the colors are stored. Unfortunately, this is not possible in WPF (was already asked before: Override a static resource in WPF). So your only solution would be to write a separate Style for each control and to re-declare the colors.
unknown
d19589
test
The same way you would add multiple users to a normal instance. I am going to assume you are using linux and can login to the instance, if not, see this post. Now you just need to add a user, and setup the ssh keys.
unknown
d19591
test
You could use regular string add operator <div id="@(Model.MyLabel + "Car")"></div> Or C# 6's string interpolation. <div id="@($"{Model.MyLabel}Car")"></div> A: What you want is to use the <text></text> pseudo tags <div id="@Model.MyLabel<text>Cars</text>" ...>
unknown
d19597
test
requires jQuery animate $('.blue').click(function(){ //expand red div width to 200px $('.red').animate({width: "200px"}, 500); setTimeout(function(){ //after 500 milliseconds expand height to 800px $('.red').animate({height:"800px"}, 500); },500); setTimeout(function(){ //after 1000 milliseconds show textarea (or textbox, span, etc) $('.red').find('input[type="textarea"]').show(); },1000); }); A: This can be done really easily with CSS. This video explains it very well. There are a ton of other neat tricks in that video, but I linked to the part where she explains a light box. .container { padding: 100px; } .red, .blue { width: 20px; height: 20px; float: left; background-color: blue; } .red { background-color: red; font-size: 0; color: white; width: 50px; transition: 1s height, 1s margin, 1s font-size, 1s 1s width; } .blue:focus ~ .red { height: 100px; width: 150px; font-size: inherit; margin-top: -40px; transition: 1s width, 1s 1s height, 1s 1s margin, 1s 1s font-size; } .red .hint { font-size: 14px; padding: 4px; transition: 1s 1s font-size; } .blue:focus ~ .red .hint { font-size: 0; transition: 1s font-size; } <div class="container"> <div class="blue" tabindex="-1"></div> <div class="red"><span class="hint">text1</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt</div> </div> A: $(window).load(function(){ $(".blue").click(function(){ $(".red").animate({width:'400px'},1000).animate({height:'400px',top:'150px'},1000).text("qwqwqwq"); }) }) ` .blue{ width: 100px; height: 100px; background-color: blue; } .red{ width:200px; height:100px; background-color: red; left:100px; } div{ display: inline-block; margin:0; padding: 0; position: absolute; top:300px; }`
unknown
d19605
test
You can place a div with that img as background-image and set 2 buttons/divs with position absolute. Like this: .home { background-color:red; width:100%; height:100vh; position:relative; } .btn1 { width:200px; height:200px; background-color:blue; position:absolute; top:20%; left:30%; } .btn2 { width:200px; height:200px; background-color:green; position:absolute; top:20%; left:50%; } <div class="home"> <a class="btn1" href="#"> page one </a> <a class="btn2" href="#"> page two </a> </div>
unknown
d19607
test
Yes you can show a form on a service's desktop. It will not be shown to any logged in user, in fact in Vista and later OSes you cannot show it to a user even if you set the service to 'interactive'. Since the desktop is not interactive the windows messages the form receives will be slightly different but the vast majority of the events should be triggered the same in a service as they would be on an interactive desktop (I just did a quick test and got the form load, shown, activated and closing events). One thing to remember is that in order to show a form your thread must be an STA thread and a message loop must be created, either by calling ShowDialog or Applicaton.Run. Also, remember all external interaction with the form will need to be marshaled to the correct thread using Invoke or BeginInvoke on the form instance. This is certainly very doable but is really not recommended at all. You must be absolutely sure that the form and any components it contains will not show any unexpected UI, such as a message box, under any circumstances. The only time this method can really be justified is when you are working with a dubious quality legacy or 3rd party tool that requires handle creation in order to function properly.
unknown
d19611
test
The regex description on MSDN: http://msdn.microsoft.com/en-us/library/bb982382.aspx Basically, you create "basic_regex" objects, then call the "regex_match" or "regex_replace" functions A: You shouldn't need any specific headers beyond <regex> to include the tr1 functionality. To get start using Regular Expressions in tr1 I suggest reading: http://www.johndcook.com/cpp_regex.html
unknown
d19613
test
I would use Automapper to map the two classes together in one call. This type of situation is what it was designed for. All you would need to do is create a mapping configuration and then map the two classes. It's a very simple but powerful tool. e.g. Something like this: var config = new MapperConfiguration(cfg => cfg.CreateMap<APICall.Group, modGroup>() .ForMember(dest => dest.modID, s=>s.MapFrom(s=>s.Id)); // etc create more mappings here ); var mapper = config.CreateMapper(); List<modGroup> modGroupList = mapper.Map<List<modGroup>>(groupData);
unknown
d19615
test
I can certainly confirm that this way will create A LOT OF PROBLEMS later while using filtering etc. In general, such an approach is critically against the very relational database architecture. It's ok as long as you treat your database as a silly key-value storage, but absolutely unacceptable if you are going to use your database as a database. The main rule for the database structure should be: each entity have to be stored separately. this way it will be accessible using standard SQL mechanisms. One of the possible ways to solve your current case, is creating a table with three columns: user_id, param_name, param_value
unknown
d19617
test
Spring is inferring the value to be a number. You can force the value to be treated as a string in YAML config by quoting it ie "845216416540" This answer covers YAML convention in detail: https://stackoverflow.com/a/22235064/13172778
unknown
d19619
test
len(pairs[]) raises a SyntaxError because the square brackets are empty: >>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>> pairs[] File "<stdin>", line 1 pairs[] ^ SyntaxError: invalid syntax >>> You need to tell Python where to index the list pairs: >>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>> pairs[0] # Remember that Python indexing starts at 0 ('cheese', 'queso') >>> pairs[1] ('red', 'rojo') >>> pairs[2] ('school', 'escuela') >>> len(pairs[0]) # Length of tuple at index 0 2 >>> len(pairs[1]) # Length of tuple at index 1 2 >>> len(pairs[2]) # Length of tuple at index 2 2 >>> I think it would be beneficial for you to read An Introduction to Python Lists and Explain Python's slice notation.
unknown
d19623
test
Multiprocessing could help but this sounds more like a threading problem. Any IO implementation should be made asynchronous, which is what threading does. Better, in python3.4 onwards, you could do asyncio. https://docs.python.org/3.4/library/asyncio.html If you have python3.5, this will be useful: https://docs.python.org/3.5/library/asyncio-task.html#example-hello-world-coroutine You can mix asyncio with multiprocessing to get the optimized result. I use in addition joblib. import multiprocessing from joblib import Parallel, delayed def parallelProcess(i): for index, label_number in enumerate(label_array): if index % i == 0: call_api_async(domain, api_call_1, api_call_2, label_number, api_key) if __name__=="__main__": num_cores_to_use = multiprocessing.cpu_count() inputs = range(num_cores_to_use) Parallel(n_jobs=num_cores_to_use)(delayed(parallelProcess)(i) for i in inputs)
unknown
d19625
test
You could calculate the empty space between blue div and pink div with a difference ($('.blue-container').height() - $('.blue').height()), then when the document scrolled till that misure you know that the pink div has touch the blue one. $(function(){ $(window).scroll(function(){ var margin = $('.blue-container').height() - $('.blue').height(); if($(this).scrollTop()>=margin){ $("body").addClass("orange") } else{ $("body").removeClass("orange") } }); }); body { margin:0; background:lightblue;} .blue-container { height:70vh; } .blue { height:40vh; position:sticky; width:70%; top:0; background:blue; margin:auto; } .pink { height:500px; position:relative; width:70%; margin-right:auto; margin-left:auto; background:pink; text-align:center; } .orange{ background:orange } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='blue-container'> <div class='blue'></div> </div> <div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div> A: I dont know if you can to that in pure CSS, but here is a vanillaJS solution: * *We trigger an event on scroll *We check blue's bottom position and pink's top position *If they are equals, we trigger the logic. var blue = document.querySelector('.blue') var pink = document.querySelector('.pink') var onTouch = false; //http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#event-type-scroll function onScrollEventHandler(ev) { var bottom = blue.getBoundingClientRect().bottom var top = pink.getBoundingClientRect().top // we set if (bottom == top && !onTouch) { document.body.style.backgroundColor = 'orange' onTouch = true } // we reset if (bottom != top && onTouch) { document.body.style.backgroundColor = 'lightblue' onTouch = false } } var el=window; if(el.addEventListener) el.addEventListener('scroll', onScrollEventHandler, false); else if (el.attachEvent) el.attachEvent('onscroll', onScrollEventHandler); body { margin:0; background:lightblue;} .blue-container { height:70vh; } .blue { height:40vh; position:sticky; width:70%; top:0; background:blue; margin:auto; } .pink { height:500px; position:relative; width:70%; margin-right:auto; margin-left:auto; background:pink; text-align:center; } <div class='blue-container'> <div class='blue'></div> </div> <div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div> This code is a work in progress. All inputs are welcome. A: You can use an intersection observer to detect when enough .pink element is inside the viewport touch the .blue element: const body = document.querySelector('body'); const blue = document.querySelector('.blue'); const target = document.querySelector('.pink'); const getHeight = (el) => el.getBoundingClientRect().height; // get the threshold in which enough of the pink elment would be inside the viewport to touch the blue element const threshold = (window.innerHeight - getHeight(blue)) / getHeight(target); const options = { rootMargin: '0px', threshold }; let prevRatio = 0; const handleIntersect = (entries, observer) => { entries.forEach(function(entry) { // if going up (above the previous threshold & above the threshold if (entry.intersectionRatio >= threshold && entry.intersectionRatio > prevRatio) { body.classList.add('body--intersected'); } else { body.classList.remove('body--intersected'); } prevRatio = entry.intersectionRatio; }); } const observer = new IntersectionObserver(handleIntersect, options); observer.observe(target); body { margin: 0; background: lightblue; } .body--intersected { background: pink; } .blue-container { height: 70vh; } .blue { height: 40vh; position: sticky; width: 70%; top: 0; background: blue; margin: auto; } .pink { height: 500px; position: relative; width: 70%; margin-right: auto; margin-left: auto; background: pink; text-align: center; } <div class='blue-container'> <div class='blue'></div> </div> <div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
unknown
d19627
test
df1 = { 'Name':['George','Andrea','micheal','maggie','Ravi', 'Xien','Jalpa'], 'Is_Male':[1,0,1,0,1,1,0]} df1 = pd.DataFrame(df1,columns=['Name','Is_Male']) Typecast to Categorical column in pandas df1['Is_Male'] = df1.Is_Male.astype('category')
unknown
d19631
test
Caveat: I haven't tried this, only read the manual. After all your include lines (including the transitive set of nested includes, and even lines created by text substitution or built by functions), the Make variable MAKEFILE_LIST will reference all your makefiles. So it should be sufficient to add a dependency to the end of your file such as %.o: $(MAKEFILE_LIST) You don't actually need the contents of the effective Makefile, just the list of files that comprise it. A: Is there a way to get make to spit out the Makefile after foo.mk has been included? No. There's gmake -d with a ton of debug output, some of which indicating which makefiles are being read: $ gmake -d|grep Reading Reading makefiles... Reading makefile `GNUmakefile'... Reading makefile `foo.mk' (search path) (no ~ expansion)... This might be helpful if there are recursive include directives or those under conditionals. Maybe you could tell us your actual problem you want to solve?
unknown
d19635
test
You can do this with the help of a Tally Table. WITH E1(N) AS( -- 10 ^ 1 = 10 rows SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N) ), E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows CteTally(N) AS( SELECT TOP(SELECT MAX(Tracks) FROM Product_Asset) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) FROM E4 ) SELECT Id = ROW_NUMBER() OVER(ORDER BY pa.PAId, t.N), pa.PAId, TrackNumber = t.N FROM Product_Asset pa INNER JOIN CteTally t ON t.N <= pa.Tracks ONLINE DEMO A: Try this,I am not using any Tally Table declare @Product_Asset table(PAId int,Tracks int) insert into @Product_Asset values (1 ,2),(2, 3) ;with CTE as ( select PAId,1 TrackNumber from @Product_Asset union all select pa.PAId,TrackNumber+1 from @Product_Asset pa inner join cte c on pa.PAId=c.PAId where c.TrackNumber<pa.Tracks ) select ROW_NUMBER()over(order by paid)id, * from cte IMHO,Recursive CTE or sub query or using temp table performance depend upon example to example. I find Recursive CTE more readable and won't use them unless they exhibit performance problem. I am not convince that Recursive CTE is hidden RBAR. CTE is just syntax so in theory it is just a subquery We can take any example to prove that using #Temp table will improve the performance ,that doesn't mean we always use temp table. Similarly in this example using Tally Table may not improve the performance this do not imply that we should take help of Tally Table at all.
unknown
d19637
test
1st method : With .split(), you can directly get the number of 'CGG' in your string. len(fragile_x_test.split('CGG'))-1 It should also be easier to calculate the tandem variable with it. 2nd method : If you don't need to work on the non 'CGG' part of the string, you can use .count() fragile_x_test.count('CGG') 3rd method : This method only counts 1 occurrence for each one or more "CGG" in a row and will add one to tandem variable each time there is more than 5 "CGG" in a row. example="|CGGCGGCGGCGGCGG|ACTACT|CGGCGGCGGCGGCGGCGGCGG|" count , repeat , tandem = 0 , 0 , 0 for element in example.split('CGG')[1:-1]: if element == '': count+=1 if count==4: tandem+=1 else: count=0 if count==1: repeat+=1 print("Number of CGG in a row : ",repeat) print("Number of CGG tandems : ",tandem) It will print repeat=2 and tandem=2.
unknown
d19639
test
Java 1.5 is the supported version for WebLogic 9.2. It looks like 10.0.3 introduced Java 6 for RH AS 5, 64-bit. Look here for links to info about each version of WebLogic. From there, you have to choose your operating system and architecture to find out what JVMs are supported. A: Weblogc 9.2.1 - 9.2.3 doesnot support JDK 1.6, any patch/revision of JDK 1.5 will get supported .Latest on today's date is patch 22 of JDK 1.5.
unknown
d19643
test
The first thing you should probably do is fix your regex. You cannot have a range like [a-Z], you can just do [a-z] and use the [NC] (no case) flag. Also, you want this rule at the very end since it'll match requests for /projects which will make it so the rule further down will never get applied. Then, you want to get rid of all your leading slashes. Lastly, you want a boundary for your regex, otherwise it'll match index.php and cause another error. So: RewriteEngine on RewriteRule ^home /index.php?page=home RewriteRule ^education /index.php?page=home&filter=1 RewriteRule ^skills /index.php?page=home&filter=2 RewriteRule ^projects /index.php?page=home&filter=3 RewriteRule ^experience /index.php?page=home&filter=4 RewriteRule ^([a-z]+)$ /index.php?page=$1 [NC]
unknown
d19645
test
Was able to fix this after removing two brackets! Oh, Python. :/ This is the fixed line: 'menuItems' : [{'action' : 'PLAY_VIDEO', 'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}],
unknown
d19647
test
To check if an object is of type List(of T) no matter of what type T is, you can use Type.GetGenericTypeDefinition() as in the following example: Public Sub Foo(obj As Object) If IsGenericList(obj) Then ... End If End Sub ... Private Function IsGenericList(ByVal obj As Object) As Boolean Return obj.GetType().IsGenericType _ AndAlso _ obj.GetType().GetGenericTypeDefinition() = GetType(List(Of )) End Function Or alternatively as an extension method: Public Sub Foo(obj As Object) If obj.IsGenericList() Then ... End If End Sub ... Imports System.Runtime.CompilerServices Public Module ObjectExtensions <Extension()> _ Public Function IsGenericList(obj As Object) As Boolean Return obj.GetType().IsGenericType _ AndAlso _ obj.GetType().GetGenericTypeDefinition() = GetType(List(Of )) End Function End Module A: List(Of Object) and List(Of String) are different types. You can do different things with them - for example, you can't add a Button to a List(Of String). If you're using .NET 4, you might want to consider checking against IEnumerable(Of Object) instead - then generic covariance will help you. Do you have any reason not to just make Foo generic itself? A: It's difficult to tell exactly what you're trying to accomplish. I'm pretty bad at mind reading, so I thought I'd let a few others try answering this question first. It looks like their solutions haven't been the silver bullet you're looking for, so I thought I'd give it a whack. I suspect that this is actually the syntax you're looking for: Public Sub Foo(Of T)(ByVal myList As List(Of T)) ' Do stuff End Sub This makes Foo into a generic method, and ensures that the object you pass in as an argument (in this case, myList) is always a generic list (List(Of T)). You can call any method implemented by a List(Of T) on the myList parameter, because it's guaranteed to be the proper type. There's really no need for anything as complicated as Reflection.
unknown
d19653
test
The following implementation maintain full compatibility with os.path.expandvars, yet allows a greater flexibility through optional parameters: import os import re def expandvars(path, default=None, skip_escaped=False): """Expand environment variables of form $var and ${var}. If parameter 'skip_escaped' is True, all escaped variable references (i.e. preceded by backslashes) are skipped. Unknown variables are set to 'default'. If 'default' is None, they are left unchanged. """ def replace_var(m): return os.environ.get(m.group(2) or m.group(1), m.group(0) if default is None else default) reVar = (r'(?<!\\)' if skip_escaped else '') + r'\$(\w+|\{([^}]*)\})' return re.sub(reVar, replace_var, path) Below are some invocation examples: >>> expandvars("$SHELL$unknown\$SHELL") '/bin/bash$unknown\\/bin/bash' >>> expandvars("$SHELL$unknown\$SHELL", '') '/bin/bash\\/bin/bash' >>> expandvars("$SHELL$unknown\$SHELL", '', True) '/bin/bash\\$SHELL' A: Try this: re.sub('\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path)) The regular expression should match any valid variable name, as per this answer, and every match will be substituted with the empty string. Edit: if you don't want to replace escaped vars (i.e. \$VAR), use a negative lookbehind assertion in the regex: re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path)) (which says the match should not be preceded by \). Edit 2: let's make this a function: def expandvars2(path): return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path)) check the result: >>> print(expandvars2('$TERM$FOO\$BAR')) xterm-256color\$BAR the variable $TERM gets expanded to its value, the nonexisting variable $FOO is expanded to the empty string, and \$BAR is not touched. A: The alternative solution - as pointed out by @HuStmpHrrr - is that you let bash evaluate your string, so that you don't have to replicate all the wanted bash functionality in python. Not as efficient as the other solution I gave, but it is very simple, which is also a nice feature :) >>> from subprocess import check_output >>> s = '$TERM$FOO\$TERM' >>> check_output(["bash","-c","echo \"{}\"".format(s)]) b'xterm-256color$TERM\n' P.S. beware of escaping of " and \: you may want to replace \ with \\ and " with \" in s before calling check_output A: Here's a solution that uses the original expandvars logic: Temporarily replace os.environ with a proxy object that makes unknown variables empty strings. Note that a defaultdict wouldn't work because os.environ For your escape issue, you can replace r'\$' with some value that is guaranteed not to be in the string and will not be expanded, then replace it back. class EnvironProxy(object): __slots__ = ('_original_environ',) def __init__(self): self._original_environ = os.environ def __enter__(self): self._original_environ = os.environ os.environ = self return self def __exit__(self, exc_type, exc_val, exc_tb): os.environ = self._original_environ def __getitem__(self, item): try: return self._original_environ[item] except KeyError: return '' def expandvars(path): replacer = '\0' # NUL shouldn't be in a file path anyways. while replacer in path: replacer *= 2 path = path.replace('\\$', replacer) with EnvironProxy(): return os.path.expandvars(path).replace(replacer, '$') A: I have run across the same issue, but I would propose a different and very simple approach. If we look at the basic meaning of "escape character" (as they started in printer devices), the purpose is to tell the device "do something different with whatever comes next". It is a sort of clutch. In our particular case, the only problem we have is when we have the two characters '\' and '$' in a sequence. Unfortunately, we do not have control of the standard os.path.expandvars, so that the string is passed lock, stock and barrel. What we can do, however, is to fool the function so that it fails to recognize the '$' in that case! The best way is to replace the $ with some arbitrary "entity" and then to transform it back. def expandvars(value): """ Expand the env variables in a string, respecting the escape sequence \$ """ DOLLAR = r"\&#36;" escaped = value.replace(r"\$", r"\%s" % DOLLAR) return os.path.expandvars(escaped).replace(DOLLAR, "$") I used the HTML entity, but any reasonably improbable sequence would do (a random sequence might be even better). We might imagine cases where this method would have an unwanted side effect, but they should be so unlikely as to be negligible. A: I was unhappy with the various answers, needing a little more sophistication to handle more edge cases such as arbitrary numbers of backslashes and ${} style variables, but not wanting to pay the cost of a bash eval. Here is my regex based solution: #!/bin/python import re import os def expandvars(data,environ=os.environ): out = "" regex = r''' ( (?:.*?(?<!\\)) # Match non-variable ending in non-slash (?:\\\\)* ) # Match 0 or even number of backslash (?:$|\$ (?: (\w+)|\{(\w+)\} ) ) # Match variable or END ''' for m in re.finditer(regex, data, re.VERBOSE|re.DOTALL): this = re.sub(r'\\(.)',lambda x: x.group(1),m.group(1)) v = m.group(2) if m.group(2) else m.group(3) if v and v in environ: this += environ[v] out += this return out # Replace with os.environ as desired envars = { "foo":"bar", "baz":"$Baz" } tests = { r"foo": r"foo", r"$foo": r"bar", r"$$": r"$$", # This could be considered a bug r"$$foo": r"$bar", # This could be considered a bug r"\n$foo\r": r"nbarr", # This could be considered a bug r"$bar": r"", r"$baz": r"$Baz", r"bar$foo": r"barbar", r"$foo$foo": r"barbar", r"$foobar": r"", r"$foo bar": r"bar bar", r"$foo-Bar": r"bar-Bar", r"$foo_Bar": r"", r"${foo}bar": r"barbar", r"baz${foo}bar": r"bazbarbar", r"foo\$baz": r"foo$baz", r"foo\\$baz": r"foo\$Baz", r"\$baz": r"$baz", r"\\$foo": r"\bar", r"\\\$foo": r"\$foo", r"\\\\$foo": r"\\bar", r"\\\\\$foo": r"\\$foo" } for t,v in tests.iteritems(): g = expandvars(t,envars) if v != g: print "%s -> '%s' != '%s'"%(t,g,v) print "\n\n" A: There is a pip package called expandvars which does exactly that. pip3 install expandvars from expandvars import expandvars print(expandvars("$PATH:${HOME:?}/bin:${SOME_UNDEFINED_PATH:-/default/path}")) # /bin:/sbin:/usr/bin:/usr/sbin:/home/you/bin:/default/path It has the benefit of implementing default value syntax (i.e., ${VARNAME:-default}).
unknown
d19655
test
With your shown samples/attempts please try following htaccess rules file. Please make sure to clear your browser cache before testing your URLs. RewriteEngine ON ##Rules for uris which starts from affiliate rewrite to affiliate.html here.. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^affiliate/?$ affiliate.html [QSA,NC,L] ##Rules for uris which starts from ref rewrite it to ref.html here.. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ref ref.html [QSA,NC,L] ##Rules for rest of the non-existing pages to rewrite to index.html here... RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [L] A: Have your rules like this instead: Options -MultiViews DirectoryIndex index.html RewriteEngine On # Prevent further processing if request maps to a static resource RewriteRule ^((index|affiliate|ref)\.html)?$ - [L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule . - [L] # /affiliate -> affiliate.html RewriteRule ^affiliate$ affiliate.html [L] # /ref/* -> ref.html RewriteRule ^ref/ ref.html [L] # * -> index.html RewriteRule . index.html [L] You do not need the RewriteBase directive here. (Or the <IfModule> wrapper.)
unknown
d19657
test
Note: This was tested with PowerShell 3.0 and 4.0. Within nested functions, all child functions have access to all of the parent functions' variables. Any changes to the variables are visible within the local scope of the current function and all the nested child functions called afterwards. When the child function has finished execution, the variables will return to the original values before the child function was called. In order to apply the variable changes throughout all the nested functions scopes, the variable scope type needs to be changed to AllScope: Set-Variable -Name varName -Option AllScope This way, no matter at what level within the nested functions the variable gets modified, the change is persistent even after the child function terminates and the parent will see the new updated value. Normal behavior of variable scopes within Nested Functions: function f1 ($f1v1 , $f1v2 ) { function f2 () { $f2v = 2 $f1v1 = $f2v #local modification visible within this scope and to all its children f3 "f2 -> f1v2 -- " + $f1v2 #f3's change is not visible here } function f3 () { "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2 $f3v = 3 $f1v2 = $f3v #local assignment will not be visible to f2 "f3 -> f1v2 -- " + $f1v2 } f2 "f1 -> f1v1 -- " + $f1v1 #the changes from f2 are not visible "f1 -> f1v2 -- " + $f1v2 #the changes from f3 are not visible } f1 1 0 Printout: f3 -> f1v1 -- 2 f3 -> f1v2 -- 3 f2 -> f1v2 -- 0 f1 -> f1v1 -- 1 f1 -> f1v2 -- 0 Nested Functions with AllScope variables: function f1($f1v1, $f1v2) { Set-Variable -Name f1v1,f1v2 -Option AllScope function f2() { $f2v = 2 $f1v1 = $f2v #modification visible throughout all nested functions f3 "f2 -> f1v2 -- " + $f1v2 #f3's change is visible here } function f3() { "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2 $f3v = 3 $f1v2 = $f3v #assignment visible throughout all nested functions "f3 -> f1v2 -- " + $f1v2 } f2 "f1 -> f1v1 -- " + $f1v1 #reflects the changes from f2 "f1 -> f1v2 -- " + $f1v2 #reflects the changes from f3 } f1 1 0 Printout: f3 -> f1v1 -- 2 f3 -> f1v2 -- 3 f2 -> f1v2 -- 3 f1 -> f1v1 -- 2 f1 -> f1v2 -- 3
unknown
d19659
test
I figured it out , it's a bit a handful but its worth it. First of all, at the ViewController where the action of sending an email should be called, put an NSNotification, like this : [self dismissViewControllerAnimated:YES completion:^{ [[NSNotificationCenter defaultCenter] postNotificationName:@"email" object:nil]; }]; Later on, when that view disappears, an original view controller will show up, since it was called through a modal view controller, in that one put : -(void)createEmail{ MFMailComposeViewController * mc = [[MFMailComposeViewController alloc] init]; NSArray *toRecipents = [NSArray arrayWithObject:@"[email protected]"]; mc.mailComposeDelegate = self; [mc setSubject:_emailSubject]; [mc setMessageBody:_emailMessage isHTML:NO]; [mc setToRecipients:toRecipents]; [self presentViewController:mc animated:YES completion:nil]; } And, in the viewDidload, add the following line : [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createEmail) name:@"email" object:nil]; That way, we are telling the original view controller, in her did load phase, to listen for a notification called email, and when we call it in the Email view controller, the app will know that a triggered notification has been fired, and will search for her following action, which is the delegate of the MFMailComposeViewController.That way, for any future developer, you will accomplish the designated target
unknown
d19661
test
I recommend using D3js, force directed graph is perfect for creating a network visualization, there are some examples here: D3 force directed graph
unknown
d19665
test
In the class, add a list of strings: private List<string> _allFiles = new List<string>(); Separate Start() to another method and call that for each of your files. At the end of each process, add the completeText variable to that list as shown below: public void Start() { theSourceFile = new FileInfo(Application.dataPath + "/puzzles.txt"); ProcessFile(theSourceFile); // set theSourceFile to another file // call ProcessFile(theSourceFile) again } private void ProcessFile(FileInfo file) { if (file != null && file.Exists) reader = file.OpenText(); if (reader == null) { Debug.Log("puzzles.txt not found or not readable"); } else { while ((txt = reader.ReadLine()) != null) { Debug.Log("-->" + txt); completeText += txt + "\n"; } _allFiles.Add(completeText); } } Finally, in your OnGui() method, add a loop around the GUI.Label call. int i = 1; foreach(var file in _allFiles) { GUI.Label(new Rect(1000, 50 + (i * 400), 400, 400), file); i++; } This assumes that you want the labels to appear vertically, and with no gap between them.
unknown
d19667
test
You should be able to concatenate everything in the <a> tag like so: echo '<a href="uploads/' . $row['bildnamn'] . '" rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">'; echo '<img src="uploads/' . $row['thumb_bildnamn'] . '">'; echo '</a>'; I inserted spaces to help emphasize where PHP does concatenation. In your case, a single quote starts/ends the string for PHP; a double quote is ignored and goes into the HTML. So this part: title="' . $row['uploaded'] . ' ' . $row['user'] . '" will make the title be the value of the uploaded column, then a space, then the value of the user column. Then just end the a tag with a >. A: you could continue to concatenate the string echo '<a href="uploads/'.$row['bildnamn'].'"'. 'rel="gallery" class="pirobox_gall" title="'.$row['uploaded'].' '.$row['user'].'">'; A: Try this: echo '<a href="uploads/' . $row['bildnamn'] . '" rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">'; echo '<img src="uploads/' . $row['thumb_bildnamn'] . '">'; echo '</a>'; A: You can do this using string concatenation, like this: $anchor = '<a href="uploads/'.$row['bildnamn'].'"'; $anchor .= 'rel="gallery" class="pirobox_gall" title="' . $row['uploaded'] . ' ' . $row['user'] . '">'; $anchor .= '<img src="uploads/'.$row['thumb_bildnamn'].'"></a>'; echo $anchor;
unknown
d19671
test
Add r before string, filter by boolean indexing and get index values to list: i = df[df.column1.str.contains(r'\b\d{5}\b')].index.tolist() print (i) [0, 2] Or if want parse only numeric values with length 5 change regex with ^ and $ for start and end of string: i = df[df.column1.str.contains(r'^\d{5}$')].index.tolist()
unknown
d19675
test
Also answered at What every developer should know about time (which includes the referenced screenshots). With daylight savings time ending today, I thought this was a good time for a post. How to handle time is one of those tricky issues where it is all too easy to get it wrong. So let's dive in. (Note: We learned these lessons when implementing the scheduling system in Windward Reports.) First off, using UTC (also known as Greenwich Mean Time) is many times not the correct solution. Yet many programmers think if they store everything that way, then they have it covered. (This mistake is why several years ago when Congress changed the start of DST in the U.S. you had to run a hotfix on Outlook for it to adjust reoccurring events.) So let's start with the key question – what do we mean by time? When a user says they want something to run at 7:00 am, what do they mean? In most cases they mean 7:00 am where they are located – but not always. In some cases, to accurately compare say web server statistics, they want each "day" to end at the same time, unadjusted for DST. At the other end, someone who takes medicine at certain times of the day and has that set in their calendar, will want that to always be on local time so a 3:00pm event is not 3:00am when they have travelled half way around the world. So we have three main use cases here (there are some others, but they can generally be handled by the following): 1.The same absolute (for lack of a better word) time. 2.The time in a given time zone, shifting when DST goes on/off (including double DST which occurs in some regions). 3.The local time. The first is trivial to handle – you set it as UTC. By doing this every day of the year will have 24 hours. (Interesting note, UTC only matches the time in Greenwich during standard time. When it is DST there, Greenwich and UTC are not identical.) The second requires storing a time and a time zone. However, the time zone is the geographical zone, not the present offset (offset is the difference with UTC). In other words, you store "Mountain Time," not "Mountain Standard Time" or "Mountain Daylight Savings Time." So 7:00 am in "Mountain Time" will be 7:00 am in Colorado regardless of the time of year. The third is similar to the second in that it has a time zone called "Local Time." However, it requires knowing what time zone it is in in order to determine when it occurs. Outlook now has a means to handle this. Click the Time Zones button: And you can now set the time zone for each event: When I have business trips I use this including my flight times departing in one zone and arriving in another. Outlook displays everything in the local timezone and adjusts when that changes. The iPhone on the other hand has no idea this is going on and has everything off when I'm on a trip that is in another timezone (and when you live in Colorado, almost every trip is to another timezone). Putting it to use Ok, so how do you handle this? It's actually pretty simple. Every time needs to be stored one of two ways: 1.As UTC. Generally when stored as UTC, you will still set/display it in local time. 2.As a datetime plus a geographical timezone (which can be "local time"). Now the trick is knowing which to use. Here are some general rules. You will need to figure this out for additional use cases, but most do fall in to these categories. 1.When something happened – UTC. This is a singular event and regardless of how the user wants it displayed, when it occurred is unchangeable. 2.When the user selects a timezone of UTC – UTC. 3.An event in the future where the user wants it to occur in a timezone – datetime plus a timezone. Now it might be safe to use UTC if it will occur in the next several months (changing timezones generally have that much warning - although sometimes it's just 8 days), but at some point out you need to do this, so you should do it for all cases. In this case you display what you stored. 4.For a scheduled event, when it will next happen – UTC. This is a performance requirement where you want to be able to get all "next events" where their runtime is before now. Much faster to search against dates than recalculate each one. However, this does need to recalculate all scheduled events regularly in case the rules have changed for an event that runs every quarter. 1.For events that are on "local time" the recalculation should occur anytime the user's timezone changes. And if an event is skipped in the change, it needs to occur immediately. .NET DateTime Diving in to .NET, this means we need to be able to get two things which the standard library does not provide: 1.Create a DateTime in any timezone (DateTime only supports your local timezone and UTC). 2.For a given Date, Time, and geographical timezone, get the UTC time. This needs to adjust based on the DST rules for that zone on that date. Fortunately there's a solution to this. We have open sourced out extensions to the DateTime timezone functionality. You can download WindwardTimeZone here. This uses registry settings in Windows to perform all calculations for each zone and therefore should remain up to date. Browser pain The one thing we have not figured out is how to know a user's location if they are using a browser to hit our web application. For most countries the locale can be used to determine the timezone – but not for the U.S. (6 zones), Canada, or Russia (11 zones). So you have to ask a user to set their timezone – and to change it when they travel. If anyone knows of a solution to this, please let me know. Update: I received the following from Justin Bonnar (thank you): document.getElementById('timezone_offset').value = new Date().getTimezoneOffset(); Using that plus the suggestion of the geo location for the IP address mentioned below will get you close. But it's not 100%. The time offset does not tell you if you for example if you are in Arizona (they & Hawaii do not observer daylight savings time) vs Pacific/Mountain (depending on DST) time zone. You also depend on javascript being on although that is true for 99% of the users out there today. The geo location based on IP address is also iffy. I was at a hotel in D.C. when I got a report of our demo download form having a problem. We pre-populate the form with city, state, & country based on the geo of the IP address. It said I was in Cleveland, OH. So again, usually right but not always. My take is we can use the offset, and for cases where there are multiple timezones with that offset (on that given day), follow up with the geo of the IP address. But I sure wish the powers that be would add a tz= to the header info sent with an HTML request.
unknown
d19679
test
@Ravi, you can use the following module to migrate data from the old field to the new field, you just need to map the fields. The module contains an example: https://www.drupal.org/project/migrate_d2d If the previous option is too complicated, you can do the following trick: export the old field table as INSERT format from the database, the table name will looks like this: field_data_field_name Then, just replace the name table from the old field to the new field table. Finally, just execute those insert into your database. This is an example, how an insert statement looks from a drupal field INSERT INTO field_data_field_name(entity_type,bundle,deleted,entity_id,revision_id,`language`,delta,field_address_type_value,field_address_type_format) VALUES ('entityform','solicitud_facturacion',0,656,656,'und',0,'AVENIDA',NULL); I hope you understand this!
unknown
d19681
test
* *Use .empty() Description: Remove all child nodes of the set of matched elements from the DOM. $("#myId").empty() console.log($("#myId").get(0).outerHTML) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myId"><div>aa</div><h3>hellow</h3><a href="#"></a></div> A: You could use different ways: // ref: https://api.jquery.com/empty/ $("#myId").empty() // ref: https://api.jquery.com/html/ $("#myId").html('') A: you can use remove() method. .empty() $( "#myId" ).empty() A: In order to remove or empty all the elements of a container div in this case, you can: $("#myId").empty(); OR $("#myId").html(''); Reference link to empty()
unknown
d19685
test
You can alter a field and make it not null without it checking the fields. If you are really concerned about not doing it off hours you can add a constraint to the field which checks to make sure it isn't null instead. This will allow you to use the with no check option, and not have it check each of the 4 million rows to see if it updates. CREATE TABLE Test ( T0 INT Not NULL, T1 INT NUll ) INSERT INTO Test VALUES(1, NULL) -- Works! ALTER TABLE Test WITH NOCHECK ADD CONSTRAINT N_null_test CHECK (T1 IS NOT NULL) ALTER COLUMN T1 int NOT NULL INSERT INTO Test VALUES(1, NULL) -- Doesn't work now! Really you have two options (added a third one see edit): * *Use the constraint which will prevent any new rows from being updated and leave the original ones unaltered. *Update the rows which are null to something else and then apply the not null alter option. This really should be run in off hours, unless you don't mind processes being locked out of the table. Depending on your specific scenario, either option might be better for you. I wouldn't pick the option because you have to run it in off hours though. In the long run, the time you spend updating in the middle of the night will be well spent compared the headaches you'll possibly face by taking a short cut to save a couple of hours. This all being said, if you are going to go with option two you can minimize the amount of work you do in off hours. Since you have to make sure you update the rows to not null before altering the column, you can write a cursor to slowly (relative to doing it all at once) * *Go through each row *Check to see if it is null *Update it appropriately. This will take a good while, but it won't lock the whole table block other programs from accessing it. (Don't forget the with(rowlock) table hint!) EDIT: I just thought of a third option: You can create a new table with the appropriate columns, and then export the data from the original table to the new one. When this is done, you can then drop the original table and change the name of the new one to be the old one. To do this you'll have to disable the dependencies on the original and set them back up on the new one when you are done, but this process will greatly reduce the amount of work you have to do in the off hours. This is the same approach that sql server uses when you make column ordering changes to tables through the management studio. For this approach, I would do the insert in chunks to make sure that you don't cause undo stress on the system and stop others from accessing it. Then on the off hours, you can drop the original, rename the second, and apply dependencies etc. You'll still have some off hours work, but it will be minuscule compared to the other approach. Link to using sp_rename. A: The only way to do this "quickly" (*) that I know of is by * *creating a 'shadow' table which has the required layout *adding a trigger to the source-table so any insert/update/delete operations are copied to the shadow-table (mind to catch any NULL's that might popup!) *copy all the data from the source to the shadow-table, potentially in smallish chunks (make sure you can handle the already copied data by the trigger(s), make sure the data will fit in the new structure (ISNULL(?) !) *script out all dependencies from / to other tables *when all is done, do the following inside an explicit transaction : * *get an exclusive table lock on the source-table and one on the shadowtable *run the scripts to drop dependencies to the source-table *rename the source-table to something else (eg suffix _old) *rename the shadow table to the source-table's original name *run the scripts to create all the dependencies again You might want to do the last step outside of the transaction as it might take quite a bit of time depending on the amount and size of tables referencing this table, the first steps won't take much time at all As always, it's probably best to do a test run on a test-server first =) PS: please do not be tempted to recreate the FK's with NOCHECK, it renders them futile as the optimizer will not trust them nor consider them when building a query plan. (*: where quickly comes down to : with the least possible downtime) A: Sorry for the discouragement, but: * *Any ways to speed it up: No, not if you want to change the table structure itself *or am I stuck just doing it overnight during off-hours? Yes, and that's probably for the best, as @HLGEM pointed out *Also could this cause a table lock? Yes Not directly relevant to you (because it's about going from NOT NULL to NULL), but interesting read on this topic: http://beyondrelational.com/blogs/sankarreddy/archive/2011/04/05/is-alter-table-alter-column-not-null-to-null-always-expensive.aspx And finally some ancient history - on an equivalent question in a forum in 2005, the same suggestion was made as @Kevin offered above - using a constraint insteadof making the column itself non-nullable: http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=50671
unknown
d19689
test
mainAxisAlignment: MainAxisAlignment.end, Try deleting this line.
unknown
d19691
test
Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts: Added a reset button to reset the game. var counter = 0; function myF() { if (counter != 5) { counter++; document.getElementById("slotLeft").innerHTML = "Try count: " + counter; var slotOne = Math.floor(Math.random() * 3) + 1; var slotTwo = Math.floor(Math.random() * 3) + 1; var slotThree = Math.floor(Math.random() * 3) + 1; document.getElementById("slotOne").innerHTML = slotOne; document.getElementById("slotTwo").innerHTML = slotTwo; document.getElementById("slotThree").innerHTML = slotThree; if (slotOne == slotTwo && slotTwo == slotThree) { document.getElementById("slotOne").style.backgroundColor = "#48bd48"; document.getElementById("slotTwo").style.backgroundColor = "#48bd48"; document.getElementById("slotThree").style.backgroundColor = "#48bd48"; document.getElementById("winner").classList.add("show"); counter = 5; // Edited this line } } else { console.log('Game over'); } } function myF1(){ counter = 0; document.getElementById("slotOne").innerHTML = ""; document.getElementById("slotTwo").innerHTML = ""; document.getElementById("slotThree").innerHTML = ""; } <button onclick="myF()">Check</button> <button onclick="myF1()">Restart Game</button> <div id="slotLeft"> </div> <div id="slotOne"> </div> <div id="slotTwo"> </div> <div id="slotThree"> </div> <div id="winner"> </div> A: function myF() { var slotOneElem = document.getElementById("slotOne"); var slotTwoElem = document.getElementById("slotTwo"); var slotThreeElem = document.getElementById("slotThree"); var generateRand = function() { return Math.floor(Math.random() * 3) + 1; } return (function () { var slotOne = generateRand(); var slotTwo = generateRand(); var slotThree = generateRand(); slotOneElem.innerHTML = slotOne; slotTwoElem.innerHTML = slotTwo; slotThreeElem.innerHTML = slotThree; if (slotOne === slotTwo && slotTwo === slotThree) { slotOneElem.style.backgroundColor = "#48bd48"; slotTwoElem.style.backgroundColor = "#48bd48"; slotThreeElem.style.backgroundColor = "#48bd48"; document.getElementById("winner").classList.add("show"); // Here is the win return true; } return false; })(); } var finished = myF(); while (!finished) { finished = myF(); }
unknown
d19697
test
NSString *name =[dataArray valueForKey:@"name"]; This doesn't do what you think it'll do. valueForKey:, when sent to an array, returns an array of the values corresponding to the given key for all the items in the array. So, that line will assign an array of the "name" values for all the items in dataArray despite the fact that you declared name as a NSString. Same goes for the subsequent lines. What you probably want instead is: for (NSManagedObject *item in dataArray) { NSString *name = [item valueForKey:@"name"]; ... Better, if you have a NSManagedObject subclass -- let's call it Person representing the entity you're requesting, you can say: for (Person *person in dataArray) { NSString *name = person.name; ... which leads to an even simpler version: for (Person *person in dataArray) { int response = [network sendName:person.name withDateOfBirth:person.dob andGender:person.gender forID:person.id]; although I'd change the name of that method to leave out the conjunctions and prepositions. -sendName:dateOfBirth:gender:id: is enough, you don't need the "with", "and", and "for."
unknown
d19699
test
Yes, you can. I just did. Write this code in your layout file: <CheckBox android:layout_width="match_parent" android:layout_height="match_parent" android:onClick="click"/> And in your activity: public void click(View view) { } A: Yes! it's possible. To define the click event handler for a checkbox, you should add android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method. The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must: 1. Be public 2. Return void, and 3. Define a View as its only parameter (this will be the View that was clicked) Below is the code examples: xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/meat" android:onClick="onCheckboxClicked"/> <CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cheese" android:onClick="onCheckboxClicked"/> </LinearLayout> The activity method should look as follows: public void onCheckboxClicked(View view) { // Is the view now checked? boolean checked = ((CheckBox) view).isChecked(); // Check which checkbox was clicked switch(view.getId()) { case R.id.checkbox_meat: if (checked) // Put some meat on the sandwich else // Remove the meat break; case R.id.checkbox_cheese: if (checked) // Cheese me else // I'm lactose intolerant break; // TODO: Veggie sandwich } } I hope you find this helpful.
unknown
d19703
test
Maybe: def myfucn(vars): vars = vars.split() try: float(vars[0]) if not "." in vars[0]: raise Exception("First var should be INT not Float") except ValueError: print("Error not Float found") try: int(vars[2]) except ValueError: print("Error Int no found") #answer a_float, b_str, c_int = vars print(" Yes ") greetings A: You are on the right track if the split() function. The problem is that when you say that user will give three values separated by ' ', you are taking in a string. The following is a string: '34.44 35.45 5' Maybe what you can do is after using split, you can cast each returned item to a variable. If you still need to check the type of variable, you can use the type() function. Hope this helps!
unknown
d19707
test
Try: $file = file_get_contents($url); $only_body = preg_replace("/.*<body[^>]*>|<\/body>.*/si", "", $file);
unknown
d19709
test
I also faced the same issue. For future people, make sure you have made the bucket public. From the same method you can also generate thumbnails and secured urls to your images public static String getImageURL(String inFilename) { String key = "/gs/" + BUCKETNAME + "/" + inFilename; ImagesService imagesService = ImagesServiceFactory.getImagesService(); ServingUrlOptions options = ServingUrlOptions.Builder .withGoogleStorageFileName(key).imageSize(150).secureUrl(true); String servingUrl = imagesService.getServingUrl(options); return servingUrl; }
unknown
d19711
test
You can use indexing with str with zfill: df = pd.DataFrame({'FLIGHT':['KL744','BE1013']}) df['a'] = df['FLIGHT'].str[:2] df['b'] = df['FLIGHT'].str[2:].str.zfill(4) print (df) FLIGHT a b 0 KL744 KL 0744 1 BE1013 BE 1013 I believe in your code need: df2 = pd.DataFrame(datatable,columns = cols) df2['a'] = df2['FLIGHT'].str[:2] df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4) df2["UPLOAD_TIME"] = datetime.now() ... ...
unknown
d19715
test
You have made a couple of mistakes in the line that calculates the mean. The most significant one is that when you try to calculate the mean for the last 9 rows of your dataframe, you go out of bounds. ie, if your dataframe has 100 rows, by row 92 your are trying to get the mean of rows 92:101; of course, there is no row 101. It should be something like this: for(i in 1: length(data[ , 5]-9)) { data$Mean [i] <- mean(data[i:min(i+9, nrow(data)),5]) } Also, it's generally a bad idea to use data as a variable name, since there already is a data() function in base R. Simply choose a similar name, like "mydata" A reproducible example follows, that will get the mean of the next ten rows, OR the mean of the n next rows for the last 9 rows. mydata <- data.frame(col_1 = rnorm(100), col_2 = rnorm(100), col_3 = rnorm(100), col_4 = rnorm(100), col_5 = rnorm(100)) for(i in 1: length(mydata[ , 5]-9)) { mydata$Mean [i] <- mean(mydata[i:min(i+9, nrow(mydata)),5]) } head(mydata) If you dont' want to get the mean for the last ten rows, do this instead: for(i in 1: length(mydata[ , 5]-9)) { mydata$Mean [i] <- ifelse( i + 9 <= nrow(mydata), mean(mydata[i:min(i+9, nrow(mydata)),5]), NA) }
unknown
d19719
test
1 . 1 2 . . . . 4 ColSums would look like: 3 . 5 RowSums would look like: 2 2 4 I would like to iterate over A and do this (1,1) > 3*2 (2,1) > 2*3 (1,3) > 2*5 (3,3) > 4*5 Creating B: 6 . 10 6 . . . . 20 How would I go about doing this in a vectorized way? I would think the function foo would look like: B=fooMap(A,fun) And fun would look like: fun(row,col) = RowSums(row) * ColSums(col) What's fooMap? EDIT: I went with flodel's solution. It uses summary to convert the sparse matrix into an i,j,x data frame, then uses with & friends to perform an operation on that frame, and then turns the result back into a sparse matrix. With this technique, the with/within operator is fooMap; the sparse matrix just has to be converted into the i,j,x data frame first so that with/within can be used. Here's a one-liner that solved this particular problem. B = with(summary(A), sparseMatrix(i=i, j=j, x = rowSums(A)[i] * colSums(A)[j])) A: Whenever I have element-wise operations on sparse matrices, I go back and forth between the matrix itself and its summary representation: summ.B <- summary(A) summ.B <- within(summ.B, x <- rowSums(A)[i]*colSums(A)[j]) B <- sparseMatrix(i = summ.B$i, j = summ.B$j, x = summ.B$x) B # 3 x 3 sparse Matrix of class "dgCMatrix" # # [1,] 6 . 10 # [2,] 6 . . # [3,] . . 20 A: Here's an approach that works with sparse matrices at each step. ## Load library and create example sparse matrix library(Matrix) m <- sparseMatrix(i = c(1,2,1,3), j = c(1,1,3,3), x = c(1,2,1,4)) ## Multiply each cell by its respective row and column sums. Diagonal(x = rowSums(m)) %*% (1*(m!=0)) %*% Diagonal(x = colSums(m)) # 3 x 3 sparse Matrix of class "dgCMatrix" # # [1,] 6 . 10 # [2,] 6 . . # [3,] . . 20 (The 1* in (1*(m!=0)) is being used to coerce the logical matrix of class "lgCMatrix" produced by m!=0 back to a numeric matrix class "dgCMatrix". A longer-winded (but perhaps clearer) alternative would to use as(m!=0, "dgCMatrix") in its place.)
unknown
d19721
test
Have your /folder/app/.htaccess like this: <IfModule mod_rewrite.c> RewriteEngine on RewriteBase /folder/app/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] </IfModule> then in /folder/app/application/config/config.php you need to have this config: $config['base_url'] = ''; $config['index_page'] = ''; $config['uri_protocol'] = 'AUTO';
unknown