qid
int64
1
74.7M
question
stringlengths
16
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
117k
response_k
stringlengths
3
61.5k
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
You can call `make` with the right arguments: ``` make -C .. -k ``` where `..` is the path to your `Makefile`
i use a script like this which allows me to run make from any sub-directory (assuming you are in a posix-like environment). just put this script in your PATH as something like "sub\_make.sh" and invoke it the same way you would invoke make: ``` #!/bin/bash # search for project base INIT_DIR=`pwd` while [ "$PWD" != "/" ] ; do if [ -e "makefile" ] ; then break fi cd .. done if [ ! -e "makefile" ] ; then echo "Couldn't find 'makefile'!" exit 1 fi # indicate where we are now echo "cd "`pwd` echo make "$@" # now run make for real exec make "$@" ```
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
Matthias Puech has a [solution](https://syntaxexclamation.wordpress.com/2011/08/11/set-the-root-directory-of-a-project-in-emacs-with-dir-locals-el/) involving a `.dir-local` file in the project root directory: ``` ((nil . ((eval . (setq default-directory (locate-dominating-file buffer-file-name ".dir-locals.el") ))))) ``` It is presumably also possible to use something like: `(shell-command-to-string "git rev-parse --show-toplevel")` as that innermost bit.
Not a completely general solution w.r.t makefile location, but adding this here for posterity because it solved my particular use-case. If you use `projectile` and your makefile is always in the root of your project directory, then you can use `projectile-compile-project`. (In my case, I wanted to lint my project, so calling `(compile "flake8")` would only flake from the current buffer's directory downwards, whereas what I really wanted was linting of the entire project. `projectile-compile-project` achieves this.)
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
You can call `make` with the right arguments: ``` make -C .. -k ``` where `..` is the path to your `Makefile`
That's what I have in some of my configs :) ``` (defun* get-closest-pathname (&optional (max-level 3) (file "Makefile")) (let* ((root (expand-file-name "/")) (level 0) (dir (loop for d = default-directory then (expand-file-name ".." d) do (setq level (+ level 1)) if (file-exists-p (expand-file-name file d)) return d if (> level max-level) return nil if (equal d root) return nil))) (if dir (expand-file-name file dir) nil))) (add-hook 'c-mode-hook (lambda () (unless (file-exists-p "Makefile") (set (make-local-variable 'compile-command) (let ((file (file-name-nondirectory buffer-file-name)) (mkfile (get-closest-pathname))) (if mkfile (progn (format "cd %s; make -f %s" (file-name-directory mkfile) mkfile)) (format "%s -c -o %s.o %s %s %s" (or (getenv "CC") "gcc") (file-name-sans-extension file) (or (getenv "CPPFLAGS") "-DDEBUG=9") (or (getenv "CFLAGS") "-ansi -pedantic -Wall -g") file))))))) ```
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
i use a script like this which allows me to run make from any sub-directory (assuming you are in a posix-like environment). just put this script in your PATH as something like "sub\_make.sh" and invoke it the same way you would invoke make: ``` #!/bin/bash # search for project base INIT_DIR=`pwd` while [ "$PWD" != "/" ] ; do if [ -e "makefile" ] ; then break fi cd .. done if [ ! -e "makefile" ] ; then echo "Couldn't find 'makefile'!" exit 1 fi # indicate where we are now echo "cd "`pwd` echo make "$@" # now run make for real exec make "$@" ```
Not a completely general solution w.r.t makefile location, but adding this here for posterity because it solved my particular use-case. If you use `projectile` and your makefile is always in the root of your project directory, then you can use `projectile-compile-project`. (In my case, I wanted to lint my project, so calling `(compile "flake8")` would only flake from the current buffer's directory downwards, whereas what I really wanted was linting of the entire project. `projectile-compile-project` achieves this.)
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
You can call `make` with the right arguments: ``` make -C .. -k ``` where `..` is the path to your `Makefile`
Matthias Puech has a [solution](https://syntaxexclamation.wordpress.com/2011/08/11/set-the-root-directory-of-a-project-in-emacs-with-dir-locals-el/) involving a `.dir-local` file in the project root directory: ``` ((nil . ((eval . (setq default-directory (locate-dominating-file buffer-file-name ".dir-locals.el") ))))) ``` It is presumably also possible to use something like: `(shell-command-to-string "git rev-parse --show-toplevel")` as that innermost bit.
9,037,842
I'm trying to get a list of 'contacts' for a specified user id. Let says my user id is 1, i need to get the list of ids of my my contacts from *chat-contactlist* then get all the infos for each id. **All users' id, name and contact information** Table usr: uid, rname, phonenumber **Online status and other stuff** Table chat-usr: uid, nickname, online\_status **Containing user id and the user id of each contact this user have :** Table chat-contactlist: uid, cid (cid = The id of the person who's int he "uid" user list So I need the name, the nickname, the online\_status for all the 'cid' for a specified 'uid'... Dont know i read a tutorial about left join but it seams complex to merge multiple tables, anyone wanna try? Any recommendation? Thank you **EDIT** Changing name by rname because name is a reserved word for SQL.
2012/01/27
[ "https://Stackoverflow.com/questions/9037842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473908/" ]
You can control this from within emacs by writing a function that (temporarily) sets `default-directory` and calls `compile`. ``` (defun compile-in-parent-directory () (interactive) (let ((default-directory (if (string= (file-name-extension buffer-file-name) "ml") (concat default-directory "..") default-directory)))) (call-interactively #'compile)) ``` When using `compile-in-parent-directory` all `ml` files will be compiled in the parent directory of where they are. Of course if they are nested deeper you can change the logic to reflect that. In fact there is a [version on the EmacsWiki](http://www.emacswiki.org/emacs/UsingMakefileFromParentDirectory) which searches parent directories until it finds a makefile. I found this after I wrote this answer, otherwise I would have just pointed you there. *sigh*. The good thing about my method is that it's not specific to `make` so that you can use the same "trick" for other commands. You can also change the call to compile to be non-interactive if you know exactly what you want the command to be. This would work particularly well if it's bound to a key in the appropriate mode hook.
Matthias Puech has a [solution](https://syntaxexclamation.wordpress.com/2011/08/11/set-the-root-directory-of-a-project-in-emacs-with-dir-locals-el/) involving a `.dir-local` file in the project root directory: ``` ((nil . ((eval . (setq default-directory (locate-dominating-file buffer-file-name ".dir-locals.el") ))))) ``` It is presumably also possible to use something like: `(shell-command-to-string "git rev-parse --show-toplevel")` as that innermost bit.
12,038,562
What operator can I pass to one of the fold variants that will allow me to sum tuple item 2 grouped by tuple item 1, in a list of tuples? So, let's say I have the list: ``` [ ('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1) ] ``` and I want to produce the list: ``` [ ('A', 4) , ('B', 4) , ('C', 11) ] ``` You can see it's a Haskell-ized table, and so the actual representation of the table here isn't important; it's the approach to taking the input data and producing the output I am interested in. I am a Haskell newcomer, and have a background in C/C++/C#. I've done enough tutorials to recognise the application of fold here, but can't figure out the sub-folding that appears to be required. EDIT: In case this helps anyone else, here is my solution using group, foldl1 and map, inspired by ingo's response: ``` import qualified Data.List as List mygroup :: [ (Char,Int) ] -> [ [(Char,Int)] ] mygroup = List.groupBy (\x y -> fst x == fst y) myfold :: [(Char,Int)] -> (Char,Int) myfold = foldl1 (\x y -> (fst x, snd x + snd y)) mysum :: [(Char,Int)] -> [(Char,Int)] mysum = map myfold . mygroup ``` When run: ``` *ListSum> mysum [ ('A',1) , ('A',2) , ('B',3) , ('C',4) , ('C',5) ] [('A',3),('B',3),('C',9)] ``` **mygroup** shows how to create groups, by providing an equivalence operator. It says that two members are in the same group if their first tuple items are the same. **myfold** shows how to sum two tuples. It uses the first tuple in the list as the initial state for the fold, and composes a result tuple from the the sum of each tuple's second items. **mysum** composes these two functions using map. I might spend a bit more time on this to see if I can break the dependence on the schema of the data, which is currently **[(Char,Int)]**. I think it means supplying the groupBy operator and the fold operator, and might just be an exercise in composing the groupBy, foldl1 and map. I'm new at this. Do I get any points for being point-free? :)
2012/08/20
[ "https://Stackoverflow.com/questions/12038562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781870/" ]
What you want is really about grouping items with a specific criteria and then folding over the groups. The simplest way to implement the example you gave is to use an associative map from `Data.Map` to group the items. ``` import qualified Data.Map as Map sumGroups :: [(Char, Int)] -> [(Char, Int)] sumGroups = Map.assocs . Map.fromListWith (+) ``` This uses the function [`fromListWith`](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map-Lazy.html#v%3afromListWith) to combine items which have the same key, and the resulting map is converted back into a list with [`assocs`](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map-Lazy.html#v%3aassocs). ``` *Main> sumGroups [ ('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1) ] [('A',4),('B',4),('C',11)] ```
You need two steps, conceptually: ``` transform [('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1)] to [('A', [1,3,4]), ('C', [10, 1])] and further to [('A', 8), ('C', 11)] ``` Functions that will help you: groupBy, using, fst, map, sum
12,038,562
What operator can I pass to one of the fold variants that will allow me to sum tuple item 2 grouped by tuple item 1, in a list of tuples? So, let's say I have the list: ``` [ ('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1) ] ``` and I want to produce the list: ``` [ ('A', 4) , ('B', 4) , ('C', 11) ] ``` You can see it's a Haskell-ized table, and so the actual representation of the table here isn't important; it's the approach to taking the input data and producing the output I am interested in. I am a Haskell newcomer, and have a background in C/C++/C#. I've done enough tutorials to recognise the application of fold here, but can't figure out the sub-folding that appears to be required. EDIT: In case this helps anyone else, here is my solution using group, foldl1 and map, inspired by ingo's response: ``` import qualified Data.List as List mygroup :: [ (Char,Int) ] -> [ [(Char,Int)] ] mygroup = List.groupBy (\x y -> fst x == fst y) myfold :: [(Char,Int)] -> (Char,Int) myfold = foldl1 (\x y -> (fst x, snd x + snd y)) mysum :: [(Char,Int)] -> [(Char,Int)] mysum = map myfold . mygroup ``` When run: ``` *ListSum> mysum [ ('A',1) , ('A',2) , ('B',3) , ('C',4) , ('C',5) ] [('A',3),('B',3),('C',9)] ``` **mygroup** shows how to create groups, by providing an equivalence operator. It says that two members are in the same group if their first tuple items are the same. **myfold** shows how to sum two tuples. It uses the first tuple in the list as the initial state for the fold, and composes a result tuple from the the sum of each tuple's second items. **mysum** composes these two functions using map. I might spend a bit more time on this to see if I can break the dependence on the schema of the data, which is currently **[(Char,Int)]**. I think it means supplying the groupBy operator and the fold operator, and might just be an exercise in composing the groupBy, foldl1 and map. I'm new at this. Do I get any points for being point-free? :)
2012/08/20
[ "https://Stackoverflow.com/questions/12038562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781870/" ]
What you want is really about grouping items with a specific criteria and then folding over the groups. The simplest way to implement the example you gave is to use an associative map from `Data.Map` to group the items. ``` import qualified Data.Map as Map sumGroups :: [(Char, Int)] -> [(Char, Int)] sumGroups = Map.assocs . Map.fromListWith (+) ``` This uses the function [`fromListWith`](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map-Lazy.html#v%3afromListWith) to combine items which have the same key, and the resulting map is converted back into a list with [`assocs`](http://hackage.haskell.org/packages/archive/containers/latest/doc/html/Data-Map-Lazy.html#v%3aassocs). ``` *Main> sumGroups [ ('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1) ] [('A',4),('B',4),('C',11)] ```
Pointless fun: ``` import Data.List import Data.Function import Control.Arrow sumGroups = map (fst . head &&& sum . map snd) . groupBy ((==) `on` fst) ```
9,320,619
I have a C binary that calls out to Java via JNI. I set CLASSPATH to somedir/\* to pick up all the jars in somedir. When I run the binary, a required class definition cannot be found. When I run ``` java that.class's.name ``` from the same command line, the class is successfully found. If I explicitly add all the jars in somedir/ to the classpath, everything works great, but that leads to a *very* long classpath which I'd like to avoid. Does a JVM executed via JNI honour wildcard expansion of the classpath? Can it be made to do so?
2012/02/16
[ "https://Stackoverflow.com/questions/9320619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2827/" ]
I figured out the answer by reading the hotspot source code. Only paths passed via either `CLASSPATH` or `-cp` / `-classpath` are subject to wildcard expansion. These are then passed as a system property to the running JVM via `-Djava.class.path`. You tell a JNI-invoked JVM about a classpath via a `JVMOptions` structure, which may include `-Djava.class.path` but `-classpath` will not *necessarily* be honoured (and in practice, isn't by the hotspot implementation). Since `java.class.path` is directly passed to the JVM as a system property, it doesn't get wildcard expanded and therefore wildcards won't work.
No. No, it cannot. Using JNI doesn't help. The way you would do this is by implementing your own class loader (in Java), but that class loader would have to be in the wildcard-free CLASSPATH. You could, of course, set the CLASSPATH to its expanded form *before* invoking the JVM. That would work and could be done via a shell script (no JNI needed).
24,454,907
I would like to restrict a user from entering values other than the given set of values into a jpa column. For example, if I have a table like this.. ``` sno sname college_name ---------------------- 101 smith Stanford 102 jack Harvard 103 tiger Stanford 104 scott Harvard ``` and the class.. ``` @Entity @Table(name="student") public class Student { @Id @GeneratedValue private Integer sno; @Column(name="SNAME", nullable=false) private String sname; @Column(name="COLLEGE_NAME", nullable=false) private String collegeName; // setters and getters omitted } ``` Is there a way, probably using annotations, to restrict the user to enter either **Stanford** or **Harvard** (case sensitive) into the college name. **Note:** Instead of writing a trigger on the database side, I would want to achieve this via the Java program to save a database call. The above entity is container managed and that `sno`,`sname`,`college_name` are persistence fields, not properties. Do I have to definitely perform a check before inserting? I am looking for another way? Thanks in advance. Hope you will reply as soon as possible.
2014/06/27
[ "https://Stackoverflow.com/questions/24454907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534090/" ]
Sanitizing text is never a task composed of just one line of text, I'm afraid. However, the procedures are somewhat common for simple cleansing. For example, `$output = preg_replace("/\s+/", " ", $input);` will get rid of excess whitespaces but I would worry a lot more about possible malicious code injections through that `<textarea>` element. Maybe you should give [HTMLPurifier](http://htmlpurifier.org/) a look, it's quite complete even if it's still not HTML5 compliant. It will sort out the majority of concerns about filtered content. Hope that helps :)
try giving `striptags("string");`
23,857,838
In C#: ``` 0x80000000==2147483648 //outputs True ``` In VB.NET: ``` &H80000000=2147483648 'outputs False ``` How is this possible?
2014/05/25
[ "https://Stackoverflow.com/questions/23857838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666697/" ]
The VB version should be: ``` &H80000000L=2147483648 ``` Without the 'long' specifier ('L'), VB will try to interpret &H8000000 as an integer. If you force it to consider this as a long type, then you'll get the same result. &H80000000UI will also work - actually this is the type (UInt32) that C# regards the literal as.
This happens because the type of the hexadecimal number is `UInt32` in C# and `Int32` in VB.NET. The binary representation of the hexadecimal number is: ``` 10000000000000000000000000000000 ``` Both `UInt32` and `Int32` take 32 bits, but because `Int32` is signed, the first bit is considered a sign to indicate whether the number is negative or not: `0` for positive, `1` for negative. To convert a negative binary number to decimal, do this: 1. Invert the bits. You get `01111111111111111111111111111111`. 2. Convert this to decimal. You get `2147483647`. 3. Add 1 to this number. You get `2147483648`. 4. Make this negative. You get `-2147483648`, which is equal to `&H80000000` in VB.NET.
23,857,838
In C#: ``` 0x80000000==2147483648 //outputs True ``` In VB.NET: ``` &H80000000=2147483648 'outputs False ``` How is this possible?
2014/05/25
[ "https://Stackoverflow.com/questions/23857838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666697/" ]
This is related to the history behind the languages. C# always supported unsigned integers. The value you use are too large for *int* so the compiler picks the next type that can correctly represent the value. Which is *uint* for both. VB.NET didn't acquire unsigned integer support until version 8 (.NET 2.0). So traditionally, the compiler was forced to pick Long as the type for the 2147483648 literal. The rule was however different for the hexadecimal literal, it traditionally supported specifying the bit pattern of a negative value (see section 2.4.2 in the language spec). So &H80000000 is a literal of type Integer with the value -2147483648 and 2147483648 is a Long. Thus the mismatch. If you think VB.NET is a quirky language then I'd invite you to [read this post](https://stackoverflow.com/a/16459680/17034) :)
The VB version should be: ``` &H80000000L=2147483648 ``` Without the 'long' specifier ('L'), VB will try to interpret &H8000000 as an integer. If you force it to consider this as a long type, then you'll get the same result. &H80000000UI will also work - actually this is the type (UInt32) that C# regards the literal as.
23,857,838
In C#: ``` 0x80000000==2147483648 //outputs True ``` In VB.NET: ``` &H80000000=2147483648 'outputs False ``` How is this possible?
2014/05/25
[ "https://Stackoverflow.com/questions/23857838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666697/" ]
This is related to the history behind the languages. C# always supported unsigned integers. The value you use are too large for *int* so the compiler picks the next type that can correctly represent the value. Which is *uint* for both. VB.NET didn't acquire unsigned integer support until version 8 (.NET 2.0). So traditionally, the compiler was forced to pick Long as the type for the 2147483648 literal. The rule was however different for the hexadecimal literal, it traditionally supported specifying the bit pattern of a negative value (see section 2.4.2 in the language spec). So &H80000000 is a literal of type Integer with the value -2147483648 and 2147483648 is a Long. Thus the mismatch. If you think VB.NET is a quirky language then I'd invite you to [read this post](https://stackoverflow.com/a/16459680/17034) :)
This happens because the type of the hexadecimal number is `UInt32` in C# and `Int32` in VB.NET. The binary representation of the hexadecimal number is: ``` 10000000000000000000000000000000 ``` Both `UInt32` and `Int32` take 32 bits, but because `Int32` is signed, the first bit is considered a sign to indicate whether the number is negative or not: `0` for positive, `1` for negative. To convert a negative binary number to decimal, do this: 1. Invert the bits. You get `01111111111111111111111111111111`. 2. Convert this to decimal. You get `2147483647`. 3. Add 1 to this number. You get `2147483648`. 4. Make this negative. You get `-2147483648`, which is equal to `&H80000000` in VB.NET.
18,073,778
I'v just learned a few languages (for 2 years now), and now I want to make programs with graphic interfaces. Thing is, I just don't know which languages to use. What languages/programs (and what methods of these programs) are used to make programs with graphic interface? (I know that C# and JAVA are graphic, but I don't know what methods...) What languages/programs (and what methods of these programs) are used to make applications to IPhone, Android ,and whatever ? languages/programs (and what methods of these programs) are used to make/edit videos? Thanks a lot!
2013/08/06
[ "https://Stackoverflow.com/questions/18073778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2650265/" ]
Almost all programming languages have libraries that help you create a GUI (Graphical User Interface). Most programming languages, including C++, C#, and Java are general-purpose programming languages - you can use them to program whatever you want. For Java for example, see this tutorial: [Creating a GUI With JFC/Swing](http://docs.oracle.com/javase/tutorial/uiswing/). If you want to write an [Android app](http://developer.android.com/index.html), you'll program in Java. For [iOS and Mac OS X](https://developer.apple.com/), you'll most likely write your app in Objective-C.
Pretty much all higher level languages use graphic interface. you just have to do your research to find out how to use GUI in each language. Applications used on the iPhone are written in Objective-C and Android uses java for their apps.
18,073,778
I'v just learned a few languages (for 2 years now), and now I want to make programs with graphic interfaces. Thing is, I just don't know which languages to use. What languages/programs (and what methods of these programs) are used to make programs with graphic interface? (I know that C# and JAVA are graphic, but I don't know what methods...) What languages/programs (and what methods of these programs) are used to make applications to IPhone, Android ,and whatever ? languages/programs (and what methods of these programs) are used to make/edit videos? Thanks a lot!
2013/08/06
[ "https://Stackoverflow.com/questions/18073778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2650265/" ]
Almost all programming languages have libraries that help you create a GUI (Graphical User Interface). Most programming languages, including C++, C#, and Java are general-purpose programming languages - you can use them to program whatever you want. For Java for example, see this tutorial: [Creating a GUI With JFC/Swing](http://docs.oracle.com/javase/tutorial/uiswing/). If you want to write an [Android app](http://developer.android.com/index.html), you'll program in Java. For [iOS and Mac OS X](https://developer.apple.com/), you'll most likely write your app in Objective-C.
Your question is quite vague. But I'll give you some advice. Before asking this kind of question on stackoverflow, you really should make a search on your own with google. About graphic interface using JAVA, you can use [swing](https://www.google.lu/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&sqi=2&ved=0CEsQFjAB&url=http://download.oracle.com/javase/tutorial/uiswing&ei=1qIAUrmUN4SMswbc3IGYDw&usg=AFQjCNEtbuJqikUwLj2JRyfcUkFgDrCI8wD) which is the most famous way to do it (especially if you're a beginner and want to familiarize with graphic interface development concepts). But there are a lot of other libraries to do GUI, for exemple if you want to do with 3D you have [openGL lib](http://opengl.j3d.org/) or [jMonkey](http://jmonkeyengine.org/) (uses openGl). About [Android](http://developer.android.com/guide/topics/ui/index.html), it has its own SDK in java. About iOS (iPhone), it is made with ObjectiveC. And about C#, I don't know a lot about it but if you do a quite search on google you can find things like [this](http://msdn.microsoft.com/en-us/library/ms173080%28v=vs.90%29.aspx).
17,373,254
I'm using a the text visualizer for multiple strings which contain SQL queries. It's frustrating when I mouse over a variable wait and then as I drag my mouse left towards the text visualizer icon (the magnification glass) it disappears. If someone knows a keyboard shortcut, or even how to set one please clue me in.
2013/06/28
[ "https://Stackoverflow.com/questions/17373254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1932579/" ]
**Alt + DownArrow** works on VS2017 :)
In my understanding, as of now visual studio not providing any shortcut for TextVisualizer Here is a useful VS2012 extension which you can clip inside a visual studio <http://visualstudiogallery.msdn.microsoft.com/f2964c90-68e2-4ddd-861a-bd66e5cd4434>
21,753,072
In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax. The problem I'm having is that the request always looks like this: ``` ?&query=%7B%22source%22:%22incident%22%7D ``` Where it should look something like this: ``` ?&query={'source': 'incident'} ``` This is how I am sending the GET request: ``` var query = {}; if ($scope.sourceFilter) { query.source = $scope.sourceFilter; } var query = JSON.stringify(query); $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { ....... ``` I am doing the same thing on other get requests and I don't get this issue. Am I doing something wrong here ? Is this to do with the way angular parses params ? Thanks
2014/02/13
[ "https://Stackoverflow.com/questions/21753072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088754/" ]
Like the `$http` [docs](http://docs.angularjs.org/api/ng.%24http) say > > **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. **If the value is not a string, it will be JSONified.** > > > Latter emphasis is added by me. So the `query` property of the object you pass to the `params` configuration option is an Object. This means is will be JSONified, which means the same as ``` JSON.stringify(query); ``` So this ``` {'source': 'incident'} ``` Turns to this: ``` '{"source": "incident"}' ``` As [RFC 1738](http://www.faqs.org/rfcs/rfc1738.html) states: > > ... only alphanumerics, the special characters "$-\_.+!\*'(),", and > reserved characters used for their reserved purposes may be used > unencoded within a URL. > > > As it happens `{`, `}` and `"` are not on that list and have to be url encoded to be used in a url. In your case `%7B` corresponds to `{`, `%7D` corresponds to `}` and `%22` corresponds to `"`. So what is happening is normal and most server software automatically decodes the url query parameters for you, so they will be presented normally. Most likely you'll need to parse it back to JSON somehow! Hope this helps!
When using RESTFul apis concider using [ngResource](http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-resource.js), [ngResource docs](http://docs.angularjs.org/api/ngResource) Include it in your module: ``` yourApp = angular.module('yourApp', ['ngResource']) ``` Add your service: ``` yourApp.factory('YourService', ['$resource', function($resource){ return $resource('link/to/your/object', {}); }]); ``` Add your controller ``` yourApp.controller('YourController', [$scope, 'YourService', function($scope, YourService) { $scope.yourData = YourService.get(); $scope.yourData = YourService.query(); //(When obtaining arrays from JSON.) ``` I've found this is the best way using a RESTFull api.
21,753,072
In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax. The problem I'm having is that the request always looks like this: ``` ?&query=%7B%22source%22:%22incident%22%7D ``` Where it should look something like this: ``` ?&query={'source': 'incident'} ``` This is how I am sending the GET request: ``` var query = {}; if ($scope.sourceFilter) { query.source = $scope.sourceFilter; } var query = JSON.stringify(query); $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { ....... ``` I am doing the same thing on other get requests and I don't get this issue. Am I doing something wrong here ? Is this to do with the way angular parses params ? Thanks
2014/02/13
[ "https://Stackoverflow.com/questions/21753072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088754/" ]
Like the `$http` [docs](http://docs.angularjs.org/api/ng.%24http) say > > **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. **If the value is not a string, it will be JSONified.** > > > Latter emphasis is added by me. So the `query` property of the object you pass to the `params` configuration option is an Object. This means is will be JSONified, which means the same as ``` JSON.stringify(query); ``` So this ``` {'source': 'incident'} ``` Turns to this: ``` '{"source": "incident"}' ``` As [RFC 1738](http://www.faqs.org/rfcs/rfc1738.html) states: > > ... only alphanumerics, the special characters "$-\_.+!\*'(),", and > reserved characters used for their reserved purposes may be used > unencoded within a URL. > > > As it happens `{`, `}` and `"` are not on that list and have to be url encoded to be used in a url. In your case `%7B` corresponds to `{`, `%7D` corresponds to `}` and `%22` corresponds to `"`. So what is happening is normal and most server software automatically decodes the url query parameters for you, so they will be presented normally. Most likely you'll need to parse it back to JSON somehow! Hope this helps!
After some digging I figured this one out. Looking at the request I was making: ``` $http.get('/api/feedbackEntries', ``` I saw that the url does not end with a trailing slash. This was the only difference I could see compared with other requests that were working fine. So I added the trailing slash and magically it works. I can't explain why, whether it's something within angular or elsewhere .. but this is how I fixed the problem. Hope this helps someone in the future.
21,753,072
In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax. The problem I'm having is that the request always looks like this: ``` ?&query=%7B%22source%22:%22incident%22%7D ``` Where it should look something like this: ``` ?&query={'source': 'incident'} ``` This is how I am sending the GET request: ``` var query = {}; if ($scope.sourceFilter) { query.source = $scope.sourceFilter; } var query = JSON.stringify(query); $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { ....... ``` I am doing the same thing on other get requests and I don't get this issue. Am I doing something wrong here ? Is this to do with the way angular parses params ? Thanks
2014/02/13
[ "https://Stackoverflow.com/questions/21753072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088754/" ]
Like the `$http` [docs](http://docs.angularjs.org/api/ng.%24http) say > > **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. **If the value is not a string, it will be JSONified.** > > > Latter emphasis is added by me. So the `query` property of the object you pass to the `params` configuration option is an Object. This means is will be JSONified, which means the same as ``` JSON.stringify(query); ``` So this ``` {'source': 'incident'} ``` Turns to this: ``` '{"source": "incident"}' ``` As [RFC 1738](http://www.faqs.org/rfcs/rfc1738.html) states: > > ... only alphanumerics, the special characters "$-\_.+!\*'(),", and > reserved characters used for their reserved purposes may be used > unencoded within a URL. > > > As it happens `{`, `}` and `"` are not on that list and have to be url encoded to be used in a url. In your case `%7B` corresponds to `{`, `%7D` corresponds to `}` and `%22` corresponds to `"`. So what is happening is normal and most server software automatically decodes the url query parameters for you, so they will be presented normally. Most likely you'll need to parse it back to JSON somehow! Hope this helps!
Below is the code I used to get search result from my server, it works for me sending POST request with JSON params without . ``` var service = { getResult: function ({"username": "roman", "gender": "male"}) { var promise = $http({ url: ServerManager.getServerUrl(), method: "POST", data: params, headers: { 'Content-Type': 'application/json' } }) .success(function (data, status, headers, config) { console.log('getResult success.'); return data; }).error(function (data, status) { console.log('getResult error.'); }); return promise; } } return service; ```
21,753,072
In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax. The problem I'm having is that the request always looks like this: ``` ?&query=%7B%22source%22:%22incident%22%7D ``` Where it should look something like this: ``` ?&query={'source': 'incident'} ``` This is how I am sending the GET request: ``` var query = {}; if ($scope.sourceFilter) { query.source = $scope.sourceFilter; } var query = JSON.stringify(query); $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { ....... ``` I am doing the same thing on other get requests and I don't get this issue. Am I doing something wrong here ? Is this to do with the way angular parses params ? Thanks
2014/02/13
[ "https://Stackoverflow.com/questions/21753072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088754/" ]
After some digging I figured this one out. Looking at the request I was making: ``` $http.get('/api/feedbackEntries', ``` I saw that the url does not end with a trailing slash. This was the only difference I could see compared with other requests that were working fine. So I added the trailing slash and magically it works. I can't explain why, whether it's something within angular or elsewhere .. but this is how I fixed the problem. Hope this helps someone in the future.
When using RESTFul apis concider using [ngResource](http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-resource.js), [ngResource docs](http://docs.angularjs.org/api/ngResource) Include it in your module: ``` yourApp = angular.module('yourApp', ['ngResource']) ``` Add your service: ``` yourApp.factory('YourService', ['$resource', function($resource){ return $resource('link/to/your/object', {}); }]); ``` Add your controller ``` yourApp.controller('YourController', [$scope, 'YourService', function($scope, YourService) { $scope.yourData = YourService.get(); $scope.yourData = YourService.query(); //(When obtaining arrays from JSON.) ``` I've found this is the best way using a RESTFull api.
21,753,072
In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax. The problem I'm having is that the request always looks like this: ``` ?&query=%7B%22source%22:%22incident%22%7D ``` Where it should look something like this: ``` ?&query={'source': 'incident'} ``` This is how I am sending the GET request: ``` var query = {}; if ($scope.sourceFilter) { query.source = $scope.sourceFilter; } var query = JSON.stringify(query); $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { ....... ``` I am doing the same thing on other get requests and I don't get this issue. Am I doing something wrong here ? Is this to do with the way angular parses params ? Thanks
2014/02/13
[ "https://Stackoverflow.com/questions/21753072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088754/" ]
After some digging I figured this one out. Looking at the request I was making: ``` $http.get('/api/feedbackEntries', ``` I saw that the url does not end with a trailing slash. This was the only difference I could see compared with other requests that were working fine. So I added the trailing slash and magically it works. I can't explain why, whether it's something within angular or elsewhere .. but this is how I fixed the problem. Hope this helps someone in the future.
Below is the code I used to get search result from my server, it works for me sending POST request with JSON params without . ``` var service = { getResult: function ({"username": "roman", "gender": "male"}) { var promise = $http({ url: ServerManager.getServerUrl(), method: "POST", data: params, headers: { 'Content-Type': 'application/json' } }) .success(function (data, status, headers, config) { console.log('getResult success.'); return data; }).error(function (data, status) { console.log('getResult error.'); }); return promise; } } return service; ```
12,474,614
I want to figure out a solution for automatic logical relationship check. For example, I have a function `IsGood()`, it will get the bool value from a, b, c .... In the main program, there is `if(a||b)` or `if(b&&c)` or `if(g&&!k&&l||!z)`, different relationship. I want to replace all of them with `IsGood()`, and I want to make this function more general, it can handle different logical relationship. So my idea is to put some ID, which will help this function to know which variables are required to handle now, for example, `IsGood()` got value k1,k2,k3, but the logical relationship `||`,`&&` between k1,k2,k3 are not known by `IsGood()`. So I want to know how to let `IsGood()` automatically get the relationship between values. Store them in database?? Like : `IsGood()` firstly check that it is in the place1, so it queries the database, the result is : (this why I don't take parameters in `IsGood()`, it will retrieve the variables it needs from database or configuration file, what it needs is only the placeID.) place 1 (the place number); k1,k2,k3 (variable name); true,true,false(value); &&, || (logical relationship). But I don't think it is good...So, could you give me some ideas? Thanks a lot! My work is based on C++. **I want to know some ideas about this :** a||b&&c, I can store the information, like 0,1, so 0 represents ||, 1 represents &&, so the structure like a&&b||c...is easy to control. But how to set (a||b)&&c? I also want to find a way to record this relationship. A smart method will be appreciated!! Thanks.
2012/09/18
[ "https://Stackoverflow.com/questions/12474614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277161/" ]
This is what I use to modify the buttons, it should give you a starting point, once you ID everthing, changing the CSS is easy.. ``` $(".gmnoprint").each(function(){ var newObj = $(this).find("[title='Draw a circle']"); newObj.parent().addClass("remove"); // ID the toolbar newObj.parent().parent().attr("id", "btnBar"); // Now remove the Circle button $(".remove").remove(); // ID the Hand button newObj = $(this).find("[title='Stop drawing']"); newObj.attr('id', 'btnStop'); // ID the Marker button newObj = $(this).find("[title='Add a marker']"); newObj.attr('id', 'btnMarker'); // ID the line button newObj = $(this).find("[title='Draw a line']"); newObj.attr('id', 'btnLine'); // ID the Rectangle Button newObj = $(this).find("[title='Draw a rectangle']"); newObj.attr('id', 'btnRectangle'); // ID the Polygon button newObj = $(this).find("[title='Draw a shape']"); newObj.attr('id', 'btnShape'); }); ``` To further modify it, I add my own buttons to the tool bar like this: ``` $("#btnBar").append('<div style="float: left; line-height: 0;"><div id="btnDelete" style="direction: ltr; overflow: hidden; text-align: left; position: relative; color: rgb(51, 51, 51); font-family: Arial,sans-serif; -moz-user-select: none; font-size: 13px; background: none repeat scroll 0% 0% rgb(255, 255, 255); padding: 4px; border-width: 1px 1px 1px 0px; border-style: solid solid solid none; border-color: rgb(113, 123, 135) rgb(113, 123, 135) rgb(113, 123, 135) -moz-use-text-color; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; border-image: none; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.4); font-weight: normal;" title="Delete Selected"><span style="display: inline-block;"><div style="width: 16px; height: 16px; overflow: hidden; position: relative;"><img style="position: absolute; left: 0px; top: -195px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px; width: 16px; height: 350px;" src="drawing.png" draggable="false"></div></span></div></div>'); ``` Then, to activate the new button and change the icons on the mouse click: ``` google.maps.event.addDomListener(document.getElementById('btnDelete'), 'click', deleteSelectedShape); google.maps.event.addDomListener(document.getElementById('btnDelete'), 'mousedown', function () { $("#btnDelete img").css("top", "-212px"); }); google.maps.event.addDomListener(document.getElementById('btnDelete'), 'mouseup', function () { $("#btnDelete img").css("top", "-195px"); }); ``` Hope this helps! :) Dennis
this is the CSS code I used to override the styles on the buttons. In my case the HTML for the icons looks like this ``` <div class="gmnoprint" style="margin: 5px; z-index: 10; position: absolute; top: 0px; left: 310px;"> <div style="float: left; line-height: 0;"> <div role="button" tabindex="0" title="Parar de desenhar" aria-label="Parar de desenhar" aria-pressed="true" draggable="false" style="direction: ltr; overflow: hidden; text-align: left; position: relative; color: rgb(0, 0, 0); font-family: Roboto, Arial, sans-serif; user-select: none; font-size: 11px; background-color: rgb(255, 255, 255); padding: 4px; border-bottom-left-radius: 2px; border-top-left-radius: 2px; background-clip: padding-box; box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px; font-weight: 500;"> <span style="display: inline-block;"> <div style="width: 16px; height: 16px; overflow: hidden; position: relative;"> <img alt="" src="https://maps.gstatic.com/mapfiles/drawing.png" draggable="false" style="position: absolute; left: 0px; top: -144px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; width: 16px; height: 192px;"> </div> </span> </div> </div> <div style="float: left; line-height: 0;"> <div role="button" tabindex="0" title="Desenhar uma forma" aria-label="Desenhar uma forma" aria-pressed="false" draggable="false" style="direction: ltr; overflow: hidden; text-align: left; position: relative; color: rgb(86, 86, 86); font-family: Roboto, Arial, sans-serif; user-select: none; font-size: 11px; background-color: rgb(255, 255, 255); padding: 4px; background-clip: padding-box; box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px; border-left: 0px;"> <span style="display: inline-block;"> <div style="width: 16px; height: 16px; overflow: hidden; position: relative;"> <img alt="" src="https://maps.gstatic.com/mapfiles/drawing.png" draggable="false" style="position: absolute; left: 0px; top: -64px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; width: 16px; height: 192px;"> </div> </span> </div> </div> <div style="float: left; line-height: 0;"> <div role="button" tabindex="0" title="Desenhar um cΓ­rculo" aria-label="Desenhar um cΓ­rculo" aria-pressed="false" draggable="false" style="direction: ltr; overflow: hidden; text-align: left; position: relative; color: rgb(86, 86, 86); font-family: Roboto, Arial, sans-serif; user-select: none; font-size: 11px; background-color: rgb(255, 255, 255); padding: 4px; background-clip: padding-box; box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px; border-left: 0px;"> <span style="display: inline-block;"> <div style="width: 16px; height: 16px; overflow: hidden; position: relative;"> <img alt="" src="https://maps.gstatic.com/mapfiles/drawing.png" draggable="false" style="position: absolute; left: 0px; top: -160px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; width: 16px; height: 192px;"> </div> </span> </div> </div> <div style="float: left; line-height: 0;"> <div role="button" tabindex="0" title="Desenhar um retΓ’ngulo" aria-label="Desenhar um retΓ’ngulo" aria-pressed="false" draggable="false" style="direction: ltr; overflow: hidden; text-align: left; position: relative; color: rgb(86, 86, 86); font-family: Roboto, Arial, sans-serif; user-select: none; font-size: 11px; background-color: rgb(255, 255, 255); padding: 4px; border-bottom-right-radius: 2px; border-top-right-radius: 2px; background-clip: padding-box; box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 4px -1px; border-left: 0px;"> <span style="display: inline-block;"> <div style="width: 16px; height: 16px; overflow: hidden; position: relative;"> <img alt="" src="https://maps.gstatic.com/mapfiles/drawing.png" draggable="false" style="position: absolute; left: 0px; top: -16px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; width: 16px; height: 192px;"> </div> </span> </div> </div> </div> ``` CSS styles applied ``` .gmnoprint > div > div[role=button] { width: 44px; height: 44px; vertical-align: middle; line-height: 40px; text-align: center; } .gmnoprint > div > div[role=button] > span > div > img { display: none; } .gmnoprint > div > div[role=button] > span > div:before { font: normal normal normal 14px/1 FontAwesome; content: "\f007"; font-size: 22px; } ```
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
Doesn't the *E* in EBS stand for *elastic* meaning something like resizing on the fly? Currently the MongoDB team is working on finishining sharding which will allow you horizontal scaling by partitioning data separately on different servers. Give it a month or two and it will work fine. The developers are quite good at keeping their promises. <http://api.mongodb.org/wiki/current/Sharding%20Introduction.html> <http://api.mongodb.org/wiki/current/Sharding%20Limits.html>
You could slave the bigger disk off the smaller until it's caught up *or* fsync+lock and take a file system snapshot and copy it onto the bigger disk.
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
If you're running out of disk, you obviously need to get a bigger disk. There are several ways to migrate your data, it really depends on the type of up-time you need. First steps of course involve bundling the machine and creating the new volume. These tips go from easiest to hardest. Can you take the database completely off-line for several minutes? ------------------------------------------------------------------ If so, do this (migration by copy): 1. Mount new EBS on the server. 2. Stop your app from connecting to Mongo. 3. Shut down mongod and wait for everything to write (check the logs) 4. Copy all of the data files (and probably the logs) to the new EBS volume. 5. While the copy is happening, update your mongod start script (or config file) to point to the new volume. 6. Start mongod and check connection 7. Restart your app. Can you take the database off-line for just a few minutes? ---------------------------------------------------------- If so, do this ([slaving](http://www.mongodb.org/display/DOCS/Master+Slave) and switch): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a --slave pointing at the current database. (you may need to re-start the current as --master) 3. The slave will do a fresh synchronization. Once the slave is up-to-date, you'll do a "switch" (next steps). 4. Turn off writes from the system. 5. Shut down the original mongod process. 6. Re-start the "new" mongod as a master instead of the slave. 7. Re-activate system writes pointing at the new master. Done correctly those last three steps can happen in minutes or even seconds. Can you not afford any down-time? --------------------------------- If so, do this ([master-master](http://www.mongodb.org/display/DOCS/Master+Master+Replication)): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a master and a slave against the current database. (may need to re-start current as master, minimal down-time?) 3. The new computer should do a fresh synchronization. 4. Once the new computer is up-to-date, switch the system to point at the new server. I know it seems like this last version is actually the best, but it can be a little dicey (as of this writing). The reason is simply that I've honestly had a lot of issues with "Master-Master" replication, especially if you don't start with both active. If you plan on using this method, I highly suggest a smaller practice run first. If something bombs here, Mongo might simply wipe all of your data files which will have the effect of taking more stuff down. If you get a good version of this please post the commands, I'd like to see it in action.
Doesn't the *E* in EBS stand for *elastic* meaning something like resizing on the fly? Currently the MongoDB team is working on finishining sharding which will allow you horizontal scaling by partitioning data separately on different servers. Give it a month or two and it will work fine. The developers are quite good at keeping their promises. <http://api.mongodb.org/wiki/current/Sharding%20Introduction.html> <http://api.mongodb.org/wiki/current/Sharding%20Limits.html>
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
Doesn't the *E* in EBS stand for *elastic* meaning something like resizing on the fly? Currently the MongoDB team is working on finishining sharding which will allow you horizontal scaling by partitioning data separately on different servers. Give it a month or two and it will work fine. The developers are quite good at keeping their promises. <http://api.mongodb.org/wiki/current/Sharding%20Introduction.html> <http://api.mongodb.org/wiki/current/Sharding%20Limits.html>
well, I am using Mongo DB now. I am pretty amazed the performance it generated, especially on some simple sorting. I believe it's a good tool for simple web application logic. The remaining concern for is how to scale and backup. I will continue to explore. The only disadvantage I have is that I didn't have any good tools to reveal the data stored inside. For example, I want to put my logging from MYSQL into Mongo as well. However, it's pretty difficult for me to view the log. Previously, i can use MYSQL query to fetch what I want easily. Anyway, it's a good tool and I will continue to use it.
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
If you're running out of disk, you obviously need to get a bigger disk. There are several ways to migrate your data, it really depends on the type of up-time you need. First steps of course involve bundling the machine and creating the new volume. These tips go from easiest to hardest. Can you take the database completely off-line for several minutes? ------------------------------------------------------------------ If so, do this (migration by copy): 1. Mount new EBS on the server. 2. Stop your app from connecting to Mongo. 3. Shut down mongod and wait for everything to write (check the logs) 4. Copy all of the data files (and probably the logs) to the new EBS volume. 5. While the copy is happening, update your mongod start script (or config file) to point to the new volume. 6. Start mongod and check connection 7. Restart your app. Can you take the database off-line for just a few minutes? ---------------------------------------------------------- If so, do this ([slaving](http://www.mongodb.org/display/DOCS/Master+Slave) and switch): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a --slave pointing at the current database. (you may need to re-start the current as --master) 3. The slave will do a fresh synchronization. Once the slave is up-to-date, you'll do a "switch" (next steps). 4. Turn off writes from the system. 5. Shut down the original mongod process. 6. Re-start the "new" mongod as a master instead of the slave. 7. Re-activate system writes pointing at the new master. Done correctly those last three steps can happen in minutes or even seconds. Can you not afford any down-time? --------------------------------- If so, do this ([master-master](http://www.mongodb.org/display/DOCS/Master+Master+Replication)): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a master and a slave against the current database. (may need to re-start current as master, minimal down-time?) 3. The new computer should do a fresh synchronization. 4. Once the new computer is up-to-date, switch the system to point at the new server. I know it seems like this last version is actually the best, but it can be a little dicey (as of this writing). The reason is simply that I've honestly had a lot of issues with "Master-Master" replication, especially if you don't start with both active. If you plan on using this method, I highly suggest a smaller practice run first. If something bombs here, Mongo might simply wipe all of your data files which will have the effect of taking more stuff down. If you get a good version of this please post the commands, I'd like to see it in action.
You could slave the bigger disk off the smaller until it's caught up *or* fsync+lock and take a file system snapshot and copy it onto the bigger disk.
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
You could slave the bigger disk off the smaller until it's caught up *or* fsync+lock and take a file system snapshot and copy it onto the bigger disk.
well, I am using Mongo DB now. I am pretty amazed the performance it generated, especially on some simple sorting. I believe it's a good tool for simple web application logic. The remaining concern for is how to scale and backup. I will continue to explore. The only disadvantage I have is that I didn't have any good tools to reveal the data stored inside. For example, I want to put my logging from MYSQL into Mongo as well. However, it's pretty difficult for me to view the log. Previously, i can use MYSQL query to fetch what I want easily. Anyway, it's a good tool and I will continue to use it.
2,802,313
I know that MongoDB can scale vertically. What about if I am running out of disk? I am currently using EC2 with EBS. As you know, I have to assign EBS for a fixed size. What if the MongoDB growth bigger than the EBS size? Do I have to create a larger EBS and Copy & Paste the files? Or shall we start more MongoDB instance and each connect to different EBS disk? In such case, I could connect to a different instance for different databases.
2010/05/10
[ "https://Stackoverflow.com/questions/2802313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331635/" ]
If you're running out of disk, you obviously need to get a bigger disk. There are several ways to migrate your data, it really depends on the type of up-time you need. First steps of course involve bundling the machine and creating the new volume. These tips go from easiest to hardest. Can you take the database completely off-line for several minutes? ------------------------------------------------------------------ If so, do this (migration by copy): 1. Mount new EBS on the server. 2. Stop your app from connecting to Mongo. 3. Shut down mongod and wait for everything to write (check the logs) 4. Copy all of the data files (and probably the logs) to the new EBS volume. 5. While the copy is happening, update your mongod start script (or config file) to point to the new volume. 6. Start mongod and check connection 7. Restart your app. Can you take the database off-line for just a few minutes? ---------------------------------------------------------- If so, do this ([slaving](http://www.mongodb.org/display/DOCS/Master+Slave) and switch): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a --slave pointing at the current database. (you may need to re-start the current as --master) 3. The slave will do a fresh synchronization. Once the slave is up-to-date, you'll do a "switch" (next steps). 4. Turn off writes from the system. 5. Shut down the original mongod process. 6. Re-start the "new" mongod as a master instead of the slave. 7. Re-activate system writes pointing at the new master. Done correctly those last three steps can happen in minutes or even seconds. Can you not afford any down-time? --------------------------------- If so, do this ([master-master](http://www.mongodb.org/display/DOCS/Master+Master+Replication)): 1. Start up a new instance and mount the new EBS on that server. 2. Install / start mongod as a master and a slave against the current database. (may need to re-start current as master, minimal down-time?) 3. The new computer should do a fresh synchronization. 4. Once the new computer is up-to-date, switch the system to point at the new server. I know it seems like this last version is actually the best, but it can be a little dicey (as of this writing). The reason is simply that I've honestly had a lot of issues with "Master-Master" replication, especially if you don't start with both active. If you plan on using this method, I highly suggest a smaller practice run first. If something bombs here, Mongo might simply wipe all of your data files which will have the effect of taking more stuff down. If you get a good version of this please post the commands, I'd like to see it in action.
well, I am using Mongo DB now. I am pretty amazed the performance it generated, especially on some simple sorting. I believe it's a good tool for simple web application logic. The remaining concern for is how to scale and backup. I will continue to explore. The only disadvantage I have is that I didn't have any good tools to reveal the data stored inside. For example, I want to put my logging from MYSQL into Mongo as well. However, it's pretty difficult for me to view the log. Previously, i can use MYSQL query to fetch what I want easily. Anyway, it's a good tool and I will continue to use it.
22,594,000
I have to tables: element and features. I would like to select the records with the nearest values to another record. I select 2 ids: mainimageid and elementid, and other 3 data fields: bp, ep, and symbolid. In the SELECT clause i put the alias `DIFF, DIFFbp and DIFFep` that are absolute values of the difference of these datas. in the `FROM clause` i put the 2 tables and in the `WHERE: symbolid = 8` last: i order the result by `DIFF, DIFFbp and DIFFep` This is my SQL query:- ``` SELECT mainimageid, elementid, symbolid, features.bp, features.ep, ABS (features.elongation - 2.63) AS DIFF, ABS (features.bp - 1) AS DIFFbp, ABS (features.ep - 4) AS DIFFepFROM iesp_schema.element, iesp_schema.features WHERE symbolid = 8 AND mainimageid <> 622 ORDER BY mainimageid, DIFF, DIFFbp, DIFFep ``` My result is a very long list of 6755 rows (i do not have all this record!) I posted below partial results of my query. I notice first that i have the data value fields different but with that same ids,that is not possible! Where am i wrong?
2014/03/23
[ "https://Stackoverflow.com/questions/22594000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223157/" ]
Access to the `request` global variable is lost as you have a local variable with the same name. Renaming either one of the variables will solve this issue: ``` var http = require("http"); var request = require("request"); http.createServer(function(req, response) { response.writeHead(200, {"Content-Type": "text/plain"}); request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Print the google web page. } }) response.end(); }).listen(8888); ```
You are no longer able to access the global variable 'request'. You need to rename your local variable 'request' with some other name and the problem will be resolved.
46,354,270
I'm using MySQL. [The documentation](https://laravel.com/docs/5.5/migrations) doesn't say anything on the matter. Let me know if there's anything else I can clarify. Thank you for your time.
2017/09/21
[ "https://Stackoverflow.com/questions/46354270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772385/" ]
Laravel does not control table locks during schema changes. This is controlled by the database itself. For MySQL < 5.6, a read lock will be held on the table for the duration of the schema change, and then a quick exclusive lock will be used to finalize the change. For MySQL >= 5.6, using InnoDB, most schema changes can be made with only the need for a quick exclusive lock at the beginning of the changes and a quick one at the end of the changes. You can read [this answer](https://stackoverflow.com/questions/35424543/alter-table-without-locking-the-entire-table) for a little more information, or you can check out the MySQL docs.
I can't affirm that migration will not lock the affected tables. But, reading the Illuminate\Database\Console\Migrations\MigrationCommand.php class code, I do not see anything that talks about lock tables when a migration command occour. I know that when you work with transactions (eg DB::beginTransactions(), DB::commit() and DB::rollback()) the lock/unlock occours.
3,607,432
I am using Apache Poi and Java for Excel manipulation. I have modified some of the cell in Excel file by programmatically using Java. After that, when I open that Excel file manually for seeing that update. After seeing, when I try to close the Excel file it again ask me like "do you want to save the changes you made to test.xls file. If I press yes button, then only I can able to read the formula cell values programmatically further. Otherwise, if I access the formula cell value it returns 0 value. How can I resolve this problem?
2010/08/31
[ "https://Stackoverflow.com/questions/3607432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452680/" ]
By default, POI reads the cached response to the formula when you read that cell. When you open the file with Excel, it will do the calculations. Then when you save the file the responses are saved along. Then when you read it with poi, you get the right answers. If you want the 'correct' answer you need to calculate the formula response. Last time I needed to do this I had to write my own parser, but now there's this : <http://poi.apache.org/spreadsheet/eval.html>. Or in short: ``` Workbook wb = new HSSFWorkbook(inputstream); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); ... snip ... CellValue value = evaluator.evaluate(cellWithFormula); ```
Can't yet post comments so i'll leave a new answer. Joeri answer is correct for just one Cell For multiple cell it is more efficient to use the folowing : ``` FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); fe.evaluateAll(); ``` Which will in fact update the cached formula value. Then to get them you'll do as you would for any other cell, for example : ``` cell.getCellStringValue(); ``` This method is worth using if you have to reevaluate an entire workbook. Take note that at the day i'm writing only the POI 3.10-beta1 version of POI can evaluate formulas using dates
20,641,487
I am trying to get a buyernumber from a SQL table. Doesn't seem to want to pull the information out of the table though. Here is what I have: I have a variable: newItemNum = 7962525; I have a table in my sql database that has 2 columns, itemnumber and buyernumber. Here is my SQL statement: ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE 'newItemNum%';" ``` The itemnumber in the table is: 7962525 Movie Set It's going into the table and not finding anything.
2013/12/17
[ "https://Stackoverflow.com/questions/20641487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785728/" ]
``` LIKE 'newItemNum%' ``` is a literal match. you have to parameterize newItemNum ``` LIKE @newItemNum + '%' ``` or if you don't wanna mess with params, do this: ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE '" + newItemNum + "%';" ``` EDIT: If you're dynamically acquiring table names use something like this: ``` var buyer="Costco"; var supplier="HomeDepot"; var newItemNum="123445656"; var strSQL = "select BuyerNumber from " +buyer+ "_" + supplier + "xref where Itemnumber LIKE '" + newItemNum + "%';" ```
Your SQL string needs to use a variable. Replace ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE 'newItemNum%';" ``` with ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE @newItemNum + '%';" ```
20,641,487
I am trying to get a buyernumber from a SQL table. Doesn't seem to want to pull the information out of the table though. Here is what I have: I have a variable: newItemNum = 7962525; I have a table in my sql database that has 2 columns, itemnumber and buyernumber. Here is my SQL statement: ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE 'newItemNum%';" ``` The itemnumber in the table is: 7962525 Movie Set It's going into the table and not finding anything.
2013/12/17
[ "https://Stackoverflow.com/questions/20641487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785728/" ]
Change this ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE 'newItemNum%';" ``` To ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE '"+newItemNum+"%';" ```
Your SQL string needs to use a variable. Replace ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE 'newItemNum%';" ``` with ``` strSQL = "select BuyerNumber from %buyer%_%supplier%xref where Itemnumber LIKE @newItemNum + '%';" ```
30,287,309
I have a `List<int[]>` as `index_position:int[] values` `input:` ``` index 0:{1,2} index 1:{1,3,5} index 2:{2} ``` How do I get the following combination in Java with or without using Lambdas. Step1: Find all such combinations ``` [{1,1,2}, {1,3,2}, {1,5,2}, {2,1,2}, {2,3,2}, {2,5,2}] -> ``` Step2: Remove duplicates from the obtanied combination ``` [{1,2}, {1,3,2}, {1,5,2}, {2,1}, {2,3}, {2,5}] ``` > > "want to do in each step like generate all n element subsets from n arrays >where first element comes from first array, second from second array..., >remove duplicates from each of resulting subsets." > > > It is not required to further reduce ``` [{1,2}, {1,2}] ``` to ``` [{1,2}] ``` or ``` [{1,2},{2,1}] ``` to ``` [{1,2}] / [{2,1}] ``` but will not affect the result in my case if done as well.
2015/05/17
[ "https://Stackoverflow.com/questions/30287309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747396/" ]
*Edit: At the time, this answer was given, the question was vague and suggested a 'remove duplicates' problem. I'll keept this answer though as it might contain helpful information to others.* Its hard to tell an exact solution to your problem as you don't properly describe the input and the wanted output. Just posting one example isn't enough. So let's assume the following: * **Input:** A list of integer arrays (`List<int[]>`). * **Output:** A list of integer arrays (`List<int[]>`), where the *n-th* array contains the values of the *n-th* array of the input list, but with duplicates removed. Copying the items of the input list into a new output list is simple: ``` List<int[]> output = new ArrayList<>(input.size()); for(int[] item : input) { output.add(removeDuplicates(item)); } ``` So the problem can be reduced to removing duplicates from an `int[]`. This is solved easily by using a intermediate `Set<Integer>`, as a `Set` does not have duplicates by default. Unfortunately, a `int[]` cannot be put directly into a `HashSet<Integer>` and vice-versa, so we have to manually copy element-wise: ``` public int[] removeDuplicates(int[] input) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < input.length; i++) set.add(input[i]); int[] output = new int[set.size()]; int i = 0; for (Integer e : set) { output[i++] = e; } return output; } ``` (See also [How to efficiently remove duplicates from an array without using Set](https://stackoverflow.com/questions/17967114/how-to-efficiently-remove-duplicates-from-an-array)) Everything is much easier of course, if you could have an `List<Collection<Integer>>` as input and output. In that case, the thing could be done easily as follows: ``` List<Collection<Integer>> output = new ArrayList<>(input.size()); for(Collection<Integer> item : input) { output.add(new HashSet<Integer>(item)); } ``` **Using Java 8 streaming API** For completeness: Java 8 streaming API makes life much easier, even with `List<int[]>`: ``` List<int[]> output = input.stream() .map(item -> Arrays.stream(item).distinct().toArray()) .collect(Collectors.toList()); ```
I assume you want to remove duplicates from each array without touching the order. You can map each array to e.g. `LinkedHashSet`, which keeps te order but doesn't allow duplicates. Then just map back to `int[]` and collect using `Collectors.toList()`: ``` list = list.stream() .map(a -> Arrays.stream(a).boxed().collect(Collectors.toList())) // map to List<Integer> .map(LinkedHashSet::new) // map to LinkedHashSet<Integer> .map(s -> s.stream().mapToInt(i -> i).toArray()) // map to int[] .collect(Collectors.toList()); ```
30,287,309
I have a `List<int[]>` as `index_position:int[] values` `input:` ``` index 0:{1,2} index 1:{1,3,5} index 2:{2} ``` How do I get the following combination in Java with or without using Lambdas. Step1: Find all such combinations ``` [{1,1,2}, {1,3,2}, {1,5,2}, {2,1,2}, {2,3,2}, {2,5,2}] -> ``` Step2: Remove duplicates from the obtanied combination ``` [{1,2}, {1,3,2}, {1,5,2}, {2,1}, {2,3}, {2,5}] ``` > > "want to do in each step like generate all n element subsets from n arrays >where first element comes from first array, second from second array..., >remove duplicates from each of resulting subsets." > > > It is not required to further reduce ``` [{1,2}, {1,2}] ``` to ``` [{1,2}] ``` or ``` [{1,2},{2,1}] ``` to ``` [{1,2}] / [{2,1}] ``` but will not affect the result in my case if done as well.
2015/05/17
[ "https://Stackoverflow.com/questions/30287309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747396/" ]
What you are asking seems to be cartesian product of N sets (`Set1 x Set2 x ... x SetN`). Unfortunately there is no standard method in Java which would allow us to build one easily, but with little help of Guava and its [`Sets.cartesianProduct`](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#cartesianProduct-java.util.List-) method this task seems quite easy. Only condition is that we need to provide as its argument `List<Set<..>>`. Because of that this answer is based on assumption that **each int[] is can be treated as set, which means that its values must be unique**. Actually to be more precise if `index 0` will be `{1,2,1}` or `{1,2,2}` it will be processed as set `{1,2}`. Here is example with `List<Set<Integer>>` with your current data (`toList` is statically imported `Collections.toList()` method, similarly `toSet`) : ``` //part 0: preparing data List<Set<Integer>> sets = new ArrayList<>( Arrays.asList( new HashSet<>(Arrays.asList(1, 2)), new HashSet<>(Arrays.asList(1, 3, 5)), new HashSet<>(Arrays.asList(2)) ) ); sets.forEach(System.out::println); System.out.println("-----------------"); //part 1: calculating cartesian products Set<List<Integer>> cartesianProducts = Sets.cartesianProduct(sets); System.out.println(cartesianProducts); System.out.println("-----------------"); //part 2 List<List<Integer>> noDuplicatesInProducts = cartesianProducts .stream()//iterate over each cartesian product .map(product -> product.stream() .distinct()//remove duplicate values .collect(toList())//store updated product as list ).collect(toList());//store all products as list System.out.println(noDuplicatesInProducts); ``` Output: ``` [1, 2] [1, 3, 5] [2] ----------------- [[1, 1, 2], [1, 3, 2], [1, 5, 2], [2, 1, 2], [2, 3, 2], [2, 5, 2]] ----------------- [[1, 2], [1, 3, 2], [1, 5, 2], [2, 1], [2, 3], [2, 5]] ``` --- If you are looking for a way to convert `List<int[]>` to `List<Set<Integer>>` here is one example: ``` private static List<Set<Integer>> convert(List<int[]> list) { return list .stream() .map(arr -> IntStream.of(arr) .mapToObj(Integer::valueOf)// same as .boxed() .collect(toSet()) ).collect(toList()); } ```
I assume you want to remove duplicates from each array without touching the order. You can map each array to e.g. `LinkedHashSet`, which keeps te order but doesn't allow duplicates. Then just map back to `int[]` and collect using `Collectors.toList()`: ``` list = list.stream() .map(a -> Arrays.stream(a).boxed().collect(Collectors.toList())) // map to List<Integer> .map(LinkedHashSet::new) // map to LinkedHashSet<Integer> .map(s -> s.stream().mapToInt(i -> i).toArray()) // map to int[] .collect(Collectors.toList()); ```
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
The `indexPath` variable contains information about the cell's position. Modifying your example: ``` if (indexPath.row == 0) { // Use a specific image. } ``` See the [NSIndexPath Class Reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html) and [NSIndexPath UIKit Additions Reference](http://developer.apple.com/library/ios/#documentation/uikit/reference/NSIndexPath_UIKitAdditions/Reference/Reference.html) for more information. It's also important to note that cell numbers reset in each section.
Use the `row` (and possibly also `section`) properties in the NSIndexPath passed to your `tableView:cellForRowAtIndexPath:` method to identify which cell is being queried.
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
Use the `row` (and possibly also `section`) properties in the NSIndexPath passed to your `tableView:cellForRowAtIndexPath:` method to identify which cell is being queried.
this function is passed an index path, which has a section and a row. indexPath.row will pass back an integer you can check.
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
Use the `row` (and possibly also `section`) properties in the NSIndexPath passed to your `tableView:cellForRowAtIndexPath:` method to identify which cell is being queried.
When cellForRowAtIndexPath is executed you have access to the indexPath variable, so if you want to customize the cell style depending on the cell index you can do something like this: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 0) { // code for cell 0 } else { if (indexPath.row == 1) { // code for cell 1 } } } ``` This is just an example, I don't think that customizing your cells by using if conditions is the best idea, but it shows you how to do what you need. Remember that indexPath contains the section of the table too. If you are using a Grouped table view, you need to manager the section too. For example: ``` if (indexPath.section == 0) { // section 0 if (indexPath.row == 0) { // code for section 0 - cell 0 } else { if (indexPath.row == 1) { // code for section 0 - cell 1 } } } else { if (indexPath.section == 1) { // section 1 if (indexPath.row == 0) { // code for section 1 - cell 0 } else { if (indexPath.row == 1) { // code for section 1 - cell 1 } } } } ```
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
Use the `row` (and possibly also `section`) properties in the NSIndexPath passed to your `tableView:cellForRowAtIndexPath:` method to identify which cell is being queried.
For a slightly nicer looking approach I would put all the images you want to use into an array: ``` _iconArray = @[@"picture1.png", @"picture2.png", @"picture3.png"]; ``` This means that when you come to the cellForRowAtIndex function you can say only: ``` cell.imageView.image = [UIImage imageNamed:_iconArray[indexPath.row]]; ``` This is also easier if you have more than one section, this time you can make an array of arrays, each containing the required pictures for the different sections. ``` _sectionsArray = @[_iconArray1, _iconArray2, _iconArray3]; cell.imageView.image = [UIImage imageNamed:_sectionsArray[indexPath.section][indexPath.row]; ``` This immediately makes it very easy to modify the pictures (as you are only dealing with the arrays. And much easier if you have more rows and sections (imagine doing it manually for 100 rows)
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
The `indexPath` variable contains information about the cell's position. Modifying your example: ``` if (indexPath.row == 0) { // Use a specific image. } ``` See the [NSIndexPath Class Reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html) and [NSIndexPath UIKit Additions Reference](http://developer.apple.com/library/ios/#documentation/uikit/reference/NSIndexPath_UIKitAdditions/Reference/Reference.html) for more information. It's also important to note that cell numbers reset in each section.
this function is passed an index path, which has a section and a row. indexPath.row will pass back an integer you can check.
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
The `indexPath` variable contains information about the cell's position. Modifying your example: ``` if (indexPath.row == 0) { // Use a specific image. } ``` See the [NSIndexPath Class Reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html) and [NSIndexPath UIKit Additions Reference](http://developer.apple.com/library/ios/#documentation/uikit/reference/NSIndexPath_UIKitAdditions/Reference/Reference.html) for more information. It's also important to note that cell numbers reset in each section.
When cellForRowAtIndexPath is executed you have access to the indexPath variable, so if you want to customize the cell style depending on the cell index you can do something like this: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 0) { // code for cell 0 } else { if (indexPath.row == 1) { // code for cell 1 } } } ``` This is just an example, I don't think that customizing your cells by using if conditions is the best idea, but it shows you how to do what you need. Remember that indexPath contains the section of the table too. If you are using a Grouped table view, you need to manager the section too. For example: ``` if (indexPath.section == 0) { // section 0 if (indexPath.row == 0) { // code for section 0 - cell 0 } else { if (indexPath.row == 1) { // code for section 0 - cell 1 } } } else { if (indexPath.section == 1) { // section 1 if (indexPath.row == 0) { // code for section 1 - cell 0 } else { if (indexPath.row == 1) { // code for section 1 - cell 1 } } } } ```
5,365,867
I have this code here within a class: ``` function getRolePerms($role) { if (is_array($role)) { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; } else { $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; } var_dump($roleSQL); $this->database->dbquery($roleSQL); $perms = array(); while($row = $this->database->result->fetch_assoc()) { $pK = strtolower($this->getPermKeyFromID($row['permID'])); var_dump($pK); if ($pK == '') { continue; } if ($row['value'] === '1') { $hP = true; } else { $hP = false; } $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); } return $perms; } ``` The var\_dump() for $roleSQL is: ``` SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC ``` and for $pK: ``` Admin ``` When running the query in the database directly i get a result with 8 rows. Why is it that the loop does not recognize the multiple rows. Also if i add the statement: ``` var_dump($this->database->result->fetch_assoc()); ``` It dumps the array of the first row then the loop does the second row. Im really baffled, Please help
2011/03/20
[ "https://Stackoverflow.com/questions/5365867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647354/" ]
The `indexPath` variable contains information about the cell's position. Modifying your example: ``` if (indexPath.row == 0) { // Use a specific image. } ``` See the [NSIndexPath Class Reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html) and [NSIndexPath UIKit Additions Reference](http://developer.apple.com/library/ios/#documentation/uikit/reference/NSIndexPath_UIKitAdditions/Reference/Reference.html) for more information. It's also important to note that cell numbers reset in each section.
For a slightly nicer looking approach I would put all the images you want to use into an array: ``` _iconArray = @[@"picture1.png", @"picture2.png", @"picture3.png"]; ``` This means that when you come to the cellForRowAtIndex function you can say only: ``` cell.imageView.image = [UIImage imageNamed:_iconArray[indexPath.row]]; ``` This is also easier if you have more than one section, this time you can make an array of arrays, each containing the required pictures for the different sections. ``` _sectionsArray = @[_iconArray1, _iconArray2, _iconArray3]; cell.imageView.image = [UIImage imageNamed:_sectionsArray[indexPath.section][indexPath.row]; ``` This immediately makes it very easy to modify the pictures (as you are only dealing with the arrays. And much easier if you have more rows and sections (imagine doing it manually for 100 rows)
20,841,085
I am trying to add partitioning on a MySQL database table schema for my database table is as ``` CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_group_id` tinyint(3) unsigned NOT NULL DEFAULT '2', `username` varchar(50) NOT NULL, `email` varchar(80) NOT NULL, `password` varchar(50) NOT NULL, `first_name` varchar(25) DEFAULT NULL, `last_name` varchar(25) DEFAULT NULL, `gender` enum('m','f','u') NOT NULL DEFAULT 'u' COMMENT 'm=>Male, f=>Female, u=>Unspecified', `profile_image` varchar(255) DEFAULT NULL, `reset_key` varchar(50) DEFAULT NULL, `block` enum('y','n') NOT NULL DEFAULT 'n' COMMENT 'y=>blocked, n=>notblocked', `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC AUTO_INCREMENT=1 ; ``` When I run following partitioning query on table ``` ALTER TABLE users PARTITION BY RANGE(id) ( PARTITION p0 VALUES LESS THAN (200000), PARTITION p1 VALUES LESS THAN (400000), PARTITION p2 VALUES LESS THAN (600000), PARTITION p3 VALUES LESS THAN (800000), PARTITION p4 VALUES LESS THAN (1000000), PARTITION p5 VALUES LESS THAN (1200000), PARTITION p6 VALUES LESS THAN (1400000), PARTITION p7 VALUES LESS THAN (1600000), PARTITION p8 VALUES LESS THAN (1800000), PARTITION p9 VALUES LESS THAN (2000000) ); ``` it is giving me error message as **`#1503 - A UNIQUE INDEX must include all columns in the table's partitioning function`** ![enter image description here](https://i.stack.imgur.com/6IbZS.png) I am using **MySQL Community Server - 5.5.16** can please anybody tell me what is error in my query?
2013/12/30
[ "https://Stackoverflow.com/questions/20841085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1868660/" ]
The [docs](http://dev.mysql.com/doc/refman/5.1/en/partitioning-limitations-partitioning-keys-unique-keys.html) says it all : > > This section discusses the relationship of partitioning keys with > primary keys and unique keys. The rule governing this relationship can > be expressed as follows: All columns used in the partitioning > expression for a partitioned table must be part of every unique key > that the table may have. > > >
after changing indexing on table it is working ``` CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_group_id` tinyint(3) unsigned NOT NULL DEFAULT '2', `username` varchar(50) NOT NULL, `email` varchar(80) NOT NULL, `password` varchar(50) NOT NULL, `first_name` varchar(25) DEFAULT NULL, `last_name` varchar(25) DEFAULT NULL, `gender` enum('m','f','u') NOT NULL DEFAULT 'u' COMMENT 'm=>Male, f=>Female, u=>Unspecified', `profile_image` varchar(255) DEFAULT NULL, `reset_key` varchar(50) DEFAULT NULL, `modify_username` enum('0','1') DEFAULT '0', `block` enum('y','n') NOT NULL DEFAULT 'n' COMMENT 'y=>blocked, n=>notblocked', `status` enum('0','1') DEFAULT '0', `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `id_username_email` (`id`,`username`,`email`), KEY `username` (`username`) KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC ```
39,335,695
I have docker swarm mode set up with 3 ubuntu 16.04 machines with vagrant. I don't think mesh routing is working at all. If I set up a service like `docker service create --name helloworld --replicas 1 -p 8888:80 nginx` I can see my service with ``` docker service ls ID NAME REPLICAS IMAGE COMMAND evbp2spkjn50 helloworld 1/1 nginx ``` I can curl to the ip of the machine that the actual container is running on: ``` curl 172.28.100.101:8888 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> .... ``` But if I go to any other machine in the swarm, I am not routed properly: ``` curl 172.28.100.102:8888 curl: (7) Failed to connect to 172.28.100.102 port 8888: Connection refused ``` Now, if I scale the service such that a container is running on all of the machines like this: ``` docker service scale helloworld=3 helloworld scaled to 3 ``` All of a sudden I can curl to it. ``` curl 172.28.100.102:8888 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> .... ``` All ports are open between these machines (they are set up with `vm.network :private_network, :ip => "172.28.100.10X", :netmask => "255.255.0.0"` in vagrant). I have tried this with a dedicated network with no change. ``` docker --version Docker version 1.12.1, build 23cf638 ```
2016/09/05
[ "https://Stackoverflow.com/questions/39335695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748268/" ]
There's an [open issue on github](https://github.com/docker/docker/issues/25325) that's likely related to what you're seeing. I think there are still some edge cases where the mesh routing isn't working right, and have seen this in some of my own tests with 1.12.
I switched from Ubuntu to RancherOS and the bad behavior disappeared. I'm guessing there is something about the kernel config that isn't right.
11,328,722
We have developed a product that is used for employee engagement. It provides a feature that shows tweets posted by members of your office if they have authorised the site. The fetching of tweets is done by a periodic cron that is run at a regular interval at about 15 minutes. This cron searches for all the users who have authorised the site's app and makes requests twitter for their tweets. For every user one request is send to twitter Currently the system is using REST API (http://api.twitter.com/1/statuses/user\_timeline.xml?user\_id='xxxxxx') that is limiting number of request to 150 per hour. We cannot make authenticated requests as it requires the user to authorise the call every time, which is not possible while making the requests by cron. So, with just 150 requests and cron running four times an hour it is possible to fetch only 35-40 users data which cannot meet our requirements. Also we have explored the option of Site Streaming API. But it requires a persistent connection to be established with twitter which would be difficult while using the cron. Another concerns with Site Streaming API is that it is in beta version and the website should be whitelisted. Kindly assist us in selecting the best possible alternative that would help us meet the above mentioned objective
2012/07/04
[ "https://Stackoverflow.com/questions/11328722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/584179/" ]
in `onDestroy()` nullify all your object variables, this will make them eligible for `System GC` to collect them. OR explicitly call `System.gc()`
Do this in your `onDestroy()`. But it is not necessary to do this, but a good prectice. As Android's GC is very intelligent. I think you have iPhone dev background, that's why you are asking this question. :)
18,138,097
So I have a weird truncate issue! Can't find a specific answer on this. So basically there's an issue with an apparent ISO character Β½ that truncates the rest of the text upon insertion into a column with UTF-8 specified. Lets say that my string is: "You need to add Β½ cup of water." MySQL will truncate that to "You need to add" if I: ``` print iconv("ISO-8859-1", "UTF-8//IGNORE", $text); ``` Then it outputs: ``` ½ ``` O\_o OK that doesn't work because I need the 1/2 by itself. If I go to phpMyAdmin and copy and paste the sentence in and submit it, it works like a charm as the whole string is in there with half symbol and remaining text! Something is wrong and I'm puzzled at what it is. I know this will probably affect other characters so the underlying problem needs to be addressed. The language I'm using is php, the file itself is encoded as UTF-8 and the data I'm bringing in has content-type set to ISO-8859-1. The column is utf8\_general\_ci and all the mysql character sets are set to UTF-8 in php: "SET character\_set\_result = 'utf8', etc..."
2013/08/08
[ "https://Stackoverflow.com/questions/18138097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521952/" ]
Something in your code isn't handling the string as UTF8. It could be your PHP/HTML, it could be in your connection to the DB, or it could be the DB itself - everything has to be set as UTF8 consistently, and if anything isn't, the string will get truncated exactly as you see when passing across a UTF8/non-UTF8 boundary. I will assume your DB is UTF8 compliant - that is easiest to check. Note that the collation can be set at the server level, database level, the table level, and the column level within the table. Setting UTF8 collation on the column should override anything else for storage, but the others will still kick in when talking to the DB if they're not also UTF8. If you're not sure, explicitly set the connection to UTF8 after you open it: ``` $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); ``` Now your DB & connection are UTF8, make sure your web page is too. Again, this can be set in more than one place (.htaccess, php.ini). If you're not sure / don't have access, just override whatever PHP is picking up as default at the top of your page: ``` <?php ini_set('default_charset', 'UTF-8'); ?> ``` Note that you want the above right at the start, before any text is output from your page. Once text gets output, it is potentially too late to try and specify an encoding - you may already be locked into whatever is default on your server. I also then repeat this in my headers (possibly overkill): ``` <head> <meta charset="UTF-8"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> </head> ``` And I override it on forms where I'm taking data as well: ``` <FORM NAME="utf8-test" METHOD="POST" ACTION="utf8-test.php" enctype="multipart/form-data" accept-charset="UTF-8">" ``` To be honest, if you've set the encoding at the top, my understanding is that the other overrides aren't required - but I keep them anyway, because it doesn't break anything either, and I'd rather just state the encoding explicitly, than let the server make assumptions. Finally, you mentioned that in phpMyAdmin you inserted the string and it looked as expected - are you sure though that the phpMyAdmin pages are UTF8? I don't think they are. When I store UTF8 data from my PHP code, it views like raw 8-bit characters in phpMyAdmin. If I take the same string and store it directly in phpMyAdmin, it looks 'correct'. So I'm guessing phpMyAdmin is using the default character set of my local server, not necessarily UTF8. For example, the following string stored from my web page: ``` I canΒΉt wait ``` Reads like this in my phpMyAdmin: ``` I canÒ€ℒt wait ``` So be careful when testing that way, as you don't really know what encoding phpMyAdmin is using for display or DB connection. If you're still having issues, try my code below. First I create a table to store the text in UTF8: ``` CREATE TABLE IF NOT EXISTS `utf8_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `my_text` varchar(8000) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ``` And here's some PHP to test it. It basically takes your input on a form, echoes that input back at you, and stores/retrieves the text from the DB. Like I said, if you view the data directly in phpMyAdmin, you might find it doesn't look right there, but through the page below it should always appear as expected, due to the page & db connection both being locked to UTF8. ``` <?php // Override whatever is set in php.ini ini_set('default_charset', 'UTF-8'); // The following should not be required with the above override //header('Content-Type:text/html; charset=UTF-8'); // Open the database $dbh = new PDO('mysql:dbname=utf8db;host=127.0.0.1;charset=utf8', 'root', 'password'); // Set the connection to UTF8 $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); // Tell MySql to do the parameter replacement, not PDO $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Throw exceptions (and break the code) if a query is bad $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $id = 0; if (isset($_POST["StoreText"])) { $stmt = $dbh->prepare('INSERT INTO utf8_test (my_text) VALUES (:my_text)'); $stmt->execute(array(':my_text' => $_POST['my_text'])); $id = $dbh->lastInsertId(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <title>UTF-8 Test</title> </head> <body> <?php // If something was posted, output it if (isset($_POST['my_text'])) { echo "POSTED<br>\n"; echo $_POST['my_text'] . "<br>\n"; } // If something was written to the database, read it back, and output it if ($id > 0) { $stmt = $dbh->prepare('SELECT my_text FROM utf8_test WHERE id = :id'); $stmt->execute(array(':id' => $id)); if ($result = $stmt->fetch()) { echo "STORED<br>\n"; echo $result['my_text'] . "<br>\n"; } } // Create a form to take some user input echo "<FORM NAME=\"utf8-test\" METHOD=\"POST\" ACTION=\"utf8-test.php\" enctype=\"multipart/form-data\" accept-charset=\"UTF-8\">"; echo "<br>"; echo "<textarea name=\"my_text\" rows=\"20\" cols=\"90\">"; // If something was posted, include it on the form if (isset($_POST['my_text'])) { echo $_POST['my_text']; } echo "</textarea>"; echo "<br>"; echo "<INPUT TYPE = \"Submit\" Name = \"StoreText\" VALUE=\"Store It\" />"; echo "</FORM>"; ?> <br> </body> </html> ```
Check into [mb\_convert\_encoding](http://php.net/manual/en/function.mb-convert-encoding.php) if you can't change the way the data is handled. Otherwise, do yourself a favor and get your encoding on the same page before it gets out of hand. UTF-8 uses multibyte characters which aren't recognized in the ISO-8859-1 (Latin) encoding. [wikipedia](http://en.wikipedia.org/wiki/UTF-8#Description). [This page](http://www.cs.tut.fi/~jkorpela/chars.html) and [this page](http://www.bluebox.net/about/blog/2009/07/mysql_encoding/) are good sources, as well as [this debug table](http://www.i18nqa.com/debug/utf8-debug.html). Finally, I've run into this when various combinations of htmlentities, htmlspecialchars and html\_entity\_decode are used..
18,138,097
So I have a weird truncate issue! Can't find a specific answer on this. So basically there's an issue with an apparent ISO character Β½ that truncates the rest of the text upon insertion into a column with UTF-8 specified. Lets say that my string is: "You need to add Β½ cup of water." MySQL will truncate that to "You need to add" if I: ``` print iconv("ISO-8859-1", "UTF-8//IGNORE", $text); ``` Then it outputs: ``` ½ ``` O\_o OK that doesn't work because I need the 1/2 by itself. If I go to phpMyAdmin and copy and paste the sentence in and submit it, it works like a charm as the whole string is in there with half symbol and remaining text! Something is wrong and I'm puzzled at what it is. I know this will probably affect other characters so the underlying problem needs to be addressed. The language I'm using is php, the file itself is encoded as UTF-8 and the data I'm bringing in has content-type set to ISO-8859-1. The column is utf8\_general\_ci and all the mysql character sets are set to UTF-8 in php: "SET character\_set\_result = 'utf8', etc..."
2013/08/08
[ "https://Stackoverflow.com/questions/18138097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521952/" ]
Something in your code isn't handling the string as UTF8. It could be your PHP/HTML, it could be in your connection to the DB, or it could be the DB itself - everything has to be set as UTF8 consistently, and if anything isn't, the string will get truncated exactly as you see when passing across a UTF8/non-UTF8 boundary. I will assume your DB is UTF8 compliant - that is easiest to check. Note that the collation can be set at the server level, database level, the table level, and the column level within the table. Setting UTF8 collation on the column should override anything else for storage, but the others will still kick in when talking to the DB if they're not also UTF8. If you're not sure, explicitly set the connection to UTF8 after you open it: ``` $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); ``` Now your DB & connection are UTF8, make sure your web page is too. Again, this can be set in more than one place (.htaccess, php.ini). If you're not sure / don't have access, just override whatever PHP is picking up as default at the top of your page: ``` <?php ini_set('default_charset', 'UTF-8'); ?> ``` Note that you want the above right at the start, before any text is output from your page. Once text gets output, it is potentially too late to try and specify an encoding - you may already be locked into whatever is default on your server. I also then repeat this in my headers (possibly overkill): ``` <head> <meta charset="UTF-8"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> </head> ``` And I override it on forms where I'm taking data as well: ``` <FORM NAME="utf8-test" METHOD="POST" ACTION="utf8-test.php" enctype="multipart/form-data" accept-charset="UTF-8">" ``` To be honest, if you've set the encoding at the top, my understanding is that the other overrides aren't required - but I keep them anyway, because it doesn't break anything either, and I'd rather just state the encoding explicitly, than let the server make assumptions. Finally, you mentioned that in phpMyAdmin you inserted the string and it looked as expected - are you sure though that the phpMyAdmin pages are UTF8? I don't think they are. When I store UTF8 data from my PHP code, it views like raw 8-bit characters in phpMyAdmin. If I take the same string and store it directly in phpMyAdmin, it looks 'correct'. So I'm guessing phpMyAdmin is using the default character set of my local server, not necessarily UTF8. For example, the following string stored from my web page: ``` I canΒΉt wait ``` Reads like this in my phpMyAdmin: ``` I canÒ€ℒt wait ``` So be careful when testing that way, as you don't really know what encoding phpMyAdmin is using for display or DB connection. If you're still having issues, try my code below. First I create a table to store the text in UTF8: ``` CREATE TABLE IF NOT EXISTS `utf8_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `my_text` varchar(8000) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ``` And here's some PHP to test it. It basically takes your input on a form, echoes that input back at you, and stores/retrieves the text from the DB. Like I said, if you view the data directly in phpMyAdmin, you might find it doesn't look right there, but through the page below it should always appear as expected, due to the page & db connection both being locked to UTF8. ``` <?php // Override whatever is set in php.ini ini_set('default_charset', 'UTF-8'); // The following should not be required with the above override //header('Content-Type:text/html; charset=UTF-8'); // Open the database $dbh = new PDO('mysql:dbname=utf8db;host=127.0.0.1;charset=utf8', 'root', 'password'); // Set the connection to UTF8 $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); // Tell MySql to do the parameter replacement, not PDO $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Throw exceptions (and break the code) if a query is bad $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $id = 0; if (isset($_POST["StoreText"])) { $stmt = $dbh->prepare('INSERT INTO utf8_test (my_text) VALUES (:my_text)'); $stmt->execute(array(':my_text' => $_POST['my_text'])); $id = $dbh->lastInsertId(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <title>UTF-8 Test</title> </head> <body> <?php // If something was posted, output it if (isset($_POST['my_text'])) { echo "POSTED<br>\n"; echo $_POST['my_text'] . "<br>\n"; } // If something was written to the database, read it back, and output it if ($id > 0) { $stmt = $dbh->prepare('SELECT my_text FROM utf8_test WHERE id = :id'); $stmt->execute(array(':id' => $id)); if ($result = $stmt->fetch()) { echo "STORED<br>\n"; echo $result['my_text'] . "<br>\n"; } } // Create a form to take some user input echo "<FORM NAME=\"utf8-test\" METHOD=\"POST\" ACTION=\"utf8-test.php\" enctype=\"multipart/form-data\" accept-charset=\"UTF-8\">"; echo "<br>"; echo "<textarea name=\"my_text\" rows=\"20\" cols=\"90\">"; // If something was posted, include it on the form if (isset($_POST['my_text'])) { echo $_POST['my_text']; } echo "</textarea>"; echo "<br>"; echo "<INPUT TYPE = \"Submit\" Name = \"StoreText\" VALUE=\"Store It\" />"; echo "</FORM>"; ?> <br> </body> </html> ```
Did you call `set_charset()` on your MySQLi database connection? It's required to properly use `real_escape_string()`. ``` $db = new mysqli(...); $db->set_charset('utf8'); ``` Setting session variables in your connection is not enough -- those affect what happens on the server-side. The `set_charset` will affect what happens client side. You can checkout the PHP reference [mysqli::real\_escape\_string](http://us1.php.net/manual/en/mysqli.real-escape-string.php)
42,838,490
I have a mysql query like this: ``` SELECT bp.id, COUNT(*) AS total FROM blog_posts bp JOIN tagged tg ON tg.taggable_id = bp.id AND tg.taggable_type = 'App\Storage\BlogPost' JOIN tags t ON t.id = tg.tag_id WHERE bp.user_id = 1 GROUP BY t.id ORDER BY total DESC, t.count DESC LIMIT 3 ``` and I got an error: > > Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'example.bp.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql\_mode=only\_full\_group\_by > > > How i can re-write this in a manner it does provide the same output? I work in MySQL 5.7.17 with Homestead Laravel
2017/03/16
[ "https://Stackoverflow.com/questions/42838490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4861352/" ]
Whenever you're doing a `GROUP BY` everything you add to your `SELECT` and `ORDER BY` clause needs to be in the `GROUP BY` clause, unless you're using an aggregate function such as MIN(), MAX(), SUM(), AVG(), etc. In this case you have `t.count DESC` in your order by clause, writing the query like this will provide you with the desired result. ``` SELECT id, total FROM ( SELECT bp.id, COUNT(*) AS total, MAX(t.count) count FROM blog_posts bp JOIN tagged tg ON tg.taggable_id = bp.id AND tg.taggable_type = 'App\Storage\BlogPost' JOIN tags t ON t.id = tg.tag_id WHERE bp.user_id = 1 GROUP BY bp.id, t.id LIMIT 3 ) a ORDER BY total DESC, `count` DESC ``` If you don't care if count is included in your final result then you can do this ``` SELECT bp.id, COUNT(*) AS total, MAX(t.count) count FROM blog_posts bp JOIN tagged tg ON tg.taggable_id = bp.id AND tg.taggable_type = 'App\Storage\BlogPost' JOIN tags t ON t.id = tg.tag_id WHERE bp.user_id = 1 GROUP BY bp.id, t.id ORDER BY total DESC, t.count DESC LIMIT 3 ```
I'm a bit confused on two points - what you are trying to pull, and how you want the same result set (given you get no result set, at the moment) The confusion comes in that you are reporting on bp.id, yet grouping on t.id. the select and group should match in this case. either select t.id, or group on bp.id, or select and group on BOTH - depending on the reporting requirements. Further, although I believe MySQL does the optimization, it is better practice to use a count(1), unless you are specifically trying to avoid counting a keyed, null data row. Hope that helps, - John
68,455,613
I have the following task to obtain a PDF from URL and return a BASE64 string. What I have currently (sorry I am not a Java Expert): ``` public String readPDFSOAP(String var, Container container) throws StreamTransformationException{ try { //get the url page from the arguments array URL url = new URL("URLPDF"); try { //get input Stream from URL InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[131072]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); String string = new String(response); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); }return String;} ``` But the string can't be returned. Any help is appreciated. Thanks, Julian
2021/07/20
[ "https://Stackoverflow.com/questions/68455613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16488172/" ]
I directly passed the childs object in the parent serializer and filtered based on it. That did the trick for me. ``` class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class ParentSerializer(serializers.ModelSerializer): name = serializers.ReadOnlyField(source='parent.name') child = serializers.SerializerMethodField() def get_child(self, obj): childs = Child.objects.filter(id=obj.id) return ChildSerializer(childs, many=True).data class Meta: model = Parent fields = ("childs", "name") ``` and then directly passed the child object in parent. ``` child = Child.objects.all() ParentSerializer(child, many=True) ```
Try changing the ***Parent Serializer*** as below. ``` class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(read_only=True) def to_representation(self, instance): child_query = Child.objects.filter(parent=instance) num_childs = child_query.count() ret_instance = {} for idx in range(num_childs): children = ChildSerializer(child_query[idx:idx + 1], many=True).data for child in children: child.pop('parent', None) temp_dict = { 'id': instance.id, 'name': instance.name, 'child': children } ret_instance[idx] = temp_dict return ret_instance class Meta: model = Parent fields = '__all__' ``` To change representation of serializer response, [***to\_representation()***](https://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior) method would need to be used.
42,656,360
I'm playing with Google Apps Script utilizing the ActiveCollab HTTPS API as a way to link Google Forms to specific projects. I can't figure out where to use the access token in the HTTP request when creating a Task in a project. Maybe I'm missing it, [but which API calls in the documentation](https://developers.activecollab.com/api-documentation/index.html) require the access token as part of the POST request? The most basic POST request I've sent was: ``` var token = // token from authentication { "name": "Test task", "token": token } ``` ...and it returned a 401 error, saying I wasn't authenticated. So, I tried: ``` var token = // token from authentication { "name": "Test task", "username": // my username, "password": // my password, "token": token } ``` ...with the same result. So, which calls require a `token` and does the token go in the POST payload? Or should it be in the POST options? **Update 3/10/2016** I have added the `Authorization` parameter to the `POST` request and am now receiving an invalid token error in the response. I've cleared my cache and reauthorized successfully. My test function is below. ``` function postTicket() { // Retrieve the stored token after a successful authorization var token = PropertiesService.getScriptProperties().getProperty("token"); var data = { "name": "Testing task" } var headers = { Authorization: 'Bearer ' + token }; var options = { "method": "post", "contentType": "application/json", "headers": headers, "payload": JSON.stringify(data) } try { var url = BASE_URL + "/projects/8/tasks"; var response = UrlFetchApp.fetch(url, options); var json = response.getContentText(); var data = JSON.stringify(json) Logger.log(data); } catch (e) { Logger.log(e); } } ``` The logged error is: > > returned code > 500.{"type":"ActiveCollab\Authentication\Exception\InvalidTokenException","message":"Authorization > token is not valid","code":0 > > >
2017/03/07
[ "https://Stackoverflow.com/questions/42656360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278429/" ]
I had the same problem, but after checking [Active Collab SDK code](https://github.com/activecollab/activecollab-feather-sdk/blob/63401d46bfe2b54c1ad173d38a887fdf83e961dc/src/Client.php#L156-L164) i figured out, that we should use these headers: ``` var headers = { 'X-Angie-AuthApiToken': token }; ``` By using this code i'm allowed to create tasks via API.
Token needs to be sent using `Authorization` HTTP header: ``` Authorization: Bearer TOKEN_THAT_YOU_GOT_FROM_ACTIVE_COLLAB ``` This means that you need to send the token as part of request header, not payload. Please check the Google Apps documentation for details (I see that `fetch` has `headers` object as one of the arguments, so there is support for this type of interaction built into the platform).
35,627,216
I am running this query in MySQL: ``` SELECT sequence from prices WHERE match_description <> '' AND 'SIP Trunk: 123456 (1 Channel)' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` I have rows that have a `match_description` of: ``` SIP Trunk (1 Channel) SIP Trunk (2 Channels) SIP Trunk (3 Channels) ``` etc... when running the above query, the string looks like `SIP Trunk: 123456 (x Channels)` how can i match these with my rows correctly? bearing in mind, the query i have works with other strings so i cannot change it too much. for example, other queries that run are like: ``` SELECT sequence from prices WHERE match_description <> '' AND 'Seat 200' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` this will match a row with `match_description` of `Seat` the queries are run when i upload a CSV file. this includes product names that are supplied to me so they are uploaded as they are sent to me. some example rows would be: ``` Seat 200 Seat 201 Seat 202 Call Queue 200 Call Group 201 Geographic Number 01234 567890 SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ``` So, using my query, I am able to match all except for the last two. for the ones I can match, i have the following in `match_description` in my table: ``` Seat Seat Seat Call Queue Call Group Geographic Number ``` i am just unsure how to match these? (the 123456 and 654321 are different for each product) ``` SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ```
2016/02/25
[ "https://Stackoverflow.com/questions/35627216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838253/" ]
You could match the first 11 characters to `SIP Trunk:`, then the last 9/ 10 characters to `channel)` or `channels)` then that way, if your match\_description is of the form: `SIP Trunk: yyyyyy (x Channels)` it will pick it up. The `MID` statements will make sure that `x` and `yyyyyy` are integers and the opening bracket is there. Also, thanks to @dwjv who points out you won't be able to index on the match\_description column. ``` SELECT sequence FROM prices WHERE match_description <> '' AND LEFT(match_description, 11) = 'SIP Trunk: ' AND (RIGHT(match_description, 9) = ' channel)' OR RIGHT(match_description, 10) = ' channels)') AND MID(match_description, 12,6) REGEXP '^-?[0-9]+$' AND MID(match_description, 18,3) = ' ( ' AND MID(match_description, 20,1) REGEXP '^-?[0-9]+$' ORDER BY length(match_description) desc LIMIT 1; ```
Try something like this ``` SELECT sequence from prices WHERE match_description <> '' AND match_description LIKE '%SIP Trunk: 123456 (% Channel%)%' ORDER BY length(match_description) desc LIMIT 1; ```
35,627,216
I am running this query in MySQL: ``` SELECT sequence from prices WHERE match_description <> '' AND 'SIP Trunk: 123456 (1 Channel)' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` I have rows that have a `match_description` of: ``` SIP Trunk (1 Channel) SIP Trunk (2 Channels) SIP Trunk (3 Channels) ``` etc... when running the above query, the string looks like `SIP Trunk: 123456 (x Channels)` how can i match these with my rows correctly? bearing in mind, the query i have works with other strings so i cannot change it too much. for example, other queries that run are like: ``` SELECT sequence from prices WHERE match_description <> '' AND 'Seat 200' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` this will match a row with `match_description` of `Seat` the queries are run when i upload a CSV file. this includes product names that are supplied to me so they are uploaded as they are sent to me. some example rows would be: ``` Seat 200 Seat 201 Seat 202 Call Queue 200 Call Group 201 Geographic Number 01234 567890 SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ``` So, using my query, I am able to match all except for the last two. for the ones I can match, i have the following in `match_description` in my table: ``` Seat Seat Seat Call Queue Call Group Geographic Number ``` i am just unsure how to match these? (the 123456 and 654321 are different for each product) ``` SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ```
2016/02/25
[ "https://Stackoverflow.com/questions/35627216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838253/" ]
You could match the first 11 characters to `SIP Trunk:`, then the last 9/ 10 characters to `channel)` or `channels)` then that way, if your match\_description is of the form: `SIP Trunk: yyyyyy (x Channels)` it will pick it up. The `MID` statements will make sure that `x` and `yyyyyy` are integers and the opening bracket is there. Also, thanks to @dwjv who points out you won't be able to index on the match\_description column. ``` SELECT sequence FROM prices WHERE match_description <> '' AND LEFT(match_description, 11) = 'SIP Trunk: ' AND (RIGHT(match_description, 9) = ' channel)' OR RIGHT(match_description, 10) = ' channels)') AND MID(match_description, 12,6) REGEXP '^-?[0-9]+$' AND MID(match_description, 18,3) = ' ( ' AND MID(match_description, 20,1) REGEXP '^-?[0-9]+$' ORDER BY length(match_description) desc LIMIT 1; ```
You can change the string to match to your match\_description For example you can encode SIP Trunk 12345(x Channel) to SIP Trunk (x Channel) 12345 This way your values will match with string. ``` SIP Trunk (1 Channel) SIP Trunk (2 Channels) SIP Trunk (3 Channels) ``` For encoding purpose you may use case statement on the variable that gives you specific type of string. Do you need to match just SIP Trunk: (x Channel) or SIP Trunk: (x Channel) first and then number 123456. You can just ignore 123456 part by doing some string operations in query or in your csv if you don't need it.
35,627,216
I am running this query in MySQL: ``` SELECT sequence from prices WHERE match_description <> '' AND 'SIP Trunk: 123456 (1 Channel)' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` I have rows that have a `match_description` of: ``` SIP Trunk (1 Channel) SIP Trunk (2 Channels) SIP Trunk (3 Channels) ``` etc... when running the above query, the string looks like `SIP Trunk: 123456 (x Channels)` how can i match these with my rows correctly? bearing in mind, the query i have works with other strings so i cannot change it too much. for example, other queries that run are like: ``` SELECT sequence from prices WHERE match_description <> '' AND 'Seat 200' LIKE CONCAT(match_description, '%') ORDER BY length(match_description) desc LIMIT 1; ``` this will match a row with `match_description` of `Seat` the queries are run when i upload a CSV file. this includes product names that are supplied to me so they are uploaded as they are sent to me. some example rows would be: ``` Seat 200 Seat 201 Seat 202 Call Queue 200 Call Group 201 Geographic Number 01234 567890 SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ``` So, using my query, I am able to match all except for the last two. for the ones I can match, i have the following in `match_description` in my table: ``` Seat Seat Seat Call Queue Call Group Geographic Number ``` i am just unsure how to match these? (the 123456 and 654321 are different for each product) ``` SIP Trunk: 123456 (2 Channels) SIP Trunk: 654321 (5 Channels) ```
2016/02/25
[ "https://Stackoverflow.com/questions/35627216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838253/" ]
Try something like this ``` SELECT sequence from prices WHERE match_description <> '' AND match_description LIKE '%SIP Trunk: 123456 (% Channel%)%' ORDER BY length(match_description) desc LIMIT 1; ```
You can change the string to match to your match\_description For example you can encode SIP Trunk 12345(x Channel) to SIP Trunk (x Channel) 12345 This way your values will match with string. ``` SIP Trunk (1 Channel) SIP Trunk (2 Channels) SIP Trunk (3 Channels) ``` For encoding purpose you may use case statement on the variable that gives you specific type of string. Do you need to match just SIP Trunk: (x Channel) or SIP Trunk: (x Channel) first and then number 123456. You can just ignore 123456 part by doing some string operations in query or in your csv if you don't need it.
8,685,993
Django keeps throwing the following when I try and save the addition of two object attributes. ``` invalid literal for int() with base 10: '' ``` The view is: ``` def buy_pack(request, pack_name): if request.method == 'POST': form = CardForm(request.POST, request.user) pack = Pack.objects.get(name=pack_name) stripe_user = request.user.username if form.is_valid(): token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=pack.cost, currency="usd", card=token, description=stripe_user+"_"+pack.name, ) datestring = charge.created dt = datetime.datetime.fromtimestamp(float(datestring)) new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4) new_purchase.save() user_profile = request.user.get_profile() t = user_profile.videos_remaining + pack.videos_allowed user_profile.videos_remaining = t user_profile.save() ``` The models in question are: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=50) videos_remaining = models.IntegerField(default=1) last_4_digits = models.IntegerField(max_length=4, blank=True) stripe_id = models.CharField(max_length=255, blank=True) def __unicode__(self): return self.name ``` And: ``` class Pack(models.Model): name = models.CharField(max_length=25) videos_allowed = models.IntegerField() cost = models.IntegerField() def __unicode__(self): return self.name ``` Traceback is: ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack 48. user_profile.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save 460. self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base 526. rows = manager.using(using).filter(pk=pk_val)._update(values) File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update 491. return query.get_compiler(self.db).execute_sql(None) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 869. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 725. sql, params = self.as_sql() File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql 834. val = field.get_db_prep_save(val, connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save 276. return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value 271. value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 876. return int(value) Exception Type: ValueError at /buy_pack/most/ Exception Value: invalid literal for int() with base 10: '' ``` For reference the stored value for user\_profile.videos\_remaining is 1 and the stored value for pack.videos\_allowed is 100. I am expecting it to add the two values together and store them as 101 in the user\_profile.videos\_remaining object attribute. If you can provide any help I would greatly appreciate it. EDIT: The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
2011/12/31
[ "https://Stackoverflow.com/questions/8685993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636784/" ]
The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
I experienced this error message as well in a Django population script with a ForeignKey having both `blank=True` and `null=True`, and passing `''` as argument to `objects.get_or_create()`. I fixed the issue by passing `argument=None`. The `None` part is the clue.
8,685,993
Django keeps throwing the following when I try and save the addition of two object attributes. ``` invalid literal for int() with base 10: '' ``` The view is: ``` def buy_pack(request, pack_name): if request.method == 'POST': form = CardForm(request.POST, request.user) pack = Pack.objects.get(name=pack_name) stripe_user = request.user.username if form.is_valid(): token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=pack.cost, currency="usd", card=token, description=stripe_user+"_"+pack.name, ) datestring = charge.created dt = datetime.datetime.fromtimestamp(float(datestring)) new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4) new_purchase.save() user_profile = request.user.get_profile() t = user_profile.videos_remaining + pack.videos_allowed user_profile.videos_remaining = t user_profile.save() ``` The models in question are: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=50) videos_remaining = models.IntegerField(default=1) last_4_digits = models.IntegerField(max_length=4, blank=True) stripe_id = models.CharField(max_length=255, blank=True) def __unicode__(self): return self.name ``` And: ``` class Pack(models.Model): name = models.CharField(max_length=25) videos_allowed = models.IntegerField() cost = models.IntegerField() def __unicode__(self): return self.name ``` Traceback is: ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack 48. user_profile.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save 460. self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base 526. rows = manager.using(using).filter(pk=pk_val)._update(values) File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update 491. return query.get_compiler(self.db).execute_sql(None) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 869. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 725. sql, params = self.as_sql() File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql 834. val = field.get_db_prep_save(val, connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save 276. return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value 271. value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 876. return int(value) Exception Type: ValueError at /buy_pack/most/ Exception Value: invalid literal for int() with base 10: '' ``` For reference the stored value for user\_profile.videos\_remaining is 1 and the stored value for pack.videos\_allowed is 100. I am expecting it to add the two values together and store them as 101 in the user\_profile.videos\_remaining object attribute. If you can provide any help I would greatly appreciate it. EDIT: The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
2011/12/31
[ "https://Stackoverflow.com/questions/8685993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636784/" ]
The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
This type of error is occur when an "Integer" inupt contains empty or string value like " 'id' ", " '.'.", etc. So, you have to find out that for what this type of input you get.
8,685,993
Django keeps throwing the following when I try and save the addition of two object attributes. ``` invalid literal for int() with base 10: '' ``` The view is: ``` def buy_pack(request, pack_name): if request.method == 'POST': form = CardForm(request.POST, request.user) pack = Pack.objects.get(name=pack_name) stripe_user = request.user.username if form.is_valid(): token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=pack.cost, currency="usd", card=token, description=stripe_user+"_"+pack.name, ) datestring = charge.created dt = datetime.datetime.fromtimestamp(float(datestring)) new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4) new_purchase.save() user_profile = request.user.get_profile() t = user_profile.videos_remaining + pack.videos_allowed user_profile.videos_remaining = t user_profile.save() ``` The models in question are: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=50) videos_remaining = models.IntegerField(default=1) last_4_digits = models.IntegerField(max_length=4, blank=True) stripe_id = models.CharField(max_length=255, blank=True) def __unicode__(self): return self.name ``` And: ``` class Pack(models.Model): name = models.CharField(max_length=25) videos_allowed = models.IntegerField() cost = models.IntegerField() def __unicode__(self): return self.name ``` Traceback is: ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack 48. user_profile.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save 460. self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base 526. rows = manager.using(using).filter(pk=pk_val)._update(values) File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update 491. return query.get_compiler(self.db).execute_sql(None) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 869. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 725. sql, params = self.as_sql() File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql 834. val = field.get_db_prep_save(val, connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save 276. return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value 271. value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 876. return int(value) Exception Type: ValueError at /buy_pack/most/ Exception Value: invalid literal for int() with base 10: '' ``` For reference the stored value for user\_profile.videos\_remaining is 1 and the stored value for pack.videos\_allowed is 100. I am expecting it to add the two values together and store them as 101 in the user\_profile.videos\_remaining object attribute. If you can provide any help I would greatly appreciate it. EDIT: The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
2011/12/31
[ "https://Stackoverflow.com/questions/8685993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636784/" ]
The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
The problem for me was that I was using `required=False, disabled=True,` that didn't send the data to the server for that field. I changed to ``` amount_payments = CharField(widget=TextInput(attrs={'readonly': 'readonly'})) ```
8,685,993
Django keeps throwing the following when I try and save the addition of two object attributes. ``` invalid literal for int() with base 10: '' ``` The view is: ``` def buy_pack(request, pack_name): if request.method == 'POST': form = CardForm(request.POST, request.user) pack = Pack.objects.get(name=pack_name) stripe_user = request.user.username if form.is_valid(): token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=pack.cost, currency="usd", card=token, description=stripe_user+"_"+pack.name, ) datestring = charge.created dt = datetime.datetime.fromtimestamp(float(datestring)) new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4) new_purchase.save() user_profile = request.user.get_profile() t = user_profile.videos_remaining + pack.videos_allowed user_profile.videos_remaining = t user_profile.save() ``` The models in question are: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=50) videos_remaining = models.IntegerField(default=1) last_4_digits = models.IntegerField(max_length=4, blank=True) stripe_id = models.CharField(max_length=255, blank=True) def __unicode__(self): return self.name ``` And: ``` class Pack(models.Model): name = models.CharField(max_length=25) videos_allowed = models.IntegerField() cost = models.IntegerField() def __unicode__(self): return self.name ``` Traceback is: ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack 48. user_profile.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save 460. self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base 526. rows = manager.using(using).filter(pk=pk_val)._update(values) File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update 491. return query.get_compiler(self.db).execute_sql(None) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 869. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 725. sql, params = self.as_sql() File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql 834. val = field.get_db_prep_save(val, connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save 276. return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value 271. value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 876. return int(value) Exception Type: ValueError at /buy_pack/most/ Exception Value: invalid literal for int() with base 10: '' ``` For reference the stored value for user\_profile.videos\_remaining is 1 and the stored value for pack.videos\_allowed is 100. I am expecting it to add the two values together and store them as 101 in the user\_profile.videos\_remaining object attribute. If you can provide any help I would greatly appreciate it. EDIT: The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
2011/12/31
[ "https://Stackoverflow.com/questions/8685993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636784/" ]
I experienced this error message as well in a Django population script with a ForeignKey having both `blank=True` and `null=True`, and passing `''` as argument to `objects.get_or_create()`. I fixed the issue by passing `argument=None`. The `None` part is the clue.
This type of error is occur when an "Integer" inupt contains empty or string value like " 'id' ", " '.'.", etc. So, you have to find out that for what this type of input you get.
8,685,993
Django keeps throwing the following when I try and save the addition of two object attributes. ``` invalid literal for int() with base 10: '' ``` The view is: ``` def buy_pack(request, pack_name): if request.method == 'POST': form = CardForm(request.POST, request.user) pack = Pack.objects.get(name=pack_name) stripe_user = request.user.username if form.is_valid(): token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=pack.cost, currency="usd", card=token, description=stripe_user+"_"+pack.name, ) datestring = charge.created dt = datetime.datetime.fromtimestamp(float(datestring)) new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4) new_purchase.save() user_profile = request.user.get_profile() t = user_profile.videos_remaining + pack.videos_allowed user_profile.videos_remaining = t user_profile.save() ``` The models in question are: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=50) videos_remaining = models.IntegerField(default=1) last_4_digits = models.IntegerField(max_length=4, blank=True) stripe_id = models.CharField(max_length=255, blank=True) def __unicode__(self): return self.name ``` And: ``` class Pack(models.Model): name = models.CharField(max_length=25) videos_allowed = models.IntegerField() cost = models.IntegerField() def __unicode__(self): return self.name ``` Traceback is: ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack 48. user_profile.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save 460. self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base 526. rows = manager.using(using).filter(pk=pk_val)._update(values) File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update 491. return query.get_compiler(self.db).execute_sql(None) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 869. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 725. sql, params = self.as_sql() File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql 834. val = field.get_db_prep_save(val, connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 28. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save 276. return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner 53. return func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value 271. value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 876. return int(value) Exception Type: ValueError at /buy_pack/most/ Exception Value: invalid literal for int() with base 10: '' ``` For reference the stored value for user\_profile.videos\_remaining is 1 and the stored value for pack.videos\_allowed is 100. I am expecting it to add the two values together and store them as 101 in the user\_profile.videos\_remaining object attribute. If you can provide any help I would greatly appreciate it. EDIT: The problem ended up being that I was not passing a value for the integer field last\_4\_digits. It seems that this happens if you have a integerField with blank=True and don't submit a value for it.
2011/12/31
[ "https://Stackoverflow.com/questions/8685993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636784/" ]
I experienced this error message as well in a Django population script with a ForeignKey having both `blank=True` and `null=True`, and passing `''` as argument to `objects.get_or_create()`. I fixed the issue by passing `argument=None`. The `None` part is the clue.
The problem for me was that I was using `required=False, disabled=True,` that didn't send the data to the server for that field. I changed to ``` amount_payments = CharField(widget=TextInput(attrs={'readonly': 'readonly'})) ```
199,801
Our production server is running *sqlite-3.3.6-2* on CentOS release 5.2 (Final). We're planning to upgrade SQLite to the latest v3.7.3 (atleast v3.5+). But there is no RPM available in [SQLite](http://www.sqlite.org/download.html "SQLite Download Page") website and not able to find one from google search also. But I'm finding v3.5+ RPM for RHEL3 [here](http://rpm.pbone.net/index.php3/stat/4/idpl/12396267/dir/redhat_el_3/com/sqlite-3.5.9-1.el3.pp.i386.rpm.html "SQLite v3.5.9"). Since we're running CentOS5 64-bit, 1. Is it OK to install a RHEL3 64-bit RPM package on a CentOS5 64-bit server? 2. In case, if it can be installed, will there be any implications/side-effects? In general, can we install a RPM built for lower version of OS (ex: RHEL3) on a higher version of OS (ex: RHEL5)?
2010/11/09
[ "https://serverfault.com/questions/199801", "https://serverfault.com", "https://serverfault.com/users/35997/" ]
The answer in my general experience is "if it works". RPMs have depdency checking built in; they know if they need a particular version of glibc, or php, or mysql, or foo, bar or baz. If you do an ``` rpm -ivh fribble-4.5.6-el3.i386.rpm ``` and it runs to completion, you're likely OK (though test it). If instead it says ``` error: Failed dependencies: libgwenhywfar.so.38 is needed by fribble-4.5.6-el3.i386.rpm libofx.so.3 is needed by fribble-4.5.6-el3.i386.rpm python(abi) = 2.4 is needed by fribble-4.5.6-el3.i386.rpm ``` that's RH's way of telling you that no, it's not going to work. You can of course override that with `--nodeps`, but you'll be in for a lot of pain if you do, so don't; find an up-to-date RPM instead.
The jump in this case is too large, and sqlite is present in the base repo. Rebuild from SRPM instead. Note that you'll be responsible for handling updates yourself should you decide to do this.
26,618,582
I have one main class Test and two others (class Book , class Order) that represent some specific objects. From my class Test I create 5 Book objects. Now i want to create two Order objects that use methods from Order class. To be specific use setCustomerName(), SetCustomerAddress(), toString() getTotlaPrice() and addBook().After i set getters and setters for setCustomerName() and SetCustomerAddress() i have no errors for them in the Test Class. My question is how can i create 5 Book instance variables in the Order class that will be filled with the member data (or parameters) of the Book objects created in the Test class if they are called(from Test class with addBook()), so that i can use them in the other methods in the same class.So for example in class Test if i call addBook(b1) the addBook() method which is in the Order class should initialize or fill one of the Book instance variables (i guess this is an object to?) created in Order with the member data of the one referenced (with b#1-5) in the Test class. These are the two classes. I havent put the Book class because it just creates the Book object. Any help is very much appreciated! ``` import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String args[]) throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat(Book.DATE_FORMAT); // Creating Book-objects... Book b1 = new Book(1, "Homo Faber", "Max Frisch", fmt.parse("01.01.1957"), -10); Book b2 = new Book(2, "Harry Potter", "J.K. Rowling", fmt.parse("25.7.2000"), 45); Book b3 = new Book(3, "Krieg und Frieden", "Leo Tolstoi", fmt.parse("24.01.1867"), 29); Book b4 = new Book(4, "Freedom", "Jonathan Franzen", fmt.parse("08.06.2010"), 39); Book b5 = new Book(5, "Goedel, Escher, Bach", "Douglas Hofstadter", fmt.parse("05.11.1979"), 42); // Creating two orders containing theses books... Order order = new Order(); order.setCustomerName("Sophie Muster"); order.setCustomerAddress("Mittelstrasse 10, 3011 Bern"); order.addBook(b1);//Here i want to fill one of the Book instance variables (i guess this is an object to?) created order.addBook(b2);//in the Order class with the member data of the order.addBook(b3);//Book objects referenced (with b#1-5) which i have created above. order.addBook(b4); order.addBook(b4); order.addBook(b5); System.out.println(order); System.out.print("\n"); Order order2 = new Order(); order2.setCustomerName("Woody Allen"); order2.setCustomerAddress("5th Avenue 7, 10001 New York"); order2.addBook(b5); System.out.println(order2); } } ``` . ``` public class Order { private static int idCounter; private int id; private String customerName; private String customerAddress; // The Constructor public Order(int tmpId, String tmpCustomerName,String tmpCustomerAddress){ if (idCounter == 1);{ id = 1;} if (idCounter == 2){ id = 2;} if (idCounter == 3);{ id = 3;} if (idCounter == 4){ id = 4;} if (idCounter == 5){ id = 5;} customerName = tmpCustomerName; customerAddress = tmpCustomerAddress; } public Order() { id = 0; customerName = "-"; customerAddress = "-"; } // The methods public String toString() { return id + ", " + customerName + ", " + customerAddress; } public String addBook(){ //HERE with this method i want to add some of the Book objects i have made in Test class // ?? Book b1 = Test.b1(); ?? return "0"; } public int getTotalPrice(){ return 0; } public String getCustomerName() { return customerName; } public String setCustomerName(String tmpCustomerName){ customerName = tmpCustomerName; return customerName; } public String getCustomerAddress() { return customerAddress; } public String setCustomerAddress(String tmpCustomerAddress){ customerAddress = tmpCustomerAddress; return customerAddress; } } ```
2014/10/28
[ "https://Stackoverflow.com/questions/26618582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4159988/" ]
Did you include the url module in your code? Because I cannot see ``` require('url'); ``` in your provided code. I just created a new node.js project, and include the url module. It seems working fine and I didn't see the problem your mentioned. If this doesn't solve, maybe you can provide more specific error code?
I get it. it related to [passing request between middleware](http://expressjs.com/api.html#middleware) . So below if i call `next()` without arguments `res.send('Hello /myroute from app.js')` will be processed. ``` app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(); // early was next(err) }); app.get('/myroute', function(req, res) { res.send('Hello /myroute from app.js') }); ``` Or would be better if put routing error handler below all routings.
26,618,582
I have one main class Test and two others (class Book , class Order) that represent some specific objects. From my class Test I create 5 Book objects. Now i want to create two Order objects that use methods from Order class. To be specific use setCustomerName(), SetCustomerAddress(), toString() getTotlaPrice() and addBook().After i set getters and setters for setCustomerName() and SetCustomerAddress() i have no errors for them in the Test Class. My question is how can i create 5 Book instance variables in the Order class that will be filled with the member data (or parameters) of the Book objects created in the Test class if they are called(from Test class with addBook()), so that i can use them in the other methods in the same class.So for example in class Test if i call addBook(b1) the addBook() method which is in the Order class should initialize or fill one of the Book instance variables (i guess this is an object to?) created in Order with the member data of the one referenced (with b#1-5) in the Test class. These are the two classes. I havent put the Book class because it just creates the Book object. Any help is very much appreciated! ``` import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String args[]) throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat(Book.DATE_FORMAT); // Creating Book-objects... Book b1 = new Book(1, "Homo Faber", "Max Frisch", fmt.parse("01.01.1957"), -10); Book b2 = new Book(2, "Harry Potter", "J.K. Rowling", fmt.parse("25.7.2000"), 45); Book b3 = new Book(3, "Krieg und Frieden", "Leo Tolstoi", fmt.parse("24.01.1867"), 29); Book b4 = new Book(4, "Freedom", "Jonathan Franzen", fmt.parse("08.06.2010"), 39); Book b5 = new Book(5, "Goedel, Escher, Bach", "Douglas Hofstadter", fmt.parse("05.11.1979"), 42); // Creating two orders containing theses books... Order order = new Order(); order.setCustomerName("Sophie Muster"); order.setCustomerAddress("Mittelstrasse 10, 3011 Bern"); order.addBook(b1);//Here i want to fill one of the Book instance variables (i guess this is an object to?) created order.addBook(b2);//in the Order class with the member data of the order.addBook(b3);//Book objects referenced (with b#1-5) which i have created above. order.addBook(b4); order.addBook(b4); order.addBook(b5); System.out.println(order); System.out.print("\n"); Order order2 = new Order(); order2.setCustomerName("Woody Allen"); order2.setCustomerAddress("5th Avenue 7, 10001 New York"); order2.addBook(b5); System.out.println(order2); } } ``` . ``` public class Order { private static int idCounter; private int id; private String customerName; private String customerAddress; // The Constructor public Order(int tmpId, String tmpCustomerName,String tmpCustomerAddress){ if (idCounter == 1);{ id = 1;} if (idCounter == 2){ id = 2;} if (idCounter == 3);{ id = 3;} if (idCounter == 4){ id = 4;} if (idCounter == 5){ id = 5;} customerName = tmpCustomerName; customerAddress = tmpCustomerAddress; } public Order() { id = 0; customerName = "-"; customerAddress = "-"; } // The methods public String toString() { return id + ", " + customerName + ", " + customerAddress; } public String addBook(){ //HERE with this method i want to add some of the Book objects i have made in Test class // ?? Book b1 = Test.b1(); ?? return "0"; } public int getTotalPrice(){ return 0; } public String getCustomerName() { return customerName; } public String setCustomerName(String tmpCustomerName){ customerName = tmpCustomerName; return customerName; } public String getCustomerAddress() { return customerAddress; } public String setCustomerAddress(String tmpCustomerAddress){ customerAddress = tmpCustomerAddress; return customerAddress; } } ```
2014/10/28
[ "https://Stackoverflow.com/questions/26618582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4159988/" ]
In this very interesting post <https://blog.safaribooksonline.com/2014/03/10/express-js-middleware-demystified/> you can find the next: > > Middleware is any number of functions that are invoked by the > Express.js routing layer before your final request handler is, and > thus sits in the middle between a raw request and the final intended > route. We often refer to these functions as the middleware stack since > they are always invoked in the order they are added > > > Hence if you want to handle 404 errors then you must put: ``` app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); ``` after all the route handlers.
I get it. it related to [passing request between middleware](http://expressjs.com/api.html#middleware) . So below if i call `next()` without arguments `res.send('Hello /myroute from app.js')` will be processed. ``` app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(); // early was next(err) }); app.get('/myroute', function(req, res) { res.send('Hello /myroute from app.js') }); ``` Or would be better if put routing error handler below all routings.
5,986,909
> > **Possible Duplicate:** > > [Ruby: Any gems for threadpooling?](https://stackoverflow.com/questions/2624861/ruby-any-gems-for-threadpooling) > > > Is there a better ruby lib thread pool? I want to use the thread pool to help me manage their running behaviors like java thread pool. Really I am not sure, so I hope you guys recommend something.
2011/05/13
[ "https://Stackoverflow.com/questions/5986909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531581/" ]
There's a question about ThreadGroup (mentioned by @Phrogz) at [What is Ruby's ThreadGroup for?](https://stackoverflow.com/questions/5944500/what-is-rubys-threadgroup-for) .
refer to @andrew-grimm answer: There's a question about ThreadGroup (mentioned by @Phrogz) at [What is Ruby's ThreadGroup for?](https://stackoverflow.com/questions/5944500/)
2,293,674
So far Django has good integration with several RDBMS. NoSQL, schema-less and document-oriented DBMS are picking up. What's the status of integration those on-trend and fashionable DBMSes with Django? Are there any production-ready or at least ready-to-use libraries for Django? So far I have these at hand: * <http://github.com/lethain/comfy-django-example> * <http://nosql.mypopescu.com/post/276069660/nosql-libraries#mongodb-python>
2010/02/19
[ "https://Stackoverflow.com/questions/2293674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128028/" ]
Pre 1.0, django ORM underwent a major queryset re-factor. One of the reasons for this was "This re-factor enables us to support non relational backends". The official support I think is definitely on the cards; but I think there were more pressing matters for 1.1 and 1.2(now in beta). However, there are of course several independent efforts to use non relational databases with django, including, but not limited to the following: * [Django-nonrel](http://www.allbuttonspressed.com/projects/django-nonrel) by Waldemar, who made django work on the appengine using the appengine patch. * Using django with mongo db, by Kevin Fricovsky: <http://bitbucket.org/gumptioncom/django-non-relational/> * Using django with couch db, an old post, by Eric: <http://www.eflorenzano.com/blog/post/using-couchdb-django/>
[Neo4j](http://neo4j.org/)- the Java graph database (on the other end of the NoSQL spectrum)- also has [initial support](http://journal.thobe.org/2009/12/seamless-neo4j-integration-in-django.html). EDIT: I've spent quite a while fleshing this support out and moving to a remote protocol. You can see the results on [GitHub](https://github.com/scholrly/neo4django).
2,293,674
So far Django has good integration with several RDBMS. NoSQL, schema-less and document-oriented DBMS are picking up. What's the status of integration those on-trend and fashionable DBMSes with Django? Are there any production-ready or at least ready-to-use libraries for Django? So far I have these at hand: * <http://github.com/lethain/comfy-django-example> * <http://nosql.mypopescu.com/post/276069660/nosql-libraries#mongodb-python>
2010/02/19
[ "https://Stackoverflow.com/questions/2293674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128028/" ]
Pre 1.0, django ORM underwent a major queryset re-factor. One of the reasons for this was "This re-factor enables us to support non relational backends". The official support I think is definitely on the cards; but I think there were more pressing matters for 1.1 and 1.2(now in beta). However, there are of course several independent efforts to use non relational databases with django, including, but not limited to the following: * [Django-nonrel](http://www.allbuttonspressed.com/projects/django-nonrel) by Waldemar, who made django work on the appengine using the appengine patch. * Using django with mongo db, by Kevin Fricovsky: <http://bitbucket.org/gumptioncom/django-non-relational/> * Using django with couch db, an old post, by Eric: <http://www.eflorenzano.com/blog/post/using-couchdb-django/>
Until there is official Django support of a MongoDB back-end, for auto-admin, etc. (wouldn't that be so great). I would take a look at [mongokit](https://github.com/namlook/mongokit), which is a thin wrapper over pymongo. There's a few alternatives, but mongokit has comprehensive documentation and is under active development.
2,293,674
So far Django has good integration with several RDBMS. NoSQL, schema-less and document-oriented DBMS are picking up. What's the status of integration those on-trend and fashionable DBMSes with Django? Are there any production-ready or at least ready-to-use libraries for Django? So far I have these at hand: * <http://github.com/lethain/comfy-django-example> * <http://nosql.mypopescu.com/post/276069660/nosql-libraries#mongodb-python>
2010/02/19
[ "https://Stackoverflow.com/questions/2293674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128028/" ]
[Neo4j](http://neo4j.org/)- the Java graph database (on the other end of the NoSQL spectrum)- also has [initial support](http://journal.thobe.org/2009/12/seamless-neo4j-integration-in-django.html). EDIT: I've spent quite a while fleshing this support out and moving to a remote protocol. You can see the results on [GitHub](https://github.com/scholrly/neo4django).
Until there is official Django support of a MongoDB back-end, for auto-admin, etc. (wouldn't that be so great). I would take a look at [mongokit](https://github.com/namlook/mongokit), which is a thin wrapper over pymongo. There's a few alternatives, but mongokit has comprehensive documentation and is under active development.
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
> > Is there a point where the complexity of a game is enough for people to say "ok, I'm going to download and play that"? > > > No. The logic of what you are suggesting is that people see simple games which are uninteresting, and then as they see progressively more complex games, they eventually think, "aha! This is complex enough for my interests - I shall download it". I don't think that is really what you mean, but that is what your logic suggests. What really happens is this: a player sees a website with a game on it, and makes an assessment of how interesting the game is to them. The degree of interest they have dictates the amount of effort they are willing to go to in order to play the game. Therefore, there is almost no situation where a person would be more willing to download and install an executable rather than play a web-based game. And if you have a downloadable executable, you will get better traction with a smaller download than a larger one. You will get more players if you remove the need to explicitly create an account - you'll have even more if there is no login process whatsoever. And so on. From your side, it's never as simple as that, because even a web-based game may involve installing a plugin, or upgrading a browser, etc. But on the whole, the complexity of your game makes no direct difference - it's a pure comparison of how interesting the game looks vs. how much effort the player will need to put in to try it. > > Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? > > > You're asking whether 9% of 100 is bigger than 90% of 10. Only you can decide whether you need to reach a wider audience at a cost of whatever sacrifices you need to make to offer it on the web. What's your monetisation strategy? What sacrifices would you have to make? You have to pick what is best for you. If there was One Right Answer then the world couldn't support both Modern Warfare 3 and Farmville, so we know that isn't the case.
In with Unity before anyone else! (or I'll delete my answer). Unity really is the standout in this space, and it can in fact be used to distribute standalone games. If you want to make a game, use something very polished like Unity. If you want to mess with technology, use one of the systems you mentioned.
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
In with Unity before anyone else! (or I'll delete my answer). Unity really is the standout in this space, and it can in fact be used to distribute standalone games. If you want to make a game, use something very polished like Unity. If you want to mess with technology, use one of the systems you mentioned.
I recommend looking into the Three.js. It's a neat abstraction (not sure if it classifies as an engine) on top of WebGL (this is the engine, technically speaking?) and it has loads of great examples. But the best thing about it? No plugins! It's all HTML5 and WebGL, which are standard features of almost all bigger browsers now! I messed around with it a little, and it is great.
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
In with Unity before anyone else! (or I'll delete my answer). Unity really is the standout in this space, and it can in fact be used to distribute standalone games. If you want to make a game, use something very polished like Unity. If you want to mess with technology, use one of the systems you mentioned.
I don't think you should go with a browser game because it might entail producing 2 version of code: one for browser and one for desktop. In addition, browser technology might not be powerful enough to handle your game (depending on your exact situation). Unity might be one of the better choices for both desktop and browser deployment, but you have to consider the download of the Unity Player. While its filesize is actually quite lightweight and likely to be much smaller than your game itself, people are rather put off by the need to download. See <http://forum.unity3d.com/threads/27081-losing-users-when-they-have-to-download-Unity-webplayer>
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
> > Is there a point where the complexity of a game is enough for people to say "ok, I'm going to download and play that"? > > > No. The logic of what you are suggesting is that people see simple games which are uninteresting, and then as they see progressively more complex games, they eventually think, "aha! This is complex enough for my interests - I shall download it". I don't think that is really what you mean, but that is what your logic suggests. What really happens is this: a player sees a website with a game on it, and makes an assessment of how interesting the game is to them. The degree of interest they have dictates the amount of effort they are willing to go to in order to play the game. Therefore, there is almost no situation where a person would be more willing to download and install an executable rather than play a web-based game. And if you have a downloadable executable, you will get better traction with a smaller download than a larger one. You will get more players if you remove the need to explicitly create an account - you'll have even more if there is no login process whatsoever. And so on. From your side, it's never as simple as that, because even a web-based game may involve installing a plugin, or upgrading a browser, etc. But on the whole, the complexity of your game makes no direct difference - it's a pure comparison of how interesting the game looks vs. how much effort the player will need to put in to try it. > > Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? > > > You're asking whether 9% of 100 is bigger than 90% of 10. Only you can decide whether you need to reach a wider audience at a cost of whatever sacrifices you need to make to offer it on the web. What's your monetisation strategy? What sacrifices would you have to make? You have to pick what is best for you. If there was One Right Answer then the world couldn't support both Modern Warfare 3 and Farmville, so we know that isn't the case.
I recommend looking into the Three.js. It's a neat abstraction (not sure if it classifies as an engine) on top of WebGL (this is the engine, technically speaking?) and it has loads of great examples. But the best thing about it? No plugins! It's all HTML5 and WebGL, which are standard features of almost all bigger browsers now! I messed around with it a little, and it is great.
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
> > Is there a point where the complexity of a game is enough for people to say "ok, I'm going to download and play that"? > > > No. The logic of what you are suggesting is that people see simple games which are uninteresting, and then as they see progressively more complex games, they eventually think, "aha! This is complex enough for my interests - I shall download it". I don't think that is really what you mean, but that is what your logic suggests. What really happens is this: a player sees a website with a game on it, and makes an assessment of how interesting the game is to them. The degree of interest they have dictates the amount of effort they are willing to go to in order to play the game. Therefore, there is almost no situation where a person would be more willing to download and install an executable rather than play a web-based game. And if you have a downloadable executable, you will get better traction with a smaller download than a larger one. You will get more players if you remove the need to explicitly create an account - you'll have even more if there is no login process whatsoever. And so on. From your side, it's never as simple as that, because even a web-based game may involve installing a plugin, or upgrading a browser, etc. But on the whole, the complexity of your game makes no direct difference - it's a pure comparison of how interesting the game looks vs. how much effort the player will need to put in to try it. > > Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? > > > You're asking whether 9% of 100 is bigger than 90% of 10. Only you can decide whether you need to reach a wider audience at a cost of whatever sacrifices you need to make to offer it on the web. What's your monetisation strategy? What sacrifices would you have to make? You have to pick what is best for you. If there was One Right Answer then the world couldn't support both Modern Warfare 3 and Farmville, so we know that isn't the case.
I don't think you should go with a browser game because it might entail producing 2 version of code: one for browser and one for desktop. In addition, browser technology might not be powerful enough to handle your game (depending on your exact situation). Unity might be one of the better choices for both desktop and browser deployment, but you have to consider the download of the Unity Player. While its filesize is actually quite lightweight and likely to be much smaller than your game itself, people are rather put off by the need to download. See <http://forum.unity3d.com/threads/27081-losing-users-when-they-have-to-download-Unity-webplayer>
30,868
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on. In particular, I'm talking about browser games vs. desktop games. I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now). Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities\* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this? (\* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.) **For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?**
2012/06/20
[ "https://gamedev.stackexchange.com/questions/30868", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/17277/" ]
I don't think you should go with a browser game because it might entail producing 2 version of code: one for browser and one for desktop. In addition, browser technology might not be powerful enough to handle your game (depending on your exact situation). Unity might be one of the better choices for both desktop and browser deployment, but you have to consider the download of the Unity Player. While its filesize is actually quite lightweight and likely to be much smaller than your game itself, people are rather put off by the need to download. See <http://forum.unity3d.com/threads/27081-losing-users-when-they-have-to-download-Unity-webplayer>
I recommend looking into the Three.js. It's a neat abstraction (not sure if it classifies as an engine) on top of WebGL (this is the engine, technically speaking?) and it has loads of great examples. But the best thing about it? No plugins! It's all HTML5 and WebGL, which are standard features of almost all bigger browsers now! I messed around with it a little, and it is great.
102,045
I would like to mirror/replicate my databases to the cloud. The cloud is setup using VPN to my actual machine. I am a bit confused by the options I have and would like to get some light into it. My setup is a SQL Server 2012 (standard edition) Instance which should be mirrored/replicated to a SQL server 2014 instance. The instance contains 30 databases which are in full recovery mode. One other option would be to take a full backup, restore in cloud and later restore a differential one. But this might take some time. I would love the minimize the downtime that's why I thought about the replica/mirror way. What are my options and riks at this point?
2015/05/20
[ "https://dba.stackexchange.com/questions/102045", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/39636/" ]
1. Create dummy, empty tables on the local server so that the procedure creation can happen. 2. Change the procedure code to use two-part synonyms. On the server that needs to use the linked server: ``` CREATE SYNONYM dbo.whatever FOR linkedserver.dbo.whatever; ``` On the local server that doesn't need the remote references to exist: ``` CREATE SYNONYM dbo.whatever FOR dbo.emptydummytable; ``` The stored procedure using the latter can be created thanks to deferred name resolution (which doesn't work when creating a procedure that references a linked server). This will require changing the stored procedure code, but it will be a one-time change.
you can create a linked server that goes nowhere ``` EXEC master.dbo.sp_addlinkedserver @server = N'THISSERVERNAME', @srvproduct=N'', @provider=N'SQLNCLI' ``` Then any queries notice that the linked server is there, but has no access to anything within it. you'll find quite often that the queries for linked servers(as far as I'm aware) just check for the linked server (since you're declaring it as not as SQL database it doesn't seem to check in as much detail it presumes you know what you're doing (If you do it in the GUI you will get an warning but can still create the linked server without it registering that it can connect. Not sure if this is an acceptable workaround for what you're after since you are actually creating a linked server, but it is essentially a dummy as it goes nowhere, if you ever tried to access it you'd get a login error
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
Node.js Package [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) should work well. I have been using the [Grunt package of that](https://www.npmjs.org/package/grunt-markdown-pdf), but just for the sake of a good answer I just quickly ran the the original via the [command line](https://www.npmjs.org/package/markdown-pdf#cli-interface); and yeap it works great. So to use the CLI of [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) just: 1. Install [Node.js](http://nodejs.org) (if necessary) 2. Install [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) - from cmdline just run `npm install -g markdown-pdf` 3. run `markdown-pdf -o readme.pdf readme.md` (or whatever source and destination and other options you want; see [CLI Options](https://www.npmjs.org/package/markdown-pdf#cli-interface) for all the details of what you can specify). It is Open-Source (MIT licenced), and has a [Github repo](https://github.com/alanshaw/markdown-pdf), it is free and as far as I've found it is is quite fast. There may be a slight problem with getting images from https:// domains but I haven't investigated what is up there - one of my images is not being loaded so this is *most likely* just something funny in my md but there is a **slight** chance that is a bug. One **significant** bug: clickable links are not created.
To build on @nick-wilde's solution, if you are using grunt there are plugins for both marked and wkhtmltopdf: * [grunt-marked](https://github.com/gobwas/grunt-marked) * [grunt-wkhtmltopdf](https://github.com/dharFr/grunt-wkhtmltopdf) **After installing the main `wkhtmltopdf` binary** you can then install the plugins using npm: ``` npm install grunt-marked --save-dev npm install grunt-wkhtmltopdf --save-dev ``` Then use something like this in your `Gruntfile.js`: ``` marked: { std : { files: { 'out.html' : ['src.md'] } } }, wkhtmltopdf: { std : { src: 'out.html', dest: 'out.pdf' } }, ``` Then in your build you just call the two in succession: ``` grunt.registerTask('build', ['marked', 'wkhtmltopdf']); ``` If you want it to look pretty, you'll have to fiddle more with the `marked` settings, but I'm sure it's doable.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I've investigated another option. Compared to [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf): * Pros: + Actually makes proper links. + Actually slightly quicker to run * Cons: + Not as "pretty" - except for the links everything looks nicer with Markdown-PDF. This would be easily fixable by adding some CSS to the HTML before PDF generation though\*. + Installation is more complicated. This is also a [Nodejs](http://nodejs.org) based solution which uses the [Marked](https://www.npmjs.org/package/marked) and [wkhtmltopdf](https://www.npmjs.org/package/wkhtmltopdf) node packages. Installation: ------------- * Install [Nodejs](http://nodejs.org). * Install [Marked](https://www.npmjs.org/package/marked) - easiest via commandline: `npm -g install marked` * Install [wkhtmltopdf NPM](https://www.npmjs.org/package/wkhtmltopdf) - easiest via commandline: `npm -g install wkhtmltopdf` * Install [wkhtmltopdf main files](http://wkhtmltopdf.org/downloads.html) - no installer available. * Add wkhtmltopdf bin directory to the PATH Usage: ------ To use takes two CLI calls. You can of course just save this as a batch file and run that. ``` marked input.md -o output.html wkhtmltopdf input.html output.pdf ``` \* Because of the links working I may switch to this method instead of [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) in which case I'll likely write a wrapper to add some CSS (with an option to add a sensible default or user defined). The wrapper would also make it one call instead of two for running and probably could make it one npm install cmd instead of the manual install. If/when I do that I'll share that here.
I just convert from HTML instead. This works for my needs: <https://github.com/dompdf/dompdf> I found that in general Markdown is not a good format to convert to PDF, as it doesnt have native CSS support. Here is the script I use: ``` <?php require 'dompdf/autoload.inc.php'; use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf->getOptions()->setIsFontSubsettingEnabled(true); $get = file_get_contents('index.html'); $dompdf->loadHtml($get); $dompdf->render(); $put = $dompdf->output(); file_put_contents('index.pdf', $put); ``` This solution just needs PHP (25 MB) and DomPdf (4 MB), so quite lightweight compared to other options.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I just convert from HTML instead. This works for my needs: <https://github.com/dompdf/dompdf> I found that in general Markdown is not a good format to convert to PDF, as it doesnt have native CSS support. Here is the script I use: ``` <?php require 'dompdf/autoload.inc.php'; use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf->getOptions()->setIsFontSubsettingEnabled(true); $get = file_get_contents('index.html'); $dompdf->loadHtml($get); $dompdf->render(); $put = $dompdf->output(); file_put_contents('index.pdf', $put); ``` This solution just needs PHP (25 MB) and DomPdf (4 MB), so quite lightweight compared to other options.
To build on @nick-wilde's solution, if you are using grunt there are plugins for both marked and wkhtmltopdf: * [grunt-marked](https://github.com/gobwas/grunt-marked) * [grunt-wkhtmltopdf](https://github.com/dharFr/grunt-wkhtmltopdf) **After installing the main `wkhtmltopdf` binary** you can then install the plugins using npm: ``` npm install grunt-marked --save-dev npm install grunt-wkhtmltopdf --save-dev ``` Then use something like this in your `Gruntfile.js`: ``` marked: { std : { files: { 'out.html' : ['src.md'] } } }, wkhtmltopdf: { std : { src: 'out.html', dest: 'out.pdf' } }, ``` Then in your build you just call the two in succession: ``` grunt.registerTask('build', ['marked', 'wkhtmltopdf']); ``` If you want it to look pretty, you'll have to fiddle more with the `marked` settings, but I'm sure it's doable.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I've investigated another option. Compared to [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf): * Pros: + Actually makes proper links. + Actually slightly quicker to run * Cons: + Not as "pretty" - except for the links everything looks nicer with Markdown-PDF. This would be easily fixable by adding some CSS to the HTML before PDF generation though\*. + Installation is more complicated. This is also a [Nodejs](http://nodejs.org) based solution which uses the [Marked](https://www.npmjs.org/package/marked) and [wkhtmltopdf](https://www.npmjs.org/package/wkhtmltopdf) node packages. Installation: ------------- * Install [Nodejs](http://nodejs.org). * Install [Marked](https://www.npmjs.org/package/marked) - easiest via commandline: `npm -g install marked` * Install [wkhtmltopdf NPM](https://www.npmjs.org/package/wkhtmltopdf) - easiest via commandline: `npm -g install wkhtmltopdf` * Install [wkhtmltopdf main files](http://wkhtmltopdf.org/downloads.html) - no installer available. * Add wkhtmltopdf bin directory to the PATH Usage: ------ To use takes two CLI calls. You can of course just save this as a batch file and run that. ``` marked input.md -o output.html wkhtmltopdf input.html output.pdf ``` \* Because of the links working I may switch to this method instead of [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) in which case I'll likely write a wrapper to add some CSS (with an option to add a sensible default or user defined). The wrapper would also make it one call instead of two for running and probably could make it one npm install cmd instead of the manual install. If/when I do that I'll share that here.
To build on @nick-wilde's solution, if you are using grunt there are plugins for both marked and wkhtmltopdf: * [grunt-marked](https://github.com/gobwas/grunt-marked) * [grunt-wkhtmltopdf](https://github.com/dharFr/grunt-wkhtmltopdf) **After installing the main `wkhtmltopdf` binary** you can then install the plugins using npm: ``` npm install grunt-marked --save-dev npm install grunt-wkhtmltopdf --save-dev ``` Then use something like this in your `Gruntfile.js`: ``` marked: { std : { files: { 'out.html' : ['src.md'] } } }, wkhtmltopdf: { std : { src: 'out.html', dest: 'out.pdf' } }, ``` Then in your build you just call the two in succession: ``` grunt.registerTask('build', ['marked', 'wkhtmltopdf']); ``` If you want it to look pretty, you'll have to fiddle more with the `marked` settings, but I'm sure it's doable.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I personally am a huge fan of **[`pandoc`](http://pandoc.org/)**. Pandoc is the "swiss-army" knife tool of format conversions: * Its core source ***input format*** supported is `Markdown` (including any of the major MD "dialects" such as the flavors of GitHub and PHP plus several special extensions). Other input formats are: `HTML`, `rST`, `Textile`, `DocBook XML`, `MediaWiki`. * As ***output formats*** it supports: `ConTeXt`, `LaTeX`, **`PDF`** and `Beamer PDF` (albeit requiring *LaTeX* in the background), `MediaWiki`, `DOCX`, `DocBook`, `rST`, `Textile`, `ASCIIDoc`, `texinfo`, `org` (Emacs Org-mode), `S5` (HTML slides), `Slidy` (HTML slides), `Slideous` (HTML slides), `ImpressJS` (HTML slides), `DZSlides` (HTML slides), `HTML`, `HTML5`, `EPUB`, `EPUB3` ...and: `manpage` (GROFF manpage) and `ODT` (OpenDocument Text). Are you still with me? Good. Did you notice the last two, `manpage` and `ODT`? Well, these are the two output formats which I personally "abuse" as intermediate formats in order to arrive at PDF for final documents when I do not want LaTeX involved. I've automated my workflow and process chain with the help of a *Makefile*. So I just need to type `make mydoc.latexpdf`, or `make mydoc.odtpdf`, or `make mydoc.manpdf`. The Makefile is set up to look for an input of `mydoc.mmd`, and then it sets the appropriate commands in motion: `pandoc` to create the PDF directly (which in the background first converts to LaTeX and then runs `pdflatex` itself), ODT or manpage. Then the next command is to create the final format: * For my ***`.odtpdf`*** target it runs ***LibreOffice*** in headless mode. Here are the basic command lines I use for the (I'm on OS X, so for Linux or Windows you'll have to adapt paths accordingly). Attention, command is in Makefile syntax -- cannot be directly used in Shell without prior adaption: ``` (cd /Applications/LibreOffice.app/Contents/MacOS; \ ./soffice "-env:UserInstallation=file:///tmp/LibO_Conversion__$(USER)" \ --headless \ --convert-to pdf:writer_pdf_Export \ --outdir $(CURRDIR)/$(FINAL) $(CURRDIR)/$(BUILD)/$(subst .odtpdf,.odt,$@) ; \ cd - ; ) ``` * For my ***`.manpdf`*** target it uses `man -t` to create PostScript from Pandoc's manpage output file, then uses Ghostscript to create the PDF. It therefore runs: ``` man -t <pandoc's manpage output file> \ | gs -o ${HOME}/<pandoc-sourcedoc-name>.pdf -sDEVICE=pdfwrite - ``` Customize the *look'n'feel* of your ODT output ---------------------------------------------- The non-LaTeX path to PDF via ODT is the most "sexy" for me... * **...because Pandoc knows how to apply some nice personalized styles to a target ODT if only these styles are properly defined in a `myreference.odt` !** (These styles will of course then transfer to the PDF too.) I can then run the Pandoc command (via Makefile or in the Shell) to create an ODT to my likings, complete with the font faces, sizes and colors I prefer, with the page sizes and page headers, footers or backgrounds I defined (again: Makefile syntax!): ``` pandoc \ --toc \ --toc-depth=4 \ --to=odt \ --chapters \ --filter=pandoc-citeproc \ --standalone \ --reference-odt=$(RESOURCES)/myreference.odt \ --from=markdown+mmd_title_block+pipe_tables+grid_tables+tex_math_dollars+raw_tex+footnotes+inline_notes+citations+link_attributes \ --bibliography=$(RESOURCES)/my.bib \ --csl=$(RESOURCES)/kp.csl \ --number-sections \ --output=./$(BUILD)/$@ \ $< ``` The `--from=markdown+...+...+` parameter tells Pandoc to accept several Markdown syntax *extensions* which I like to use in my MD source files. The sweet secret to get the styles in the ODT document lies with the `--reference-odt=/path/to/myreference.odt` command line parameter. The ODT output works with references and bibliography even *(if your Markdown input is properly written for this)*! --- Using Windows? -------------- In principle, this workflow should work on Windows too, because Pandoc also runs on Windows. I have run Pandoc on Windows before, but I have not myself setup a completely automatic workflow, first **"`Pandoc`: *Markdown -> ODT*"**, then **"`.\soffice`: *ODT-> PDF*"** based on a Makefile here, though... But you may want to ***explore another path on Windows***: * create a DOCX output from Pandoc first; * then convert the DOCX to PDF (automatically or interactively via WinWord). Yes, you can also customize the styles of the DOCX output files by using the `--reference-docx=my-reference.docx` switch. Just create a `my-reference.docx` file first which uses exactly the styles you want. Pandoc will then extract these from the reference doc and apply them to the output DOCX it generates! From there, you can look how to convert the intermediate DOCX file to PDF. This can also be done automatically: you may also want to consider **[OfficeToPDF.exe](https://officetopdf.codeplex.com/releases/view/612089)**. It is hosted on CodePlex, licensed with the Apache 2.0 License and available in binary and in source code. ***Finally: be sure to use the latest and greatest version of Pandoc (currently [v1.17.0.3 or later](http://pandoc.org/releases.html)) -- there have been a lot of features added in recent months, esp. when it comes to DOCX output!***
To build on @nick-wilde's solution, if you are using grunt there are plugins for both marked and wkhtmltopdf: * [grunt-marked](https://github.com/gobwas/grunt-marked) * [grunt-wkhtmltopdf](https://github.com/dharFr/grunt-wkhtmltopdf) **After installing the main `wkhtmltopdf` binary** you can then install the plugins using npm: ``` npm install grunt-marked --save-dev npm install grunt-wkhtmltopdf --save-dev ``` Then use something like this in your `Gruntfile.js`: ``` marked: { std : { files: { 'out.html' : ['src.md'] } } }, wkhtmltopdf: { std : { src: 'out.html', dest: 'out.pdf' } }, ``` Then in your build you just call the two in succession: ``` grunt.registerTask('build', ['marked', 'wkhtmltopdf']); ``` If you want it to look pretty, you'll have to fiddle more with the `marked` settings, but I'm sure it's doable.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I just convert from HTML instead. This works for my needs: <https://github.com/dompdf/dompdf> I found that in general Markdown is not a good format to convert to PDF, as it doesnt have native CSS support. Here is the script I use: ``` <?php require 'dompdf/autoload.inc.php'; use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf->getOptions()->setIsFontSubsettingEnabled(true); $get = file_get_contents('index.html'); $dompdf->loadHtml($get); $dompdf->render(); $put = $dompdf->output(); file_put_contents('index.pdf', $put); ``` This solution just needs PHP (25 MB) and DomPdf (4 MB), so quite lightweight compared to other options.
I have recently created a service to convert markdown documents to PDF. It supports GitHub flavoured markdown as well as syntax highlighting. The service is located at: <http://markdown2pdf.com>
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I personally am a huge fan of **[`pandoc`](http://pandoc.org/)**. Pandoc is the "swiss-army" knife tool of format conversions: * Its core source ***input format*** supported is `Markdown` (including any of the major MD "dialects" such as the flavors of GitHub and PHP plus several special extensions). Other input formats are: `HTML`, `rST`, `Textile`, `DocBook XML`, `MediaWiki`. * As ***output formats*** it supports: `ConTeXt`, `LaTeX`, **`PDF`** and `Beamer PDF` (albeit requiring *LaTeX* in the background), `MediaWiki`, `DOCX`, `DocBook`, `rST`, `Textile`, `ASCIIDoc`, `texinfo`, `org` (Emacs Org-mode), `S5` (HTML slides), `Slidy` (HTML slides), `Slideous` (HTML slides), `ImpressJS` (HTML slides), `DZSlides` (HTML slides), `HTML`, `HTML5`, `EPUB`, `EPUB3` ...and: `manpage` (GROFF manpage) and `ODT` (OpenDocument Text). Are you still with me? Good. Did you notice the last two, `manpage` and `ODT`? Well, these are the two output formats which I personally "abuse" as intermediate formats in order to arrive at PDF for final documents when I do not want LaTeX involved. I've automated my workflow and process chain with the help of a *Makefile*. So I just need to type `make mydoc.latexpdf`, or `make mydoc.odtpdf`, or `make mydoc.manpdf`. The Makefile is set up to look for an input of `mydoc.mmd`, and then it sets the appropriate commands in motion: `pandoc` to create the PDF directly (which in the background first converts to LaTeX and then runs `pdflatex` itself), ODT or manpage. Then the next command is to create the final format: * For my ***`.odtpdf`*** target it runs ***LibreOffice*** in headless mode. Here are the basic command lines I use for the (I'm on OS X, so for Linux or Windows you'll have to adapt paths accordingly). Attention, command is in Makefile syntax -- cannot be directly used in Shell without prior adaption: ``` (cd /Applications/LibreOffice.app/Contents/MacOS; \ ./soffice "-env:UserInstallation=file:///tmp/LibO_Conversion__$(USER)" \ --headless \ --convert-to pdf:writer_pdf_Export \ --outdir $(CURRDIR)/$(FINAL) $(CURRDIR)/$(BUILD)/$(subst .odtpdf,.odt,$@) ; \ cd - ; ) ``` * For my ***`.manpdf`*** target it uses `man -t` to create PostScript from Pandoc's manpage output file, then uses Ghostscript to create the PDF. It therefore runs: ``` man -t <pandoc's manpage output file> \ | gs -o ${HOME}/<pandoc-sourcedoc-name>.pdf -sDEVICE=pdfwrite - ``` Customize the *look'n'feel* of your ODT output ---------------------------------------------- The non-LaTeX path to PDF via ODT is the most "sexy" for me... * **...because Pandoc knows how to apply some nice personalized styles to a target ODT if only these styles are properly defined in a `myreference.odt` !** (These styles will of course then transfer to the PDF too.) I can then run the Pandoc command (via Makefile or in the Shell) to create an ODT to my likings, complete with the font faces, sizes and colors I prefer, with the page sizes and page headers, footers or backgrounds I defined (again: Makefile syntax!): ``` pandoc \ --toc \ --toc-depth=4 \ --to=odt \ --chapters \ --filter=pandoc-citeproc \ --standalone \ --reference-odt=$(RESOURCES)/myreference.odt \ --from=markdown+mmd_title_block+pipe_tables+grid_tables+tex_math_dollars+raw_tex+footnotes+inline_notes+citations+link_attributes \ --bibliography=$(RESOURCES)/my.bib \ --csl=$(RESOURCES)/kp.csl \ --number-sections \ --output=./$(BUILD)/$@ \ $< ``` The `--from=markdown+...+...+` parameter tells Pandoc to accept several Markdown syntax *extensions* which I like to use in my MD source files. The sweet secret to get the styles in the ODT document lies with the `--reference-odt=/path/to/myreference.odt` command line parameter. The ODT output works with references and bibliography even *(if your Markdown input is properly written for this)*! --- Using Windows? -------------- In principle, this workflow should work on Windows too, because Pandoc also runs on Windows. I have run Pandoc on Windows before, but I have not myself setup a completely automatic workflow, first **"`Pandoc`: *Markdown -> ODT*"**, then **"`.\soffice`: *ODT-> PDF*"** based on a Makefile here, though... But you may want to ***explore another path on Windows***: * create a DOCX output from Pandoc first; * then convert the DOCX to PDF (automatically or interactively via WinWord). Yes, you can also customize the styles of the DOCX output files by using the `--reference-docx=my-reference.docx` switch. Just create a `my-reference.docx` file first which uses exactly the styles you want. Pandoc will then extract these from the reference doc and apply them to the output DOCX it generates! From there, you can look how to convert the intermediate DOCX file to PDF. This can also be done automatically: you may also want to consider **[OfficeToPDF.exe](https://officetopdf.codeplex.com/releases/view/612089)**. It is hosted on CodePlex, licensed with the Apache 2.0 License and available in binary and in source code. ***Finally: be sure to use the latest and greatest version of Pandoc (currently [v1.17.0.3 or later](http://pandoc.org/releases.html)) -- there have been a lot of features added in recent months, esp. when it comes to DOCX output!***
I just convert from HTML instead. This works for my needs: <https://github.com/dompdf/dompdf> I found that in general Markdown is not a good format to convert to PDF, as it doesnt have native CSS support. Here is the script I use: ``` <?php require 'dompdf/autoload.inc.php'; use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf->getOptions()->setIsFontSubsettingEnabled(true); $get = file_get_contents('index.html'); $dompdf->loadHtml($get); $dompdf->render(); $put = $dompdf->output(); file_put_contents('index.pdf', $put); ``` This solution just needs PHP (25 MB) and DomPdf (4 MB), so quite lightweight compared to other options.
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I personally am a huge fan of **[`pandoc`](http://pandoc.org/)**. Pandoc is the "swiss-army" knife tool of format conversions: * Its core source ***input format*** supported is `Markdown` (including any of the major MD "dialects" such as the flavors of GitHub and PHP plus several special extensions). Other input formats are: `HTML`, `rST`, `Textile`, `DocBook XML`, `MediaWiki`. * As ***output formats*** it supports: `ConTeXt`, `LaTeX`, **`PDF`** and `Beamer PDF` (albeit requiring *LaTeX* in the background), `MediaWiki`, `DOCX`, `DocBook`, `rST`, `Textile`, `ASCIIDoc`, `texinfo`, `org` (Emacs Org-mode), `S5` (HTML slides), `Slidy` (HTML slides), `Slideous` (HTML slides), `ImpressJS` (HTML slides), `DZSlides` (HTML slides), `HTML`, `HTML5`, `EPUB`, `EPUB3` ...and: `manpage` (GROFF manpage) and `ODT` (OpenDocument Text). Are you still with me? Good. Did you notice the last two, `manpage` and `ODT`? Well, these are the two output formats which I personally "abuse" as intermediate formats in order to arrive at PDF for final documents when I do not want LaTeX involved. I've automated my workflow and process chain with the help of a *Makefile*. So I just need to type `make mydoc.latexpdf`, or `make mydoc.odtpdf`, or `make mydoc.manpdf`. The Makefile is set up to look for an input of `mydoc.mmd`, and then it sets the appropriate commands in motion: `pandoc` to create the PDF directly (which in the background first converts to LaTeX and then runs `pdflatex` itself), ODT or manpage. Then the next command is to create the final format: * For my ***`.odtpdf`*** target it runs ***LibreOffice*** in headless mode. Here are the basic command lines I use for the (I'm on OS X, so for Linux or Windows you'll have to adapt paths accordingly). Attention, command is in Makefile syntax -- cannot be directly used in Shell without prior adaption: ``` (cd /Applications/LibreOffice.app/Contents/MacOS; \ ./soffice "-env:UserInstallation=file:///tmp/LibO_Conversion__$(USER)" \ --headless \ --convert-to pdf:writer_pdf_Export \ --outdir $(CURRDIR)/$(FINAL) $(CURRDIR)/$(BUILD)/$(subst .odtpdf,.odt,$@) ; \ cd - ; ) ``` * For my ***`.manpdf`*** target it uses `man -t` to create PostScript from Pandoc's manpage output file, then uses Ghostscript to create the PDF. It therefore runs: ``` man -t <pandoc's manpage output file> \ | gs -o ${HOME}/<pandoc-sourcedoc-name>.pdf -sDEVICE=pdfwrite - ``` Customize the *look'n'feel* of your ODT output ---------------------------------------------- The non-LaTeX path to PDF via ODT is the most "sexy" for me... * **...because Pandoc knows how to apply some nice personalized styles to a target ODT if only these styles are properly defined in a `myreference.odt` !** (These styles will of course then transfer to the PDF too.) I can then run the Pandoc command (via Makefile or in the Shell) to create an ODT to my likings, complete with the font faces, sizes and colors I prefer, with the page sizes and page headers, footers or backgrounds I defined (again: Makefile syntax!): ``` pandoc \ --toc \ --toc-depth=4 \ --to=odt \ --chapters \ --filter=pandoc-citeproc \ --standalone \ --reference-odt=$(RESOURCES)/myreference.odt \ --from=markdown+mmd_title_block+pipe_tables+grid_tables+tex_math_dollars+raw_tex+footnotes+inline_notes+citations+link_attributes \ --bibliography=$(RESOURCES)/my.bib \ --csl=$(RESOURCES)/kp.csl \ --number-sections \ --output=./$(BUILD)/$@ \ $< ``` The `--from=markdown+...+...+` parameter tells Pandoc to accept several Markdown syntax *extensions* which I like to use in my MD source files. The sweet secret to get the styles in the ODT document lies with the `--reference-odt=/path/to/myreference.odt` command line parameter. The ODT output works with references and bibliography even *(if your Markdown input is properly written for this)*! --- Using Windows? -------------- In principle, this workflow should work on Windows too, because Pandoc also runs on Windows. I have run Pandoc on Windows before, but I have not myself setup a completely automatic workflow, first **"`Pandoc`: *Markdown -> ODT*"**, then **"`.\soffice`: *ODT-> PDF*"** based on a Makefile here, though... But you may want to ***explore another path on Windows***: * create a DOCX output from Pandoc first; * then convert the DOCX to PDF (automatically or interactively via WinWord). Yes, you can also customize the styles of the DOCX output files by using the `--reference-docx=my-reference.docx` switch. Just create a `my-reference.docx` file first which uses exactly the styles you want. Pandoc will then extract these from the reference doc and apply them to the output DOCX it generates! From there, you can look how to convert the intermediate DOCX file to PDF. This can also be done automatically: you may also want to consider **[OfficeToPDF.exe](https://officetopdf.codeplex.com/releases/view/612089)**. It is hosted on CodePlex, licensed with the Apache 2.0 License and available in binary and in source code. ***Finally: be sure to use the latest and greatest version of Pandoc (currently [v1.17.0.3 or later](http://pandoc.org/releases.html)) -- there have been a lot of features added in recent months, esp. when it comes to DOCX output!***
I have recently created a service to convert markdown documents to PDF. It supports GitHub flavoured markdown as well as syntax highlighting. The service is located at: <http://markdown2pdf.com>
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
Node.js Package [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) should work well. I have been using the [Grunt package of that](https://www.npmjs.org/package/grunt-markdown-pdf), but just for the sake of a good answer I just quickly ran the the original via the [command line](https://www.npmjs.org/package/markdown-pdf#cli-interface); and yeap it works great. So to use the CLI of [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) just: 1. Install [Node.js](http://nodejs.org) (if necessary) 2. Install [Markdown-PDF](https://www.npmjs.org/package/markdown-pdf) - from cmdline just run `npm install -g markdown-pdf` 3. run `markdown-pdf -o readme.pdf readme.md` (or whatever source and destination and other options you want; see [CLI Options](https://www.npmjs.org/package/markdown-pdf#cli-interface) for all the details of what you can specify). It is Open-Source (MIT licenced), and has a [Github repo](https://github.com/alanshaw/markdown-pdf), it is free and as far as I've found it is is quite fast. There may be a slight problem with getting images from https:// domains but I haven't investigated what is up there - one of my images is not being loaded so this is *most likely* just something funny in my md but there is a **slight** chance that is a bug. One **significant** bug: clickable links are not created.
I personally am a huge fan of **[`pandoc`](http://pandoc.org/)**. Pandoc is the "swiss-army" knife tool of format conversions: * Its core source ***input format*** supported is `Markdown` (including any of the major MD "dialects" such as the flavors of GitHub and PHP plus several special extensions). Other input formats are: `HTML`, `rST`, `Textile`, `DocBook XML`, `MediaWiki`. * As ***output formats*** it supports: `ConTeXt`, `LaTeX`, **`PDF`** and `Beamer PDF` (albeit requiring *LaTeX* in the background), `MediaWiki`, `DOCX`, `DocBook`, `rST`, `Textile`, `ASCIIDoc`, `texinfo`, `org` (Emacs Org-mode), `S5` (HTML slides), `Slidy` (HTML slides), `Slideous` (HTML slides), `ImpressJS` (HTML slides), `DZSlides` (HTML slides), `HTML`, `HTML5`, `EPUB`, `EPUB3` ...and: `manpage` (GROFF manpage) and `ODT` (OpenDocument Text). Are you still with me? Good. Did you notice the last two, `manpage` and `ODT`? Well, these are the two output formats which I personally "abuse" as intermediate formats in order to arrive at PDF for final documents when I do not want LaTeX involved. I've automated my workflow and process chain with the help of a *Makefile*. So I just need to type `make mydoc.latexpdf`, or `make mydoc.odtpdf`, or `make mydoc.manpdf`. The Makefile is set up to look for an input of `mydoc.mmd`, and then it sets the appropriate commands in motion: `pandoc` to create the PDF directly (which in the background first converts to LaTeX and then runs `pdflatex` itself), ODT or manpage. Then the next command is to create the final format: * For my ***`.odtpdf`*** target it runs ***LibreOffice*** in headless mode. Here are the basic command lines I use for the (I'm on OS X, so for Linux or Windows you'll have to adapt paths accordingly). Attention, command is in Makefile syntax -- cannot be directly used in Shell without prior adaption: ``` (cd /Applications/LibreOffice.app/Contents/MacOS; \ ./soffice "-env:UserInstallation=file:///tmp/LibO_Conversion__$(USER)" \ --headless \ --convert-to pdf:writer_pdf_Export \ --outdir $(CURRDIR)/$(FINAL) $(CURRDIR)/$(BUILD)/$(subst .odtpdf,.odt,$@) ; \ cd - ; ) ``` * For my ***`.manpdf`*** target it uses `man -t` to create PostScript from Pandoc's manpage output file, then uses Ghostscript to create the PDF. It therefore runs: ``` man -t <pandoc's manpage output file> \ | gs -o ${HOME}/<pandoc-sourcedoc-name>.pdf -sDEVICE=pdfwrite - ``` Customize the *look'n'feel* of your ODT output ---------------------------------------------- The non-LaTeX path to PDF via ODT is the most "sexy" for me... * **...because Pandoc knows how to apply some nice personalized styles to a target ODT if only these styles are properly defined in a `myreference.odt` !** (These styles will of course then transfer to the PDF too.) I can then run the Pandoc command (via Makefile or in the Shell) to create an ODT to my likings, complete with the font faces, sizes and colors I prefer, with the page sizes and page headers, footers or backgrounds I defined (again: Makefile syntax!): ``` pandoc \ --toc \ --toc-depth=4 \ --to=odt \ --chapters \ --filter=pandoc-citeproc \ --standalone \ --reference-odt=$(RESOURCES)/myreference.odt \ --from=markdown+mmd_title_block+pipe_tables+grid_tables+tex_math_dollars+raw_tex+footnotes+inline_notes+citations+link_attributes \ --bibliography=$(RESOURCES)/my.bib \ --csl=$(RESOURCES)/kp.csl \ --number-sections \ --output=./$(BUILD)/$@ \ $< ``` The `--from=markdown+...+...+` parameter tells Pandoc to accept several Markdown syntax *extensions* which I like to use in my MD source files. The sweet secret to get the styles in the ODT document lies with the `--reference-odt=/path/to/myreference.odt` command line parameter. The ODT output works with references and bibliography even *(if your Markdown input is properly written for this)*! --- Using Windows? -------------- In principle, this workflow should work on Windows too, because Pandoc also runs on Windows. I have run Pandoc on Windows before, but I have not myself setup a completely automatic workflow, first **"`Pandoc`: *Markdown -> ODT*"**, then **"`.\soffice`: *ODT-> PDF*"** based on a Makefile here, though... But you may want to ***explore another path on Windows***: * create a DOCX output from Pandoc first; * then convert the DOCX to PDF (automatically or interactively via WinWord). Yes, you can also customize the styles of the DOCX output files by using the `--reference-docx=my-reference.docx` switch. Just create a `my-reference.docx` file first which uses exactly the styles you want. Pandoc will then extract these from the reference doc and apply them to the output DOCX it generates! From there, you can look how to convert the intermediate DOCX file to PDF. This can also be done automatically: you may also want to consider **[OfficeToPDF.exe](https://officetopdf.codeplex.com/releases/view/612089)**. It is hosted on CodePlex, licensed with the Apache 2.0 License and available in binary and in source code. ***Finally: be sure to use the latest and greatest version of Pandoc (currently [v1.17.0.3 or later](http://pandoc.org/releases.html)) -- there have been a lot of features added in recent months, esp. when it comes to DOCX output!***
3,588
Almost every existing md to PDF goes through LaTeX: kramdown, pandoc, multimarkdown, etc. Are there the options that don't, in any language, e.g. using a backend such as [Prawn](https://github.com/prawnpdf/prawn), [libharu](https://github.com/libharu/libharu) or [jsPDF](https://github.com/MrRio/jsPDF)? So far I have only found: * [asciidoctor-pdf](https://github.com/asciidoctor/asciidoctor-pdf) This Prawn based asciidoc converter is quite active and has a lot of stars. Markdown to Asciidoc with Pandoc and then this is the best option I've seen so far. It is not however perfect to the point of being professional production ready, in particular: + floats like code and image don't... float, so you get vertical whitespace on line breaks when you have large floats: <https://github.com/asciidoctor/asciidoctor-pdf/issues/353> + some lines have too few words, but they are still justified horizontally, which leads to too much white space between words. TODO find / create ticket. * [Gimli](https://github.com/walle/gimli), but it does not seem very active (last commit 7 months ago). Backend? * [markdown\_prawn](https://github.com/thehappygeek/markdown_prawn). Not many stars. Last commit 3 years ago. * [Kramdown Prawn experimental converter](https://github.com/gettalong/kramdown/issues/78). Experimental. * [cmarkpdf](https://github.com/jgm/cmarkpdf): CommonMark to PDF through libharu by @jgm. Experimental. * [Qt5 QPrinter](http://doc.qt.io/qt-5/qprinter.html). Used by the [Retext editor](http://sourceforge.net/p/retext/git/ci/41c9f8598f8ec16d4e76010da74076afb60438b6/tree/ReText/window.py#l1058) through the [PyQt5 Python API](https://pypi.python.org/pypi/PyQt5). TODO test. Likely to be analogous to a PhantomJS-like solution but for Qt instead of browser. If you can convert the HTML subset generated from Markdown to PDF well, then that is a solution, but I am yet to find a free software that does it properly. For example, PhantomJS conversions break markdown links `<http://a.com>`, which show as simple styled text on the PDF, not as clickable links that open on preferred browser, which are generated through LaTeX conversions. Non free possibilities: * [O'Reilly Atlas](http://atlas.oreilly.com/) is doing it for their HTMLBook (HTML5 subset), [but they're not gonna open source that anytime soon](http://forum.atlas.oreilly.com/t/is-is-possible-to-compile-books-locally/11). * [Prince XML](http://www.princexml.com/download/). Free for non-commercial use. Related: Ruby only [SO question](https://stackoverflow.com/questions/4377849/how-to-generate-pdf-from-markdown-using-pure-ruby). Why I want this: LaTeX is slow, produces horrible error messages, is hard to install, and is overly complex for the small subset needed for Markdown. Partial solutions: * Sphinx allows RST to PDF with <https://code.google.com/p/rst2pdf/> which uses <https://bitbucket.org/rptlab/reportlab> on the backend.
2014/04/25
[ "https://softwarerecs.stackexchange.com/questions/3588", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/2066/" ]
I personally am a huge fan of **[`pandoc`](http://pandoc.org/)**. Pandoc is the "swiss-army" knife tool of format conversions: * Its core source ***input format*** supported is `Markdown` (including any of the major MD "dialects" such as the flavors of GitHub and PHP plus several special extensions). Other input formats are: `HTML`, `rST`, `Textile`, `DocBook XML`, `MediaWiki`. * As ***output formats*** it supports: `ConTeXt`, `LaTeX`, **`PDF`** and `Beamer PDF` (albeit requiring *LaTeX* in the background), `MediaWiki`, `DOCX`, `DocBook`, `rST`, `Textile`, `ASCIIDoc`, `texinfo`, `org` (Emacs Org-mode), `S5` (HTML slides), `Slidy` (HTML slides), `Slideous` (HTML slides), `ImpressJS` (HTML slides), `DZSlides` (HTML slides), `HTML`, `HTML5`, `EPUB`, `EPUB3` ...and: `manpage` (GROFF manpage) and `ODT` (OpenDocument Text). Are you still with me? Good. Did you notice the last two, `manpage` and `ODT`? Well, these are the two output formats which I personally "abuse" as intermediate formats in order to arrive at PDF for final documents when I do not want LaTeX involved. I've automated my workflow and process chain with the help of a *Makefile*. So I just need to type `make mydoc.latexpdf`, or `make mydoc.odtpdf`, or `make mydoc.manpdf`. The Makefile is set up to look for an input of `mydoc.mmd`, and then it sets the appropriate commands in motion: `pandoc` to create the PDF directly (which in the background first converts to LaTeX and then runs `pdflatex` itself), ODT or manpage. Then the next command is to create the final format: * For my ***`.odtpdf`*** target it runs ***LibreOffice*** in headless mode. Here are the basic command lines I use for the (I'm on OS X, so for Linux or Windows you'll have to adapt paths accordingly). Attention, command is in Makefile syntax -- cannot be directly used in Shell without prior adaption: ``` (cd /Applications/LibreOffice.app/Contents/MacOS; \ ./soffice "-env:UserInstallation=file:///tmp/LibO_Conversion__$(USER)" \ --headless \ --convert-to pdf:writer_pdf_Export \ --outdir $(CURRDIR)/$(FINAL) $(CURRDIR)/$(BUILD)/$(subst .odtpdf,.odt,$@) ; \ cd - ; ) ``` * For my ***`.manpdf`*** target it uses `man -t` to create PostScript from Pandoc's manpage output file, then uses Ghostscript to create the PDF. It therefore runs: ``` man -t <pandoc's manpage output file> \ | gs -o ${HOME}/<pandoc-sourcedoc-name>.pdf -sDEVICE=pdfwrite - ``` Customize the *look'n'feel* of your ODT output ---------------------------------------------- The non-LaTeX path to PDF via ODT is the most "sexy" for me... * **...because Pandoc knows how to apply some nice personalized styles to a target ODT if only these styles are properly defined in a `myreference.odt` !** (These styles will of course then transfer to the PDF too.) I can then run the Pandoc command (via Makefile or in the Shell) to create an ODT to my likings, complete with the font faces, sizes and colors I prefer, with the page sizes and page headers, footers or backgrounds I defined (again: Makefile syntax!): ``` pandoc \ --toc \ --toc-depth=4 \ --to=odt \ --chapters \ --filter=pandoc-citeproc \ --standalone \ --reference-odt=$(RESOURCES)/myreference.odt \ --from=markdown+mmd_title_block+pipe_tables+grid_tables+tex_math_dollars+raw_tex+footnotes+inline_notes+citations+link_attributes \ --bibliography=$(RESOURCES)/my.bib \ --csl=$(RESOURCES)/kp.csl \ --number-sections \ --output=./$(BUILD)/$@ \ $< ``` The `--from=markdown+...+...+` parameter tells Pandoc to accept several Markdown syntax *extensions* which I like to use in my MD source files. The sweet secret to get the styles in the ODT document lies with the `--reference-odt=/path/to/myreference.odt` command line parameter. The ODT output works with references and bibliography even *(if your Markdown input is properly written for this)*! --- Using Windows? -------------- In principle, this workflow should work on Windows too, because Pandoc also runs on Windows. I have run Pandoc on Windows before, but I have not myself setup a completely automatic workflow, first **"`Pandoc`: *Markdown -> ODT*"**, then **"`.\soffice`: *ODT-> PDF*"** based on a Makefile here, though... But you may want to ***explore another path on Windows***: * create a DOCX output from Pandoc first; * then convert the DOCX to PDF (automatically or interactively via WinWord). Yes, you can also customize the styles of the DOCX output files by using the `--reference-docx=my-reference.docx` switch. Just create a `my-reference.docx` file first which uses exactly the styles you want. Pandoc will then extract these from the reference doc and apply them to the output DOCX it generates! From there, you can look how to convert the intermediate DOCX file to PDF. This can also be done automatically: you may also want to consider **[OfficeToPDF.exe](https://officetopdf.codeplex.com/releases/view/612089)**. It is hosted on CodePlex, licensed with the Apache 2.0 License and available in binary and in source code. ***Finally: be sure to use the latest and greatest version of Pandoc (currently [v1.17.0.3 or later](http://pandoc.org/releases.html)) -- there have been a lot of features added in recent months, esp. when it comes to DOCX output!***
It's not sexy, but [AbiWord](http://abisource.com/) will convert HTML to PDF. So, assuming you've got abiword installed: ``` markdown some.md > some.html abiword -t pdf -o some.pdf some.html ```
65,176,858
We have a situation that I have been able to recreate with the following simple example. I have the following two sample tables: ``` CREATE TABLE contact_info ( id INT UNSIGNED AUTO_INCREMENT, priContactId INT, secContactId INT, blahBlah VARCHAR(32), PRIMARY KEY(id) ); ``` and ``` CREATE TABLE name_lookup ( id INT UNSIGNED AUTO_INCREMENT, contactID INT, contactName VARCHAR(32), PRIMARY KEY(id) ); ``` I populate them as follows: ``` INSERT INTO contact_info(priContactId, secContactId, blahBlah) VALUES(1, 3, "Team A"), (4, 2, "Team B"); INSERT INTO name_lookup(contactID, contactName) VALUES(1, "John Doe"), (2, "Mary Smith"), (3, "Jose Garcia"), (4, "Larry Brown"); ``` Obviously, the contents of the tables are as follows: ``` +----+--------------+--------------+----------+ | id | priContactId | secContactId | blahBlah | +----+--------------+--------------+----------+ | 1 | 1 | 3 | Team A | | 2 | 4 | 2 | Team B | +----+--------------+--------------+----------+ +----+-----------+-------------+ | id | contactID | contactName | +----+-----------+-------------+ | 1 | 1 | John Doe | | 2 | 2 | Mary Smith | | 3 | 3 | Jose Garcia | | 4 | 4 | Larry Brown | +----+-----------+-------------+ ``` We would like to perform a JOIN operation so that we get output like this: ``` +-------------+-------------+--------+ | John Doe | Jose Garcia | Team A | +-------------+-------------+--------+ | Larry Brown | Mary Smith | Team B | +-------------+-------------+--------+ ``` The join constraints for both the `priContactId` and `secContactId` columns are the same and I am having tough time figuring out what the JOIN query should look like. FYI, we are using MySQL version `5.6.49`.
2020/12/07
[ "https://Stackoverflow.com/questions/65176858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5651468/" ]
As has been explained in comments, it looks like your compiler's C runtime library has a bad rand function. But you're not using C, you're using C++! Starting at C++11, you have all sorts of random-number generation facilities available in the C++ standard library. ``` #include <iostream> #include <string> #include <random> int main() { std::random_device eng; // or any other type of engine using dist_params = typename std::uniform_int_distribution<int>::param_type; int max = 99; std::uniform_int_distribution<int> dist (0, max); for (int a = 0; a < 7; a++) { int i = dist(eng); std::cout << i << ' '; dist.param(dist_params{0, max}); } std::cout << '\n'; return 0; } ``` Or, what I expect you were really going for: ``` #include <iostream> #include <string> #include <random> #include <time.h> int main() { std::string bag0 = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ"; std::random_device eng; time_t t; using dist_params = typename std::uniform_int_distribution<size_t>::param_type; std::uniform_int_distribution<size_t> dist; for (auto j = 0; j<100; ++j) { auto bag = bag0; for (int a = 0; a < 7; a++) { dist.param(dist_params{0, (bag.length())-1}); int i = dist(eng); std::cout << bag[i] << ' '; bag.erase(i, 1); } std::cout << '\n'; } return 0; } ``` The only caveat is that `random_device` may not produce random numbers on your platform.
`rand()` or `std::rand()` never generates **true** random number. It generates **pseudo-random** numbers. This is because computers are unable to generate truly random numbers itself, it requires assistance. Let's say you pressed a key exactly 2.054 seconds after the previous keypress. This is truly a random number. Computers use this data to generate truly random numbers. `rand()` or `std::rand()` generates a pseudo-random number, so needs to be seeded (with `srand()` or `std::srand()`). If the number you used to seed isn't random, the output wouldn't be random too. Moreover, you are using `time()` (or `std::time()`) which returns an `int` holding the number of seconds passed since epoch. So if you execute the program multiple times too rapidly, the seed would be the same and the output too. It also seems that your standard library a bad `rand()` or `std::rand()` function. ### Example: Output of the program (compiled from your code) executed 10 times rapidly (environment: Ubuntu, bash): ``` $ for i in {0..9} ; do ./a.out ; done 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 50 11 3 60 36 17 42 ``` ### What to do? I can suggest you use another time function to seed, which outputs time in milliseconds (or even nanoseconds) or get your own random number generator. See [this article](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) to know how pseudo-random number generators work. This will also help you to build your own as it seems that your standard library gives a bad `rand()` or `std::rand()` function.
18,259,012
I'm trying to open a URL in Python that needs username and password. My specific implementation looks like this: ``` http://char_user:char_pwd@casfcddb.example.com/...... ``` I get the following error spit to the console: ``` httplib.InvalidURL: nonnumeric port: 'char_pwd@casfcddb.example.com' ``` I'm using urllib2.urlopen, but the error is implying it doesn't understand the user credentials. That it sees the ":" and expects a port number rather than the password and actual address. Any ideas what I'm doing wrong here?
2013/08/15
[ "https://Stackoverflow.com/questions/18259012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578210/" ]
Use BasicAuthHandler for providing the password instead: ``` import urllib2 passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, "http://casfcddb.xxx.com", "char_user", "char_pwd") auth_handler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) urllib2.urlopen("http://casfcddb.xxx.com") ``` or using the requests library: ``` import requests requests.get("http://casfcddb.xxx.com", auth=('char_user', 'char_pwd')) ```
I ran into a situation where I needed BasicAuth handling and only had urllib available (no urllib2 or requests). The answer from Uku mostly worked, but here are my mods: ``` import urllib.request url = 'https://your/url.xxx' username = 'username' password = 'password' passman = urllib.request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, username, password) auth_handler = urllib.request.HTTPBasicAuthHandler(passman) opener = urllib.request.build_opener(auth_handler) urllib.request.install_opener(opener) resp = urllib.request.urlopen(url) data = resp.read() ```
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
Yes of course. Read on GROUP BY and aggregate functions. e.g. ``` SELECT col1, col2, SUM(col3) FROM table GROUP BY col1, col2 ```
Yes, add them to GROUP BY clause.
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
You should use the [group by statement](http://www.w3schools.com/sql/sql_groupby.asp). > > The GROUP BY statement is used in > conjunction with the aggregate > functions to group the result-set by > one or more columns. > > > For example: ``` SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ``` You can see a complete example [here](http://www.w3schools.com/sql/sql_groupby.asp).
Yes, add them to GROUP BY clause.
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
Yes of course. Read on GROUP BY and aggregate functions. e.g. ``` SELECT col1, col2, SUM(col3) FROM table GROUP BY col1, col2 ```
If you GROUP BY some fields, you can show those fields, and aggregate others; e.g.: ``` SELECT colA, colB, SUM(colC) FROM TheTable GROUP BY colA, colB ``` aggregation can be by SUM, MIN, MAX, etc.
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
You should use the [group by statement](http://www.w3schools.com/sql/sql_groupby.asp). > > The GROUP BY statement is used in > conjunction with the aggregate > functions to group the result-set by > one or more columns. > > > For example: ``` SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ``` You can see a complete example [here](http://www.w3schools.com/sql/sql_groupby.asp).
If you GROUP BY some fields, you can show those fields, and aggregate others; e.g.: ``` SELECT colA, colB, SUM(colC) FROM TheTable GROUP BY colA, colB ``` aggregation can be by SUM, MIN, MAX, etc.
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
Yes of course. Read on GROUP BY and aggregate functions. e.g. ``` SELECT col1, col2, SUM(col3) FROM table GROUP BY col1, col2 ```
You can show ordinary columns or expressions based on ordinary columns, but only if they are included in the set of columns/expressions you are agregating over ( what is listed in Group By clause ).
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
You should use the [group by statement](http://www.w3schools.com/sql/sql_groupby.asp). > > The GROUP BY statement is used in > conjunction with the aggregate > functions to group the result-set by > one or more columns. > > > For example: ``` SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ``` You can see a complete example [here](http://www.w3schools.com/sql/sql_groupby.asp).
Yes of course. Read on GROUP BY and aggregate functions. e.g. ``` SELECT col1, col2, SUM(col3) FROM table GROUP BY col1, col2 ```
1,249,125
Is it possible for a SQL query to return some normal columns and some aggregate ones? like : ``` Col_A | Col_B | SUM ------+-------+------ 5 | 6 | 7 ```
2009/08/08
[ "https://Stackoverflow.com/questions/1249125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95511/" ]
You should use the [group by statement](http://www.w3schools.com/sql/sql_groupby.asp). > > The GROUP BY statement is used in > conjunction with the aggregate > functions to group the result-set by > one or more columns. > > > For example: ``` SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ``` You can see a complete example [here](http://www.w3schools.com/sql/sql_groupby.asp).
You can show ordinary columns or expressions based on ordinary columns, but only if they are included in the set of columns/expressions you are agregating over ( what is listed in Group By clause ).
63,584,271
Below is some dummy code of what I would like to achieve and my question is at the end.I would like to shuffle blocks of data frame (different sizes) in a list in Python. Thanks. Set up a dummy dictionary: ```py dummy = {"ID":[1,2,3,4,5,6,7,8,9,10], "Alphabet":["A","B","C","D","E","F","G","H","I","J"], "Fruit":["apple","banana","coconut","date","elephant apple","feijoa","guava","honeydew","ita palm","jack fruit"]} ``` Turn dictionary into data frame: ```py dummy_df = pd.DataFrame(dummy) ``` Create blocks of data frame with required size: ```py blocksize = [1,2,3,4] blocks = [] i = 0 for j in range(len(blocksize)): a = blocksize[j] blocks.append(dummy_df[i:i+a]) i += a blocks ``` Below is the output of "blocks". It is 4 blocks of data frame with size of 1-4 rows in a list: ``` [ ID Alphabet Fruit 0 1 A apple, ID Alphabet Fruit 1 2 B banana 2 3 C coconut, ID Alphabet Fruit 3 4 D date 4 5 E elephant apple 5 6 F feijoa, ID Alphabet Fruit 6 7 G guava 7 8 H honeydew 8 9 I ita palm 9 10 J jack fruit] ``` I am stuck after the above. I have tried many different things but kept getting errors. I would like to shuffle those blocks of data frame in the list, then combined them back into a dataframe. Below is an example of the shuffled output. How could I do this please? Example ideal output: ``` ID Alphabet Fruit 1 2 B banana 2 3 C coconut 0 1 A apple 6 7 G guava 7 8 H honeydew 8 9 I ita palm 9 10 J jack fruit 3 4 D date 4 5 E elephant apple 5 6 F feijoa ```
2020/08/25
[ "https://Stackoverflow.com/questions/63584271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14165275/" ]
The real issue was because of colon symbol inside url ":", so url should start from dot and slash symbols "./": ``` @POST("./accounts:signInWithPassword") ``` Found this on github and it helps <https://github.com/square/retrofit/issues/2730> UPD: A little explanation why I used url like `"accounts/signInWithPassword"` with slash symbol inside instead of colon symbol: I tried with colon first, but got an error "Malformed url" so I dug a bit deeper with that mistake :)
You can add a header like this. But I think if you miss the header response, the error code wouldn't be 404. Anyway, try this. ``` @FormUrlEncoded @Headers({"Content-Type: application/json"}) @POST("accounts/signInWithPassword") Call<Transaction.Result> loginWithEmail( @Query("key") String key, @Field("email") String email, @Field("password") String password, @Field("returnSecureToken") boolean returnSecureToken ); ```
40,637,483
I'm trying to merge two lists.. I often do this successfully when I have merging something like `ProductsList1.Product.Id` with `ProductList2.Product.Id` , however In this case its more Like `ProductsList.Product.Id` with `ProductCategoriesList.ProductCategory.ProductId`. The 3rd level property is what's getting me! ``` // LIST OF PRODUCTS IN RESULT SETS List<Product> products = new List<Product>(); products.Add(new Product() { Id = 1 }); products.Add(new Product() { Id = 2 }); // LIST OF ALL PRODUCTS AND THEIR CATEGORY TAXONOMIES List<ProductCategory> allProductCategories = new List<ProductCategory>(); allProductCategories.Add(new ProductCategory() { ProductId = 1, CategoryUid = 101, ParentCategoryUid = 30 }); allProductCategories.Add(new ProductCategory() { ProductId = 1, CategoryUid = 30, ParentCategoryUid = 2 }); allProductCategories.Add(new ProductCategory() { ProductId = 1, CategoryUid = 2, ParentCategoryUid = 1 }); allProductCategories.Add(new ProductCategory() { ProductId = 3, CategoryUid = 101, ParentCategoryUid = 43 }); allProductCategories.Add(new ProductCategory() { ProductId = 3, CategoryUid = 43, ParentCategoryUid = 8 }); allProductCategories.Add(new ProductCategory() { ProductId = 3, CategoryUid = 8, ParentCategoryUid = 1 }); // NEED TO MERGE THE 2ND LIST INTO THE 1ST BY PRODUCTID VIA SQL EQUIV INNER JOIN // END RESULT SHOULD BE products list has 2 objects. one object has 1 list product category with 3 child objects // THIS IS THE CLOSEST I GOT products.Select(x => x.Id).Intersect(allProductCategories.Select(a => a.ProductId).ToList()); } public class Product { private int _id; private List<ProductCategory> _productCategories; public int Id { get { return _id; } set { _id = value; } } public List<ProductCategory> ProductCategories { get { return _productCategories; } set { _productCategories = value; } } } public class ProductCategory { private int _productId; private int _categoryUid; private int _parentCategoryUid; public int ProductId { get { return _productId; } set { _productId = value; } } public int CategoryUid { get { return _categoryUid; } set { _categoryUid = value; } } public int ParentCategoryUid { get { return _parentCategoryUid; } set { _parentCategoryUid = value; } } } ```
2016/11/16
[ "https://Stackoverflow.com/questions/40637483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580285/" ]
Following query will do the job: ``` var result = products.Join(allProductCategories, p => p.Id, pc => pc.ProductId, (p, pc) => new { p, pc}) .GroupBy(x => x.p.Id) .Select(x => new Product{ Id = x.Key, ProductCategories = x.Select(y => y.pc).ToList()}); ``` > > Requirement: > > > * Get Data from two different lists, which have common Id, and create a merged version, which contain Id of the parent `Product`, and all the matching rows of the `ProductCategory` **Explanation:** * Inner Join two list on Id * Groupby `ProductId` to aggregate the `ProductCategory` data * Select them in separate collection, where Id is the Key and data is the collection of all the aggregated / grouped results You may run it using Linqpad and `result.Dump()`, will provide a clear view of the final result
```cs // LIST OF PRODUCTS IN RESULT SETS List<Product> products = new List<Product> { new Product() {Id = 1, ProductCategories = new List<ProductCategory>()}, new Product() {Id = 2, ProductCategories = new List<ProductCategory>()} }; // LIST OF ALL PRODUCTS AND THEIR CATEGORY TAXONOMIES List<ProductCategory> allProductCategories = new List<ProductCategory> { new ProductCategory() {ProductId = 1, CategoryUid = 101, ParentCategoryUid = 30}, new ProductCategory() {ProductId = 1, CategoryUid = 30, ParentCategoryUid = 2}, new ProductCategory() {ProductId = 1, CategoryUid = 2, ParentCategoryUid = 1}, new ProductCategory() {ProductId = 3, CategoryUid = 101, ParentCategoryUid = 43}, new ProductCategory() {ProductId = 3, CategoryUid = 43, ParentCategoryUid = 8}, new ProductCategory() {ProductId = 3, CategoryUid = 8, ParentCategoryUid = 1} }; // General logic going on here: // Add all ProductCategory where the ProductID is equal // to the Prdoduct.ID to the current Product.ProductCategories products.ForEach(pr=> allProductCategories.Where(pC=> pC.ProductId.Equals(pr.Id)).ToList().ForEach(pC=> pr.ProductCategories.Add(pC))); // products.ToList().ForEach(x=>Console.WriteLine(x.ProductCategories.Count)); ``` --- Output: > > 3 > > > 0 > > > --- I do not know if there is an easier way using the intersect method, but this one does work! According to the [documentation](https://msdn.microsoft.com/en-us/library/bb460136(v=vs.110).aspx) (for using `Enumerable.Intersect`) you would need to implement a custom [IEqualityComparer](https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx) using multiple types. Because of that it is currently impossible to do such things or would simple take more lines of code than my current solution. If you do want to know more about [`Enumerable.Intersect`](https://www.dotnetperls.com/intersect), I suggest visiting [*dotnetperls.com*](https://www.dotnetperls.com/)!
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
Noticed the same behavior but my linux roots had me try:`.\file.rb` and it loaded into the irb. Try explicitly declaring the current directory.
If you're trying to do this with rvmsudo, I found this worked for me: ``` rvmsudo irb -I '/Absolute/path/to/your/project' ```
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
``` require './hede' ``` or ``` require_relative 'hede' ``` This works for me in both Ruby (1.9.3) and JRuby (1.7.x) on linux. I haven't tested it on windows.
If you're trying to do this with rvmsudo, I found this worked for me: ``` rvmsudo irb -I '/Absolute/path/to/your/project' ```
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
``` require './hede' ``` or ``` require_relative 'hede' ``` This works for me in both Ruby (1.9.3) and JRuby (1.7.x) on linux. I haven't tested it on windows.
it's damn dirty, but you can always do at the very first line: ``` $: << '.' ``` and off you go with pwd'ed require. It's quite useful for interactive/creative testing with IRB
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
How about this command? A little cumbersome to write but really clean and it should always work: ``` ➜ $ irb > require "#{Dir.pwd}/file_to_load.rb" => true ```
I believe both of the previous posts are correct, just for different uses. In IRB use an absolute path with `require`, with a file you can also use `require` with an absolute path, or use `require_relative`.
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
None of these worked for me, but this did: ``` irb -I . >require 'file' => true ```
Noticed the same behavior but my linux roots had me try:`.\file.rb` and it loaded into the irb. Try explicitly declaring the current directory.
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
I believe both of the previous posts are correct, just for different uses. In IRB use an absolute path with `require`, with a file you can also use `require` with an absolute path, or use `require_relative`.
If you're trying to do this with rvmsudo, I found this worked for me: ``` rvmsudo irb -I '/Absolute/path/to/your/project' ```
3,898,174
I'm having a really noob problem with importing files in Ruby. I'm making a Ruby app in Windows XP. All the class files for the app are in `"C:/Documents/Prgm/Surveyor_Ruby/lib"`. But when I `require` a file in another file, neither ruby nor irb can find the required file. The current directory's contents: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>dir Volume in drive C has no label. Volume Serial Number is AAAA-BBBB Directory of C:\Documents\Prgm\Surveyor_Ruby\lib 10/09/2010 06:32 PM <DIR> . 10/09/2010 06:32 PM <DIR> .. 10/08/2010 03:22 PM 5,462 main (commented).rb 10/08/2010 03:41 PM 92 question.rb 10/08/2010 09:06 PM 2,809 survey.rb 10/09/2010 06:25 PM 661 surveyor.rb 10/08/2010 01:39 PM 1,546 test.rb 5 File(s) 10,570 bytes 2 Dir(s) 40,255,045,632 bytes free ``` Confirmation that irb is in correct directory: ``` C:\Documents\Prgm\Surveyor_Ruby\lib>irb irb(main):001:0> Dir.pwd => "C:/Documents/Prgm/Surveyor_Ruby/lib" ``` ...yet irb can't load survey.rb: ``` irb(main):002:0> require 'survey' LoadError: no such file to load -- survey from <internal:lib/rubygems/custom_require>:29:in `require' from <internal:lib/rubygems/custom_require>:29:in `require' from (irb):2 from C:/Ruby192/bin/irb:12:in `<main>' ```
2010/10/09
[ "https://Stackoverflow.com/questions/3898174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243500/" ]
None of these worked for me, but this did: ``` irb -I . >require 'file' => true ```
``` require './hede' ``` or ``` require_relative 'hede' ``` This works for me in both Ruby (1.9.3) and JRuby (1.7.x) on linux. I haven't tested it on windows.