qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
11,316,996
``` <div id="dialog" title="dialog" style="display:none" > Test <p>Test</p> </div> ``` I want all the text in "p" tag to be bold
2012/07/03
[ "https://Stackoverflow.com/questions/11316996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1135534/" ]
css : ``` #dialog p {font-weight:bold} ``` jquery ``` $('#id').find('p').css("font-weight","bold"); ```
102,401
I was just playing the board game *[Sorry!](https://en.wikipedia.org/wiki/Sorry!_(game))* with some people, and I realized that I could base a few interesting challenges off of it. This one is pretty simple. You task is simply to output an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") version of a sorry board, placing pieces where I tell you to. Specs ===== First, here is an image of an actual *Sorry!* board for reference: ![Sorry! Board](https://orig13.deviantart.net/7844/f/2015/355/7/5/sorry__game_board_1990_s_by_jdwinkerman-d9kw43c.png) The empty board looks like: ``` # > - - o # # # # > - - - o # # # # S v o # H # # # # # | | # | | # S o | # # ^ H # # # # # # H v # # | o S # | | # | | # # # # # H # o ^ S # # # # o - - - < # # # # o - - < # ``` Notice a few features. * The `#`'s are empty squares. * The `S`'s and `H`'s are Start's and Home's respectively. * The `>v<^`'s are the start of the slides, depending on which direction they face. * The `|`'s and `-`'s are the middles of slides, depending on if they're horizontal or vertical. * The `o`'s are the end's of slides. * Each column is separated by a column of spaces to make it look more square-like. Now here is what *you* have to do: * Your input is a list of coordinates of various pieces that have been placed on the board. * The coordinates start at `0` at the square outside the Start of the bottom color (yellow in the picture), and increase by one per square clockwise. * After these 60 squares, the safe zones have the next and last 20 coordinates, starting from the one on the bottom (which gets 60-64), then going clockwise. * You will have to place star's(`*`'s) on the correct coordinate, replacing the character underneath for all players. * Additionally, if any of the players are on the start square of a slider, move them to the end of the slider before placing them. * You can assume that there will be no collisions, before or after resolving sliders. * You con't need to worry about the Home's or Start's. * You can be 1-indexed if you want, but the test cases are 0-indexed. Test Cases ========== ``` [0, 20] -> # > - - o # # # # > - - - o # # # # S v * # H # # # # # | | # | | # S o | # # ^ H # # # # # # H v # # | o S # | | # | | # # # # # H # o ^ S # # # # o - - - < # # # # * - - < # [2, 7, 66] -> # > - - o # # # # > - - - o # # # # S v o # H # # # # # | | # | | # S o | # # ^ H # # # # # # H v # # | o S # | | # | | # * # # # H # o ^ S # # # # o - * - < # # * # o - - < # ```
2016/12/07
[ "https://codegolf.stackexchange.com/questions/102401", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/31343/" ]
Python 2, 476 bytes ------------------- Short 3-line solution ([Try it online](https://tio.run/nexus/python2#RVFRa4MwEH7fr5DmIUk9hxdN3Lp10JaB7z6KhZatkNEmol3ZQPzr3cVuTMjdl3yXz@9y13552rXiaPszcH7/4a0T@8geIgqOs@3l@SUZfFWO/P3Yv/OIz607iz2gkQffTVXRjL0kiWf0UQ5gZMiwWl1Gj8yUgWDDOCDbTHFd@WnDxi2WFNnr79qUeKHIcBh9tQ5pmDbDpFAahn7crirSpmLm6V/PgfAhz@R93x7tWfCRS3kXvNngzbr28yzk4gu@l@K4O@3fdpFbiBoxcYC6maOK6xSUSRzhPK5dogykhE1cowaX5Hgjir8bhDEjQlOVpvM0nGcTVlDoIKSDjtGgCMpazd2CVqwaKf495PTIwV9NZSlkGkgvvHGU/RGoQBWQK9DFjUmlsDK28qmvv5v6q1nyOZ9a7UKr/aLtaDg0o9sYO3m9UmsICjLIQQPpkXFdgH4A/QgmBYNALosUisfmBw)) ``` s=map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in "#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#").split('~')) for i in input():x,y=(lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[70-n,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2])((lambda n:4if n in[5,20,35,50]else 3if n in[12,27,42,57]else 0)(i)+i);s[y][x]='*' for r in s:print' '.join(r) ``` One-liner in 534 ([Try it online](https://tio.run/nexus/python2#VVFNa/MwDP4rZj44bpQRObGzlTFYxwvZOUeTQspScGntkmY9hfz1vnK6Hmaw9FiPPq3bPgxsYM4nx@60@@7YBr7W1loHh9Z5durOD8KvE4uYeUDdrlClNgdlMk@4TK3PlIGcsEktavBZiXeiekQQxoIITV46BpgSsFiwgkrHRHezBkVQWrXya7qpauFPFz4t3Z55atmSaw6FBsrZHy8982nxoFCBqqBUoKtfDr6k7Py3WAmaeMfi3A525Mt6/3Pqh27sk0620X6A7q99I1uZLF24ywhCPB8C/RgF71nMIPj2@vaeTaGpZxGrCSZWzo/JDtDI/VLP@Sf@nmWB0yEdwcyRY/NxnQNyU0eCT/OE/HORmyYsDz5vsSbJ//3ezxqvJDlOc2g2UU3LY1oy1IZjmLcfDeUmZx6o1lskQtRP8vlyProxEbOQEpw//4yJlOvzQO1S1/fBBnm70XoRFBRQggb6TVqerkC/gH4Fk4NBoE1VOVSv7X8)): ``` for r in(lambda B,I:[[[i,j]in map(lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[n-64,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2],map(lambda n:n+4if n in[5,20,35,50]else n+3if n in[12,27,42,57]else n,I))and'*'or b for i,b in enumerate(a)]for j,a in enumerate(B)])(map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in"#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#").split('~')),input()):print' '.join(r) ``` I assume indices of safe zone this way: ``` # > - - o # # # # > - - - o # # # 74 S v o 73 H 75 76 77 78 79 | | 72 | | 71 S o | 70 # ^ H # # # # # # H v # 60 | o S 61 | | 62 | | 69 68 67 66 65 H 63 o ^ S 64 # # # o - - - < # # # # o - - < # ``` Explanation (lines are separated a bit for better understanding): ``` # Hardcode board. Spaces are changed to their number in hex (as there are up to 14 spaces in row) # Unfortunatly v^<> characters made board non-symmetrical and replacing chars costs too much in python, so I had to hardcode it all B="#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#" # Encode board to list of lists of characters s=map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in B).split('~')) # Map coordinates, based on n (awfully long) # Creates long list (lenght of 80) with values based on n and only one valid, which occures under index n l=lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[70-n,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2] # Returns additional move of n if it appers to be on slide start j=lambda n:4if n in[5,20,35,50]else 3if n in[12,27,42,57]else 0 # Here takes input as list of numbers, get coordinates for them and update board with * for i in input():x,y=l(j(i)+i);s[y][x]='*' # Print board, spacing characters with one whitespace for r in s:print' '.join(r) ```
8,935,352
I have a small program in c ``` #include <stdio.h> #include <string.h> #define SIZE 30 int main() { char name[ SIZE ]; FILE *fpPtr; if ( ( fpPtr = fopen( "sorted_file.txt", "r" ) ) == NULL ) { printf( "File could not be opened\n" ); } else { printf( "%s\n", "Name" ); fscanf( fpPtr, "%s", name ); while( !feof( fpPtr ) ) { printf( "%s\n", name ); fscanf( fpPtr, "%s", name ); } fclose( fpPtr ); } return 0; }; ``` I want to find out how much memory is this program using . Any code or function i should add to find the total memory used by this program. I don't want to check task manager for this. I need to print the memory usage.
2012/01/20
[ "https://Stackoverflow.com/questions/8935352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1155111/" ]
You asked this just the other day over [here](https://stackoverflow.com/questions/8903512/memory-usage-of-a-c-program-under-windows/8903655), and I gave you this answer: > > Although it's no longer being actively developed, for C and ObjC code > (all I've used it for), I haven't found anything better than [MSS: > Memory Supervision System](http://hem.passagen.se/blizzar/mss/). > > > It's extremely straightforward and easy to setup; has been very > accurate in my experience and I've used it to great effect to weed out > any memory leaks in my applications. > > > To give you an idea of how easy it is to use: I compiled it into a > static library, link it to my program's debug targets and put the > include (import for ObjC) for the singular header into a common shared > header that all the rest of my program uses, so it tracks memory > across the entire program without even needed to think about it. > > > MSS will do exactly what you're asking for; it'll give you a ton of extra (extremely-useful) information as well, but the top of the report includes these lines: ``` MSG: Listing info about allocated blocks at end of program: INFO: 107 blocks currently allocated INFO: 11720 bytes of memory currently used. INFO: 2384479 bytes maximum memory used. ``` In just those lines, it tells you how many blocks of memory leaked, exactly how much memory leaked and the maximum memory footprint your program used. How to use MSS: First build the library using the makefile; just use `make lib` as we don't need the test programs. If you're not using gcc, you'll need to change the default compiler in the makefile. If you're using gcc and want both 64-bit and 32-bit versions, add either `-m64` or `-m32` to line 53 `CFLAGS=...` and then just run `make` on the file. You should now have a static library of MSS you can link into your program. The only header you need to include in your program along with the library is `mss.h`. To actually use MSS, you need to `#define MSS` and `#include <mss.h>` into every file you wish to have it track. If you want the entire program tracked, define MSS in the arguments to the compiler and include into a universal header that every source file includes. That is literally it; there's config files you can add to your program directory if you wish to change the verbosity of its logs and other features, but to just get it working, that is all you need to do. By the way, MSS includes a full read me in its doc folder that describes all this in much more detail.
511,238
I have used a 'Union' to combine two reports showing different dates. When I open the report on it's own it works fine with the two dates shown. However when I drill to the (union) report from another on the dashboard it only shows one date. Is there a dashboard filter that I may need to un apply or is there some other explanation!? I cannot seem to get the report to function as required from the drill.
2009/02/04
[ "https://Stackoverflow.com/questions/511238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Specificity can be omitted by not nesting elements in divs, and instead just giving elements themselves unique identifiers. ``` <div id="mylist"> <ul> <li>ListItem1</li> <li>ListItem2</li> </ul> </div> ``` Replace with ``` <ul id="mylist"> <li>ListItem1</li> <li>ListItem2</li> </ul> ``` That way your CSS would go from ``` div#mylist ul li { } ``` to ``` ul#mylist li { } ``` And there'd be less HTML. **EDIT**: In unnecessary circumstances :)
320,130
There is an old urban legend about an arcade game Polybius. An arcade machine that would have been made to be a government experiment, appeared just for a few days in a few arcades, and then some men in black took it away, never to be seen again. So is there a nugget of truth to this myth? Did the game ever exist? Or was it all created from nothing just to be a creepypasta?
2017/10/23
[ "https://gaming.stackexchange.com/questions/320130", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/15236/" ]
The game never existed. Both [Wikipedia](https://en.wikipedia.org/wiki/Polybius_(urban_legend)) and [Snopes](https://www.snopes.com/inboxer/hoaxes/roundup.asp) state this definitively. One theory for the creation of this urban legend is that is was started by Kurt Koller in an effort to get more visitors to his site dedicated to arcade gaming.
16,471,112
I am new to android development. I have the following class for downloading some data in JSON format. I keep getting a Source not found error on the HttpResponse httpResponse = httpClient.execute(httpPost); line... I'm sure this must be a simple fix... Here is the class code... ``` package com.example.tankandroid; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } ```
2013/05/09
[ "https://Stackoverflow.com/questions/16471112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1273520/" ]
Put this code in onCreate method ``` StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); ```
44,374,249
I am new to android. I haven't worked with SQLite DBs before. I think this is a very basic question, but I am unable to find the solution. The code is here (assume declarations) ``` public void onCreate(SQLiteDatabase db) { String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "(" + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY KEY(CAT_CD,S_CAT_CD))"; db.execSQL(CREATE_CATEGORIES_TABLE); String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + " ("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) "; db.execSQL(CREATE_CAT_DESC_TABLE); String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+ CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) "; db.execSQL(CREATE_CURRENCY_TABLE); String query= "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +", "+CURRENCY_SIGN+ ") VALUES " + "('INR', '₹'), " + " ('USD','$') " + "('JPY','¥') "; db.execSQL(query); } ``` The first three commands execute successfully, while by executing the insert command, SQLite throws an exeption.
2017/06/05
[ "https://Stackoverflow.com/questions/44374249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5872686/" ]
You could create a sql statement for each record ``` String query1 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹')" ; String query2 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('USD','$')" ; String query3 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('JPY','¥')" ; db.execSQL(query1); db.execSQL(query2); db.execSQL(query3); ``` Or insert multiple values in one statement, with the correct sintax it would be like this: ``` String query = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹'), " + "('USD','$'), " + "('JPY','¥')"; db.execSQL(query); ``` For more information visit [SqlLite](http://www.sqlitetutorial.net/sqlite-insert/)
19,309,306
I'm building a PhoneGap app, targeted for Android now, using Google Maps. If I only whitelist maps.googleapis.com, it doesn't work. The events object isn't there. If I whitelist all domains, it works. I'd rather not allow access to all domains. What domains other than maps.googleapis.com do I need to allow access to?
2013/10/11
[ "https://Stackoverflow.com/questions/19309306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1399027/" ]
According to [this](https://stackoverflow.com/a/8836591/1775295) answer, you need to whitelist: * \*.google.com * \*.googleapis.com * \*.gstatic.com Notice that answer was over a year old now so some of the domains might be outdated or missing. This should get you started though.
150,211
This is a follow-up question to *[How to reduce temperature on a Dell XPS (L502X)?](https://unix.stackexchange.com/questions/148731/how-to-reduce-temperature-on-a-dell-xps-l502x)*. After reading the answer, I noticed that my harddrive is spinning constantly, even when running TLP in bat-mode (mostly default settings, laptop-mode=5). **What I already do** * `/tmp` is mounted as a `tmpfs`. AFAIK this is not recommended for `/var/tmp`, is it? * `TLP` is running with [this configuration](http://pastebin.com/gjGAs0nX) * `/` and `/boot` are [ext4](http://en.wikipedia.org/wiki/Ext4) mounted with `commit=15,noatime` * `/` is mounted from a [LUKS](http://en.wikipedia.org/wiki/Linux_Unified_Key_Setup) partition, is this a problem? **What I am searching for** I guess that constant disk access is the major cause of my disk spinning all the time. Are there any other ways to reduce disk access and/or ways to allow the disk to spin down?
2014/08/14
[ "https://unix.stackexchange.com/questions/150211", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/79930/" ]
There is another, and suprprisingly not well-known source of the unneeded disk writes in the linux world. And this is the uneededly fast write cache writeout. You can make it much more seldom if you write the following into `/etc/sysctl.conf`: ``` vm.dirty_background_ratio = 20 vm.dirty_expire_centisecs = 360000 vm.dirty_writeback_centisecs = 360000 ``` On your filesystems, use ext4 (ext3 makes much more hard drive sync), and mount it with the following flags (example fstab line follows): ``` /dev/sda1 / ext4 defaults,noatime,commit=4780,barrier=0,data=writeback,nobarrier,max_batch_time=0 0 1 ``` On swap, use a big swap partition (2 times of your physical ram - even in current times.) If you have multiple data partitions (for example, a system and a home, or a windows and a linux), then make the swap partition between them, to the middle of the disk. Of course this has some disadvantages as well: if an unwaited system shutdown occurs, you will have a bigger risk of a data damage. But if your hardware is okay, your machine is stable, and you don't like to shut down it with 5sec long power buttons, then everything is okay. Crypted filesystems hasn't big disk usage overhead. They overload the cpu, and not the disk. The used disk is exactly as if it weren't encrypted, but the read and write operations require some (not really much) additional cpu computation as well. Thus LUKS is not a problem.
11,774,841
I have a Jboss application using Seam. The application is a user-facing web application. One page containing a large `rich:dataTable` (800 rows, 11 columns). This page is very slow to load, taking 14 seconds of which only a negligible portion is spent downloading the page. I would prefer to keep displaying the table on one page rather than paginating it. I would like to measure the time used by the different phases of the JSF life-cycle. The database queries fetching data for the page are fairly optimized, and I suspect that the response rendering is taking significant time, but would like to confirm this by measurement. The application runs on Jboss 4.2.3 with Seam 2.1.0.GA and RichFaces 3.3.3.
2012/08/02
[ "https://Stackoverflow.com/questions/11774841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616150/" ]
I would recomend JProfiler or any other profiler you think is good. I also use firebug in Firefox to se how long the server side takes compaired to the client side. And read this articile by Dan Allen <http://www.jsfcentral.com/articles/speed_up_your_jsf_app_1.html>
35,605,593
I have a data set, what looks approximately like the one below. ``` column1 column2 column3 column4 1 2 3 string 4 2 3 56 string 6 3 86 23 string 4 ``` All of the columns have numeric values except column3. I am trying to figure out the way how to count how many times the value in `column3` was mentioned with a particular value from `column4`. In other words, in this example, there are `2` values of `string` with a value `4`. For now, I've come up with a following code: ``` data$new_column = ifelse(data$column3=="string" && data$column4==4, "", "") table(data$new_column) ``` But it gives me a total number of all the values, which is in example case `3` I have tried this solution: [Counting the number of elements with the values of x in a vector](https://stackoverflow.com/questions/1923273/counting-the-number-of-elements-with-the-values-of-x-in-a-vector), but it didn't help much as it gives me an error: ``` [ reached getOption("max.print") -- omitted x rows ] ``` What, as far as I understand, that this solution doesn't work on large datasets. What would be the best way to realize this solution? Thanks for the ideas in advance!
2016/02/24
[ "https://Stackoverflow.com/questions/35605593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5153030/" ]
Since I can't add a comment I will post here the answer. ``` def single_insert_or_delete(s1,s2): s1,s2 = s1.lower(), s2.lower() count = 0 if s1 == s2: return 0 elif len(s1) == len(s2): return 2 elif len(s1) - len(s2) == -1: if s1 == s2[:-1]: return 1 else: for i in range(len(s2)): if s1 == s2[:i] + s2[i+1:]: return 1 else: return 2 elif len(s1) - len(s2) == 1: if s1[:-1] == s2 or s1[1:] == s2: return 1 else: for i in range(len(s1)): if s2 == s1[:i] + s1[i+1:]: return 1 else: return 2 else: return 2 ```
602,645
I would like to set a GIT server and let my developers to login using username and password in order to commit and make changes to the projects. I need also to manage developer access to projects (I think I should use gitolite for this). How can I do that? I am used to SVN which is easy because you can set username and password for each developer, which can easily access the repository without having the generate an ssh key and put it on the server. Thanks
2014/06/08
[ "https://serverfault.com/questions/602645", "https://serverfault.com", "https://serverfault.com/users/224322/" ]
Perhaps you aren't aware of this, but Git is a distributed VCS. Thats essential to your understanding. OTOH SVN and CVS are centralized. You can still have a central repository in Git, and if you do, your users will need to be able to log into that server using SSH or HTTP access, look it up. Generally speaking, Git depends on the server's authentication. So to make a git repo on a Debian or Ubuntu server for centralized use: ``` # apt-get install git # cd /var/git # git init --bare myreponame.git # adduser <username> as needed ``` At this point you have an empty repo. To clone it to your desktop Debian or Ubuntu: For SSH connections: look up ssh keygen and set up a passwordless connection to your server- keygen and sharing is only two commands. To clone a repo: ``` $ git clone <server>:/var/git/myreponame.git $ cd myreponame ``` Now you can add files and directories... when you have used git add and git commit, then you can use git push to push commits to the central repo. * There are non-bare repositories, you must read up on this, use the standard Git references, just Google. * Warning a "shared repository" is not what you think from the name.
12,025,336
I need to run a script that will disable a another script on the page. How do I do this? (Internet Explorer Issues is why I am having to do this.) I am using jQuery 1.8. Please provide examples.
2012/08/19
[ "https://Stackoverflow.com/questions/12025336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825757/" ]
Using jQuery you can **test for IE and then load the script** if it returns true. jQuery.browser might be moved to a plugin later, if it breaks when you update your library start looking into it first. Keep in mind that it is usually not advisable to test for a specific browser, better to test for features the browser can work with. Sometimes you don't have a choice: ``` if(jQuery.browser.msie) { $.getScript("lynda-ie.js"); } ``` If you need a script for a specific version if IE you can also test for its version : ``` if(jQuery.browser.msie) { switch (parseInt(jQuery.browser.version,10)) { case 6 : $.getScript("lynda-ie-6.js"); break; case 7 : $.getScript("lynda-ie-7.js"); break; case 8 : case 9 : default : $.getScript("lynda-ie.js"); break; } ```
6,572,344
I'm trying to setup a rails application so that I can choose between different mail delivery methods depending on whether some condition is true or not. So, given two delivery methods: ``` ActionMailer::Base.add_delivery_method :foo ActionMailer::Base.add_delivery_method :bar ``` I thought I'd be able to just create an email interceptor to do something like this: ``` class DeliveryMethodChooser def self.delivering_email(message) if some_condition # code to use mail delivery method foo else # code to use mail delivery method bar end end end ``` The problem though, is that I'm not sure how to actually set change what mail delivery method is used for a given message. Any ideas? Is it even possible to dynamically choose what delivery\_method to use?
2011/07/04
[ "https://Stackoverflow.com/questions/6572344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/746882/" ]
So, it turns out that you can actually pass a `Proc` as a default parameter to `ActionMailer`. It's therefore fully possible to do this: ``` class SomeMailer < ActiveMailer::Base default :delivery_method => Proc.new { some_condition ? :foo : :bar } end ``` I'm not sure I really sure I like this solution, but it works for the time being and it will only be for a relatively short amount of time.
70,630,174
i trying to build this layout with tailwind css but i can't figure out [layout i want to create](https://imgur.com/a/lIvnbY6) [my layout](https://imgur.com/oJVzSTv) ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="/dist/output.css" /> <title>Document</title> </head> <body class="font-Rubik grid grid-cols-[80px_minmax(400px,_1fr)_250px] grid-rows-2 h-screen" > <nav class="bg-slate-800 row-span-2">nav</nav> <menu class="bg bg-violet-700 col-span-2 text-white">Menu</menu> <section class="bg-slate-300">Inbox</section> <main class="bg-slate-300">Email view</main> <aside class="bg-slate-300">Additional info</aside> </body> </html> ```
2022/01/08
[ "https://Stackoverflow.com/questions/70630174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17207271/" ]
The approach is correct. However, there are a few things that can be done differently. 1. A `setInterval` keeps on running to update the cursor position, even when the mouse is not moving - which will impact the performance. Instead of using `setInterval`, use [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) to update the cursor position when mouse movement is detected. 2. To update the cursor position, use [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property over position top and left, because `transform` will use hardware acceleration if possible and will perform better. 3. Use `clientX` and `clientY` instead of `pageX` and `pageY` to detect cursor position. See [What is the difference between screenX/Y, clientX/Y and pageX/Y?](https://stackoverflow.com/questions/6073505/what-is-the-difference-between-screenx-y-clientx-y-and-pagex-y) 4. To detect mouse movement stop, on every `mousemove`, do a `setTimeout` for say `X` milliseconds in future and clear all the past timeouts using [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout). 5. Use [`opacity`](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) and [`transition`](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) to achieve the fade-out effect when mouse movement stops. Since `jQuery` is not necessarily required, following is a solution that does not use `jQuery` (and can be tweaked to work with `jQuery`). ```js const cursor = document.querySelector(".cursor"); let mouseMovementStoppedTimer; const mouseMovementStopped = function() { cursor.style.opacity = 0; } window.addEventListener('mousemove', (function(e) { // Make the cursor visible immediately cursor.style.opacity = 1; // Change position of cursor only when mousemove is detected setTimeout(() => { // Change cursor position using translate, clientX & clientY cursor.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`; }, 100); clearTimeout(mouseMovementStoppedTimer); mouseMovementStoppedTimer = setTimeout(mouseMovementStopped, 200); })); ``` ```css .cursor { position: absolute; background-color: red; width: 25px; height: 25px; border-radius: 50%; opacity: 0; transition: opacity 0.5s linear; } ``` ```html <div> <span>Move the mouse to see the cursor</span> <div class="cursor" ></div> </div> ```
239,419
How can I get Modelsim to run faster for simulation rather than something in the picosecond range (time interval)? Are there any other methods for speeding up simulation? It takes 45 minutes to get to 1ms as of now. I want the simulation to run for 20 ms to check on certain counters, timer modules and events. The system clock runs at 50 MHz. And if there is an option will there be any drawbacks. For example missing events etc.?
2016/06/06
[ "https://electronics.stackexchange.com/questions/239419", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/91959/" ]
This is a really common issue for all FPGA developers. Here are my advice (there are probably many other). First you can decide to watch only few signals, so that the calculation will run faster. You just need to separate your design into smaller modules (or only look at one process after one). Or you can define different constants for simulation like this: ``` CONSTANT MY_CONSTANT : integer := 50; -- for simu --CONSTANT MY_CONSTANT : integer := 500; -- for real ``` Doing this for every counter can really make you save time. And finally you can obviously accelerate your `clock` too.
22,986
For a simulation, I want to compute the path that light follows near a black hole. Non-relativistically, a massive point particle in a central newtonian gravitational field follows either an ellipse, a parabola, or a hyperbola. Is the same true relativistically for light around a black hole? A problem I see with this, is that while particles gain velocity when approaching a black hole, a photon gains energy instead. So do photons behave differently?
2012/03/29
[ "https://physics.stackexchange.com/questions/22986", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/8375/" ]
Yes, photons behave differently, which I'm sure is no surprise! Any graduate book on GR will derive the orbits for a Schwarzchild metric. In my copy of "A first course in general relativity" by Bernard F. Schutz the orbits are calculated in chapter 11. Cribbing from this, for photons the orbit is: $$ \left(\frac {dr}{d\lambda}\right)^2 = E^2 - \left(1 - \frac {2M}{r}\right) \frac {L^2}{r^2} $$ so you get an effective central potential: $$ V^2(r) = \left(1 - \frac{2M}{r}\right) \frac {L^2}{r^2} $$ $L$ is the $p\_\phi$ component of the four momentum and is constant. For particles the first equation would give you $dr/d\tau$ but proper time is always zero for a photon hence the use of the affine parameter $\lambda$ instead, where $\lambda$ is defined by $p^r$ = $dr/d\lambda$. The $r$ and $\phi$ are the Scharwzchild co-ordinates i.e. as seen by an observer at infinity.
14,390,979
I'm trying to make my nav bar stay at the top of the page like on [forbes.com](http://www.forbes.com) I know I could do ``` nav { position: fixed; top: 0; } ``` but the nav bar isn't at the top of the page, it comes after the logo... When you scroll down however, I want the nav bar to stick to the top of the screen.. [This is my site](http://fusedigital.eu)
2013/01/18
[ "https://Stackoverflow.com/questions/14390979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1732907/" ]
the solution is easy, keep your css while adding px ``` nav { position: fixed; top: 0px; } ```
23,394,427
This is my base database class: ``` class _getDatabase { private $db; function __construct(PDO $connection) { $this->db = $connection; } /* Selection wrapper*/ public function getSelected($requestDatabase, $arguments) { foreach ($requestDatabase as $getBranchDatabase) { $this->db->query('USE '. $getBranchDatabase); //error on this line $sql = $this->db->prepare($arguments['query']); $sql->execute(array( $arguments['parameters'] )); return $sql->fetchALL(PDO::FETCH_OBJ); } } } $dbh = new PDO('XXXXX'); $dbFactory = new _getDatabase($dbh); ``` This is my child class: ``` function __autoload($classname) { $filename = "../database/" . $classname . ".php"; include_once($filename); } class _getBranch extends _getDatabase { public $requestDatabase = array(); public function __construct(array $selectedBranch) { $this->branch = $selectedBranch; } public function getBranch($query) { parent::getSelected($this->branch, $query); } } $setDbObject = new _getBranch(array( "esoftcar_jaf", "esoftcar_jaf" )); $arguments = array(); $arguments['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?'; $arguments['parameters'] = 'AMB'; var_dump($setDbObject->getBranch($arguments)); ``` Now I'm getting the following error: > > PHP Fatal error: Call to a member function query() on a non-object > > > What am I doing wrong?
2014/04/30
[ "https://Stackoverflow.com/questions/23394427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1521771/" ]
Your DB connection is failing, because `$this->db` doesn't exist. You are calling the `getSelected()` method from the parent which is good, but the $this->db value is never declared and initiated because the parent constructor isn't called.. In `__construct()` use ``` parent::__construct($connection); ``` To fix this.
23,799,836
I am using Brad Larson's great library [GPUImage](https://github.com/BradLarson/GPUImage) for my application. Currently I am stuck with an issue. My application captures 10 second videos and after that allows `filter` applying. While applying `filters` in `GPUImageMovie`, I am not able to pause the play and apply new `filter` so that video will play continuously without starting from the beginning. I saw an open github issue [here](https://github.com/BradLarson/GPUImage/issues/1247). If anyone faced similar issue and found a solution, please post your answers. Thanks in advance.
2014/05/22
[ "https://Stackoverflow.com/questions/23799836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2285033/" ]
And finally I fixed this after too many searches and try. We need to initiate GPUImageMovie with AVPlayerItem instead of URL. I got this valuable clue from [here](https://stackoverflow.com/questions/21781359/gpuimagemovie-playback-controls). I am posting my code which I am currently using in my application and it is working as expected. But there are performance issues in iPod 6.1 and I am working on enhancements of the same. Initial method to setup GPUImageMovie, ``` - (void)setupVideo { playerItem = [[AVPlayerItem alloc]initWithURL:self.recordSession.outputUrl]; player = [AVPlayer playerWithPlayerItem:playerItem]; movieFile = [[GPUImageMovie alloc] initWithPlayerItem:playerItem]; movieFile.runBenchmark = YES; movieFile.playAtActualSpeed = YES; [self.view sendSubviewToBack:self.videoView]; [movieFile addTarget:filter]; [filter addTarget:self.videoView]; [movieFile startProcessing]; movieRunning = YES; dispatch_async(dispatch_get_main_queue(), ^{ self.playButton.hidden = YES; }); player.rate = 1.0; } ``` This method is called when user clicks on a filter button. ``` - (void)filterClicked:(UIButton *)button { // Set paused time. If player reaches end of the video, set pausedTime to 0. if (CMTIME_COMPARE_INLINE(pausedTime, !=, player.currentItem.asset.duration)) { pausedTime = player.currentTime; } else { pausedTime = CMTimeMake(0, 600.0); } [self.videoView setBackgroundColor:[UIColor clearColor]]; [movieFile cancelProcessing]; switch (button.tag) { case 0: filter = [[GPUImageFilter alloc] init]; break; case 1: filter = [[GPUImageColorInvertFilter alloc] init]; break; case 2: filter = [[GPUImageEmbossFilter alloc] init]; break; case 3: filter = [[GPUImageGrayscaleFilter alloc] init]; break; default: filter = [[GPUImageFilter alloc] init]; break; } [self filterVideo]; } ``` After filter generation, video play resume is handled in this method. ``` - (void)filterVideo { // AVPlayerItem is initialized with required url playerItem = [[AVPlayerItem alloc]initWithURL:self.outputUrl]; [player replaceCurrentItemWithPlayerItem:playerItem]; //GPUImageMovie is initialized with AVPlayerItem movieFile = [[GPUImageMovie alloc] initWithPlayerItem:playerItem]; movieFile.runBenchmark = YES; movieFile.playAtActualSpeed = YES; // Adding targets for movieFile and filter [movieFile addTarget:filter]; [filter addTarget:self.videoView]; // self.videoView is my GPUImageView [movieFile startProcessing]; movieRunning = YES; dispatch_async(dispatch_get_main_queue(), ^{ self.playButton.hidden = YES; }); // Player rate is set to 0 means player is paused [player setRate:0.0]; // Seeking to the point where video was paused if (CMTIME_COMPARE_INLINE(pausedTime, !=, player.currentItem.asset.duration)) { [player seekToTime:pausedTime]; } [player play]; } ```
48,456,770
I have a section header which shows the number of comments. When the user adds a new comment, I call insertRow and want to change the cell that shows the number of comments. The problem is though that any variation of .reloadData ruins the animation. I've tried using CA.commit() with completion set on CAtransaction and reloading just the individual cell. Any ideas how I can reload the data after **both** the insertion and scrolling are complete? ``` let indexPath:IndexPath = IndexPath(row:(self.comments.count - 1), section:3) self.tableView.beginUpdates() self.tableView.insertRows(at: [indexPath], with: .bottom) self.tableView.endUpdates() self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) //I want to call self.tableView.reloadData() here ```
2018/01/26
[ "https://Stackoverflow.com/questions/48456770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4411101/" ]
Try following code (instead of reloading the whole table, reload just the single one row that contains comments): ``` let indexPath:IndexPath = IndexPath(row:(self.comments.count - 1), section:3) self.tableView.beginUpdates() self.tableView.insertRows(at: [indexPath], with: .bottom) // lets try to reload just the cell with comments self.tableView.reloadRows(at: [indexPathOfCellWithComments], with: .fade) self.tableView.endUpdates() self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) ``` Moreover, it cannot be seen from the code, but don't forget to update the data so that inserted row has a backing new item in data model.
102,118
I'm guessing that the majority of the Senate would have had to vote to agree with Jar Jar's proposal to give Palpatine emergency powers (although in the film it doesn't show any vote, it seems as though Palpatine just needed Jar Jar to propose it) and the obvious reason for giving Palpatine emergency powers is so that he can order the use of the clones to fight the droids. If this is the obvious reason for giving him emergency powers, and my assumption is correct that the majority of the Senate agreed to this, why can't the Senate just vote to use the clones without having to resort to giving Palpatine emergency powers?
2015/09/06
[ "https://scifi.stackexchange.com/questions/102118", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/52661/" ]
That is pretty close how it works in real life; emergency powers are not granted for using the Clone Army, but for anything that may needed afterwards. It grants Palpatine a way to bypass (most of) the legal checks and securities to protect from his rule. For example, if Palpatine wanted the Republic to take control of privately owned spaceships, usually he would propose a law that would be discussed in the Senate; even if Senate agreed with it, it would mean a considerable delay just in approving it. Additionally, affected parties may try to take the issue to judges/local jurisdictions/etc. With emergency powers, Palpatine is granted to make such a law that comes into effect automatically, even if that law concurs rights granted by other laws. Usually, most constitutions have a limit on what rights may be violated, and usually force the government to seek approval of the law by Senate/Congress **after** the law comes into effect. So, in short, it is not a power needed to use the Clone Army (because that was already granted) but to ease the creation of new laws as needed by the course of war.
37,303,265
If I have: ``` type a = B | C ``` How do I write the static members ToJson and FromJson? I know how to write it for a Record Type (which is shown in the examples at [Chiron: JSON + Ducks + Monads](https://neoeinstein.github.io/blog/2015/12-13-chiron-json-ducks-monads/index.html) ) but I can't find any examples for a DU. --- EDIT Following s952163 helpful answer (and follow up comment), I have adapted the code to try and work with a 'simple' DU of choice A | B (rather than A of string | B of ...). My code is now: ``` type SimpleDU = | A | B static member ToJson (t : SimpleDU) = match t with | A -> Json.writeNone "a" | B -> Json.writeNone "b" static member FromJson (_ : SimpleDU) = json { let! duA = Json.tryRead "a" match duA with | Some s -> return s | None -> return SimpleDU.B } ``` This compiles but when I try it with the sample operation code: ``` let a = A let b = B let a2json = a |> Json.serialize let (json2a:SimpleDU) = a2json |> Json.deserialize let b2json = b |> Json.serialize let (json2b:SimpleDU) = b2json |> Json.deserialize ``` json2a is incorrectly returning SimpleDU.B
2016/05/18
[ "https://Stackoverflow.com/questions/37303265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059440/" ]
An implementation which serializes `A` to `Object (map [("SimpleDU", String "a")])` instead of `Object (map [("a", Null null)])` is: ``` #I @"..\packages\Chiron.6.1.0\lib\net40" #I @"..\packages\Aether.8.1.2\lib\net35" #r "Chiron.dll" #r "Aether.dll" open Chiron type SimpleDU = | A | B static member ToJson x = Json.write "SimpleDU" <| match x with | A -> "a" | B -> "b" static member FromJson(_ : SimpleDU) = json { let! du = Json.tryRead "SimpleDU" match du with | Some "a" -> return A | Some "b" -> return B | Some x -> return! Json.error <| sprintf "%s is not a SimpleDU case" x | _ -> return! Json.error "Not a SimpleDU JSON" } // val serializedA : Json = Object (map [("SimpleDU", String "a")]) let serializedA = A |> Json.serialize let serializedB = B |> Json.serialize let (a : SimpleDU) = serializedA |> Json.deserialize let (b : SimpleDU) = serializedB |> Json.deserialize let aMatches = a = A let bMatches = b = B let serializedABBAA = [ A; B; B; A; A ] |> Json.serialize let (abbaa : SimpleDU list) = serializedABBAA |> Json.deserialize let abbaaMatches = abbaa = [ A; B; B; A; A ] // allFine = true let allFine = aMatches && bMatches && abbaaMatches let defects = Array [ Object <| Map.ofList [ ("SimpleDU", String "c") ] Object <| Map.ofList [ ("Foo", String "bar") ] ] // attempt = Choice2Of2 "Not a SimpleDU JSON" let (attempt : Choice<SimpleDU list, string>) = defects |> Json.tryDeserialize ``` Instead of `"a"`and `"b"` you could use `true`and `false` which would get rid of the `Some x` case, but I'd rather have readable cases in the JSON.
54,531,425
Due to the floating point "approx" nature, its possible that two different sets of values return the same value. [Example](http://coliru.stacked-crooked.com/a/bcda30ca75fe59d3): ``` #include <iostream> int main() { std::cout.precision(100); double a = 0.5; double b = 0.5; double c = 0.49999999999999994; std::cout << a + b << std::endl; // output "exact" 1.0 std::cout << a + c << std::endl; // output "exact" 1.0 } ``` But is it also possible with subtraction? I mean: is there two sets of different values (keeping one value of them) that return `0.0`? i.e. `a - b = 0.0` and `a - c = 0.0`, given some sets of `a,b` and `a,c` with `b != c`??
2019/02/05
[ "https://Stackoverflow.com/questions/54531425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365251/" ]
The IEEE-754 standard was deliberately designed so that subtracting two values produces zero if and only if the two values are equal, except that subtracting an infinity from itself produces NaN and/or an exception. Unfortunately, C++ does not require conformance to IEEE-754, and many C++ implementations use some features of IEEE-754 but do not fully conform. A not uncommon behavior is to “flush” subnormal results to zero. This is part of a hardware design to avoid the burden of handling subnormal results correctly. If this behavior is in effect, the subtraction of two very small but different numbers can yield zero. (The numbers would have to be near the bottom of the normal range, having some significand bits in the subnormal range.) Sometimes systems with this behavior may offer a way of disabling it. Another behavior to beware of is that C++ does not require floating-point operations to be carried out precisely as written. It allows “excess precision” to be used in intermediate operations and “contractions” of some expressions. For example, `a*b - c*d` may be computed by using one operation that multiplies `a` and `b` and then another that multiplies `c` and `d` and subtracts the result from the previously computed `a*b`. This latter operation acts as if `c*d` were computed with infinite precision rather than rounded to the nominal floating-point format. In this case, `a*b - c*d` may produce a non-zero result even though `a*b == c*d` evaluates to true. Some C++ implementations offer ways to disable or limit such behavior.
20,519,794
a friend of mine told me that using this script to authenticate users is real risk to sql vulns ``` <?php if(strlen(strstr($_SERVER['HTTP_USER_AGENT'],"-- IPB Vaidation --")) <= 0 ){ die('Login Failed!, Please try again.'); } $name = strtolower($_GET["name"]); $password = $_GET["password"]; $digits = $_GET["digits"]; $random_number = 70; $sum_total2 = $digits * $random_number; $con = mysql_connect("127.0.0.1","usernamehere","passhere"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database here", $con); $sql = "SELECT * FROM ipbmembers WHERE members_seo_name='{$name}'"; $result = mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_array($result)) { $trueHash = $row['members_pass_hash']; $salt = $row['members_pass_salt']; } $hash = md5(md5($salt) . md5($password)); if($hash == $trueHash) { echo "Thank you for logging in"; echo ($sum_total2); } else { echo "Login Failed!, Please try again."; echo ($sum_total2); } ?> ``` can anyone show me how its done? or what iam doing wrong? Thanks!
2013/12/11
[ "https://Stackoverflow.com/questions/20519794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3091150/" ]
Yes, your code is vulnerable. Look at this statement: ``` $sql = "SELECT * FROM ipbmembers WHERE members_seo_name='{$name}'"; ``` What if `$name` has the value of `'; DROP TABLE ipbmembers; --`? Then the SQL statement you build will be: ``` SELECT * FROM ipbmembers WHERE members_seo_name=''; DROP TABLE ipbmembers; --' ``` You'll do a SELECT followed by DROPping the table. **Don't build SQL from outside variables.** Use placeholders and prepared statements.
12,654,540
i am working on Urdu Hindi translation/transliteration. my objective is to translate an Urdu sentence into Hindi and vice versa, i am using visual c++ 2010 software with c++ language. i have written an Urdu sentence in a text file saved as UTF-8 format. now i want to get a single character one by one from that file so that i can work on it to convert it into its equivalent Hindi character. when i try to get a single character from input file and write this single character on output file, i get some unknown ugly looking character placed in output file. kindly help me with proper code. my code is as follows ``` #include<iostream> #include<fstream> #include<cwchar> #include<cstdlib> using namespace std; void main() { wchar_t arry[50]; wifstream inputfile("input.dat",ios::in); wofstream outputfile("output.dat"); if(!inputfile) { cerr<<"File not open"<<endl; exit(1); } while (!inputfile.eof()) // i am using this while just to // make sure copy-paste operation of // written urdu text from one file to // another when i try to pick only one character // from file, it does not work. { inputfile>>arry; } int i=0; while(arry[i] != '\0') // i want to get urdu character placed at // each-index so that i can work on it to convert // it into its equivalent hindi character { outputfile<<arry[i]<<endl; i++; } inputfile.close(); outputfile.close(); cout<<"Hello world"<<endl; } ```
2012/09/29
[ "https://Stackoverflow.com/questions/12654540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708430/" ]
Assuming you are on Windows, the easiest way to get "useful" characters is to read a larger chunk of the file (for example a line, or the entire file), and convert it to UTF-16 using the [MultiByteToWideChar](http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130%28v=vs.85%29.aspx) function. Use the "pseudo"-codepage CP\_UTF8. In many cases, decoding the UTF-16 isn't required, but I don't know about the languages you are referring to; if you expect non-BOM characters (with codes above 65535) you might want to consider decoding the UTF-16 (or decode the UTF-8 yourself) to avoid having to deal with 2-word characters. You can also write your own UTF-8 decoder, if you prefer. It's not complicated, and just requires some bit-juggling to extract the proper bits from the input bytes and assemble them into the final unicode value. HINT: Windows also has a [NormalizeString()](http://msdn.microsoft.com/en-us/library/windows/desktop/dd319093%28v=vs.85%29.aspx) function, which you can use to make sure the characters from the file are what you expect. This can be used to transform characters that have several representations in Unicode into their "canonical" representation. EDIT: if you read up on [UTF-8](http://en.wikipedia.org/wiki/UTF-8) encoding, you can easily see that you can read the first byte, figure out how many more bytes you need, read these as well, and pass the whole thing to MultiByteToWideChar or your own decoder (although your own decoder could just read from the file, of course). That way you could really do a "read one char at a time".
16,434,494
I am new to Unity. I am following the car tutorial and trying to port it to Android. Some how I managed to move the car in device. The problem is that I am using a 3D text which will be clicked to accelerate the car. What I did is Created a 3D Text. Added box collider to it. Check the is Trigger option of Box Collider. Added the following script. ``` public var Mainref:TouchPlaneScript; function FixedUpdate() { var touch: Touch = Input.touches[0]; if(touch.phase == TouchPhase.Began) { Mainref.applyBrake = true; } if(touch.phase == TouchPhase.Ended) { Mainref.applyBrake = false; } } function Start () { // Find the OtherScript which is attached to any game object in the scene. Mainref = FindObjectOfType(TouchPlaneScript); } function OnMouseUp() { Mainref.applyBrake = false; Debug.Log("Stop Brake"); } function OnMouseDown() { Mainref.applyBrake = true; Debug.Log("Apply Brake"); } ``` The logic inside the Touch Methods might be wrong don't worry about that. I have also commented the code for mouse functions while running it on device. But the problem remains the same. **THE PROBLEM IS THAT** TOUCH METHODS ARE CALLED IF TOUCHED ON THE SCREEN ANY WHERE I WANT TOUCH FUNCTIONS TO BE CALLED ONLY WHEN CLICKED ON THE TEXT. Please note that I have four buttons on the scene. left,right,brake,accel all are 3d text and have the same structure and same problem.
2013/05/08
[ "https://Stackoverflow.com/questions/16434494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922140/" ]
Your code have detect the click event by checking input touches, but you didn't check the position of the target, so once you click on the screen, every thing happens. You need to check the position of the touch to make sure you are doing the right operation. Code below(not familiar with JS, this is C# version, you need to translate it on your own): ``` void FixedUpdate () { if ( Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android ) { if ( Input.touchCount <= 0 ) return; // detect single touch only Touch touch = Input.touches[0]; if ( touch.phase == TouchPhase.Began ) { Debug.Log( 123 ); OnTouchBegan( touch.position ); } } else { if ( Input.GetMouseButtonDown( 0 ) ) { Debug.Log(Input.mousePosition); OnTouchBegan( Input.mousePosition ); } } } void OnTouchBegan (Vector2 screenPos) { Ray ray = Camera.main.ScreenPointToRay( screenPos ); RaycastHit hit; if ( Physics.Raycast( ray, out hit ) ) { hit.collider.gameObject.SendMessage("OnClick", SendMessageOptions.DontRequireReceiver); } } ``` after this, you need to create a new script implementing a method OnClick() and attach it on your 3D text game object. Then your 3D text will receive the OnClick message when you click on it. Hope this helps. By the way, if there is more than one camera in your scene, you need to change Camera.main to the camera which sees the 3D text.
206,471
I have a hallway light fixture with three switches. When the circuit is off, a small voltage persists to the fixture causing LED and CFL bulbs to stop working prematurely. It is believed that the phantom voltage is coming from induction between the traveler wires. Suggestions to [my previous question regarding this situation](https://diy.stackexchange.com/questions/198875) involved using a resistor, relay, or other circuitry to bond the hot to ground. I'm not particularly fond of this idea because if something were to go wrong it could invalidate my insurance. Last night I woke up with a crazy idea (yes, this has literally been keeping me awake at night), why not use a DPDT switch on the source end of the circuit to connect the open traveler to neutral. I've created the following diagram of what I intend: [![4-way switch: line and neutral to travelers, 4-way switch travelers to travelers, 3-way switch travelers to fixture](https://i.stack.imgur.com/ix3xa.png)](https://i.stack.imgur.com/ix3xa.png) Is this configuration allowed by code? Is there a name for this type of a multi-way switch setup? *Location: Utah, United States*
2020/10/13
[ "https://diy.stackexchange.com/questions/206471", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/55821/" ]
Better idea: use a part *listed for the job* to bypass the errant current around the lights ------------------------------------------------------------------------------------------- Fortunately, there's a way to bypass the errant "phantom" current (from capacitive coupling through the parallel traveler wires) back to neutral *without* doing anything that'd void your insurance. Simply nut a Lutron LUT-MLC in between switched-hot and neutral at the first light fixture on the circuit; they're *listed* (as an appliance control) for use in mains wiring, so there's no need to worry about your insurance complaining. As to your original idea... --------------------------- While your original idea *seems* sound, it falls into a grey area of Code interpretation regarding the meaning of NEC 404.2(A), which was originally put in to prohibit dangerous Carter 3-way setups: > > **(A) Three-Way and Four-Way Switches.** Three-way and four-way switches shall be wired so that all switching is done only in > the ungrounded circuit conductor. Where in metal raceways or > metal-armored cables, wiring between switches and outlets shall > be in accordance with 300.20(A). > > > In your case, neutral is never *broken* by any switch (breaking the neutral with a multiway switch also violates NEC 404.2(B)), but simply connected to an otherwise floating traveler wire to short out a voltage that got coupled over by a parasitic capacitor. Note that this configuration doesn't *parallel* the neutral either, because the neutral-connected traveler and the actual neutral are connected to opposite sides of the load, which means that the normal issues with wires in parallel and NEC 310.10(H) don't apply here.
138,685
My Friend's mobile was lost yesterday and I tried to delete all his data using the android device manager. But it shows only the "ring button" and "Enable Lock and Erase". I Clicked "Enable Lock and Erase". I want to confirm weather it has performed already automatically when mobile data is switched on, or does the user need to confirm to perform the next step. Please Help me.
2016/03/03
[ "https://android.stackexchange.com/questions/138685", "https://android.stackexchange.com", "https://android.stackexchange.com/users/154306/" ]
ADM will notify the account owner when the wipe is successful, and the location it occurred, by email. Once the event is set in ADM, it will occur automatically as soon as the device makes contact with Google servers. It doesn't matter if it's immediately or after several months or even years (theoretically).
56,151,504
I want to deploy Strapi to my Azure. Anyone here who has an experience doing such and making it up and running completely? Somehow I couldn't find any detailed instructions how to do that in Azure.. I'm looking for something that is as easy as deploying it to [Heroku](https://blog.strapi.io/deploying-a-strapi-api-on-heroku/) - but it's fine though if it'll require more steps as long as I can make it to work completely.
2019/05/15
[ "https://Stackoverflow.com/questions/56151504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9272180/" ]
This is the complete instruction I have also created in the README of the repository. Strapi-Azure 3.1.3 ================== This is a working repository of [Strapi 3.1.3](https://github.com/jaybanaticla/strapi-azure) which you can already deploy as an Azure Web App. This requres a paid subscription, minimum of B1 plan (32 USD estimated), so we can enable the 64-bit platform configuration and the Always On feature. To get started, let us first create and configure our Azure Web App: **Create an instance:** * Name: The name of your choice that is still available * Publish: Code * Runtime staci: Node 12 LTS * Operating System: Windows * Region: select near you ![Create Instance](https://drive.google.com/uc?id=1dQDNngfR-uk2c49Ez5BjlBhDH_QjEBQV "Create Instance") * Sku and Size: select B1 (minimum) ![Sku and Size](https://drive.google.com/uc?id=1_CXMHbduk1FhgWSmLDqLQMoTXKhlBUSb "Sku and Size") **Configure the Environment variables:** * Add the following key-value pairs: ![Environment variables](https://drive.google.com/uc?id=1w3l9ofll197aERa0Tb0GvGHpPyw4AbAy "Environment variables") * For the **HOST** make a ping to your *.azurewebsites.net* instance and get the IP ![Ping](https://drive.google.com/uc?id=1p9V9DoaFAMNGTrPOjbd3crLYdPlvCrpc "Ping") **Configure the Platform Settings** * In the *General Settings* tab (beside the *Application Settings*), change the Platform from 32 Bit to 64 Bit ![Platform config](https://drive.google.com/uc?id=1z27I0Dq94n_xZCwzQLvCltsYswA7pRMc "Platform config") * To confirm if you are indeed now on 64 Bit mode, go to Console and run **node -p "process.arch"** ![64bit](https://drive.google.com/uc?id=1DoZF4UfBejQ_yhXO20aEsKaMf2usxDYy "64bit") **Install yarn:** Go again to Console and run: **npm install -g yarn** ![Yarn](https://drive.google.com/uc?id=1yOqe2HJvRW36HfqavqWG2Sb9Jbxp72b_ "Yarn") **Deploy from your github account a copy of *strapi-azure* repo** * In the Deployment Center tab, connect your GitHub account and browse your copy of **strapi-azure** ![Wizard1](https://drive.google.com/uc?id=1NkesfYWGUYxF0_a1LZ-7WTn-yupOpUfw "Wizard2") * Select **App Service build service** as your build provider ![Wizard2](https://drive.google.com/uc?id=1fECtJ_nKioWbgrk1261Npgb77APMYUYQ "Wizard2") * Select repository and branch ![Wizard3](https://drive.google.com/uc?id=1Fe_7KWrovD-EM6u4fvCOFQltNh4sQiGi "Wizard3") * **Deploy!** ![Successfully deployed](https://drive.google.com/uc?id=1m1a8R9ll5mA-fzCCvAD2o9w6UFogbqXp "Successfully deployed") **Build your Admin UI using Kudu service** * Go to Advance Tools -> Go -> expand Debug console from the toolbar -> CMD * Inside the wwwroot directory (site/wwwroot/), execute **yarn build** ![Excute yarn build](https://drive.google.com/uc?id=1OfZ2ThazRmxB5eF6r34TSJnYhePMYp_q "Execute yarn build") ![Admin UI built](https://drive.google.com/uc?id=1wiivLA1LAC3X6f215gAglJEjyEQXycsK "Admin UI built") **See it in action** ![Production live mode](https://drive.google.com/uc?id=1ltKEZeLdyiu_n4UAavID6DKAap34IbKD "Production live mode")
68,648,417
I need to do the following. I have a date column in my data frame and I need to add x months to it like this: ``` df = pd.DataFrame({'date':['2019-01-01', '2018-01-01']}) df['date'] = pd.to_datetime(df['date']).dt.date months = 24 df['date'] = df['date'] + np.timedelta64(months, 'M') ``` The problem is I don't want to take leap years into account so I have '2021-01-01' as the result of the first date instead of '2020-12-31'. (2020 was a leap year.) The other date is fine. Is there a simple solution to this? I haven't found any so far. Thank you.
2021/08/04
[ "https://Stackoverflow.com/questions/68648417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7993018/" ]
``` import pandas as pd import datetime import numpy as np df = pd.DataFrame({'date':['2019-01-01', '2018-01-01']}) df['date'] = pd.to_datetime(df['date']) months=24 if df['date'].dt.is_leap_year.any() == False: df['date'] = df['date'] + np.timedelta64(months, 'M') else: df['date'] = df['date'] + np.timedelta64(months, 'M') - np.timedelta64(df['date'].dt.is_leap_year.sum(), 'D') ```
44,074,218
I'm getting the following error when navigating to a page with css animation after upgrading my app to {N} v3 [![enter image description here](https://i.stack.imgur.com/E89lO.png)](https://i.stack.imgur.com/E89lO.png) I'm using the following code: HTML: ``` <DockLayout flexDirection="row" class="actionText" backgroundColor="#E1E1E1" stretchLastChild="true" minHeight="65"> <Label (tap)="navigate()" dock="left" [text]="'ion-location'| fonticon" class="ion x-large c-white faa-bounce" textAlignment="center" width="65" style="text-align: center; vertical-align: center;"></Label> <Label [text]="address" textWrap="true" ></Label> </DockLayout> ``` Css: ``` @keyframes bounce { 0%,10%,20%,50%,80%{transform:translateY(0)} 40%{transform:translateY(-15px)} 60%{transform:translateY(-15px)} } .faa-bounce { animation-name: bounce; animation-duration: 2s; animation-iteration-count: 3; animation-timing-function: ease; } ```
2017/05/19
[ "https://Stackoverflow.com/questions/44074218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497840/" ]
They are the structure. You should do something like this ``` render_book("file.Rmd", epub_book()) ``` to build the ebook. Some variables can be passed to epub\_book(). You could take a look to <https://bookdown.org/yihui/bookdown/> . It is a book about bookdown written in bookdown.
103,056
I have a player who has an Aasimar character. My player argues that the book does not state the Aasimar has to flap its wings, and instead can hover because the wings don't use concentration. This statement and assumption has led to odd arguments. If his character is knocked out or falls unconscious, do the wings stay? If the character is stunned, does it fall?
2017/07/07
[ "https://rpg.stackexchange.com/questions/103056", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/24548/" ]
Your player is correct in that maintaining the wings does not require concentration. If it did, it would say so in the effect description. Once triggered, the wings will exist for 1 minute. Period. Your player is incorrrect in claiming that the wings give him a Hover effect. If a creature has a Fly (Hover) speed, it is explicitly called out in their Stats. See: Banshee, Beholder, Air Elemental, etc. Because flight is subject to the following rule: > > If a flying creature is knocked prone, has its speed reduced to 0, or is otherwise deprived of the ability to move, the creature falls, unless it has the ability to hover or it is being held aloft by magic, such as by the *fly* spell. > > > In short, the default assumption is that "if you can fly, you will fall out of the sky if your speed is reduced to 0, unless you have one of these explicitly called out effects keeping you in the air." The Protector Aasimar simply says "You have a flying speed." It doesn't call out any of the specific effects that let you hover even while unconcious, stunned, or otherwise deprived of the ability to intentionally stay aloft--and thus the general rule for flight applies, such that an Aasimar will fall out of the sky if their speed is reduced to 0. The 'Hover' effect laid out in the Flight Rules refers to the ability to remain airborne even if you are unconscious...not the ability to stay in one place while flying. To address his point that "it doesn't say they flap their wings," I refer you to the Aarakocra in the Elemental Evil Player's Companion. These bird-people have actual physical wings that they use for flight, but nowhere in their write-up does it specify that they flap to stay in the air. The absence of an explicit explanation does not mean that's not how it works.
25,773,969
I am designing a web page which has a list of dates appearing on below the other. I want to align the dates such that they line up perfectly below each other. I have tried using align but it didn't make a difference. I also tried putting a style tag but I got an error which said: "Element "style" not allowed as child of element "div" in this context." Here's the code of the page: ``` <div class="report-title"> <h1>Response Tracking Report</h1> </div> <div class="info"> <div style="width:93%;float:left;"> <p class="title">Project: </p> <p class="value"><?php echo $response_data['project_name']; ?></p> </div> <div class="spacer"></div> <div style="width:7%;float:left;"> <p class="value"><?php echo date("Y-m-d"); ?></p> </div> <div class="bottom"></div> </div> <div id='response-info' class='info'> <div style='width:100%;'> <p class='title'>Risk Statement: </p> <p id='risk_statement' class='value'><?php echo $response_data['risk_statement']; ?></p> <br/><br/> </div> <div style='width:24%;float:left;'> <p class='title'>WBS: </p><p class='value'><?php echo $response_data['WBS']; ?></p> <br/><br/> <p class='title'>Date of Plan: </p><p class='value' ><?php echo $response_data['date_of_plan']; ?></p> <br/><br/> <p class='title'>Last Updated: </p><p class='value' ><?php echo $response_data['date_of_update']; ?></p> <br/><br/> <p class='title'>Planned Closure: </p><p class='value' ><?php echo $response_data['planned_closure']; ?></p> </div> <div class='spacer' style='width:1%;float:left;height:1px;'></div> <div style='width:24%;float:left;'> <p class='title'>Owner: </p><p class='value'><?php echo $response_data['owner']; ?></p> <br/><br/> <p class='title'>Cost: </p><p class='value'>$<?php echo round($response_data['cost']); ?></p> <br/><br/> <p class='title'>Release Progress: </p><p class='value'><?php echo $response_data['release_progress']; ?></p> <br/><br/> <p class='title'>Action: </p><p class='value'><?php echo $response_data['action']; ?></p> </div> <div class='spacer' style='width:1%;float:left;height:1px;'></div> <div style='width:50%;float:left;'> <p class='title'>Current Status: <br/> </p><p class='value'><?php echo $response_data['current_status']; ?></p> <br/> <br/> <p class='title'>Action Plan: <br/> </p><p class='value'><?php echo $response_data['action_plan']; ?></p> </div> <div id='bottom' style='clear:both;width:100%'></div> </div> <div id="ResponseUpdateTableContainer" class="jTableContainer" style="width:100%;"></div> </body> ``` How dates are displayed currently: <http://imgur.com/UxbugwX> How I am trying to get them: <http://imgur.com/mAgfRYO> I am new to html so please excuse my errors. All help is greatly appreciated.
2014/09/10
[ "https://Stackoverflow.com/questions/25773969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4004851/" ]
To have those `DIV's`aligned, you need to give them the same width, the problem with this, is when you have dynamic text, and the length overflow your already specifyed width. One solution, is emulate the native `table` style, with `display` property in your `css` like this for example: ``` .table { display: table; } .row { display: table-row; } .cell { display: table-cell; } ``` Then, your `html` will have something similar to this markup: ``` <div class="table"> <div class="row"> <span class="cell title">WBS:</span> <span class="cell value">1.1</span> </div> <div class="row"> <span class="cell title">Planned Closure:</span> <span class="cell value">2014-07-18</span> </div> <div class="row"> <span class="cell title">Last Updated:</span> <span class="cell value">2014-09-10</span> </div> <div class="row"> <span class="cell title">Date of Plan:</span> <span class="cell value">2014-04-26</span> </div> </div> ``` jsFiddle example: <http://jsfiddle.net/gmolop/csx10g64/>
54,983,841
I want to use a HOC component to display a loading animation. Some components have the prop "isLoading" and others "isPending". How can I give the HOC a defauult prop, that will make it show the loader? ``` isLoading isPending isNotReady ... const WithLoader = ControlledComponent => ({ isPending, ...props }) => { ```
2019/03/04
[ "https://Stackoverflow.com/questions/54983841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204835/" ]
As BA\_Webimax pointed out, you should be using Wordpress' built-in email functions, though due to WP's reliance on outdated PHP versions, you will end up using a very old version of PHPMailer with it. Back to your current problem: It's not your `require_once` statements that are failing, it's that you have not imported the namespaced PHPMailer classes into your namespace. Add these at the top of your script: ``` use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\SMTP; ``` Alternatively, use the FQCN when creating your instance: ``` $mail = new PHPMailer\PHPMailer\PHPMailer; ``` Note that this applies to the `Exception` class too, so you'd need to say: ``` catch (PHPMailer\PHPMailer\Exception $e) { ```
30,626,153
I'm a C# developer who is trying to build something useful using PowerShell. That's why I'm keep trying to use well-known idioms from .NET world in PowerShell. I'm writing a script that has different layer of abstractions: database operations, file manipulation etc. At some point I would like to catch an error and wrap it into something more meaningful for the end user. This is a common pattern for C#/Java/C++ code: ``` Function LowLevelFunction($arg) { # Doing something very useful here! # but this operation could throw if (!$arg) {throw "Ooops! Can't do this!"} } ``` Now, I would like to call this function and wrap an error: ``` Function HighLevelFunction { Try { LowLevelFunction } Catch { throw "HighLevelFunction failed with an error!`nPlease check inner exception for more details!`n$_" } } ``` This approach is almost what I need, because `HighLevelFunction` will throw new error and the root cause of the original error would be lost! In C# code I always can throw new exception and provide original exception as an inner exception. In this case `HighLevelFunction` would be able to communicate their errors in a form more meaningful for their clients but still will provide inner details for diagnostic purposes. The only way to print original exception in PowerShell is to use `$Error` variable that stores all the exceptions. This is OK, but the user of my script (myself for now) should do more things that I would like. So the question is: **Is there any way to raise an exception in PowerShell and provide original error as an inner error?**
2015/06/03
[ "https://Stackoverflow.com/questions/30626153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250833/" ]
A macro is able to expand to things like patterns, expressions and items, but not everything; specifically, macros expand to complete AST nodes, but what you’re dealing with here is not a complete AST node. Each branch of a `match` expression can have one or more patterns, separated by pipes, and an optional pattern guard (`if *condition*`). This is all special `match`-specific syntax, and thus not a complete AST node, and thus not something that a macro can expand to. The parser is looking for a pattern at that point of its parsing, so it expands the macro as a pattern, which concludes before the `|`, which doesn’t fit in a pattern grammar. The macro has thus produced more than can be consumed, and the rest is discarded with an error.
33,015,829
I am building an Editor Template, which will accept `htmlAttributes` object. Example is simple. In main view I have something like ``` @Html.EditorFor(Function(x) x.SomeProperty, New With {.htmlAttributes = New With {.class = "form-control"}}). ``` And in Editor Template I need `class="form-control"` attribute being written. If within template I use something like `@Html.TextBoxFor(Function(x) x, ViewData("htmlAttributes"))`, then everything is ok. But if I build a tag manually, I have no means to output `htmlAttributes`, i.e. I build `<input type="text" {htmlAttributes should be here} />` Is there any public method to render HTML attributes within tag correctly?
2015/10/08
[ "https://Stackoverflow.com/questions/33015829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694939/" ]
I'm not sure exactly what you're looking for here. Traditionally, an editor template will just pass-through the htmlAttributes. For example: **View** ``` @Html.EditorFor(m => m.FooString, new { htmlAttributes = new { @class = "foo" } }) ``` **String.cshtml** ``` @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue.ToString(), ViewData["htmlAttributes"]) ``` If you're asking about how to do something like set defaults that can then be overridden or added to by passing `htmlAttributes`. Then, you're pretty much on your own there. There's nothing existing in MVC to help you out (at least fully). However, I did write my own HtmlHelper extension to take care of this. I actually wrote a [blog post](http://cpratt.co/html-editorfor-and-htmlattributes/) to explain what this does and how to use it. I recommend you check it out, but I'll post the code here for completeness. ``` using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; public static partial class HtmlHelperExtensions { public static IDictionary<string, object> MergeHtmlAttributes(this HtmlHelper helper, object htmlAttributesObject, object defaultHtmlAttributesObject) { var concatKeys = new string[] { "class" }; var htmlAttributesDict = htmlAttributesObject as IDictionary<string, object>; var defaultHtmlAttributesDict = defaultHtmlAttributesObject as IDictionary<string, object>; RouteValueDictionary htmlAttributes = (htmlAttributesDict != null) ? new RouteValueDictionary(htmlAttributesDict) : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesObject); RouteValueDictionary defaultHtmlAttributes = (defaultHtmlAttributesDict != null) ? new RouteValueDictionary(defaultHtmlAttributesDict) : HtmlHelper.AnonymousObjectToHtmlAttributes(defaultHtmlAttributesObject); foreach (var item in htmlAttributes) { if (concatKeys.Contains(item.Key)) { defaultHtmlAttributes[item.Key] = (defaultHtmlAttributes[item.Key] != null) ? string.Format("{0} {1}", defaultHtmlAttributes[item.Key], item.Value) : item.Value; } else { defaultHtmlAttributes[item.Key] = item.Value; } } return defaultHtmlAttributes; } } ``` Then, in your editor template (`Date.cshtml` in this example): ``` @{ var defaultHtmlAttributesObject = new { type = "date", @class = "form-control" }; var htmlAttributesObject = ViewData["htmlAttributes"] ?? new { }; var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesObject, defaultHtmlAttributesObject); } @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue.ToString(), htmlAttributes) ``` **UPDATE** > > I cannot use @Html.TextBox, but need to write manually `<input type="text" {htmlAttributes should be here} />` > > > *Why?* There's not really anything you can't do with the helper version. However, if you insist on going that route, you're going to have a hard time doing it with Razor. Assuming you can actually write it without Razor syntax errors, the code is going to be virtual unreadable. I'd suggest using `TagBuilder` and/or `StringBuilder` in pure C# to construct a string and then just make sure you return/set a variable of type `MvcHtmlString`: ``` var output = new MvcHtmlString(builder.ToString()); ``` However, if you're going that far, it kind of negates the purpose of using an editor template, unless you're trying to override one of the default editor templates. Regardless, I'd recommend just creating your own HtmlHelper extension and then either using this directly in your view or using it in your editor template.
14,072,806
I'm new to android programming so please I need your help I want to make a mobile application that connects to a databse on my laptop through internet without configuring my router I'm using phpmyadmin in which i created a database, and I made a file called login.php that can make sure of username and password from database I enabled the port 80 in firewall now i wrote in eclipse this url : http:"//192.168.1.3:80/Day%20Manager/Login.php" the ip address is optained by writing ipconfig in cmd and getting the IPV4 address well it's not working it's giving me NetworkOnMainThreadException can you help me please
2012/12/28
[ "https://Stackoverflow.com/questions/14072806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925027/" ]
Have a look at this [**link**](http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/). This might help. Ofcourse if you are going to need to access it from your application you would have to provide an intermediary php script to get it working correctly.
5,309,972
> > **Possible Duplicate:** > > [PHP syntax for dereferencing function result](https://stackoverflow.com/questions/742764/php-syntax-for-dereferencing-function-result) > > > ``` function returnArray(){ $array = array( 0 => "kittens", 1 => "puppies" ); return $array; } echo returnArray()[0]; ``` How do i do that without assigning the whole array to a variable?
2011/03/15
[ "https://Stackoverflow.com/questions/5309972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215672/" ]
Why don't you pass a parameter in your function? ``` function returnArray($key=null){ $array = array( 0 => "kittens", 1 => "puppies" ); return is_null($key) ? $array : $array[$key]; } echo returnArray(0); // only 0 key echo returnArray(); // all the array ```
51,632,645
I have a huge folder with a lot of documents (`.txt`files). I would like to check if there are some identical content of some files. The filenames are all unique. I know how to compare two files as follow: ``` >>> import filecmp >>> filecmp.cmp('file1.txt', 'file1.txt') True >>> filecmp.cmp('file1.txt', 'file2.txt') False ``` But I would like to compare all files at once. Does somebody know how I could do that?
2018/08/01
[ "https://Stackoverflow.com/questions/51632645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8023753/" ]
Here's a simple way to classify all your .txt files by MD5 sum: ``` import glob import hashlib import json from collections import defaultdict def md5(filename): hash_md5 = hashlib.md5() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() dct = defaultdict(list) for filename in glob.iglob('**/*.txt', recursive=True): dct[md5(filename)].append(filename) ``` So if you just want to check which ones will have the same content you just query like: ``` print([v for k, v in dct.items() if len(v) > 1]) ```
33,056,132
I have successfully installed the Ransack gem and have it working in my app for both simple and advanced searches. I am trying to add a feature for users to "Save a Search". Essentially the idea is they can bookmark a search query, and access it later at any time. I set it up by creating a SavedSearch model. When a user saves the search it takes the params[:q] from their ransack search and stores it in the database. Later I pull this record from the database, and access the query. I try to recreate the search by passing the query to ransack, but it does not seem to be working. The search pulls ALL RECORDS for that model, rather than simply those that fit the query. Any idea why? I am thinking perhaps the search parameters need to be modified to a different format before passing them back to ransack? Here is my code: Here is the code from my controller model (advanced\_search action works flawlessly, but saved\_search does not filter correctly when recycling the query): ``` def advanced_search @query = params[:q] @saved_search = SavedSearch.new @q = Variant.search(params[:q]) @q.build_grouping unless @q.groupings.any? @variants = params[:distinct].to_i.zero? ? @q.result.paginate(per_page: 100, page: params[:page]) : @q.result.includes(:supplier).paginate(per_page: 100, page: params[:page]) respond_with @variants end def saved_search @id = params[:id] @saved_search = SavedSearch.find(@id) @query = @saved_search.query_parameters @distinct = @saved_search.distinct @q = Variant.search(@saved_search.query_parameters) @q.build_grouping unless @q.groupings.any? @variants = @distinct.to_i.zero? ? @q.result.paginate(per_page: 100, page: params[:page]) : @q.result.includes(:supplier).paginate(per_page: 100, page: params[:page]) render 'advanced_search' end ``` Here is how the search parameters from a successful query look when they are stored in the database: ``` {"g"=>{"0"=>{"m"=>"and", "c"=>{"0"=>{"a"=>{"0"=>{"name"=>"total_revenue"}}, "p"=>"gt", "v"=>{"0"=>{"value"=>"1000"}}}}}}, "s"=>{"0"=>{"name"=>"stock_health", "dir"=>"asc"}}} ```
2015/10/10
[ "https://Stackoverflow.com/questions/33056132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536325/" ]
I think in the database you are storing the query as String.While you are pulling it from database `@saved_search.query_parameters` is returning you the string.But the ransack needs it to be a Hash.This is the main problem I guess. While you are passing through params its gets a Hash but from database its getting String.You need to parse the string you are getting from the `@query` variable and then pass it to the search. For String to Hash conversion you can have a look at [How do I convert a String object into a Hash object?](https://stackoverflow.com/questions/1667630/how-do-i-convert-a-string-object-into-a-hash-object) question's answers.
45,731,810
I have a spring boot application deployed in Glassfish 5.0. When trying to access a REST service in this application with spring security basic auth, I'm getting the below error: > > java.lang.NoSuchMethodError: sun.security.ssl.SessionId.checkLength(Lsun/security/ssl/ProtocolVersion;)V > > > The application works fine in Tomcat server. This error is occurring only in glassfish server. My `JAVA_HOME` is already set to `jdk1.8.0_31`. What could be the issue ? Below is the error when I'm trying to access the service using postman: [![enter image description here](https://i.stack.imgur.com/TTGJS.png)](https://i.stack.imgur.com/TTGJS.png)
2017/08/17
[ "https://Stackoverflow.com/questions/45731810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389221/" ]
You can try this: ``` ^(?=.*[A-Z])(?=.*[a-z])(?!.*[A-Z][A-Z])(?!.*[a-z][a-z]).{10,15}$ ``` [Demo](https://regex101.com/r/vZ1NSU/3)
10,475,854
This: ``` $difference = 05-1; ``` results in ``` 4 ``` same if I do this: ``` $difference = 05-01; ``` is there a inbuilt way to subtract while keeping leading zeros? I know I can check to see if the difference has only 1 character or not and if so add a leading zero but was just wondering if there is a default way to get the result back with 0 already in it.
2012/05/07
[ "https://Stackoverflow.com/questions/10475854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Cyclomatic Complexity, CC, is measured at the granularity of the function or method. Sometimes it is summed up for a class and called the Weighted Method Count, WMC, i.e. the sum of the CC's for every method in the class.
55,460,007
I want to read 4 lines from a file and put each line in a separate variable. From what I can tell, I can't use: ```py for file in f ``` since it only takes 1 line at a time, and I need to put 4 lines in 4 separate variables my current "solution" looks like this: ```py while f.readline != None: tempName = f.readline() print(tempName) tempColour = f.readline() tempAge = f.readline() tempWeight = f.readline() # this try is taking the varables and making an object try: tempSheep = Sheep(tempName, tempColour, int(tempAge), int(tempWeight)) except: print("your file is in an improper format") break else: sheepList.append(tempSheep) ``` from what I can tell, the problem lies in the putting the variables in an object. The program runs through fine, then it runs through an extra time for some reason, in which case the variables are not properly filled with compatable data types, and the class throws an error. Ultimately, I guess my question is: how do I make the loop exit correctly? It is running beyond the end of the file, making variables equal to none, and then throwing an error when I make the object. Sorry if this post is messy, this is my first post on stack overflow.
2019/04/01
[ "https://Stackoverflow.com/questions/55460007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11293836/" ]
1. Install React Native Debugger tool * brew update && brew cask install react-native-debugger * brew cask reinstall react-native-debugger 2. Quit Google Chrome if it already running. 3. Launch the React Native Debugger app from Applications folder. 4. Activate iOS simulator and Run command+d using keyboard. In the debug menu select “Debug JS Remotely” option. 5. Go to React Native Debugger. Select ‘Toggle Developer Tools’ sub menu item from ‘View’ menu. 6. Select Sources tab (in the React Native Debugger window). 7. In the left side menu, expand RNDebuggerWorker.js and expand sub option localhost:\*\*\*\*. You will see the project root folder. 8. Select a .js file and add break point. Break point will get activated when the respective line is executed. 9. You can see the console logs in the console area at the bottom.
420,659
These characters show fine when I cut-and-paste them here from the VisualStudio debugger, but both in the debugger, and in the TextBox where I am trying to display this text, it just shows squares. 说明\r\n海流受季风影响,3-9 月份其流向主要向北,流速为2 节,有时达3 节;10 月至次年4 月份其流向南至东南方向,流速为2 节。\r\n注意\r\n附近有火山爆发的危险,航行时严加注意\r\n I thought that the TextBox supported Unicode text. Any idea how I can get this text to display in my application?
2009/01/07
[ "https://Stackoverflow.com/questions/420659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25640/" ]
I changed from using a TextBox to using a RichTextBox, and now the characters display in the RichTextBox.
41,905,563
Using `SelectedRows.Count` I can get a count of the number of grid rows selected. For example, if the user selected 3 rows, I can put a button on the form and clicking that can show me the number selected. Fine. BUT how could I update the number of rows as the user selects them ("on the fly"). I have tried many of the `Grid` events, like `OnColEnter` or `OnMouseDown`. They seem to update the count only when the user clicks just outside the data columns, and not when a row is first selected. Not seeing events related to changing ROWS in the `Grid` component, I tried many events in the underlying data query, but they too were inconsistent or often required clicking in certain places. The best result I found (actual code) was after scrolling the query: ``` procedure TDataHerd10.QuCowsAfterScroll(DataSet: TDataSet); begin if MenuOpt = 'UpdtInd' then MainView.NumSelEdit.Text:= IntToStr(MainView.CowSelGrid.SelectedRows.Count); end; ``` This event seems to lag one behind, and adds one more to the count initially when the user abandons the multiselect to go back to a single row. Seems like with the right event, I should be able to count the selected rows to report to the user as they select/unselect rows?
2017/01/28
[ "https://Stackoverflow.com/questions/41905563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7020169/" ]
**Update:** I found it trickier than I was expecting to modify my original answer to reliably meet your requirement to have the select count displayed when the form first shows. Below are the essentials of the testbed project which I hope reliably behaves as you asked for. In addition to the DBGrid, the form has a TEdit, which I use to ensure that the dbgrid is not initially focused (so as to make it easier to observe the dbgrid's behaviour) and 3 TButtons whose functions should be self-evident from their OnClick handlers. You'll notice that the code that catches the changing count of the dbgrid's selection count is only triggered in the dbgrid's OnDrawColumnCell event. However, this is called rather too frequently (in my case over 700 times before the form is first displayed) to be doing something else in the gui every time it is triggered. So instead, the form has a variable which keeps track of the selection count and only updates the display of it when the count changes (in the SetSelectedCount setter). ``` type TForm1 = class(TForm) [...] private FSelectedCount: Integer; procedure SetSelectedCount(const Value: Integer); public procedure ShowSelectedCount; property SelectedCount : Integer read FSelectedCount write SetSelectedCount; end; [...] procedure TForm1.btnClearSelectedClick(Sender: TObject); begin DBGrid1.SelectedRows.Clear; end; procedure TForm1.btnGetSelectedClick(Sender: TObject); begin ShowSelectedCount; end; procedure TForm1.btnSetSelectedClick(Sender: TObject); begin DBGrid1.SelectedRows.CurrentRowSelected := True; end; procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin SelectedCount := DBGrid1.SelectedRows.Count; end; procedure TForm1.FormCreate(Sender: TObject); begin ActiveControl := Edit1; // so the grid does not have focus when the form is first shown SelectedCount := -1; end; procedure TForm1.SetSelectedCount(const Value: Integer); begin if FSelectedCount <> Value then begin FSelectedCount := Value; ShowSelectedCount; end; end; procedure TForm1.ShowSelectedCount; begin Caption := IntToStr(DBGrid1.SelectedRows.Count); end; ``` Original answer follows I usually use `DataSet.AfterScroll` for doing non-gui things which need to be synchronised with its current row. Unfortunately, it doesn't work so well with a DBGrid, as you've obviously found, not least because the current row's selection state in the grid can be changed (e.g. by clicking it) without the dataset scrolling. Unfortunately, ``` procedure TForm1.DBGrid1CellClick(Column: TColumn); begin Caption := IntToStr(DBGrid1.SelectedRows.Count); end; ``` doesn't quite do the job, either, for the fairly obvious reason that you can extend a selection from the current row without using the mouse - e.g. `Shift` + `Down` will do it, too. However, if you just add ``` procedure TForm1.DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Caption := IntToStr(DBGrid1.SelectedRows.Count); end; ``` that takes use of the keyboard to change the selection(s) into account and has so far resisted my attempts to wrong-foot it. If you are allowing the user to do in-place editing in the grid, you might want to filter the `Key` values which are used to update your display of the selection count. Btw, taking the keyboard wrinkleas well as the problem with AfterScroll into account, your q doesn't seem to deserve (to me at any rate) the downvote it's got , so I've given it a +1.
13,183,182
> > **Possible Duplicate:** > > [Solving Rubik’s cube programmatically](https://stackoverflow.com/questions/5563671/solving-rubiks-cube-programmatically) > > > i would like to create an application to solve rubik's cube. I read that a computer can solve it in max 20 moves. However searching on internet I can't find how to implement that. So i think about the Fridrich method ( <http://en.wikipedia.org/wiki/Fridrich_Method> ). But it's hard to teach to the pc all the algorithms. Any suggestions? p.s. Sorry for my english :)
2012/11/01
[ "https://Stackoverflow.com/questions/13183182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247153/" ]
The proof that any position can be solved in 20 moves required [35 CPU-years](http://www.cube20.org/) to compute. It was, however, a constructive proof: for each position (modulo symmetry) it computed an actual solution of 20 moves or less (though not necessarily the optimal solution for that position). The [source code](http://www.cube20.org/src/) they used to do this is available. It's written in C but using literate programming through CWeb, so it's fairly self-documenting.
11,355,902
I have my `.htaccess` file, and I have a folder with config files in there, and they contain sensitive content, e.g. database details etc. What I would like to know is, how can I block access from a browser, but allow them to be accessed via my scripts? I know that this can be achieved inside the PHP files themselves, but I'd rather use the `.htaccess` approach where possible. Is this actually able to be done? I've attempted it before, but in the process of denying access to the file from the browser, it also denied access from the coding. I have looked into this before, and some of the answers I came across suggested changing the extension to something like `.inc`, and then denying access to that. However, a couple of issues I have with that is that a) It instantly alerts anyone that can see that filename, for whatever reason, that it is a config file. Also, b) If my denial code breaks, browsers will not parse it as a PHP file, but rather an `inc` file, meaning it will print the code in the browser. Basically, can this be done within a `.htaccess` file, or do I need to put something in the header of every config file?
2012/07/06
[ "https://Stackoverflow.com/questions/11355902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563460/" ]
Put these files outside of your web server's document root. You can still access them via your server-side scripts, but this ensures no direct access to them from the outside world.
5,585,990
I am trying to write a small interactive game-like application, where I need to have a `Draw` method that's gonna draw on screen, but can't figure out how to structure the method for WPF. If this was `Winforms`, I could use: ``` public void Draw (Graphics g) { } ``` But for a `WPF Window`, what should I have on it in the xaml (currently only have a `Grid`), and what should this `Draw` method receive as an argument? First I want to do it like this to get it working, then I can think about how to make it more `WPF`, etc. But now I am more interested in getting this to work.
2011/04/07
[ "https://Stackoverflow.com/questions/5585990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51816/" ]
Typically, you "draw" in WPF in a completely different manner. In Windows Forms/GDI, the graphics API is an immediate mode graphics API. Each time the window is refreshed/invalidated, you explicitly draw the contents using Graphics. In WPF, however, things work differently. You rarely ever directly draw - instead, it's a retained mode graphics API. You tell WPF where you want the objects, and it takes care of the drawing for you. The best way to think of it is, in Windows Forms, you'd say "Draw a line from X1 to Y1. Then draw a line from X2 to Y2. Then ...". And you repeat this every time you need to "redraw" since the screen is invalidated. In WPF, instead, you say "I want a line from X1 to Y1. I want a line from X2 to Y2." WPF then decides when and how to draw it for you. This is done by placing the shapes on a Canvas, and then letting WPF do all of the hard work.
24,843,514
I have a class like below: ``` public class Poligon { public static void main(String[] args) { try { Context ctx = new InitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/javaee7/ConnectionFactory"); Destination destination = (Destination) ctx.lookup("jms/javaee7/Topic"); JMSContext context = connectionFactory.createContext(); OrderDTO order = context.createConsumer(destination).receiveBody(OrderDTO.class); System.out.println("Order received: " + order); } catch (NamingException ex) { Logger.getLogger(Poligon.class.getName()).log(Level.SEVERE, null, ex); } } } ``` I would like to get the InitialContext() form the server (glassfish) running on localhost, but I get the below error: ``` SEVERE: null javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307) at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344) at javax.naming.InitialContext.lookup(InitialContext.java:411) at poligon.Poligon.main(Poligon.java:29) ``` I know I have to create ldap realm on glassfish and add the below code (? - dont know the exact values) to my class: ``` Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "?"); env.put(Context.PROVIDER_URL, "?"); env.put(Context.SECURITY_PRINCIPAL, "?"); env.put(Context.SECURITY_CREDENTIALS, "?"); Context ctx = new InitialContext(env); ``` My problem is that I dont know what values should be at: ``` Context.INITIAL_CONTEXT_FACTORY Context.PROVIDER_URL (I want it on localhost) Context.SECURITY_PRINCIPAL Context.SECURITY_CREDENTIALS ``` And I dont know how I should configure glassfish server? ![enter image description here](https://i.stack.imgur.com/yPY3H.png) maven dependencies ``` <dependency> <groupId>org.glassfish.main.extras</groupId> <artifactId>glassfish-embedded-all</artifactId> <version>4.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.main.appclient.client</groupId> <artifactId>gf-client</artifactId> <version>3.1.2.2</version> </dependency> ```
2014/07/19
[ "https://Stackoverflow.com/questions/24843514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1466580/" ]
I think the error is already given to you. > > > > > > Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs > > > > > > > > > So the file reader is already busy but only when you drop multiple files? Then it is probably busy with the first file (and the second crashes). When you put `var reader = new FileReader();` in your jQuery each loop it will work like below: ``` $.each(files, function(i, j) { var reader = new FileReader(); $("td.photos span.status").html("Processing file: "+j.name); formdata.append('file', j); .... <snip> } ```
12,711
Here is an MWE that shows the problem: ``` \documentclass{article} \usepackage{framed} \setlength{\FrameSep}{3pt} \setlength{\parindent}{0pt} \begin{document} \fbox{Foo} \fbox{Foo} \begin{framed} Foo \end{framed} \begin{framed} Foo \end{framed} \end{document} ``` ![vertical spacing problem](https://i.stack.imgur.com/Puisz.png) --- The [`framed`](http://ctan.org/pkg/framed) package puts more spacing around its argument than `\fbox` does. I can reduce the "cell padding" to its default by fixing `\FrameSep` but I don't know how to fix the horizontal spacing outside the frame. The documentation is... sparse. I don't read TeX fluently enough to understand `framed.sty` but it's a fairly small file, so I expect is it easy to do...
2011/03/05
[ "https://tex.stackexchange.com/questions/12711", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/215/" ]
You can try mdframed.sty, extending the package framed.sty. You have a better control of parameters. Look at the documentation for all the options (mdframed-doc-en.pdf) [mdframed](http://www.ctan.org/tex-archive/macros/latex/contrib/mdframed/). The parameters to adjust the text inside the box are : innerleftmargin,innerrightmargin, innertopmargin etc. and you have a macro `\mdfsetup` to set all these options. ``` \documentclass{article} \usepackage{mdframed} \setlength{\parindent}{0pt} \begin{document} \fbox{Foo} \fbox{Foo} \begin{mdframed} Foo \end{mdframed} \begin{mdframed} Foo \end{mdframed} \end{document} ``` ![mdframed](https://i.stack.imgur.com/H3dhz.png)
11,355,537
I want to create peer-to-peer connections between 2 nodejs client. using websocket (dnode) here is the limit: * nodejs client run at 2 pc which is in different network. * they don't have static ip (192.168.1.100 && 192.168.2.200) behind NAT or firewalls * no permission to change the mapping of router. * has only static web server in public network. (can change the file by human) * can install application at pc (win) is it possible? thanks
2012/07/06
[ "https://Stackoverflow.com/questions/11355537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/537353/" ]
May be you can use [PeerJS](http://peerjs.com/) to achieve your objectives. PeerJS simplifies WebRTC peer-to-peer data, video, and audio calls. PeerJS wraps the browser's WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API. Equipped with nothing but an ID, a peer can create a P2P data or media stream connection to a remote peer. Also to broker connections, PeerJS connects to a [PeerServer](https://github.com/peers/peerjs-server). Note that no peer-to-peer data goes through the server; **The server acts only as a connection broker.**
60,157,621
I have a very old asp.net application that uses C# .Net and JQuery Mobile, and I need to add 1 feature: **Export a list of data to a csv file.** Thus far, I have the UI stuff sorted out. I have a jquery button that passes a parameter in the request query string to indicate on page load that we need to export data to Excel. I also have the following C# in the page load event. Unfortunately, when I run this code in Visual Studio with Chrome (or any browser), I do not get a prompt to save the csv file. When I run it with IE, I get the following error: "Unhandled exception at line 2371, column 4 in <http://localhost:53748/js/libs/jquery-mobile/jquery.mobile-1.0a4.1.js> 0x800a138f - Javascript runtime error:Unable to get property '\_trigger' of undefined or null reference." I'm not sure if I am handling everything with the response object correctly. ``` if (Request.QueryString["isExportToExcelRequired"] == "true") { StringWriter sw = new StringWriter(); sw.WriteLine("\"ItemID\",\"Description\",\"Price\""); if (MasterList.Count > 0) { for (int i = 0; i < MasterList.Count; i++) { sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"", MasterList[i].item.ItemID, MasterList[i].item.ItemDesc, MasterList[i].P0 )); } string fileName = string.Format("{0}_{1}", SubClassID, DateTime.UtcNow.ToString("dd-MM-yyyy")); // Write response. Response.ClearContent(); Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".csv"); Response.ContentType = "text/csv"; Response.Write(sw.ToString()); Response.End(); } } ```
2020/02/10
[ "https://Stackoverflow.com/questions/60157621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969296/" ]
Create a pr on github or at least an issue, this is a bug
30,794,171
We need to add terms to named entity extraction tables/model in Stanford and can't figure out how. Use case - we need to build up a set of IED terms over time and want to the Stanford pipeline to extract the terms when found in text files. Looking to see if this is something someone has done before
2015/06/12
[ "https://Stackoverflow.com/questions/30794171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4379999/" ]
Improved Answer --------------- The functionality described in my original answer (below) is now available in my [TimeZoneConverter](https://github.com/mj1856/TimeZoneConverter) library for .NET. All the hard work is done for you, and it is kept updated with changes to the world's time zones. The examples in the project readme show how to convert between Windows, IANA, and Rails identifiers. Since the app described in the question is in Rails, I suggest running a background job in .NET to convert Windows time zone IDs to those needed in your Rails app and keep them in a separate column. --- ### Original Answer The resource you're looking for is the Windows to IANA mapping file maintained as part of the [Unicode CLDR](http://cldr.unicode.org/) project. The file is located within the CLDR release at `common/supplemental/windowsZones.xml`, and you can find the current "development version" of it [here](http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml). Be aware of a few things: * The file *does* get updated as new time zones come out from Microsoft and from IANA, or occasionally when governments change their time zone rules significantly enough that a different mapping applies. * The offsets in your list would just be the *standard* offset - that is, the one that applies when daylight saving time is not in effect. A "time zone" is composed of the standard offsets, the daylight offsets, and the specific dates and times of the DST transitions, along with the history of changes for the offsets and transitions. * The Rails time zone names should not be used anywhere outside of Rails. My understanding is that they were actually created *before* Rails decided to use standard IANA/Olson time zones, then later when the Ruby [tzinfo gem](http://tzinfo.github.io/) became viable, the Rails zones were retrofitted through the `MAPPING` constant shown [on this page](http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html), then some were added afterwards as individual complaints arose. If possible, just use the IANA time zones directly, via the tzinfo gem. If not, then you will have two layers of mapping to go through (Microsoft -> IANA -> Rails). * I do not know of a Rails-specific implementation of the CLDR mappings. I checked a couple of CLDR for Rails projects, and found they didn't include that particular portion of the CLDR. However, if you have control over the Windows side of things, then you might consider using the .NET implementation I describe [in this answer](https://stackoverflow.com/q/17348807/634824). You would do the Windows to IANA conversion on the Windows side, then either use the IANA zones directly with tzinfo, or map to Rails zones in your Rails app. * Also realize that the number of Rails time zones are significantly less than those supported by IANA. I haven't checked, but it's likely that some of the Windows zones map to IANA zones that aren't in Rails. Also, there are some Rails zones that have multiple Rails entries, but only one IANA mapping - essentially making them equivalent aliases. * Both Rails and Windows use "UTC" as a zone id, which Rails maps to "Etc/UTC", but CLDR maps to "Etc/GMT". You'll have to handle this one manually. * Lastly, recognize that the CLDR uses "stable" identifiers in a different way than IANA's "canonical" identifiers, which may cause some difficulties during the mapping. + As an example, consider that the Microsoft zone "India Standard Time" maps to "Asia/Calcutta" in the CLDR, because that's what the *original* IANA zone was. However, IANA changed the zone to "Asia/Kolkata", and set up a link for backward compatibility for "Asia/Calcutta". When you look in the Rails `MAPPING` constant, there are four Rails zones, "Chennai", "Kolkata", "Mumbai", and "New Delhi" - all of which are mapped to "Asia/Kolkata". + To overcome this, you will *also* need another file from the CLDR, [`common/bcp47/timezone.xml`](http://unicode.org/repos/cldr/trunk/common/bcp47/timezone.xml). You can use this file to find all of the links between aliased IANA zones, which can help you map back to the Rails zone. So yes, it's possible - but it's not easy. ;) I've performed the current mappings for you, which are as follows: ```csv "Windows","IANA","Rails" "W. Central Africa Standard Time","Africa/Algiers","West Central Africa" "Egypt Standard Time","Africa/Cairo","Cairo" "Morocco Standard Time","Africa/Casablanca","Casablanca" "South Africa Standard Time","Africa/Harare","Harare" "South Africa Standard Time","Africa/Johannesburg","Pretoria" "Greenwich Standard Time","Africa/Monrovia","Monrovia" "E. Africa Standard Time","Africa/Nairobi","Nairobi" "Argentina Standard Time","America/Argentina/Buenos_Aires","Buenos Aires" "SA Pacific Standard Time","America/Bogota","Bogota" "Venezuela Standard Time","America/Caracas","Caracas" "Central Standard Time","America/Chicago","Central Time (US & Canada)" "Mountain Standard Time (Mexico)","America/Chihuahua","Chihuahua" "Mountain Standard Time","America/Denver","Mountain Time (US & Canada)" "Greenland Standard Time","America/Godthab","Greenland" "Central America Standard Time","America/Guatemala","Central America" "SA Western Standard Time","America/Guyana","Georgetown" "Atlantic Standard Time","America/Halifax","Atlantic Time (Canada)" "US Eastern Standard Time","America/Indiana/Indianapolis","Indiana (East)" "Alaskan Standard Time","America/Juneau","Alaska" "SA Western Standard Time","America/La_Paz","La Paz" "SA Pacific Standard Time","America/Lima","Lima" "SA Pacific Standard Time","America/Lima","Quito" "Pacific Standard Time","America/Los_Angeles","Pacific Time (US & Canada)" "Mountain Standard Time (Mexico)","America/Mazatlan","Mazatlan" "Central Standard Time (Mexico)","America/Mexico_City","Guadalajara" "Central Standard Time (Mexico)","America/Mexico_City","Mexico City" "Central Standard Time (Mexico)","America/Monterrey","Monterrey" "Montevideo Standard Time","America/Montevideo","Montevideo" "Eastern Standard Time","America/New_York","Eastern Time (US & Canada)" "US Mountain Standard Time","America/Phoenix","Arizona" "Canada Central Standard Time","America/Regina","Saskatchewan" "Pacific SA Standard Time","America/Santiago","Santiago" "E. South America Standard Time","America/Sao_Paulo","Brasilia" "Newfoundland Standard Time","America/St_Johns","Newfoundland" "Pacific Standard Time","America/Tijuana","Tijuana" "Central Asia Standard Time","Asia/Almaty","Almaty" "Arabic Standard Time","Asia/Baghdad","Baghdad" "Azerbaijan Standard Time","Asia/Baku","Baku" "SE Asia Standard Time","Asia/Bangkok","Bangkok" "SE Asia Standard Time","Asia/Bangkok","Hanoi" "China Standard Time","Asia/Chongqing","Chongqing" "Sri Lanka Standard Time","Asia/Colombo","Sri Jayawardenepura" "Bangladesh Standard Time","Asia/Dhaka","Astana" "Bangladesh Standard Time","Asia/Dhaka","Dhaka" "China Standard Time","Asia/Hong_Kong","Hong Kong" "North Asia East Standard Time","Asia/Irkutsk","Irkutsk" "SE Asia Standard Time","Asia/Jakarta","Jakarta" "Israel Standard Time","Asia/Jerusalem","Jerusalem" "Afghanistan Standard Time","Asia/Kabul","Kabul" "Russia Time Zone 11","Asia/Kamchatka","Kamchatka" "Pakistan Standard Time","Asia/Karachi","Islamabad" "Pakistan Standard Time","Asia/Karachi","Karachi" "Nepal Standard Time","Asia/Kathmandu","Kathmandu" "India Standard Time","Asia/Kolkata","Chennai" "India Standard Time","Asia/Kolkata","Kolkata" "India Standard Time","Asia/Kolkata","Mumbai" "India Standard Time","Asia/Kolkata","New Delhi" "North Asia Standard Time","Asia/Krasnoyarsk","Krasnoyarsk" "Singapore Standard Time","Asia/Kuala_Lumpur","Kuala Lumpur" "Arab Standard Time","Asia/Kuwait","Kuwait" "Magadan Standard Time","Asia/Magadan","Magadan" "Arabian Standard Time","Asia/Muscat","Abu Dhabi" "Arabian Standard Time","Asia/Muscat","Muscat" "N. Central Asia Standard Time","Asia/Novosibirsk","Novosibirsk" "Myanmar Standard Time","Asia/Rangoon","Rangoon" "Arab Standard Time","Asia/Riyadh","Riyadh" "Korea Standard Time","Asia/Seoul","Seoul" "China Standard Time","Asia/Shanghai","Beijing" "Singapore Standard Time","Asia/Singapore","Singapore" "Russia Time Zone 10","Asia/Srednekolymsk","Srednekolymsk" "Taipei Standard Time","Asia/Taipei","Taipei" "West Asia Standard Time","Asia/Tashkent","Tashkent" "Georgian Standard Time","Asia/Tbilisi","Tbilisi" "Iran Standard Time","Asia/Tehran","Tehran" "Tokyo Standard Time","Asia/Tokyo","Osaka" "Tokyo Standard Time","Asia/Tokyo","Sapporo" "Tokyo Standard Time","Asia/Tokyo","Tokyo" "Ulaanbaatar Standard Time","Asia/Ulaanbaatar","Ulaanbaatar" "Central Asia Standard Time","Asia/Urumqi","Urumqi" "Vladivostok Standard Time","Asia/Vladivostok","Vladivostok" "Yakutsk Standard Time","Asia/Yakutsk","Yakutsk" "Ekaterinburg Standard Time","Asia/Yekaterinburg","Ekaterinburg" "Caucasus Standard Time","Asia/Yerevan","Yerevan" "Azores Standard Time","Atlantic/Azores","Azores" "Cape Verde Standard Time","Atlantic/Cape_Verde","Cape Verde Is." "UTC-02","Atlantic/South_Georgia","Mid-Atlantic" "Cen. Australia Standard Time","Australia/Adelaide","Adelaide" "E. Australia Standard Time","Australia/Brisbane","Brisbane" "AUS Central Standard Time","Australia/Darwin","Darwin" "Tasmania Standard Time","Australia/Hobart","Hobart" "AUS Eastern Standard Time","Australia/Melbourne","Canberra" "AUS Eastern Standard Time","Australia/Melbourne","Melbourne" "W. Australia Standard Time","Australia/Perth","Perth" "AUS Eastern Standard Time","Australia/Sydney","Sydney" "UTC","Etc/UTC","UTC" "W. Europe Standard Time","Europe/Amsterdam","Amsterdam" "GTB Standard Time","Europe/Athens","Athens" "Central Europe Standard Time","Europe/Belgrade","Belgrade" "W. Europe Standard Time","Europe/Berlin","Berlin" "W. Europe Standard Time","Europe/Berlin","Bern" "Central Europe Standard Time","Europe/Bratislava","Bratislava" "Romance Standard Time","Europe/Brussels","Brussels" "GTB Standard Time","Europe/Bucharest","Bucharest" "Central Europe Standard Time","Europe/Budapest","Budapest" "Romance Standard Time","Europe/Copenhagen","Copenhagen" "GMT Standard Time","Europe/Dublin","Dublin" "FLE Standard Time","Europe/Helsinki","Helsinki" "Turkey Standard Time","Europe/Istanbul","Istanbul" "Kaliningrad Standard Time","Europe/Kaliningrad","Kaliningrad" "FLE Standard Time","Europe/Kiev","Kyiv" "GMT Standard Time","Europe/Lisbon","Lisbon" "Central Europe Standard Time","Europe/Ljubljana","Ljubljana" "GMT Standard Time","Europe/London","Edinburgh" "GMT Standard Time","Europe/London","London" "Romance Standard Time","Europe/Madrid","Madrid" "Belarus Standard Time","Europe/Minsk","Minsk" "Russian Standard Time","Europe/Moscow","Moscow" "Russian Standard Time","Europe/Moscow","St. Petersburg" "Romance Standard Time","Europe/Paris","Paris" "Central Europe Standard Time","Europe/Prague","Prague" "FLE Standard Time","Europe/Riga","Riga" "W. Europe Standard Time","Europe/Rome","Rome" "Russia Time Zone 3","Europe/Samara","Samara" "Central European Standard Time","Europe/Sarajevo","Sarajevo" "Central European Standard Time","Europe/Skopje","Skopje" "FLE Standard Time","Europe/Sofia","Sofia" "W. Europe Standard Time","Europe/Stockholm","Stockholm" "FLE Standard Time","Europe/Tallinn","Tallinn" "W. Europe Standard Time","Europe/Vienna","Vienna" "FLE Standard Time","Europe/Vilnius","Vilnius" "Russian Standard Time","Europe/Volgograd","Volgograd" "Central European Standard Time","Europe/Warsaw","Warsaw" "Central European Standard Time","Europe/Zagreb","Zagreb" "Samoa Standard Time","Pacific/Apia","Samoa" "New Zealand Standard Time","Pacific/Auckland","Auckland" "New Zealand Standard Time","Pacific/Auckland","Wellington" "Tonga Standard Time","Pacific/Fakaofo","Tokelau Is." "Fiji Standard Time","Pacific/Fiji","Fiji" "Central Pacific Standard Time","Pacific/Guadalcanal","Solomon Is." "West Pacific Standard Time","Pacific/Guam","Guam" "Hawaiian Standard Time","Pacific/Honolulu","Hawaii" "UTC+12","Pacific/Majuro","Marshall Is." "UTC-11","Pacific/Midway","International Date Line West" "UTC-11","Pacific/Midway","Midway Island" "Central Pacific Standard Time","Pacific/Noumea","New Caledonia" "UTC-11","Pacific/Pago_Pago","American Samoa" "West Pacific Standard Time","Pacific/Port_Moresby","Port Moresby" "Tonga Standard Time","Pacific/Tongatapu","Nuku'alofa" ``` Note that the above list includes entries where more than one Rails zone maps back to the same Windows zone. You may want to pick just one of these when mapping in the Windows-to-Rails direction. Also, the above list does not include the zones that could not be mapped, which are as follows (CSV): ```csv "Windows","IANA","Rails" "","Pacific/Chatham","Chatham Is." "Dateline Standard Time","Etc/GMT+12","" "Pacific Standard Time (Mexico)","America/Santa_Isabel","" "Eastern Standard Time (Mexico)","America/Cancun","" "Paraguay Standard Time","America/Asuncion","" "Central Brazilian Standard Time","America/Cuiaba","" "SA Eastern Standard Time","America/Cayenne","" "Bahia Standard Time","America/Bahia","" "Namibia Standard Time","Africa/Windhoek","" "Jordan Standard Time","Asia/Amman","" "Middle East Standard Time","Asia/Beirut","" "Syria Standard Time","Asia/Damascus","" "E. Europe Standard Time","Etc/GMT-2","" "Libya Standard Time","Africa/Tripoli","" "Mauritius Standard Time","Indian/Mauritius","" "Line Islands Standard Time","Pacific/Kiritimati","" ```
4,293
It is a bit late into this new year, being that we're already in the second month, but we are now cycling the Community Promotion Ads for 2017! ### What are Community Promotion Ads? Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Images of the advertisements are provided, and community voting will enable the advertisements to be shown. ### Why do we have Community Promotion Ads? This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things: * the site's twitter account * interesting journey logs and journal blogs * helpful travel guidebooks and research resources * cool events or conferences * anything else your community would genuinely be interested in The goal is for future visitors to find out about *the stuff your community deems important*. This also serves as a way to promote information and resources that are *relevant to your own community's interests*, both for those already in the community and those yet to join. ### Why do we reset the ads every year? Some services will maintain usefulness over the years, while other things will wane to allow for new faces to show up. Resetting the ads every year helps accommodate this, and allows old ads that have served their purpose to be cycled out for fresher ads for newer things. This helps keep the material in the ads relevant to not just the subject matter of the community, but to the current status of the community. We reset the ads once a year, every December. The community promotion ads have no restrictions against reposting an ad from a previous cycle. If a particular service or ad is very valuable to the community and will continue to be so, it is a good idea to repost it. It may be helpful to give it a new face in the process, so as to prevent the imagery of the ad from getting stale after a year of exposure. ### How does it work? The answers you post to this question *must* conform to the following rules, or they will be ignored. 1. All answers should be in the exact form of: ``` [![Tagline to show on mouseover][1]][2] [1]: http://image-url [2]: http://clickthrough-url ``` Please **do not add anything else to the body of the post**. If you want to discuss something, do it in the comments. 2. The question must always be tagged with the magic [community-ads](/questions/tagged/community-ads "show questions tagged 'community-ads'") tag. In addition to enabling the functionality of the advertisements, this tag also pre-fills the answer form with the above required form. ### Image requirements * The image that you create must be 300 x 250 pixels, or double that if high DPI. * Must be hosted through our standard image uploader (imgur) * Must be GIF or PNG * No animated GIFs * Absolute limit on file size of 150 KB * If the background of the image is white or partially white, there must be a 1px border (2px if high DPI) surrounding it. ### Score Threshold There is a **minimum score threshold** an answer must meet (currently **6**) before it will be shown on the main site. You can check out the ads that have met the threshold with basic click stats [here](https://travel.meta.stackexchange.com/ads/display/4293).
2017/02/02
[ "https://travel.meta.stackexchange.com/questions/4293", "https://travel.meta.stackexchange.com", "https://travel.meta.stackexchange.com/users/552/" ]
[![Improve the world: Contribute to OpenStreetMap](https://i.stack.imgur.com/ZdmiV.png)](https://www.openstreetmap.org/about)
102,617
Does adding text effects (drop shadows, glow, etc.) in InDesign lower the resolution of text or file when it goes to print?
2017/12/12
[ "https://graphicdesign.stackexchange.com/questions/102617", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/110364/" ]
No. The file is output at the resolution set in the output.
66,258,345
What I'm trying to do is to search the corresponding from each line from a file into another file; but with EACH lines finding a corresponding line, if possible, in the other file, even if two lines from the first file are the same. Here are the content of the different files: Data\_1.txt ``` chr12 132401672 132401673 GA - chr12 132401743 132401743 T - chr12 132401743 132401743 T - chr12 132402020 132402020 T C ``` Data\_2.txt ``` chr12 132401675 132401675 - TT intronic chr12 132401743 132401743 T - intronic chr12 132401951 132401951 C T splicing ``` I'm trying to "grep" the content of Data\_1 to have corresponding lines in Data\_2. Here is **wanted** result: ``` chr12 132401743 132401743 T - intronic chr12 132401743 132401743 T - intronic ``` My current code is this one: ``` grep -w -f Data_1.txt Data_2.txt ``` But the current result is: ``` chr12 132401743 132401743 T - intronic ``` Because there is the two same lines in Data\_1.txt, grep only gives me one result (because it exists only one time in the second). But I would like to have, for each line of Data\_1.txt, a corresponding result (if it does exist) in Data\_2.file, even if it is the same line. I know that I could make a loop with a: `for a in 'more Data_1.txt'; do grep -w "$a" Data_2.txt; done` , but the original file from this example come from is much, much bigger, and it's taking too much time to run it. Maybe there's a way to do it with awk or another function, but I don't know how. Thank you!
2021/02/18
[ "https://Stackoverflow.com/questions/66258345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15234236/" ]
If there is no repetition of same postcode for any name then you can have names with two post codes as below ``` SELECT NAME FROM RESIDENT_POSTCODE GROUP BY NAME HAVING COUNT(POSTCODE)=2 ``` But if any postcode can be specified more than once (for example **1001** is specified more than once for **Alan**) then you need to use below query: ``` select name from ( SELECT distinct NAME, postcode FROM RESIDENT_POSTCODE) group by name having count(*)=2 ``` if you want all names having two or more than 2 postcode then use below query: ``` select name from ( SELECT distinct NAME, postcode FROM RESIDENT_POSTCODE) group by name having count(*)>=2 ```
42,740
I have a rectangular pulse: ``` w = 20; pln = 10; v =[zeros(1, pln), ones(1, w),zeros(1, pln)]; figure(); plot(v,'-o'); ``` by perform `fft` and `fftshift` the pulse center to zero to get its frequency domain representation: ``` yf = fftshift(fft(v)); xf = [-0.5000 -0.4750 -0.4500 -0.4250 -0.4000 -0.3750 -0.3500 -0.3250... -0.3000 -0.2750 -0.2500 -0.2250 -0.2000 -0.1750 -0.1500 -0.1250... -0.1000 -0.0750 -0.0500 -0.0250 0 0.0250 0.0500 0.0750... 0.1000 0.1250 0.1500 0.1750 0.2000 0.2250 0.2500 0.2750... 0.3000 0.3250 0.3500 0.3750 0.4000 0.4250 0.4500 0.4750]; yf = yf.*exp(-2j*pi*xf*(pln+w/2)); % this shifts the time domain signal to zero ``` `yf` is close to the sinc function - the Fourier transform of a rectangular function - but not exactly the same, it has imaginary part while sinc is is purely real: ``` yf_sinc = w*sinc(w*xf); ``` Why is the difference and why `ifft` of samples taken from a sinc function will not produce an exact rectangular pulse but with ripples close to the edge while `ifft(fft(v))` will exactly reproduce the original rectangular pulse: ``` % has ripples around the edges figure(); plot(fftshift(ifft(fftshift(yf_sinc)))); % reproduces the exact rectangular pulse figure(); plot(fftshift(ifft(fftshift(yf)))); ``` herer `yf`, if we assume it was directly sampled form a underlying function, that is ingoring the fact that it is produced by `fft` of a rectangular pulse (it's just some numbers anyway), what function would it be? Is it possible by sampling a function in the frequency domain (not need to be the sinc function) and take the `ifft` will produce an exact rectangular pulse? [![rectangular pulse and fft compared to a sinc function sampes](https://i.stack.imgur.com/TEqze.png)](https://i.stack.imgur.com/TEqze.png)
2017/07/28
[ "https://dsp.stackexchange.com/questions/42740", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/29982/" ]
That is not symmetrical around index 0 (supposedly the first index). You probably need to apply `fftshift` before the transform as well as afterwards in order to get the representation you expect both in time and frequency domain.
33,331,083
[The Link to the code](https://jsfiddle.net/9nek2sxw/) I'm trying to re-size the 5x buttons that I have centered near the middle/bottom of the page. How do I shorten (whilst keeping them in the same location) the buttons to half the width they currently are? ``` /* Nav */ .nav li { list-style: none; padding-top: 10px; padding-bottom: 10px; text-align: center; Color: White; Border: 3px Solid; border-color: black; font-family: 'Roboto',sans-serif; background-color: #99CCFF; letter-spacing: 1px; margin-bottom: 20px; } .nav li:hover { background: #117bff; cursor: pointer; transition: background 1s; font-weight: bold; } ```
2015/10/25
[ "https://Stackoverflow.com/questions/33331083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5439914/" ]
Randomize your seed before generation. For best results, dont use the inbuilt randomize procedure.
6,618
I've been trying to write a jQuery script where when someone clicks on the input the space clears and then if they don't type anything in, it reappears. This is what I came up with. Is there a better way to do this? If so why is it better? ``` $(document).ready(function() { // set all input.text default value according to alt attribute $("input.contactStyle").each(function(){ $(this).val($(this).attr("alt")); }); // clear input.text on focus, if still in default $("input.contactStyle").focus(function() { if($(this).val()==$(this).attr("alt")) { $(this).val(""); } }); // if field is empty afterward, add text again $("input.contactStyle").blur(function() { if($(this).val()=="") { $(this).val($(this).attr("alt")); } }); // set all input.text default value according to alt attribute $("textarea.contactStyle").each(function(){ $(this).val($(this).attr("title")); }); // clear input.text on focus, if still in default $("textarea.contactStyle").focus(function() { if($(this).val()==$(this).attr("title")) { $(this).val(""); } }); // if field is empty afterward, add text again $("textarea.contactStyle").blur(function() { if($(this).val()=="") { $(this).val($(this).attr("title")); } }); }); ```
2011/12/08
[ "https://codereview.stackexchange.com/questions/6618", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/8981/" ]
It seems like you're trying to recreate the functionality of the [`placeholder`](https://developer.mozilla.org/en/HTML/Element/input#attr-placeholder) attribute that exists in HTML5. For browsers that support it--and that's all modern browsers with the exception of IE9 (I think)--your above code can be replaced with e.g.: ```html <input type="text" class="contactStyle" placeholder="Your placeholder text"> ``` If you want to also use this functionality in less-modern browsers it'll take some JavaScript, but best not to reinvent the wheel. Several [polyfills](http://remysharp.com/2010/10/08/what-is-a-polyfill/) have been written by other people that let you use the `placeholder` attribute regardless of browser. There are several listed on [this page](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills) (do a Ctrl+F for "placeholder").
60,230,534
The following code creates a dictionary of email addresses and how frequently each email appears. What is the best way to pull out the key and value for the email with the max frequency? ``` fname = input("Enter file:") try: fhand = open(fname) except: print('File cannot be opened:') exit() counts = dict() for line in fhand: if line.startswith('From:'): words = line.split(' ', 1)[1] words = words.rstrip('\n') counts[words] = counts.get(words,0)+1 print(counts) ```
2020/02/14
[ "https://Stackoverflow.com/questions/60230534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12859513/" ]
Based on [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) ``` import operator max(counts.iteritems(), key=operator.itemgetter(1))[0] ``` Or you can define two variables ``` max_count = 0 frequent = None ``` and append the following to the if clause ``` if counts[words] > max_count max_count = counts[words] frequent = words ``` At the end `frequent` would contain most frequent email (or `None` if there is no email in file).
17,710,849
Premise: I am trying to make a bunch of buttons in Tkinter and put them in a grid layout one after the other. I don't want to hard code each grid value that way I can add more buttons later with ease. My first thought was to: ``` Button(root, text = "example", command = self.example_action).grid(row = count++) ``` But this did not work, I did some searching and found that python does not have a pre or post increment operator ([Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python)). So my next thought was to: ``` Button(root, text = "example", command = self.example_action).grid(row = count = count + 1) ``` This gives: SyntaxError: invalid syntax So other than splitting my code onto two lines (use the variable then update it on the next line) is there a good way to do this all on one line to make my code more beautiful?
2013/07/17
[ "https://Stackoverflow.com/questions/17710849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2395610/" ]
I suppose you could use a generator. Initialize count like: ``` count = itertools.count() ``` then you can do the following as much as you like Python 2.x: ``` Button(root, text = "example", command = self.example_action).grid(row = count.next()) ``` Python 3.x: ``` Button(root, text = "example", command = self.example_action).grid(row = next(count)) ``` But I probably wouldn't
22,149,839
Localhost follows the loopback mechanism. why we have to loop back the packets to our computer itself? what is the need for that(general case and specially socket programming)? Also kindly specify some practical applications of localhost too? And another clarfication i need was localhost resolves to 127.0.0.1 (most time) myhost name say "vinoth-computer" resolves to 192.168.111.12 is 127.0.0.1 and 192.168.111.12 one and same?
2014/03/03
[ "https://Stackoverflow.com/questions/22149839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2530921/" ]
Because the set data structure is, by definition, unordered: <http://en.wikipedia.org/wiki/Set_(data_structure)> To be more precise, Clojure's built-in set (which `#{blah blah blah}` gives you) is a hash set -- that is, a set backed by a hash table (<http://en.wikipedia.org/wiki/Hash_tables>). It provides you with the following guarantees: * Uniqueness of every element (no duplicates allowed). * O(1) performance characteristics for insertion and containment checks. * Iteration works -- calling `seq` will give you every element in the set, but in an undefined order. Undefined order, here, means that the iteration order depends on the elements you inserted in the set, their number, the order in which you inserted them, all the other operations you may have tried on that set before, and various other implementation details *that might change from a language version to the other* (and even between implementations -- you might, and probably will, get different results in Clojure, Clojure running on a 64-bit JVM, or ClojureScript). The important thing to take away is, if you're writing code that works with sets (or maps), never make it depend on any notion of order in said sets/maps. It'll break.
18,467
I am having trouble understanding working with structs in assembly from disassembly. can you please explain the code below. Disassembly below: [![disassembly snippet](https://i.stack.imgur.com/zJhO2.jpg)](https://i.stack.imgur.com/zJhO2.jpg) Source code: [![source code snippet](https://i.stack.imgur.com/d4zvB.jpg)](https://i.stack.imgur.com/d4zvB.jpg)
2018/06/06
[ "https://reverseengineering.stackexchange.com/questions/18467", "https://reverseengineering.stackexchange.com", "https://reverseengineering.stackexchange.com/users/24603/" ]
This is manual string assignment. Notice how all DWORDs are composed of printable characters? hit `r` in IDA to convert the hex values to string characters. This code seems to be assigning strings into different stack addresses, 4 characters at a time. This is a common optimization over calling a function that iterates over strings byte by byte. As others pointed out, this optimization is usually called "loop unrolling" as it unrolls several iterations of a loop into sequential assembly, however I often find that type of direct string characters assignment to be more commonly the output of a code similar to the following: ``` char str[] = "this is a string"; ```
24,527,264
I have a file with this content (tab separated): ``` bin_id chr bin EURO.hz chrF1_17700000 chrF1 17700000 102 chrF1_17800000 chrF1 17800000 199 chrF1_17900000 chrF1 17900000 398 chrF1_18000000 chrF1 18000000 410 chrF1_18100000 chrF1 18100000 342 chrF1_18200000 chrF1 18200000 447 ``` I load it with: ``` jo <- read.table("tmp.tsv",header=T,row.names=1,sep="\t") ``` And everything goes fine. Then, when I do: ``` jo["chrF1_1800",] ``` I get row name "chrF1\_18000000": ``` chr bin EURO.hz chrF1_18000000 chrF1 18000000 410 ``` Note the different number of zeros. To rephrase the problem: although row names "chrF1\_180000" or "chrF1\_180" do not exists, R returns "chrF1\_18000000". I have tried this in two different machines (linux, mac) with different R versions (3.0.1 (2013-05-16) and R version 2.15.2 (2012-10-26)). This kind of behaviour is completely unexpected to me (and is responsible of many errors in my scripts). Is this a bug??? Thanks! Federico
2014/07/02
[ "https://Stackoverflow.com/questions/24527264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3796965/" ]
Subsetting a `data.frame` by row names uses *partial matching*, as stated in the [documentation](http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.data.frame.html) : > > Both [ and [[ extraction methods partially match row names. By default > neither partially match column names, but [[ will if exact = FALSE > (and with a warning if exact = NA). If you want to exact matching on > row names use match, as in the examples. > > > If you want exact matching, you can use [match](http://stat.ethz.ch/R-manual/R-patched/library/base/html/match.html) function e.g. : ``` # partial matching does not work jo[match("chrF1_18000",row.names(jo)),] # chr bin EURO.hz # NA <NA> NA NA # exact matching works jo[match("chrF1_18000000",row.names(jo)),] # chr bin EURO.hz # chrF1_18000000 chrF1 18000000 410 ```
25,863,786
I am working at an application that currently will have data only locally (server part is not ready) - the apk must contain the displayed data too. So I will have a list of items, each item having an image. Where it is the best place to store those images, such that the apk size is kept as small as possible? Searching I found that /raw or /assets can be such places. Or is it better to store images as base64 encoded dirrectly in the loaded JSONs? Which is best?
2014/09/16
[ "https://Stackoverflow.com/questions/25863786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459573/" ]
We would need to see the actual response you are getting in order to determine if something is wrong. However, [HTTP::Request](https://metacpan.org/pod/HTTP::Request) has a method `as_string` that will give you the textual representation of your request. ``` # ... stuff $req->content($post_data); # show the request print $req->as_string; # ... my $resp = $ua->request($req); ``` It will show something like this: ``` POST foo Content-Type: application/json X-Auth-Token: kfksj48sdfj4jd9d { "value1" : "SMRT23489MER", "value2" : "7352009 ", "date" : "20140813", "time" : "2033", "info" : ["2424","324","545","565"] } ``` Which is basically a fine request as far as I can tell.
67,646,527
I'm new at programming in WPF and C# and getting used to OOP, I'm trying to code my program using the best programming practices but I have been stuck for a couple of days now and I wasn't able to figure out how to complete this, hope someone out there can help. what I'm trying to do is very simple, I have a WPF window with a progress bar and a button, that's it, and in the C# backend code for this window, I have a click event that calls a method in another class from another file, in that class I have a BackgroundWorker and I have been trying to update a ProgressBar based on the BackgroundWorker. I confirmed that the code works by writing the progress and events in the console, what I have not idea how to do is how to access that BackgroundWorker in the other class to update the progress bar in my xaml file, or if this is not the best approach I would like to know what would be the best way to do this XAML: ```xml <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="35"/> <RowDefinition Height="15"/> <RowDefinition Height="40"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <ProgressBar x:Name="progressBar" Grid.Row = "1" Width ="500" Value="0"/> <Button x:Name="btn_start" Grid.Row = "3" Content ="Start" Height="30" Width="125" Click="btn_start_Click"/> </Grid> ``` c# XAML Backend: ```cs namespace progressBar { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btn_start_Click(object sender, RoutedEventArgs e) { GeneralTasks GT = new GeneralTasks(); GT.start(); } } } ``` And finally the unreadable class "GeneralTasks": ```cs public class GeneralTasks { BackgroundWorker worker = new BackgroundWorker(); public void start() { worker.RunWorkerCompleted += worker_RunWorkerCompleted; worker.WorkerReportsProgress = true; worker.DoWork += worker_DoWork; worker.ProgressChanged += worker_ProgressChanged; worker.RunWorkerAsync(); } private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { Console.WriteLine(e.ProgressPercentage + "% " + (string)e.UserState); } private void worker_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; worker.ReportProgress(0, string.Format("Percentage completed: 0")); for (int i = 0; i <= 100; i++) { worker.ReportProgress(i, string.Format("Percentage completed: {0}", i)); Console.WriteLine("Percentage Completed: {0}",i); Thread.Sleep(100); } worker.ReportProgress(100, string.Format("Done Processing")); } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Console.WriteLine("Done Processing"); } } ```
2021/05/22
[ "https://Stackoverflow.com/questions/67646527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931690/" ]
You're just following a tutorial where the choice of which kind of Blazor app to make was made on a later screen Decide which kind of app you want to make: **Server** - the server runs the c# code and delivers small fragments of HTML to the browser over a websockets connection, and the browser patches its display to make it look like things are happening. It starts up quickly and is good for keeping things like connection strings that the code uses as a secret because they never leave the server. It is more difficult to scale to thousands of users because effectively the server runs the app and the users "use it remotely" but the server has to remember state for all of them and load balancing across multiple servers is tricky. Microsoft claim good performance for thousands of concurrent users on even quite low spec Azure web apps (3.5g ram) but I'm sure the test app that supported th claims wasn't the most complex app in the world ;) **WebAsm** - the server sends a small version of .Net engine and your code, to the browser which then runs all your c# code in the browser and generates html locally that is used to patch the display and make changes. It is slower to start because a lot of data has to be downloaded(but some of it can then be cached) and if there are things you want to keep secret (let's say you invent an awesome new algorithm for something, be aware that if you do it in the c# that is sent to the browser to run, it could also be captured and decompiled) then you need to be careful to have them done by an api on the server that you have the client side app call (just like you would with a typical api+Json+javascript app), but it can scale more easily because the server has much less work to do overall. WebAsm apps can also (do long as they don't rely on the server for everything) potentially carry on working if three is no network connection. A server app stops because essentially the browser is only "a VNC" or "Remote Desktop" to an app that runs on the server and ships html back and forth
15,516,123
I want to give the user access according to the user role. I have two user roles. they are Admin and user. I write my controller like this. ``` [Authorize(Roles = "Admin")] // my Problem is here. I don't know how to set the current user role public ActionResult Index() { var query = from company in db.tblCompanies select company; return View(query.ToList()); } ``` But I don't know how to set the `Roles = "Admin"` after cutomer login. In my user tale I have Roles coloum and it can save Admin or user. But I don't know how to set and where should I set `Roles = "Admin".`
2013/03/20
[ "https://Stackoverflow.com/questions/15516123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348351/" ]
Try this :: .h File ``` @property (nonatomic,retain) NSDictionary *dict; ``` .m file ``` NSString *errorDesc = nil; NSPropertyListFormat format; NSString *rootPath; rootPath = [[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"plist"]; NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:rootPath]; dict = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; //NSLog(@"PLIST retrive:%@",plistXML); if (!dictLang) { NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); } ``` Get Value :: ``` NSLog(@" Success :: %@", [dict objectForKey:@"success"]); ``` Hope, it'll help you. Thanks.
173,903
Some pdf readers for windows allow you to highlight and type notes into PDF files. The pdf readers that I've seen for Linux only allow you to read pdfs. Are there any that allow you to highlight text and add notes?
2010/08/09
[ "https://superuser.com/questions/173903", "https://superuser.com", "https://superuser.com/users/44339/" ]
You can use [okular](http://okular.kde.org/) for that purpose. Be aware that it doesn't actually change the PDF. The annotations are stored in a separate file and can (only?) be displayed by okular. [screenshots](http://okular.kde.org/screenshots.php)
30,647,138
I'm working on a project where there is a row of controls, each of which is a button element. There is content inside of the buttons, and they are laid out in a row with flexbox. The button element centers its content vertically, and I can't figure out how to override it to vertically align it at the top of the button. The controls all need to be the same height and same width, and clicking anywhere in the borders must count as a click on the button. This Codepen shows the problem clearly: <http://codepen.io/anon/pen/RPpqdz> ```css .wrapper { display: flex; flex-direction: row; width: 80%; } button, .object { font-family: sans-serif; font-size: 1em; padding: 1em; background: #fff; flex: 1; border: 1px solid red; text-align: left; } ``` ```html <h1>What it looks like</h1> <div class="wrapper"> <button>I am Content</button> <button>I am Much Longer Content That Goes Here and Here</button> <button>I am Content</button> </div> <h1>What I want it to look like</h1> <div class="wrapper"> <div class="object">I am Content</div> <div class="object">I am Much Longer Content That Goes Here and Here</div> <div class="object">I am Content</div> </div> ``` I realize this issue could be solved by not using button elements, but I also feel like I SHOULD be able to override this behavior of button elements. I'd like to figure this out for my own sanity!
2015/06/04
[ "https://Stackoverflow.com/questions/30647138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1991746/" ]
Look closely at this part of the error message: > > Cannot convert value of type [java.util.ArrayList] to required type [**java.awt.List**] for property 'examplelist' > > > You have imported the wrong `List` in your code. Change this: ``` import java.awt.List; ``` to this: ``` import java.util.List; ```
22,713,128
I'm working on an android application, that uses a navigation drawer to switch between two fragments. However, each time I switch, the fragment is completely recreated. Here is the code from my main activity. ``` /* The click listener for ListView in the navigation drawer */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { android.support.v4.app.Fragment fragment; String tag; android.support.v4.app.FragmentManager; fragmentManager = getSupportFragmentManager(); switch(position) { case 0: if(fragmentManager.findFragmentByTag("one") != null) { fragment = fragmentManager.findFragmentByTag("one"); } else { fragment = new OneFragment(); } tag = "one"; break; case 1: if(fragmentManager.findFragmentByTag("two") != null) { fragment = fragmentManager.findFragmentByTag("two"); } else { fragment = new TwoFragment(); } tag = "two"; break; } fragment.setRetainInstance(true); fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); setTitle(mNavTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } ``` I've set up some debug logging, and every time selectItem is called, one fragment is destroyed, while the other is created. Is there any way to prevent the fragments from being recreated, and just reuse them instead?
2014/03/28
[ "https://Stackoverflow.com/questions/22713128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38695/" ]
After @meredrica pointed out that replace() destroys the fragments, I went back through the FragmentManager documentation. This is the solution I've come up with, that seems to be working. ``` /* The click listener for ListView in the navigation drawer */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { android.support.v4.app.FragmentManager; fragmentManager = getSupportFragmentManager(); switch(position) { case 0: if(fragmentManager.findFragmentByTag("one") != null) { //if the fragment exists, show it. fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("one")).commit(); } else { //if the fragment does not exist, add it to fragment manager. fragmentManager.beginTransaction().add(R.id.container, new OneFragment(), "one").commit(); } if(fragmentManager.findFragmentByTag("two") != null){ //if the other fragment is visible, hide it. fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("two")).commit(); } break; case 1: if(fragmentManager.findFragmentByTag("two") != null) { //if the fragment exists, show it. fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("two")).commit(); } else { //if the fragment does not exist, add it to fragment manager. fragmentManager.beginTransaction().add(R.id.container, new TwoFragment(), "two").commit(); } if(fragmentManager.findFragmentByTag("one") != null){ //if the other fragment is visible, hide it. fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("one")).commit(); } break; } // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); setTitle(mNavTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } ``` I also added this bit, but I'm not sure if it's necessary or not. ``` @Override public void onDestroy() { super.onDestroy(); FragmentManager fragmentManager = getSupportFragmentManager(); if(fragmentManager.findFragmentByTag("one") != null){ fragmentManager.beginTransaction().remove(fragmentManager.findFragmentByTag("one")).commit(); } if(fragmentManager.findFragmentByTag("two") != null){ fragmentManager.beginTransaction().remove(fragmentManager.findFragmentByTag("two")).commit(); } } ```
252,279
I developed a custom module in Drupal 7. I asked a similar question here: [Drupal 7 Get field value by machine name and pass to javascript](https://drupal.stackexchange.com/questions/247431/drupal-7-get-field-value-by-machine-name-and-pass-to-javascript) But the difference in this question is, instead of a taxonomy term, I want to get the field value of a regular text field. Here is the code that I use to get the field value of a taxonomy term to pass to javascript, which currently resides in my theme's hook\_process\_page function: ``` if ($node = menu_get_object('node')) { $tid = $node->field_test['und'][0]['tid']; $term = taxonomy_term_load($tid); drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting'); } ``` Some things that I can see might ned to be changed right away are "tid," "taxonomy\_term\_load." How can I change this code to instead get the text value of a field instead of a taxonomy term, to pass to mymodule? EDIT: Per a suggested change, I've modified the code, though I'm not sure this is what was meant: ``` if ($node = menu_get_object('node')) { $fieldValue = $node->field_test['und'][0]['value']; $term = taxonomy_term_load($fieldValue); drupal_add_js(array('jsblock' => array('test' => $fieldValue->name)), 'setting'); } ``` The in response to Drupal.settings.jsblock.test, the console outputs null. Here is the Drupal notice: [![property of non-object](https://i.stack.imgur.com/zTDIi.png)](https://i.stack.imgur.com/zTDIi.png) Devel results: [![enter image description here](https://i.stack.imgur.com/Wwj3n.png)](https://i.stack.imgur.com/Wwj3n.png) How can I get the field value and pass it to my jsblock module?
2017/12/17
[ "https://drupal.stackexchange.com/questions/252279", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/79646/" ]
* More than likely, you have a redirect base directive in your .htaccess. This is used when serving your Drupal site out of a subfolder of your webhosting provider's webroot. You should check your .htaccess file for the directive `RewriteBase /abc` and replace with `RewriteBase /xyz` * If that still doesn't work, check the vhost entry of your webserver for the same directive. * Otherwise, if the site still redirects to "/abc", then you may have a $base\_url defined in settings.php causing the redirect.
56,787,633
I have an image gallery on my site and when you click on it, it opens into a lightbox kind of effect. I want them to be able to click off of the preview image on the lightbox background and close the preview but not if they click on the actual preview image itself. ``` function get_image_preview(){ var lightbox = document.getElementById("lightbox"); var image_src = document.getElementById("gallery_image").src; lightbox.style.display = "block"; lightbox.setAttribute("onclick", "end_image_preview()"); var new_image = document.createElement("img"); new_image.setAttribute("id", "preview_image"); new_image.setAttribute("src", image_src); new_image.setAttribute("onclick", "return false"); lightbox.appendChild(new_image); } function end_image_preview(){ var lightbox = document.getElementById("lightbox"); lightbox.style.display = "none"; lightbox.innerHTML = ""; } ``` So basically this line: ``` lightbox.setAttribute("onclick", "end_image_preview()"); ``` does what it is supposed to do and close the preview. However, the preview is a child of this and I want them to be able to click on the image without ending the preview, so I tried this: ``` new_image.setAttribute("onclick", "return false"); ```
2019/06/27
[ "https://Stackoverflow.com/questions/56787633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376843/" ]
I think you mignt want to use [event.stopPropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation): ``` function new_image_click(e) { e.stopPropagation(); } new_image.setAttribute("onclick", "new_image_click(event)"); ```
2,216,529
I have some problem to figure out how I can maintain the pipe and redirect functionality of a shell once I find out that there are missing command line arguments. If I for example use a scanf call, that will work with a re-direct or a pipe from a shell, but in absence of this I get a prompt, which I don't want. I would like to accept command line arguments through argv[], a pipe or re-direct but I can't figure out how to do it with out getting the prompt. If I for example try something like this: ``` if(argc < 2) exit(0); ``` Then the program will terminate if I try this: ``` echo arg | myProgram ``` Or this: ``` myProgram < fileWithArgument ``` I have tried to look this up but I always get some bash scripting reference.
2010/02/07
[ "https://Stackoverflow.com/questions/2216529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248630/" ]
The common way to handle situations like this is to check if the standard input stream is connected to a terminal or not, using [isatty](http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html) or similar functions depending on your OS. If it is, you take parameters from the command line, if not (it's been redirected), you read standard input.
3,672,849
Got a weird problem here. I have created a template for a ListBox based on the standard template (i.e. I have not changed anything other than what I indicate below). I am trying to add a couple of buttons to the side of the template so that I can scroll the ScrollViewer (which is part of the standard ListBox template) left and right. **The problem is that it only recognises the ScrollBar.PageLeftCommand OR the ScrollBar.PageRightCommand ... I cannot get it to response to both.** In other words if I click the right button it will page right, but if I click the left button it doesn't do anything. Depending on the ordering of the Button in the XAML that will dictate which command works and which doesn't (it appears the command works for the last button defined in the XAML). ``` <ControlTemplate TargetType="{x:Type s:SurfaceListBox}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.137*"/> <ColumnDefinition Width="0.726*"/> <ColumnDefinition Width="0.137*"/> </Grid.ColumnDefinitions> <Border x:Name="Border" Grid.ColumnSpan="1" Grid.Column="1"> <s:SurfaceScrollViewer x:Name="scrollViewer" > <ItemsPresenter /> </s:SurfaceScrollViewer> </Border> <s:SurfaceButton x:Name="rightScroll" Content="&gt;" Command="ScrollBar.PageRightCommand" CommandTarget="{Binding ElementName=scrollViewer}" Grid.Column="2" /> <s:SurfaceButton x:Name="leftScroll" Content="&lt;" Command="ScrollBar.PageLeftCommand" CommandTarget="{Binding ElementName=scrollViewer}"/> </Grid> </ControlTemplate> ``` (Yes this is using the Surface classes but I have tried it with normal ones and I get the same behaviour..) I have had a look at it running with Snoop but it tells me nothing useful about the commands - according to Snoop both the commands are handled successfully!
2010/09/09
[ "https://Stackoverflow.com/questions/3672849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61714/" ]
The standard WPF controls do not support all of the events with the SurfaceScrollViewer, however, there are other controls packaged with the SurfaceScrollViewer that support some events, like Click. The problem is that the SurfaceScrollViewer not only accepts touch input on the scrollbar, but also on the content itself.
22,804
En lisant [cet article](http://fr.aleteia.org/2016/11/01/les-6-phrases-a-eviter-pour-ne-pas-se-decredibiliser-au-premier-contact/?utm_campaign=NL_fr&utm_source=daily_newsletter&utm_medium=mail&utm_content=NL_fr), au quatrième point de discussion, l'auteur a écrit «elle veut vos contacts et elle ne passe pas par 4 chemins.» Quel est le sens de cette expression?
2016/11/06
[ "https://french.stackexchange.com/questions/22804", "https://french.stackexchange.com", "https://french.stackexchange.com/users/5316/" ]
Comme écrit au début du paragraphe : > > La discussion ne fait que commencer et la personne entre dans le vif du sujet directement > > > Cette expression signifie aller directement au but, sans prendre de chemins détournés.
4,723
How can I import contacts in CiviCRM using the command line (CLI) rather than using the CiviCRM user interface and its importing wizard?
2015/08/14
[ "https://civicrm.stackexchange.com/questions/4723", "https://civicrm.stackexchange.com", "https://civicrm.stackexchange.com/users/711/" ]
When you are importing a large number of contacts, you could face timeout issues when using the user interface. Importing through CLI is an alternative. There is a file called import.php in /civicrm/civicrm/bin/csv/import.php. We will call this file from the command line. After you have exported your CSV file, here are the steps for the import: 1. Put the CSV file on your CiviCRM server, outside the webroot somewhere. (Do not place this file within the website root, or you risk exposing your contacts' data to the internet.) 2. In the command prompt (shell), type `php path/to/import.php -e Contact --file path/to/file.csv` (check this [forum post](https://forum.civicrm.org/index.php?topic=34033.0) for some more detail). Provide an absolute path to the CSV file. 3. At this point, depending on the contents of your CSV file, you will likely get an error such as `ERROR line 2: Mandatory key(s) missing from params array: contact_type`. It expects you to pass a contact\_type parameter **inside the CSV file**. If you don't have one in your exported CSV file, you can very easily add a contact\_type column in it using a Notepad++ macro (note: turn off autocompletion for words and quotes in Notepadd++ as it may screw up the macro). Just add the new column at the end. Here is an example of a CSV file: "email","contact\_type" "[email protected]","Individual" "[email protected]","Individual" 4. Now run the command again and you should see a success message for each imported contact. The message looks like this: `line 2: created Contact id: 114` The down side is that you cannot (yet) assign a group or a tag to the imported contacts. I looked into the [API](http://wiki.civicrm.org/confluence/display/CRMDOC/Using+the+API) but could not see an ability to add contacts to groups or tags. Troubleshooting: 1. If you get an error such as "cli.php can only be run from command line.", and you wonder about it because you ARE running from the command line, then likely you are using php as cgi/fcgi. To overcome this there is a little hack (which I am not too happy with, but we actually are using the code as intended here). In /bin/cli.class.php, on line 85 the function \_accessing\_from\_cli() checks whether the program is run from CLI. It does this by checking the contents of PHP\_SAPI. But according to the first comment [here](http://php.net/manual/en/function.php-sapi-name.php), that variable is not reliable in some cases. So we can modify the function like this: `public function _accessing_from_cli() { if (PHP_SAPI === 'cli') { return TRUE; } else { /* Temporary hack since the PHP_SAPI check does not work correctly for cgi/fcgi. See first comment here: http://php.net/manual/en/function.php-sapi-name.php */ return TRUE; //trigger_error("cli.php can only be run from command line.", E_USER_ERROR); } }` After you import your contacts, do not forget to return the file back to its original version. 2. I really suggest you either configure php to show up errors or make sure you have access to the php error log. This way, if the import suddenly stops after some time, you'll be able to see the reason and take appropriate measures (increase memory\_limit, max\_execution\_time, etc.).
8,805,274
I'm working on a site with a client they've just realised that they've given me all of their prices inclusive of sales tax (20%) - is there a way for me to iterate through the price fields and update the value to remove 20% from every entry? In a sql query?
2012/01/10
[ "https://Stackoverflow.com/questions/8805274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503524/" ]
Ultimately you need the new features that have been added to mod\_wsgi 4.0. These will allow for daemon mode better control over automatic restarts when requests block. When restarting upon blocked condition mod\_wsgi will attempt to dump out Python stack traces for what each of the Python request threads was doing at the time so you can see why they are blocked. Suggest you take up the issue on the mod\_wsgi mailing list and can explain the new features in more detail if need be. Have posted before about it at: <http://groups.google.com/group/modwsgi/msg/2a968d820e18e97d> The mod\_wsgi 4.0 code is only available from source code repository at this time. Current trunk head believed to be stable.
27,678,340
I'm trying to direct to a JS function using `onClick` but nothing seems to be working, I have tried: HTML: ``` <button type="button" id="deleteBtn" onClick="toDelete();">Delete Event</button> ``` JS: ``` document.getElementById("deleteBtn").onclick = function() {toDelete()} ``` JS: ``` document.getElementById("deleteBtn").addEventListener("click", toDelete); ``` This is my function: ``` function toDelete() { var answer = confirm("Are you sure you want to delete this event?\nPress OK to confirm deletion or CANCEL otherwise"); if (answer) { alert("The event has been deleted!"); <?php echo "<form id='deleteForm' name='deleteForm' method='post' action='redirected/deleteRecord.php'>"; echo "<input name='EVENT_ID' type='hidden' value='{$EVENT_ID}'>"; echo "<input name='eventName' type='hidden' value='{$eventName}'>"; echo "<input name='addressLine_1' type='hidden' value='{$addressLine_1}'>"; echo "<input name='addressLine_2' type='hidden' value='{$addressLine_2}'>"; echo "<input name='townCity' type='hidden' value='{$townCity}'>"; echo "<input name='postcode' type='hidden' value='{$postcode}'>"; echo "<input name='description' type='hidden' value='{$description}'>"; echo "<input name='cost' type='hidden' value='{$cost}'>"; echo "<input name='eventDate' type='hidden' value={$eventDate}'>"; echo "</form>"; ?> document.getElementById('deleteForm').submit(); } else location.replace("events.php"); } ```
2014/12/28
[ "https://Stackoverflow.com/questions/27678340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4400016/" ]
***getSupportFragmentManager()*** is method of ***FragmentActivity***. Your Parent activity should have extends FragmentActivity Check this <http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html>
14,532,415
I've been researching and having a hard time trying to figure out how to work my solution out. Basically my end goal is to be able to log into Google Calendar and grab a dates events and work with the information. If possible, be able to use multiple accounts. I've done some research and have come across Google's own API but I just don't know where to start.
2013/01/26
[ "https://Stackoverflow.com/questions/14532415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710489/" ]
This is the API documentation (with python code examples): <https://developers.google.com/google-apps/calendar/v2/developers_guide_protocol> you will need this library: <http://code.google.com/p/gdata-python-client/> more concrete you need to use this class: <http://code.google.com/p/gdata-python-client/source/browse/src/gdata/calendar/client.py> in order to get the data from a users, you will need to have the auth\_token for each of them. I'm not sure if this API allows you to use direct login instead of auth\_token. UPDATE: current API version is 3: <https://developers.google.com/google-apps/calendar/>
67,776,239
I have deployed a java package to Github packages successfully, I tried to consume it **successfully** as a dependency: ``` <dependency> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency> ``` but I can't resolve(fetch) it as a maven plugin like this: ``` <build> <plugins> <plugin> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>1.0.0-SNAPSHOT</version> </plugin> ... ``` I am getting this error: ``` Plugin com.example:demo:1.0.0-SNAPSHOT or one of its dependencies could not be resolved: Could not find artifact com.example:demo:1.0.0-SNAPSHOT -> [Help 1] ``` also the `.m2/settings.xlm` is ready and works fine as I tested it by fetching the package as a dependency not plugin, and it contains: ``` <server> <id>github</id> <username>USER</username> <password>PERSONAL_TOKEN_SCOPE_REPO_W_R_PACKAGES</password> </server> <profile> <id>github</id> <repositories> <repository> <id>github</id> <name>GitHub OWNER Apache Maven Packages</name> <url>https://maven.pkg.github.com/OWNER/REPO-NAME</url> <releases> <enabled>true</enabled> </releases> <snapshots> <updatePolicy>always</updatePolicy> <enabled>true</enabled> </snapshots> </repository> </repositories> </profile> <activeProfiles> <activeProfile>github</activeProfile> </activeProfiles> ``` Any Idea? Thanks in advance
2021/05/31
[ "https://Stackoverflow.com/questions/67776239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7378293/" ]
instead of `print(outputs)` use ``` for output in outputs: print(output) ``` and exclude the appending of "\n". so finally your code must look like: ``` output = net_connect.send_command(request.POST.get("cmds"), use_textfsm=True) outputs.append(request.POST.get("cmds")) for output in outputs: print(output) ```
18,342,477
I have a PHP file to store an array: ``` <?php $arr = array ( "A" => "one", "B" => "two", "C" => "three" ); ?> ``` I am using `require` to open the file, and each entry loads into a form. (`foreach` loop) I would like to save the `$_POST` variables back (overwriting) to the original file **in the same format**. I have no trouble making the form and sending back the variables. I just need a way to print the array back into the original file. Example result: ``` <?php $arr = array ( "A" => "new value", "B" => "other new value", "C" => "third new value" ); ?> ``` I have been unable to use `print_r`, as the format returned is incorrect. How can I do this successfully? Thank you.
2013/08/20
[ "https://Stackoverflow.com/questions/18342477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1234256/" ]
The function you're looking for is [`var_export`](http://php.net/manual/en/function.var-export.php) You would use it like this ``` file_put_contents($filename, '<?php $arr = ' . var_export($arr, true) . ';'); ``` [DEMO](http://ideone.com/jS1xBd) --------------------------------
48,632,585
I am trying to generate a json file from a .xlsx file. so far I was able to get data from the file but I am not sure how to put them on json using jinja2. There is a problem in template structure. How can I solve this? Output should be like this ``` "Matches": { "1": { "time": "19:00", "teams": "Team 1 - Team 2" }, "2": { "time": "21:00", "teams": "Team 3 - Team 4" }, ... ... ... } ``` My code is something like this. Obviously template section is wrong. ``` from openpyxl import load_workbook from jinja2 import Template start_coloumn_of_matches = 3 end_coloumn_of_matches = 20 wb = load_workbook(filename = 'myfile.xlsx') sheet_ranges = wb['Sheet1'] keys = [] teams = [] times = [] for x in range(start_coloumn_of_matches, end_coloumn_of_matches + 1): team_column = 'A' + str(x) time_column = 'D' + str(x) teams.append(sheet_ranges[team_column].value) times.append(sheet_ranges[time_column].value) keys.append(x) template = Template(''' "Matches": { {% for key in keys %} "{{key}}": {% endfor %} { {% for team in teams %} "teams": "{{team}}", {% endfor %} {% for time in times %} "time": "{{time}}" {% endfor %} } }, ''' ) print(template.render(teams = teams, times = times, keys = keys)) ```
2018/02/05
[ "https://Stackoverflow.com/questions/48632585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122577/" ]
Manually constructing json runs the risk of accidentally producing an invalid json string. It's safer to use a tool to do this, and it keeps your templates less cluttered. If you are using Jinja 2.9 or later, you can use the built-in [tojson](https://jinja.palletsprojects.com/en/2.11.x/templates/#tojson) filter to convert Python objects\* to json automatically. ```py >>> import pprint >>> # Construct some test data >>> matches = ['1', '2', '3'] >>> times = ['19:00', '21:00', '23:00'] >>> teams = ['Team 1 - Team 2', 'Team 3 - Team 4', 'Team 5 - Team 6'] >>> # Combine the data structures to match the required output >>> match_data = [dict(zip(['time', 'team'], pair)) for pair in zip(times, teams)] >>> combined = {x: y for x, y in zip(matches, match_data)} >>> pprint.pprint(combined) {'1': {'team': 'Team 1 - Team 2', 'time': '19:00'}, '2': {'team': 'Team 3 - Team 4', 'time': '21:00'}, '3': {'team': 'Team 5 - Team 6', 'time': '23:00'}} >>> template = jinja2.Template("""{{ matches | tojson(indent=2) }}""") >>> print(template.render(matches=combined)) { "1": { "team": "Team 1 - Team 2", "time": "19:00" }, "2": { "team": "Team 3 - Team 4", "time": "21:00" }, "3": { "team": "Team 5 - Team 6", "time": "23:00" } } ``` For earlier Jinja releases, construct the json using the [json](https://docs.python.org/3.9/library/json.html) package in Python's standard library, and then render the json in your template. ```py >>> import json >>> # Serialise our object as json; setting the indent argument gives >>> # the pretty printed format that we want. >>> jdata = json.dumps(combined, indent=2) >>> print(jdata) { "1": { "time": "19:00", "team": "Team 1 - Team 2" }, "2": { "time": "21:00", "team": "Team 3 - Team 4" }, "3": { "time": "23:00", "team": "Team 5 - Team 6" } } >>> # Pass the json to the template for rendering. >>> template = jinja2.Template("""{{ matches }}""") >>> print(template.render(matches=jdata)) { "1": { "time": "19:00", "team": "Team 1 - Team 2" }, "2": { "time": "21:00", "team": "Team 3 - Team 4" }, "3": { "time": "23:00", "team": "Team 5 - Team 6" } } ``` --- \* The filter only handles primitives AFAICT; if your data includes datetimes for example you will need to stringify them first.
46,217
The Shulchan Aruch in siman 657 says that a child which knows how to shake the lulav properly, his father is obligated to buy a lulav for him (because of chinuch). The Beur Halacha d"h *keday lechancho bemitzvos* states that it's obvious that arba minim you buy for your child must be kosher, just like they are for a gadol. My question is: If my child did not yet reach the stage of chinuch for this mitzvah, may I buy pasul arba minim? What about non-arba minim, like buying a lemon for the esrog?
2014/10/08
[ "https://judaism.stackexchange.com/questions/46217", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/1769/" ]
The Ritva in Sukka 2b basing himself on the story regarding Helene Hamalkah that when children reach the age of Chinuch, the parents are obligated to provide real kosher mitzvos ie. Lulav and esrog. The Gemara in Sukka: > > אמר רבי יהודה מעשה בהילני המלכה בלוד שהיתה סוכתה גבוהה מעשרים אמה והיו > זקנים נכנסין ויוצאין לשם ולא אמרו לה דבר אמרו לו משם ראייה אשה היתה > ופטורה מן הסוכה אמר להן והלא שבעה בנים הוו לה ועוד כל מעשיה לא עשתה > אלא על פי חכמים למה לי למיתני ועוד כל מעשיה לא עשתה אלא על פי חכמים > הכי קאמר להו כי תאמרו בנים קטנים היו וקטנים פטורין מן הסוכה כיון דשבעה > הוו אי אפשר דלא הוי בהו חד שאינו צריך לאמו וכי תימרו קטן שאינו צריך > לאמו מדרבנן הוא דמיחייב ואיהי בדרבנן לא משגחה ת''ש ועוד כל מעשיה לא > עשתה אלא ע''פ חכמים > > > The Ritva points out that by the fact that the Gemara tried to prove from the young children of Helene Hamalkah whom have reached the age of Chinuch that her Sukka was kosher implies that Helena Hamalkah and parents in general are obligated to provide their children with fully kosher mitzvos. The obvious implication is that if her children were below that age than one could not assume that her Sukka was kosher. Thus we see that below the age of Chinuch a parent is not obligated to acquire kosher mitzvos for their children. Rav Ovadia Yosef quotes this lehalacha: ואף שהריטב''א בריש סוכה כתב, דקטן שמחנכים אותו למצות צריך לעשות לו המצוה בהכשר גמור כמו הגדול, ובעי' סוכה מעלייתא. י''ל שהחפצא של המצוה צריך שתהיה בהכשר גמור, אך א''צ לדקדק בפרטי המצוה במצות חינוך לקטן. וכמ''ש בביאה''ל (ס''ס תרנז). וראה בחזון עובדיה סוכות עמוד תג].
27,862,712
Is there a way to count the elements in selenium webdriver. I.e. I have : ``` <div id="test"> <div class="Computer"></div> <div class="Computer"></div> <div class="Computer"></div> </div> ``` I need to get an amount of the `div.Computer`. I've tried to use : ``` List<WebElement> v_ct = Login.driver.findElements(By.cssSelector(".Computer")); System.out.println("The amount s "+v_ct.size()); ``` But amount is 0 instead 3.
2015/01/09
[ "https://Stackoverflow.com/questions/27862712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4377656/" ]
It may be easy to just include the css file and the fonts in your code. But with the package * Its a one-liner to install `meteor add fontawesome:fontawesome` * Its easy to include in other packages as a dependency * Its kept up to date * Its memorable: you can add bootstrap or something off head. * You could tell someone else how to do it very easily * Packages allow customisation for Meteor specifics, such as `select2` and diacritics with the spiderable package so others don't have to go through the pain. With font awesome its the path to the font (usually its `../fonts` but it needs to be `/fonts`) to work with nested routes. * Its very easy to remove if you don't want it. * The installation is local, so you don't need to be online, as with the method with including the remote css file. (and hence also a lower chance of xsrf) * Your projects' codebase is a bit smaller. * Other packages can be added at the same time when you add font awesome e.g `meteor add mizzao:boostrap-3 natestrauser:select2 fontawesome:fontawesome` which can save a chunk of time too. * Older versions/locking versions are a synch too i.e `meteor add fontawesome:[email protected]` * Very often you get a meteor specific readme on atmospherejs.com which can be helpful sometimes.. * Packages are precompiled, so each time you change your Meteor app, it can be a bit faster than having the source files since you have to wait for them to be compiled. * If another package uses `fontawesome:fontawesome`, then you can be sure you won't have two copies of it in your bundled code. * The css is included in your single minified css file, so instead of the browser requesting two files (in the case of adding it to `<head></head>`, you request one css file for your entire Meteor app, meaning your app is a bit faster to load. In addition, in general regarding packages * Packages allow customisation with file loading order * Packages allow you to add bundled testing/and or restrictions on which platform the package can be used such as Cordova * Packages can have npm modules embedded that can contain binaries built for a specific architecture (e.g windows, \*nix, 32bit or 64 bit all in a single bundle). * Packages can be attached to Meteor's tool-chain so you can use them during the build process only, or in debug mode only or production mode only. **Edit: This is about font awesome but I realise there is also a generic, why add a package when I can add it myself that can be applied to any package so I've added a few more reasons that may not specifically apply to font-awesome only.**
144,470
Do RGB cubic-coordinate and HSL cylindrical-coordinate systems both support the same colors? Does one system support more or fewer colors than the other, or does one system support a color that cannot be achieved with the other system?
2021/01/23
[ "https://graphicdesign.stackexchange.com/questions/144470", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/160102/" ]
Both can present the same colors if you have no limitation in your number system. If it happens that the numeric resolution is limited, for ex. to integers only, both systems present a little different set of points in RGB color space. It can also happen that your computer system can produce different color just for each possible RGB combination and it's controlled by sending RGB combinations. If you have only integer values 0...255 for R,G and B but you can input HSL numbers with steps say 0,1 degrees for Hue and say 0...100% with 0,1% steps for S and L then some HSL combinations maybe cannot be shown in your system. HSL has more possible color combinations as numbers, but not all of them can be shown as different colors. Many HSL combinations are rounded to the same RGB combination. Find conversion formulas and calculate with math or test with a color system conversion calculator how much say RGB numbers must change to get the minimum possible change in HSL system. An example: [![enter image description here](https://i.stack.imgur.com/9xEss.jpg)](https://i.stack.imgur.com/9xEss.jpg) That's pure max bright green RGB(0,255,0) You must insert 3 units blue i.e. to RGB(0,255,3) before the hue grows one degree - from 120 dgrees to 121 degrees. If you can use only integers as your hue angle you cannot input RGB(0,255,1) nor RGB(0,255,2) as HSL numbers. [![enter image description here](https://i.stack.imgur.com/NCvNm.png)](https://i.stack.imgur.com/NCvNm.png) The used calculator was <https://www.rapidtables.com/convert/color/rgb-to-hsl.html> It has also conversion formulas.
2,213,675
I tried `find('meta[http-equiv="Content-type"]')` but it failed to retrieve that information.
2010/02/06
[ "https://Stackoverflow.com/questions/2213675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198729/" ]
SimpleHTMLDom doesn't use quoted string literals in the selector. It's just `elem[attr=value]`. And the comparison of *value* seems to be case-sensitive (there may be a way to make it case-insensitive, but that I don't know)\* E.g. ``` require 'simple_html_dom.php'; $html = file_get_html('http://www.google.com/'); // most likely one one element but foreach doesn't hurt foreach( $html->find('meta[http-equiv=content-type]') as $ct ) { echo $ct->content, "\n"; } ``` prints `text/html; charset=ISO-8859-1`. \*edit: yes, there is a way to perform a case-insensitive match, use `*=` instead of `=` ``` find('meta[http-equiv*=content-type]') ``` edit2: btw that `http-equiv*=content-type` thingy would also match `<meta http-equiv="haha-no-content-types"...` (it only tests if the string is somewhere in the attribute's value). But it's the only case-insensitive function/operator I could find. I guess you can live with it in this case ;-) edit 3: It uses preg\_match('.../i') and the pattern/selector is directly passed to that function. Therefore you *could* do something like `http-equiv*=^content-type$` to match `http-equiv="Content-type"` but not `http-equiv="xyzContent-typeabc"`. But I don't know if this is a warranted feature.
2,338,110
First of all, I know that there are many posts on this topic, but my question, as you will see, has important differences. I am in the **last year of my undergraduate** studies, and I **have been** **taught introductory courses of Group Theory and Ring Theory**. Now, I want to attend Galois Theory, but I see that I have **no good knowledge of Linear Algebra**. So, I thought that this is a good chance to **refresh and complete my knowledge**. And I look for a good book with many **exercises** to solve. In other words, I'm looking for a good Linear Algebra book, which will have all the necessary chapters with exercises and will be useful for Galois Theory, Algebraic Geometry, Representation Theory, Coding Theory and other more advanced algebra courses. **What are your recommendations?** *PS: I didn't like Gilbert Strang's book "Linear Algebra and Its Applications".* *PPS: What's your opinion for the books: 1) Linear Algebra, Serge Lang, 2) Introduction to Linear Algebra, Serge Lang and more generally your opinion about Lang's books, 3) Linear Algebra: Step by Step, Kuldeep Singh?* *PPS: I apologize for my English!* Thank you in advance!
2017/06/27
[ "https://math.stackexchange.com/questions/2338110", "https://math.stackexchange.com", "https://math.stackexchange.com/users/326865/" ]
I think the best book for you will be Linear Algebra done Right by Sheldon Axler. The reasons being 1.) It takes an abstract but intuitive approach, is heavy on proofs. 2.) Exercises are not too numerous, about 20-25 in each chapter and are not unreasonably hard; and cover most of the techniques used in the chapter. 3.) Since you will be doing a course on galois theory, you will find the discussions in the later chapter on minimal polynomial etc illuminating. 4.) Finally, I was in a similar state 6 months back and had to pick up linear algebra properly before course on galois theory. It took me about 10 days to finish it. It is not dense but is still quit thin. And the writing is superlative when compared to other books on the same topic. Rest other books that you have mentioned have one or two of the flaws that I mentioned that Axler doesn't have. GO for it.
37,318,171
So I am doing a background fetch, and after I want to update the UI. The background fetching itself (database) works, but when I want to update the UI, I get a crash `unexpectedly found nil while unwrapping an Optional value` According to my xCode `self.newestPublicationsCollectionView.reloadData()` is where the crash occurs in the updateCollections() function. ``` func updateCollections() { // get latest data from Database latestPublications = getNewestPublications() self.newestPublicationsCollectionView.reloadData() self.newestPublicationsCollectionView.layoutIfNeeded() // fix wrong content height self.newestPublicationsCollectionViewHeight.constant = self.newestPublicationsCollectionView.collectionViewLayout.collectionViewContentSize().height } ``` Other code in the AppDelegate: ``` func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { let fetchViewController = PublicationOverviewController() fetchViewController.fetch { dispatch_async(dispatch_get_main_queue()) { fetchViewController.updateCollections() } completionHandler(.NewData) } } ``` The .fetch in my PublicationOverviewController ``` func fetch(completion: () -> Void) { PublicationFetcher.shared.fetchAllPublications() completion() } ``` I thought the crash was because I needed the UI on the main thread, but that didn't help. Any input would be nice. **DETAILS:** In my PublicationFetcher.shared.fetchAllPublications() I do the following: * get data from backend * `dispatch_async(dispatch_get_main_queue()) { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("RELOAD_NOTIFICATION", object: nil) }` and under that Reload Notification I do a `updateCollections()` **Swift 3**: ------------ ``` DispatchQueue.global(attributes: .qosBackground).async { print("This is run on the background queue") DispatchQueue.main.async { print("This is run on the main queue, after the previous code in outer block") } } ```
2016/05/19
[ "https://Stackoverflow.com/questions/37318171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372793/" ]
> > **EDIT 1:** > > > **Use `<br/>` instead of `\n`:** ``` text += "<a href='https://www.rkz.nl/eerste_polikliniekbezoek'> Wat neem ik mee naar een eerste afspraak?</a><br/><br/>"; // I have added \u2022 here for second Bullet. text += " \u2022 <a href='https://www.rkz.nl/wachttijden'> Wat zijn de wachttijden?</a>"; ``` Modify your string like this : ``` <string name="title_activity_afspraak"><b>Afspraak</b>&lt;br /&gt;&lt;br /&gt;<b>Maken en wijzigen</b>&lt;br /&gt;&lt;br /&gt;Zelf uw afspraak maken of wijzigen? Dat kan, mits us al als patiënt geregistreerd staat bij het RKZ. Is dit nog niet het geval? Dan wordt de afspraak telefonish gepland. Meer info&lt;br /&gt;&lt;br /&gt;<b>Bekijk ook</b>&lt;br /&gt;&lt;br /&gt;\u2022 </string> // At last there is a \u2022 for First Bullet ``` Because there is no meaning of adding `<a>` in string.xml. Hope this helps..!!
8,542,335
Preferably with just javascript. But if that's too hard, jquery will be ok (I don't want to load jquery because the page has to load really fast).
2011/12/17
[ "https://Stackoverflow.com/questions/8542335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/649482/" ]
This question is pretty ambiguous, and I get the impression that you might be a little confused in your wording. This handler will disable the horizontal scrollbar if the body width exceeds 1000px, and the vertical scrollbar if the body height exceeds 600px. If this is really the functionality you're looking for, you should be aware that it's likely to frustrate users who are used to having full control over the scroll position of the page. Anyway, here's what (I think) you asked for: ``` function scrollStuff() { if (document.body.offsetHeight > 600) { document.body.style.overflowY = 'hidden'; } else { document.body.style.overflowY = 'auto'; } if (document.body.offsetWidth > 1000) { document.body.style.overflowX = 'hidden'; } else { document.body.style.overflowX = 'auto'; } } window.onload = scrollStuff; ```
162,507
The Enlightenment brought both technological and scientific advancement (starting a period of discovery and achievement that hasn't yet ended) and social/political advancement. We generally think of the revolutionizing of science (towards more fact-oriented, provable science instead of sentimental, unprovable theories) as being linked to the revolutionizing of politics (moving from monarchies and tight connections between the church and state to democracies and republics founded on human rights and freedom), because they happened so close together. But could a society be as technologically and scientifically developed as our society (or maybe slightly more advanced) exist as a monarchy, or a country using the feudal system? Or is there something in scientific discoveries and research that would lead to a political/social revolution and eventually the replacement of the feudal system and monarchies with a democracy? Essentially, could a society exist with the technological advancement we have today, but not the social or political advancement?
2019/12/02
[ "https://worldbuilding.stackexchange.com/questions/162507", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/70516/" ]
The main feature of a feudal monarchy is the "vassalic contract". It means that one vassal serves it's liege while the liege provide protection. It can be on a small scale : organizing a local police force to protect from day to day violence, or it can be on a huge scale... organizing intergalactic diplomacy to prevent war between the carebear monarchy and the villain republic of evil. In this system you can have free men, you can have serfs, slaves and any kind of social class (or even caste) that you want, as long as you have a top down authority with (somewhat) personal link between each strata of your population. As long as everyone keep to their roles, the structure can keep on working, it can even work along with a capitalistic economy. The higher ups have to keep to their oaths and contracts, still ensuring the working of society. A good example in literature would be Barrayar from Lois McMaster Bujold. You get an intergalactic feudal empire that works quite well in... a composition of everything you might envision. So, if - the lords, through time, kept on their appointed roles (protection of the vassals and self-checking). - Most traditional limitation on trade and industry for nobles should be lifted. - Joe Average could get more power with sufficient works without needing a revolution (classical example includes rewards and mariage). - You can even add vassality transference where someone either go up in the hierarchy or goes to a new liege, ensuring mobility. - The king/emperor were, globally, capable enough to deal with the most aggressive competition. At least capable at the right time. (meaning no heavy loss of authority) You can have enough social stability for your feudal intergalactic empire to work, with any kind of economy and in addition to some other ideology to mix up with the basis.
57,691,713
I started studying Java. One part I got stuck is about how to create and use object which is originated from other class. Directory structure: ``` /temp_dir/Java_code Main.java /java_db_code/ User_Table.java ``` Source codes are like these. ``` // File: /temp_dir/Java_code/Main.java package temp_dir.java_code; // Package configuration of this java file import temp_dir.java_code.java_db_code.User_Table; // import other class public class Main { public static void main(String[] args) { int temp=5; // Create obj_user_table object from User_Table class located in package of temp_dir.java_code.java_db_code.User_Table, through its int parameterized constructor User_Table obj_user_table=new User_Table(temp); System.out.println(obj_user_table); // Expected: obj_user_table object System.out.println(obj_user_table.user_a); // Expected: 5 } } ``` ``` // File: /temp_dir/Java_code/java_db_code/User_Table.java package temp_dir.java_code.java_db_code; public class User_Table { public User_table(int a) { this.user_a=a; } } ``` Run ``` cd /temp_dir/Java_code javac -d . Main.java ./java_db_code/User_Table.java ``` Error ``` ./java_db_code/User_Table.java:22: error: invalid method declaration; return type required public User_table(int a) ^ 1 error ``` I wrote `public User_table(int a)` in `User_Table.java` as the constructor But I don't know why error says that `invalid method declaration; return type required`
2019/08/28
[ "https://Stackoverflow.com/questions/57691713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8979023/" ]
Method names are case sensitive: `User_table` is not the same as `User_Table` (notice the capital T). The constructor must have the same exact name as the class, so use `User_Table`. Still, the compiler will complain about one other thing once you fix that: in the constructor you do ```java this.user_a=a; ``` But `user_a` is not declared in your class, which will make the compiler throw an error. To fix that, you just have to declare it in the class; since you want to access the field outside the class (for example, in `Main.main()`) make it `public`: ```java public class User_Table { public int user_a; public User_table(int a) { this.user_a=a; } } ``` As a recommendation, you should really consider following the Java naming and style conventions: - You should use more whitespaces: `this.user_a = a`, `int temp = 5`, `obj_user_table = new` - Class names use the `UpperCamelCase`, with no underscores: `UserTable` - Method and variable names use the `lowerCamelCase`, with no underscores: `userA` This won't change the functionality of the code, but it will make it more readable and standard for other Java users.
3,279,152
How do I convincingly differentiate $\sin 3x$ or any trig function that comes in the form $\tan nx$, $\sin nx$, $\cos nx$ from the first principle? I have tried expanding some forms using some trig identities but the $n$ coefficient isn't just showing up
2019/06/30
[ "https://math.stackexchange.com/questions/3279152", "https://math.stackexchange.com", "https://math.stackexchange.com/users/455866/" ]
You do it the usual way. You use trigonometric identities. For example: $$ \frac{d}{dx}\left[\sin{(nx)}\right]= \lim\_{\Delta x\to0}\frac{\sin{[n(x+\Delta x)]}-\sin{(nx)}}{\Delta x}=\\ \lim\_{\Delta x\to0}\frac{2\sin{\left(n\frac{x+\Delta x-x}{2}\right)}\cos{\left(n\frac{x+\Delta x+x}{2}\right)}}{\Delta x}=\\ n\lim\_{\Delta x\to0}\frac{\sin{\left(n\frac{\Delta x}{2}\right)}}{n\frac{\Delta x}{2}}\cdot\lim\_{\Delta x\to0}\left[\cos{\left(nx+n\frac{\Delta x}{2}\right)}\right]. $$ Let $t=n\frac{\Delta x}{2}$, then $\Delta x\to0\implies t\to0$. $$ n\lim\_{t\to0}\frac{\sin{t}}{t}\cdot\lim\_{t\to0}\left[\cos{\left(nx+t\right)}\right]= n\cdot1\cdot\cos{(nx+0)}=\\ =n\cos{(nx)}. $$ And you do a similar thing for the cosine function. When you're going to do the tangent and cotangent functions, don't forget that they are defined in terms of the cosine and sine functions.
72,140,688
Net core application. I have below query in my application ``` var result = sourceProposal.Quotes .Where(x=>x.QuotationId == sourceQuoteId) .FirstOrDefault() .QuoteLines.Select(x=>(x.Quantity,x.WtgType)).ToArray(); ``` This yields in two array elements such as ``` 0 element 1, "string1" 1 element 2, "string2" ``` What I am expecting is ``` (int[] sourceQuantity, string[] destinationTurbineType) = sourceProposal.Quotes .Where(x=>x.QuotationId == sourceQuoteId) .FirstOrDefault() .QuoteLines.Select(x=>(x.Quantity,x.WtgType)).ToArray(); ``` I want to copy to tuple which has `int[] sourceQuantity`, `string[] destinationTurbineType` this piece of code is not working and throwing error does not contain definition for destructor and no accessible extension method Descontruct accepting first argument of type `int(sourceQuantity, string destinationTurbineType)[]`. Can someone help me to copy values to `sourceQuantity` and `destinationTurbineType`. Any help would be appreciated. Thanks
2022/05/06
[ "https://Stackoverflow.com/questions/72140688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14033262/" ]
[`Select<TSource,TResult>`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=net-6.0#system-linq-enumerable-select-2(system-collections-generic-ienumerable((-0))-system-func((-0-1)))) returns enumerable/queryable of the type returned by selector (`IEnumerabe<TResult>`/`IQueryable <TResult>`). If you want to achieve this with LINQ you can use `Aggregate`: ```cs // note that sourceQuantity and destinationTurbineType would be lists, not arrays var (sourceQuantity, destinationTurbineType) = sourceProposal.Quotes .Where(x=>x.QuotationId == sourceQuoteId) .FirstOrDefault() .QuoteLines .Aggregate((ints: new List<int>(), strs: new List<string>()), (aggr, curr) => { aggr.ints.Add(curr.Quantity); aggr.strs.Add(curr.WtgType); return aggr; }); ``` Or just use simple `for` loop and copy data to destination arrays (possibly move to some extension method). Something along this lines: ```cs var quoteLines = sourceProposal.Quotes .Where(x=>x.QuotationId == sourceQuoteId) .FirstOrDefault() .QuoteLines; // assuming it is materialized collection with indexer like an array or list int[] sourceQuantity = new int[quoteLines.Length]; // or Count string[] destinationTurbineType = new string[quoteLines.Count()]; for(int i = 0; i < quoteLines.Length; i++) { var curr = quoteLines[i]; sourceQuantity[i] = curr.Quantity; destinationTurbineType[i] = curr.WtgType; } ```
3,236,008
It seems the header value is always encoded as "ISO8859-1".
2010/07/13
[ "https://Stackoverflow.com/questions/3236008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291096/" ]
Query the AD like this: ``` $dn = "DC=mydomain,DC=local"; $group_DN = "CN=Intra,OU=Common Security Groups,DC=mydomain,DC=local"; $filter = "(&(objectCategory=user)(memberOf=$group_DN))"; // ... $sr = ldap_search($ad, $dn, $filter); ``` Have a look at the [MSDN article about the LDAP search filter syntax](http://msdn.microsoft.com/en-us/library/aa746475(VS.85).aspx) for info on more complex filters. Be sure to pay attention to the **Special Characters** section down on that page. A correct solution must pass `$group_DN` through an escaping mechanism before using it in the filter string! Always try build filters as specific as possible. It is more efficient to let the LDAP server sort out records you don't want, instead of having more records transferred over the wire than you need and throw away half of them on the client.
4,941,602
I have a product that consists of multiple features that can be installed to different locations e.g. Feature 1 is an executable installed in Program Files and Feature 2 is a website installed in wwwroot. However both Feature 1 and Feature 2 rely on many of the same dll's and hence require the components containing those dll's to be installed in 2 different locations depending on which Features are installed. Is there a way to achieve this without defining every component twice? To provide a further complete example of what I am trying to achieve, the following complete wxs file can be compiled using: *> candle.exe Foobar.wxs* *> light.exe -ext WixUIExtension Foobar.wixobj* *> msiexec /i Foobar.msi* ``` <?xml version='1.0' encoding='windows-1252'?> <Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'> <Product Name='Foobar 1.0' Id='E578DF12-DDE7-4BC2-82CD-FF11862862D5' UpgradeCode='90F09DD5-E01B-4652-8971-515997730195' Language='1033' Codepage='1252' Version='1.0.0' Manufacturer='Acme Ltd.'> <Package Id='*' Keywords='Installer' Description="Acme 1.0 Installer" InstallerVersion='100' Languages='1033' Compressed='yes' SummaryCodepage='1252' /> <Media Id='1' Cabinet='Sample.cab' EmbedCab='yes' DiskPrompt="CD-ROM #1" /> <Property Id='DiskPrompt' Value="Acme 1.0 Installation" /> <Directory Id='TARGETDIR' Name='SourceDir'> <!-- Directory 1 (Program Files) --> <Directory Id="ProgramFilesFolder" Name="PFiles"> <Directory Id="PROGRAM_INSTALLDIR" Name="Acme" /> </Directory> <!-- Directory 2 (wwwroot) --> <Directory Id="Inetpub" Name="Inetpub"> <Directory Id="wwwroot" Name="wwwroot"> <Directory Id="WEBSITE_INSTALLDIR" Name="AcmeWebSite" /> </Directory> </Directory> </Directory> <DirectoryRef Id='PROGRAM_INSTALLDIR'> <Component Id="Component1" Guid="79EC9E0B-8325-427B-A865-E1105CB16B62"> <File Id="File1" Name="File1.txt" Source="File1.txt" /> </Component> </DirectoryRef> <DirectoryRef Id='WEBSITE_INSTALLDIR'> <Component Id="Component2" Guid="702E6573-8FBC-4269-A58D-FD1157111F0F"> <File Id="File2" Name="File2.txt" Source="File2.txt" /> </Component> </DirectoryRef> <Feature Id="Feature.Program" Title="My Program" TypicalDefault="install" Level="1" ConfigurableDirectory="PROGRAM_INSTALLDIR" > <ComponentRef Id="Component1"/> <ComponentRef Id="Component2"/> </Feature> <Feature Id="Feature.Website" Title="My Website" TypicalDefault="install" Level="1" ConfigurableDirectory="WEBSITE_INSTALLDIR" > <ComponentRef Id="Component1"/> <ComponentRef Id="Component2"/> </Feature> <UIRef Id="WixUI_Mondo" /> <UIRef Id="WixUI_ErrorProgressText" /> </Product> </Wix> ``` This will however result in ONLY File1.txt being installed in *C:\Program Files (x86)\Acme* and ONLY File2.txt being installed in \_C:\Inetpub\wwwroot\AcmeWebsite\_ One solution is to define the components twice such as: ``` <DirectoryRef Id='PROGRAM_INSTALLDIR'> <Component Id="Component1" Guid="79EC9E0B-8325-427B-A865-E1105CB16B62"> <File Id="File1" Name="File1.txt" Source="File1.txt" /> </Component> <Component Id="Component2" Guid="702E6573-8FBC-4269-A58D-FD1157111F0F"> <File Id="File2" Name="File2.txt" Source="File2.txt" /> </Component> </DirectoryRef> <DirectoryRef Id='WEBSITE_INSTALLDIR'> <Component Id="Component1.Web" Guid="397E93AA-32FB-425A-A783-386E0CCA2357"> <File Id="File1.Web" Name="File1.txt" Source="File1.txt" /> </Component> <Component Id="Component2.Web" Guid="5C3AFF06-3623-4524-A90B-72B46DE5572A"> <File Id="File2.Web" Name="File2.txt" Source="File2.txt" /> </Component> </DirectoryRef> <Feature Id="Feature.Program" Title="My Program" TypicalDefault="install" Level="1" ConfigurableDirectory="PROGRAM_INSTALLDIR" > <ComponentRef Id="Component1"/> <ComponentRef Id="Component2"/> </Feature> <Feature Id="Feature.Website" Title="My Website" TypicalDefault="install" Level="1" ConfigurableDirectory="WEBSITE_INSTALLDIR" > <ComponentRef Id="Component1.Web"/> <ComponentRef Id="Component2.Web"/> </Feature> ``` But then what happens if we add a third feature that is to be installed in another location? Do we then have to redefine every component again? With over 100 components, managing duplicate components will become a big job. Any suggestions?
2011/02/09
[ "https://Stackoverflow.com/questions/4941602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90852/" ]
You are seeing a limitation in the Windows Installer. A Component can only be installed once via an MSI. Each Component can only be installed to a single Directory. To have the contents of a Component installed to two different locations, you either have to create another Component with the same content or try to use the CopyFile element to duplicate the content. Probably not what you wanted to hear but that is the way the Windows Installer works. Fortunately, if you chose to go with option 1, then WiX toolset will only compress the duplicated content across the Components once. [Smart cabbing rocks!](http://robmensching.com/blog/posts/2007/6/1/quotSmart-cabbingquot-added-to-WiX-toolset)
287,519
I'm trying to write a generic function summ in rust - but to no avail. Could someone please elucidate the problem? ``` fn summ<T:Add>(a:T,b:T)->T { a+b } ```
2015/06/22
[ "https://softwareengineering.stackexchange.com/questions/287519", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/184420/" ]
[`Add`'s `add` method](https://doc.rust-lang.org/std/ops/trait.Add.html) does not return `Self` - it returns `Self::Output`. This allows the addition to return a different type than the addends. The return type of `summ` should reflect that: ``` fn summ<T: Add>(a: T, b: T) -> T::Output { a + b } ```
26,943,093
I am new to angularjs. I want to get angularjs variable to other js file. My angular js file code is... ``` angular.module('myApp.menu', ['myApp.cloverApi', 'myApp.preOperation']) .controller('popMenuCtrl', ['$scope', '$http', '$routeParams', 'category', 'order', 'init', 'mInfoService', 'preop', 'mobileDetector', function($scope, $http, $routeParams, category, order, init, mInfoService, preop, mobileDetector) { mInfoService.init($scope.errorCallback) .success(function (data) { $scope.merchant.shopName = $scope.capitalizing(data.name); ``` I want to get merchant.shopName to other js file so how can i get this variable value. and my html file code. ``` <span ng-show="!isMerchant">{{merchant.shopName}}</span> ``` I want to catch this variable in script file as below ``` <script> addToHomescreen({ message: 'Add {{merchant.shopName}} to Your Phone, tap %icon, then <strong>Add to Home Screen </strog>', displayPace: 0 }); </script> ``` but is not working
2014/11/15
[ "https://Stackoverflow.com/questions/26943093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4031007/" ]
This a good use-case for an angular service. In another file, you create a service like this: ``` angular.module('app').factory('factoryName', function(){ // create factory object var data = {}; data.someProperty = 'Some Property'; data.someMethod = function(){ console.log('Service Method'); } // return the factory object return data; }) ``` Now that you have created your 'factoryName' service, inject it into a controller and scope it for your view. ``` angular.module('app').controller('YourCtrl', function($scope, factoryName){ $scope.fromService = factoryName; }); ``` You're just about done. You'll of course need to reference the .js file in your index.html and finally use it in your html template, for example: ``` <div ng-controller="YourCtrl"> <input ng-model="fromService.someProperty"/> <button ng-click="fromService.someMethod()">Console Log</button> </div> ``` Please let me know if you'd like a Plnkr example.
34,949,786
How could I identify all the Pandas DataFrames created in my current notebook session? Something like in SAS seeing all the members in the Work library would be ideal. Thanks.
2016/01/22
[ "https://Stackoverflow.com/questions/34949786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5401419/" ]
Solution ======== ``` %who DataFrame ``` Explanation =========== All objects ----------- > > ... seeing all the members in the Work library would be ideal. > > > ``` In [1]: a = 10 b = 'abs' c = [1, 2, 3] ``` `%who` shows all used names: ``` In [2]: %who a b c ``` Conveniently as a list: ``` In [3]: %who_ls Out[3]: ['a', 'b', 'c'] ``` Or as table with data types: ``` In [4]: %whos Variable Type Data/Info ---------------------------- a int 10 b str abs c list n=3 ``` Filter for DataFrames ===================== ``` In [5]: import pandas as pd df1 = pd.DataFrame({'a': [100, 200, 300]}) df2 = pd.DataFrame({'b': [100, 200, 300]}) In [6]: %whos DataFrame Variable Type Data/Info --------------------------------- df1 DataFrame a\n0 100\n1 200\n2 300 df2 DataFrame b\n0 100\n1 200\n2 300 In [7]: %who DataFrame df1 df2 In [8]: %who_ls DataFrame Out[8]: ['df1', 'df2'] ```
58,784,800
I was reading about CAP Theorem and got confused. For CA I took Oracle as an example. Consistency: Oracle is consistent since we don't have multiple nodes and agreed. Availability: How come it is highly available because it has only one node and what if it gets crashed?
2019/11/10
[ "https://Stackoverflow.com/questions/58784800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8072124/" ]
Oracle has Real Application Cluster (RAC) technology that helps keep it highly available on multiple nodes (servers). I am not sure of the limit of servers in RAC cluster, but you can many (2, 3, 5, 8, etc). If the DBA designs things correctly, they can assign more than one node for an application service (either active-active or active-passive). If a node becomes un-available, planned or unplanned, the service will either fail over (active passive) or continue to operate (active-active) on other nodes. Oracle also has very sophisticated technology to continue read activity and even write activity if a node becomes unavailable. If designed correctly, the user wouldn't even know the node was unavailable in some cases. The "sticking-point" of RAC is the storage. Oracle RAC uses shared storage. If the storage has an issue, then all nodes in the RAC cluster are affected. It is not distributed like Cassandra. Hardware has many features to protect against storage issues (e.g. RAID). However, the bottom line is if, for whatever reason, the storage is affected, RAC can also be affected with it. Oracle does offer sharding, which is their answer to distributed systems, but it isn't quite as elegant. Without that, you don't have the distributed portion (partitioning) that other distributed systems have. All that being said, hopefully that answers your question about about Oracle's high availability. -Jim