qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Another [answer](https://stackoverflow.com/a/39489661/147511) shows the best way for obtaining (at runtime) a `Type` defined in an `Assembly` that might not be loaded: ``` var T1 = Type.GetType("System.Web.Configuration.IAssemblyCache, " + "System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a"); ``` As you can see, unfortunately that method requires you to supply the full [AssemblyQualifiedName](https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx) of the `Type` and will not work with any of the [abbreviated forms](https://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx#Anchor_2) of the [assembly name](https://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx) that I tried. This somewhat defeats our main purposes here. If you knew that much detail about the assembly, it wouldn't be that much harder to just load it yourself: ``` var T2 = Assembly.Load("System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a") .GetType("System.Web.Configuration.IAssemblyCache"); ``` Although these two examples look similar, they execute very different code paths; note for example, that the latter version calls an *instance* overload on `Assembly.GetType` versus the *static* call `Type.GetType`. Because of this, the second version is probably faster or more efficient. Either way, though, you seem to end up at the following CLR internal method, and with the second argument set to `false`, and this is why *neither method* goes to the trouble of searching for the required assembly on your behalf. > > [System.Runtime.Remoting.RemotingServices] > > private static RuntimeType **LoadClrTypeWithPartialBindFallback**( > >                   String typeName, > >                   bool partialFallback); > > > A tiny step forward from these inconveniences would be to instead call this CLR method yourself, but with the `partialFallback` parameter set to **true**. In this mode, the function will accept a truncated version of the `AssemblyQualifiedName` and will *locate and load* the relevant assembly, as necessary: ``` static Func<String, bool, TypeInfo> LoadClrTypeWithPartialBindFallback = typeof(RemotingServices) .GetMethod("LoadClrTypeWithPartialBindFallback", (BindingFlags)0x28) .CreateDelegate(typeof(Func<String, bool, TypeInfo>)) as Func<String, bool, TypeInfo>; // ... var T3 = LoadClrTypeWithPartialBindFallback( "System.Web.Configuration.IAssemblyCache, System.Web", true); // <-- enables searching for the assembly ``` This works as shown, and also continues to support specifying the full `AssemblyQualifiedName` as in the earlier examples. This is a small improvement, but it's still not a fully unqualified namespace search, because you do still have to specify the short name of the assembly, even if it might be deduced from the namespace that appears in the type name itself.
BTW if you *do* know the `FullName` of the assembly containing the type (or an assembly containing a `TypeForwardedToAttribute` for the type) you *can* use `Type.GetType`. Specifically, `Type.GetType(Assembly.CreateQualifiedName(assembly.FullName, myTypeName))` which will look something like: ``` Type.GetType("Some.Complete.Namespace.myTypeName, Some.Assembly.Name, Version=1.2.3.4, Culture=neutral, PublicKeyToken=ffffffffffffffff"); ``` This *will load* the assembly if it is not already, assuming the framework can resolve the location of the assembly. Here's my sample LinqPad query confirming the parenthetic `TypeForwardedToAttribute` remark: ``` var u = (from a in AppDomain.CurrentDomain.GetAssemblies() let t = a.GetType("System.Lazy`2") where t != null select t).FirstOrDefault(); (u?.AssemblyQualifiedName).Dump(); u = Type.GetType("System.Lazy`2, System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); (u?.AssemblyQualifiedName).Dump(); ``` Output: > > *null* > > System.Lazy`2, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 > > >
55,225,131
I am doing full outer join on 4 tables on the same column. I want to generate only 1 row for each different value in the Join column. Inputs are: ``` employee1 +---------------------+-----------------+--+ | employee1.personid | employee1.name | +---------------------+-----------------+--+ | 111 | aaa | | 222 | bbb | | 333 | ccc | +---------------------+-----------------+--+ employee2 +---------------------+----------------+--+ | employee2.personid | employee2.sal | +---------------------+----------------+--+ | 111 | 2 | | 200 | 3 | +---------------------+----------------+--+ employee3 +---------------------+------------------+--+ | employee3.personid | employee3.place | +---------------------+------------------+--+ | 111 | bbsr | | 300 | atl | | 200 | ny | +---------------------+------------------+--+ employee4 +---------------------+---------------+--+ | employee4.personid | employee4.dt | +---------------------+---------------+--+ | 111 | 2019-02-21 | | 300 | 2019-03-18 | | 400 | 2019-03-18 | +---------------------+---------------+--+ ``` Expected Result one record for each personid, so total there should be 6 records(111,222,333,200,300,400) Like: ``` +-----------+---------+--------+----------+-------------+--+ | personid | f.name | u.sal | v.place | v_in.dt | +-----------+---------+--------+----------+-------------+--+ | 111 | aaa | 2 | bbsr | 2019-02-21 | | 200 | NULL | 3 | ny | NULL | | 222 | bbb | NULL | NULL | NULL | | 300 | NULL | NULL | atl | 2019-03-18 | | 333 | ccc | NULL | NULL | NULL | | 400 | NULL | NULL | NULL | 2019-03-18 | +-----------+---------+--------+----------+-------------+--+ ``` Result i am getting is: ``` +-----------+---------+--------+----------+-------------+--+ | personid | f.name | u.sal | v.place | v_in.dt | +-----------+---------+--------+----------+-------------+--+ | 111 | aaa | 2 | bbsr | 2019-02-21 | | 200 | NULL | 3 | NULL | NULL | | 200 | NULL | NULL | ny | NULL | | 222 | bbb | NULL | NULL | NULL | | 300 | NULL | NULL | atl | NULL | | 300 | NULL | NULL | NULL | 2019-03-18 | | 333 | ccc | NULL | NULL | NULL | | 400 | NULL | NULL | NULL | 2019-03-18 | +-----------+---------+--------+----------+-------------+--+ ``` Query used: ``` select coalesce(f.personid, u.personid, v.personid, v_in.personid) as personid,f.name,u.sal,v.place,v_in.dt from employee1 f FULL OUTER JOIN employee2 u on f.personid=u.personid FULL OUTER JOIN employee3 v on f.personid=v.personid FULL OUTER JOIN employee4 v_in on f.personid=v_in.personid; ``` Please suggest how to generate the expected result.
2019/03/18
[ "https://Stackoverflow.com/questions/55225131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326784/" ]
You can use `union all` & do conditional aggregation : ``` select truckid, sum( tbl = 'delivery' ) as delivery_count, sum( tbl = 'delivery2' ) as delivery2_count from (select truckid, deliveryid, 'delivery' as tbl from delivery where year(deliverydate) = 2019 and month(deliverydate) = 1 union all select truckid, deliverid, 'delivery2' from delivery2 where YEAR(ddate) = 2019 and MONTH(ddate) = 1 ) t group by truckid; ```
You can simulate a `FULL OUTER JOIN` by `UNION`-ing a `LEFT JOIN` with a `RIGHT JOIN`, as in: ``` with a (truckid, cnt) as ( -- query #1 SELECT truckid, count(deliveryid) FROM delivery WHERE year(deliverydate) = 2019 and month(deliverydate) = 1 group by truckid ), b (truckid, cnt) as ( -- query #2 SELECT truckid, count(deliverid) FROM delivery2 WHERE YEAR(ddate) = 2019 and MONTH(ddate) = 1 GROUP BY truckid ) select -- now the full outer join from a.truck_id, a.cnt as a_cnt, b.cnt as b_cnt left join b on a.truck_id = b.truck_id union select from b.truck_id, a.cnt as a_cnt, b.cnt as b_cnt right join b on a.truck_id = b.truck_id ```
55,225,131
I am doing full outer join on 4 tables on the same column. I want to generate only 1 row for each different value in the Join column. Inputs are: ``` employee1 +---------------------+-----------------+--+ | employee1.personid | employee1.name | +---------------------+-----------------+--+ | 111 | aaa | | 222 | bbb | | 333 | ccc | +---------------------+-----------------+--+ employee2 +---------------------+----------------+--+ | employee2.personid | employee2.sal | +---------------------+----------------+--+ | 111 | 2 | | 200 | 3 | +---------------------+----------------+--+ employee3 +---------------------+------------------+--+ | employee3.personid | employee3.place | +---------------------+------------------+--+ | 111 | bbsr | | 300 | atl | | 200 | ny | +---------------------+------------------+--+ employee4 +---------------------+---------------+--+ | employee4.personid | employee4.dt | +---------------------+---------------+--+ | 111 | 2019-02-21 | | 300 | 2019-03-18 | | 400 | 2019-03-18 | +---------------------+---------------+--+ ``` Expected Result one record for each personid, so total there should be 6 records(111,222,333,200,300,400) Like: ``` +-----------+---------+--------+----------+-------------+--+ | personid | f.name | u.sal | v.place | v_in.dt | +-----------+---------+--------+----------+-------------+--+ | 111 | aaa | 2 | bbsr | 2019-02-21 | | 200 | NULL | 3 | ny | NULL | | 222 | bbb | NULL | NULL | NULL | | 300 | NULL | NULL | atl | 2019-03-18 | | 333 | ccc | NULL | NULL | NULL | | 400 | NULL | NULL | NULL | 2019-03-18 | +-----------+---------+--------+----------+-------------+--+ ``` Result i am getting is: ``` +-----------+---------+--------+----------+-------------+--+ | personid | f.name | u.sal | v.place | v_in.dt | +-----------+---------+--------+----------+-------------+--+ | 111 | aaa | 2 | bbsr | 2019-02-21 | | 200 | NULL | 3 | NULL | NULL | | 200 | NULL | NULL | ny | NULL | | 222 | bbb | NULL | NULL | NULL | | 300 | NULL | NULL | atl | NULL | | 300 | NULL | NULL | NULL | 2019-03-18 | | 333 | ccc | NULL | NULL | NULL | | 400 | NULL | NULL | NULL | 2019-03-18 | +-----------+---------+--------+----------+-------------+--+ ``` Query used: ``` select coalesce(f.personid, u.personid, v.personid, v_in.personid) as personid,f.name,u.sal,v.place,v_in.dt from employee1 f FULL OUTER JOIN employee2 u on f.personid=u.personid FULL OUTER JOIN employee3 v on f.personid=v.personid FULL OUTER JOIN employee4 v_in on f.personid=v_in.personid; ``` Please suggest how to generate the expected result.
2019/03/18
[ "https://Stackoverflow.com/questions/55225131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326784/" ]
You can use `union all` & do conditional aggregation : ``` select truckid, sum( tbl = 'delivery' ) as delivery_count, sum( tbl = 'delivery2' ) as delivery2_count from (select truckid, deliveryid, 'delivery' as tbl from delivery where year(deliverydate) = 2019 and month(deliverydate) = 1 union all select truckid, deliverid, 'delivery2' from delivery2 where YEAR(ddate) = 2019 and MONTH(ddate) = 1 ) t group by truckid; ```
I would write this as: ``` select truckid, max(delivery1) as delivery1, max(delivery2) as delivery2 from ((select truckid, count(*) as delivery1, 0 as delivery2 from delivery where deliverydate >= '2019-01-01' and deliverydate < '2019-01-02' group by truckid ) union all (select truckid, 0, count(*) as delivery2 from delivery2 where deliverydate >= '2019-01-01' and deliverydate < '2019-01-02' group by truckid ) ) t group by truckid; ``` I think this is the most efficient approach. First, the date ranges allow the use of indexes. Second, the `group by` on the individual tables is on a smaller sized data. `GROUP BY` scales worse than linearly, so smaller is better. The `UNION ALL` is also on smaller data. And as a convenience, no conditional logic is directly needed.
19,104,146
I am interested in the situation where **one thread is waiting** for change of a variable in the `while` loop: ``` while (myFlag == false) { // do smth } ``` It is repeating an infinite number of times. In the meantime, **another thread have changed** the value of this variable: ``` myFlag = true; ``` Can the reader-thread see the result of changing the value of the variable in the other thread if this variable is NOT volatile? In general, as I understand it will never happen. Or am I wrong? Then when and under what circumstances, the first thread can see the change in the variable and exit the loop? Is this possible without using `volatile` keyword? Does size of processor's cache play role in this situation? Please explain and help me understand! Thank you in advance!!
2013/09/30
[ "https://Stackoverflow.com/questions/19104146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1932170/" ]
> > Can the reader-thread see the result of changing the value of the variable in the other thread if this variable is NOT volatile? > > > It *may* be able to, yes. It's just that it won't *definitely* see the change. > > In general, as I understand it will never happen. > > > No, that's not the case. You're writing to a variable and then reading from it in a different thread. Whether or not you see it will depend on the exact processor and memory architecture involved. Without any memory barriers involved, you aren't *guaranteed* to see the new value - but you're certainly not guaranteed *not* to see it either.
> > Can the reader-thread see the result of changing the value of the variable in the other thread if this variable is NOT volatile? > > > I'd like to expand a bit on @Jon's excellent answer. The Java memory model says that *all* memory in a particular thread will be updated if it crosses *any* memory barrier. Read barriers cause all cached memory in a particular thread to be updated from central memory and write barriers cause local thread changes to be written to central. So if your thread that writes to another `volatile` field or enters a `synchronized` block it will cause your flag to be updated in central memory. If the reading thread reads from another `volatile` field or enters a `synchronized` block in the `// do smth` section after the update has happened, it will see the update. You just can't rely on *when* this will happen or if the order of write/read happens appropriately. If your thread doesn't have other memory synchronization points then it may *never* happen. **Edit:** Given the discussion below, which I've had a couple times now in various different questions, I thought I might expand more on my answer. There is a big difference between the guarantees provided by the Java language and its memory-model and the reality of JVM implementations. The JLS and JMM define memory-barriers and talk about "happens-before" guarantees only between `volatile` reads and writes on the *same* field and `synchronized` locks on the *same* object. However, on all architectures that I've heard of, the implementation of the memory barriers that enforce the memory synchronization are *not* field or object specific. When a read is done on a `volatile` field and the read-barrier is crossed on a specific thread, it will be updated with *all* of central memory, not just the particular `volatile` field in question. This is the same for `volatile` writes. After a write is made to a `volatile` field, *all* updates from the local thread are written to central memory, not just the field. What the JLS *does* guarantee is that instructions cannot be reordered past the `volatile` access. So, if thread-A has written to a `volatile` field then all updates, even those *not* marked as `volatile` will have been written to central memory. After this operation has completed, if thread-B then reads from a different `volatile` field, he will see all of thread-A's updates, even those not marked as `volatile`. Again, there is *no* guarantees around the timing of these events but if they happen in that order then the two threads will be updated.
27,170,575
Where can i put custom css files to customize ActiveAdmin CSS? I see in active\_admin.rb there is the following line: ``` config.register_stylesheet 'active_admin.css' ``` but i can't understand where the file has to go. All i want to do is add some extra custom styles to AA's default ones
2014/11/27
[ "https://Stackoverflow.com/questions/27170575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490947/" ]
Lets say I have 2 css files, highlight.css and select2.css In `config/initializers/active_admin.rb`, I would add it like this: ``` config.register_stylesheet 'highlight.min.css' config.register_stylesheet 'select2.css' ``` **Note:** *highlight.css* and *select2.css* should be inside/under `app/assets/stylesheets`
> > To keep separate directory for admin style-sheet. > > > I am using `gem 'activeadmin'` in an application. I wanted to use my own style-sheet which stored in separate directory, here is how I archive that- 1. Created new directory as **`admin`** inside style-sheet . Ex. **`app/assets/stylesheets/admin`** 2. Opened `config/initializers/active_admin.rb`. 3. Looked for ***register\_stylesheet*** and found commented line as- `# config.register_stylesheet 'my_stylesheet.css'` 4. Modified this line with- `config.register_stylesheet 'admin/active_style.css'` 5. Restart rails server and found desired result. Hope will work for you!
2,726,054
> > Let $g(x)$ be a continuous function for any $x \in R$ that satisfies: > > > $$2x^5 + 64 = \int\_c^x g(t) \,dt$$ > > > Find the value of $c$ or prove it does not exist. > > > > > --- > > > I suppose the starting point is the following: $$2(x^5 + 2^5) = \int\_c^x g(t) \,dt$$ $$x^5 = \frac{\int\_c^x g(t) \,dt}{2} - 2^5$$ $$x^5 = \frac{G(x) - G(c)}{2} - 2^5$$ But what should follow afterwards? Thanks in advance.
2018/04/07
[ "https://math.stackexchange.com/questions/2726054", "https://math.stackexchange.com", "https://math.stackexchange.com/users/514257/" ]
Well put $x=c$ in your equation, which will give $\int\_c^{c} g(t)dt = 0$. You will simply get $-2c^5 = 64 \iff c = -2$.
By the Fundamental Theorem of Calculus we have \begin{align\*} (2x^{5}+64)'=g(x), \end{align\*} then $g(x)=10x^{4}$. Substituting back to the expression we get \begin{align\*} 2x^{5}+64=\int\_{c}^{x}10t^{4}dt=2t^{5}\bigg|\_{t=c}^{t=x}=2x^{5}-2c^{5}, \end{align\*} so $c^{5}=-32$ and hence $c=-2$.
52,595,505
I have a code like below - columns with full-width images. ``` <div class="col-3"> <img src="..." class="w-100" /> <div>Name</div> </div> ``` As images can be of different size, it's not guaranteed that content below images will be displayed in one line (image's height is supposed to differ, depending on image's width). In other words, when an image within `.col` is 200 px width, should be 200 px height, etc. (width = height).
2018/10/01
[ "https://Stackoverflow.com/questions/52595505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1274664/" ]
Example 1 with css: ```css @import url('https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css'); .img-prev { height: 200px; overflow: hidden; } .img-prev img { max-height: 100%; width: auto; max-width: inherit; margin: auto; display: block; } ``` ```html <div class="container"> <div class="row"> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538356913997-b04286765811?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=39e83600a508d87be2ea636e02f30f95&auto=format&fit=crop&w=600&q=60" alt="" class="img-fluid"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538333785596-1cc0b5e03551?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=c942fc493dad02801a99aa191414a535&auto=format&fit=crop&w=600&q=60" alt="" class="img-fluid"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538379585867-44bf200a3d25?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=29782178fb2019f60bee12c2fcfacff4&auto=format&fit=crop&w=600&q=60" alt="" class="img-fluid"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538367735494-5e6cc0ff555a?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=3066861f0cf81849de20853676dee717&auto=format&fit=crop&w=600&q=60" alt="" class="img-fluid"> </div> </div> </div> </div> ``` Example 2 html: ```html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <div class="container"> <div class="row"> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538356913997-b04286765811?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=39e83600a508d87be2ea636e02f30f95&auto=format&fit=crop&w=600&q=60" alt="" height="200" width="150"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538333785596-1cc0b5e03551?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=c942fc493dad02801a99aa191414a535&auto=format&fit=crop&w=600&q=60" alt="" height="200" width="150"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538379585867-44bf200a3d25?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=29782178fb2019f60bee12c2fcfacff4&auto=format&fit=crop&w=600&q=60" alt="" height="200" width="150"> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538367735494-5e6cc0ff555a?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=3066861f0cf81849de20853676dee717&auto=format&fit=crop&w=600&q=60" alt="" height="200" width="150"> </div> </div> </div> </div> ``` Example 3 with jq: ```js var imgs = $('.img-prev>img'); imgs.each(function(){ var item = $(this).closest('.img-prev'); item.css({ 'background-image': 'url(' + $(this).attr('src') + ')', 'background-position': 'center center', '-webkit-background-size': 'cover', 'background-size': 'cover', }); $(this).hide(); }); ``` ```css .img-prev { height: 200px; } ``` ```html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <div class="container"> <div class="row img-list"> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538356913997-b04286765811?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=39e83600a508d87be2ea636e02f30f95&auto=format&fit=crop&w=600&q=60" alt=""> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538333785596-1cc0b5e03551?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=c942fc493dad02801a99aa191414a535&auto=format&fit=crop&w=600&q=60" alt=""> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538379585867-44bf200a3d25?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=29782178fb2019f60bee12c2fcfacff4&auto=format&fit=crop&w=600&q=60" alt=""> </div> </div> <div class="col-4 mb-2"> <div class="img-prev"> <img src="https://images.unsplash.com/photo-1538367735494-5e6cc0ff555a?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=3066861f0cf81849de20853676dee717&auto=format&fit=crop&w=600&q=60" alt=""> </div> </div> </div> </div> ```
try this one, ``` <div class="container"> <img src="loginBackground.jpg" class="img-fluid" alt="Cinque Terre" width="200" height="200"> </div> ```
23,235,738
Im trying to sort this around, im making an ajax requests of get type, and the page will be returning many responses, OK is one of those, is the page returns OK then I need to proceed for form submitting, else I need to halt the form submission, but Im unable to access the data out side of the function, it is available inside the fall back function alone, is it due to asynchronous mannerism?, can some one assist me to get out of this? ``` $.get('ajax.html',function(data){ //some code here }); if(data == 'ok'){return true; } else {return false;} ```
2014/04/23
[ "https://Stackoverflow.com/questions/23235738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2750761/" ]
`$.get` fires an asynchronous request, and the execution of you program continues. So in your case `data` is available only after the ajax call finishes and only inside your callback function. You need to do whatever you want to do with `data` inside your callback function. You need to re-arrange you code to do something like: ``` $.get('ajax.html', function (data) { if(data === 'OK') { // do what you need to do in this case } }); // at this point there's no data ```
No, you are accessing data which is not a variable available. How about assigning it to another variable? ``` var resp = ""; get('ajax.html', function (data) { resp = data; }); if(resp == "OK") {alert(1);} ``` alternatively you can go use asyn false ``` $.ajax({ url: url, type: "GET", async: false, data: data, success: function(ret) { //alert(ret); resp = data; } }); alert(resp); ``` Cheers!
48,539,019
In PHP there is fopen('r+') for Read/Write. (start at beginning of the file) There is also fopen('a+') for Read/Write. (append to the end of the file) I made a simple $\_POST['data'] form that writes whatever is written in the form to a file. My problem is that if I write a few things, for example. ``` 'Red ' 'Green ' 'Blue ' ``` If I append this data, it will show up in the file in the order I write in. But, I need to write to the beginning of the file, so that it's in reverse order. ``` 'Blue ' 'Green ' 'Red ' ``` $file\_data = 'What to write in the file'; $file\_data .= file\_get\_contents('testz.php'); file\_put\_contents('testz.php', $file\_data); 1. This will write whatever is in the $file\_data variable to the file and then write the data that was originally in the file afterwards. Thus causing it to show up before everything else that was originally in the file. This works fine. --- The problem starts when I want to include a line of code at the beginning of the file. > > Specifically I want '!DOCTYPE html html head' to always be at the > top of the document. I could of course put that in the file data like: > file\_put\_contents('testz.php', $headerinformation.$file\_data); > > > But the problem with that is gonna be everytime I submit the POST, It's gonna be repeating ``` <!DOCTYPE html><html><head>Blue <!DOCTYPE html><html><head>Green <!DOCTYPE html><html><head>Red ``` What I want is ``` <!DOCTYPE html><html><head> Blue Green Red ``` So, then I can keep writing more information to the file via the POST form WITHOUT REPLACING THE FIRST LINE. ``` <!DOCTYPE html><html><head> ``` I know this is gonna be kind of a bad question, what what exactly can I do to achieve this?
2018/01/31
[ "https://Stackoverflow.com/questions/48539019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4305147/" ]
Why don't you check if file is already with some data in it, for eg.: ``` $data_to_write = file_get_contents('testz.php'); $header_data = '<!DOCTYPE html><html><head>'; $file_data .= (empty($data_to_write))?$header_data.$data_to_write:$data_to_write; file_put_contents('testz.php', $file_data); ```
I ended up doing it this way, ``` <?php $f=fopen('WriteFile.php', 'r+'); $W='<!DOCTYPE html>'.file_get_contents('WriteFile.php'); $S='New Data'; fwrite($f, "$W"); fgets($f); fseek($f,15); fwrite($f, "$S"); ?> ```
48,539,019
In PHP there is fopen('r+') for Read/Write. (start at beginning of the file) There is also fopen('a+') for Read/Write. (append to the end of the file) I made a simple $\_POST['data'] form that writes whatever is written in the form to a file. My problem is that if I write a few things, for example. ``` 'Red ' 'Green ' 'Blue ' ``` If I append this data, it will show up in the file in the order I write in. But, I need to write to the beginning of the file, so that it's in reverse order. ``` 'Blue ' 'Green ' 'Red ' ``` $file\_data = 'What to write in the file'; $file\_data .= file\_get\_contents('testz.php'); file\_put\_contents('testz.php', $file\_data); 1. This will write whatever is in the $file\_data variable to the file and then write the data that was originally in the file afterwards. Thus causing it to show up before everything else that was originally in the file. This works fine. --- The problem starts when I want to include a line of code at the beginning of the file. > > Specifically I want '!DOCTYPE html html head' to always be at the > top of the document. I could of course put that in the file data like: > file\_put\_contents('testz.php', $headerinformation.$file\_data); > > > But the problem with that is gonna be everytime I submit the POST, It's gonna be repeating ``` <!DOCTYPE html><html><head>Blue <!DOCTYPE html><html><head>Green <!DOCTYPE html><html><head>Red ``` What I want is ``` <!DOCTYPE html><html><head> Blue Green Red ``` So, then I can keep writing more information to the file via the POST form WITHOUT REPLACING THE FIRST LINE. ``` <!DOCTYPE html><html><head> ``` I know this is gonna be kind of a bad question, what what exactly can I do to achieve this?
2018/01/31
[ "https://Stackoverflow.com/questions/48539019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4305147/" ]
First of all, you should write the first line at the time you create the file, e.g.: ``` $first_line = "<!DOCTYPE html><html><head>" . PHP_EOL; file_put_contents("somefile.txt", $first_line); ``` And when you want to insert new content you could load your file into an array with [`file()`](http://php.net/manual/en/function.file.php) and insert the content at index 1 of the array (which is the second line in the file) by using [`array_splice()`](http://php.net/manual/en/function.array-splice.php): ``` $lines = file("somefile.txt"); array_splice($lines, 1, 0, "new content"); ``` Use [`implode()`](http://php.net/manual/en/function.implode.php) to join the array elements to a string and finally write to the file: ``` $file_content = implode(PHP_EOL, $lines); file_put_contents("somefile.txt", $file_content); ``` Note that this approach will lead to memory issues when dealing with large files.
Why don't you check if file is already with some data in it, for eg.: ``` $data_to_write = file_get_contents('testz.php'); $header_data = '<!DOCTYPE html><html><head>'; $file_data .= (empty($data_to_write))?$header_data.$data_to_write:$data_to_write; file_put_contents('testz.php', $file_data); ```
48,539,019
In PHP there is fopen('r+') for Read/Write. (start at beginning of the file) There is also fopen('a+') for Read/Write. (append to the end of the file) I made a simple $\_POST['data'] form that writes whatever is written in the form to a file. My problem is that if I write a few things, for example. ``` 'Red ' 'Green ' 'Blue ' ``` If I append this data, it will show up in the file in the order I write in. But, I need to write to the beginning of the file, so that it's in reverse order. ``` 'Blue ' 'Green ' 'Red ' ``` $file\_data = 'What to write in the file'; $file\_data .= file\_get\_contents('testz.php'); file\_put\_contents('testz.php', $file\_data); 1. This will write whatever is in the $file\_data variable to the file and then write the data that was originally in the file afterwards. Thus causing it to show up before everything else that was originally in the file. This works fine. --- The problem starts when I want to include a line of code at the beginning of the file. > > Specifically I want '!DOCTYPE html html head' to always be at the > top of the document. I could of course put that in the file data like: > file\_put\_contents('testz.php', $headerinformation.$file\_data); > > > But the problem with that is gonna be everytime I submit the POST, It's gonna be repeating ``` <!DOCTYPE html><html><head>Blue <!DOCTYPE html><html><head>Green <!DOCTYPE html><html><head>Red ``` What I want is ``` <!DOCTYPE html><html><head> Blue Green Red ``` So, then I can keep writing more information to the file via the POST form WITHOUT REPLACING THE FIRST LINE. ``` <!DOCTYPE html><html><head> ``` I know this is gonna be kind of a bad question, what what exactly can I do to achieve this?
2018/01/31
[ "https://Stackoverflow.com/questions/48539019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4305147/" ]
You can only add to the end of a file. You can write in the middle of it but only writing over existing data. So in order to add lines of text always as the second line you should load the data, add the line in the right place, then write the file again. But I think what you are doing is a very weird thing to do, and most likely avoidable. You are writing an HTML file which makes me think you are going to display it at some point, in which case you should separate data handling and presentation. For example you can treat the file as a data file where you just append lines without a header, then when you want to serve the data as html you output a header first and then the lines in reverse order.
I ended up doing it this way, ``` <?php $f=fopen('WriteFile.php', 'r+'); $W='<!DOCTYPE html>'.file_get_contents('WriteFile.php'); $S='New Data'; fwrite($f, "$W"); fgets($f); fseek($f,15); fwrite($f, "$S"); ?> ```
48,539,019
In PHP there is fopen('r+') for Read/Write. (start at beginning of the file) There is also fopen('a+') for Read/Write. (append to the end of the file) I made a simple $\_POST['data'] form that writes whatever is written in the form to a file. My problem is that if I write a few things, for example. ``` 'Red ' 'Green ' 'Blue ' ``` If I append this data, it will show up in the file in the order I write in. But, I need to write to the beginning of the file, so that it's in reverse order. ``` 'Blue ' 'Green ' 'Red ' ``` $file\_data = 'What to write in the file'; $file\_data .= file\_get\_contents('testz.php'); file\_put\_contents('testz.php', $file\_data); 1. This will write whatever is in the $file\_data variable to the file and then write the data that was originally in the file afterwards. Thus causing it to show up before everything else that was originally in the file. This works fine. --- The problem starts when I want to include a line of code at the beginning of the file. > > Specifically I want '!DOCTYPE html html head' to always be at the > top of the document. I could of course put that in the file data like: > file\_put\_contents('testz.php', $headerinformation.$file\_data); > > > But the problem with that is gonna be everytime I submit the POST, It's gonna be repeating ``` <!DOCTYPE html><html><head>Blue <!DOCTYPE html><html><head>Green <!DOCTYPE html><html><head>Red ``` What I want is ``` <!DOCTYPE html><html><head> Blue Green Red ``` So, then I can keep writing more information to the file via the POST form WITHOUT REPLACING THE FIRST LINE. ``` <!DOCTYPE html><html><head> ``` I know this is gonna be kind of a bad question, what what exactly can I do to achieve this?
2018/01/31
[ "https://Stackoverflow.com/questions/48539019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4305147/" ]
First of all, you should write the first line at the time you create the file, e.g.: ``` $first_line = "<!DOCTYPE html><html><head>" . PHP_EOL; file_put_contents("somefile.txt", $first_line); ``` And when you want to insert new content you could load your file into an array with [`file()`](http://php.net/manual/en/function.file.php) and insert the content at index 1 of the array (which is the second line in the file) by using [`array_splice()`](http://php.net/manual/en/function.array-splice.php): ``` $lines = file("somefile.txt"); array_splice($lines, 1, 0, "new content"); ``` Use [`implode()`](http://php.net/manual/en/function.implode.php) to join the array elements to a string and finally write to the file: ``` $file_content = implode(PHP_EOL, $lines); file_put_contents("somefile.txt", $file_content); ``` Note that this approach will lead to memory issues when dealing with large files.
You can only add to the end of a file. You can write in the middle of it but only writing over existing data. So in order to add lines of text always as the second line you should load the data, add the line in the right place, then write the file again. But I think what you are doing is a very weird thing to do, and most likely avoidable. You are writing an HTML file which makes me think you are going to display it at some point, in which case you should separate data handling and presentation. For example you can treat the file as a data file where you just append lines without a header, then when you want to serve the data as html you output a header first and then the lines in reverse order.
48,539,019
In PHP there is fopen('r+') for Read/Write. (start at beginning of the file) There is also fopen('a+') for Read/Write. (append to the end of the file) I made a simple $\_POST['data'] form that writes whatever is written in the form to a file. My problem is that if I write a few things, for example. ``` 'Red ' 'Green ' 'Blue ' ``` If I append this data, it will show up in the file in the order I write in. But, I need to write to the beginning of the file, so that it's in reverse order. ``` 'Blue ' 'Green ' 'Red ' ``` $file\_data = 'What to write in the file'; $file\_data .= file\_get\_contents('testz.php'); file\_put\_contents('testz.php', $file\_data); 1. This will write whatever is in the $file\_data variable to the file and then write the data that was originally in the file afterwards. Thus causing it to show up before everything else that was originally in the file. This works fine. --- The problem starts when I want to include a line of code at the beginning of the file. > > Specifically I want '!DOCTYPE html html head' to always be at the > top of the document. I could of course put that in the file data like: > file\_put\_contents('testz.php', $headerinformation.$file\_data); > > > But the problem with that is gonna be everytime I submit the POST, It's gonna be repeating ``` <!DOCTYPE html><html><head>Blue <!DOCTYPE html><html><head>Green <!DOCTYPE html><html><head>Red ``` What I want is ``` <!DOCTYPE html><html><head> Blue Green Red ``` So, then I can keep writing more information to the file via the POST form WITHOUT REPLACING THE FIRST LINE. ``` <!DOCTYPE html><html><head> ``` I know this is gonna be kind of a bad question, what what exactly can I do to achieve this?
2018/01/31
[ "https://Stackoverflow.com/questions/48539019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4305147/" ]
First of all, you should write the first line at the time you create the file, e.g.: ``` $first_line = "<!DOCTYPE html><html><head>" . PHP_EOL; file_put_contents("somefile.txt", $first_line); ``` And when you want to insert new content you could load your file into an array with [`file()`](http://php.net/manual/en/function.file.php) and insert the content at index 1 of the array (which is the second line in the file) by using [`array_splice()`](http://php.net/manual/en/function.array-splice.php): ``` $lines = file("somefile.txt"); array_splice($lines, 1, 0, "new content"); ``` Use [`implode()`](http://php.net/manual/en/function.implode.php) to join the array elements to a string and finally write to the file: ``` $file_content = implode(PHP_EOL, $lines); file_put_contents("somefile.txt", $file_content); ``` Note that this approach will lead to memory issues when dealing with large files.
I ended up doing it this way, ``` <?php $f=fopen('WriteFile.php', 'r+'); $W='<!DOCTYPE html>'.file_get_contents('WriteFile.php'); $S='New Data'; fwrite($f, "$W"); fgets($f); fseek($f,15); fwrite($f, "$S"); ?> ```
13,071,399
I am writing a WCF client to communicate with a JAX-WS web service. Basically communication with the service works. But when investigating the XML generated by the WCF client there are some elements missing. All the properties are correctly generated and I have set them in my code. I am new to WCF and web services in general so I have problems to analize what could be wrong here. What could cause the missing elements in the XML? The only thing I noticed all these missing properties have in common is that they are enumeration types. But other than that I found nothing. For example there is a enumeration for country codes. An entitity has 3 properties of that enumeration type. Only one of the 3 related elements is generated in the XML. Thanks for your help.
2012/10/25
[ "https://Stackoverflow.com/questions/13071399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698597/" ]
As the OP discovered, when a WCF client (including proxy classes generated by the `XSD.exe` utility) imports an enumerator from the WSDL or XSD, the proxy also has a corresponding `bool` property. For an enumeration element named 'Foobar' there is also 'FoobarSpecified' which must be set to `true` or WCF will not serialize the data element. This is still true 6 years after the question was asked, even when using the new WCF Client in .NET Core and Visual Studio 2017, and it isn't especially obvious, so I thought I'd promote the OP's comment response to wiki answer.
This is most likely occuring because WCF contracts treat enums differently. For data contracts you mark the class with a `DataContract` attribute and the members with a `DataMember` attribute. What's not as well known is that enums have their own attribute called `EnumMember` which WCF uses to serialize them properly. There is an MSDN article called [Enumeration Types in Data Contracts](http://msdn.microsoft.com/en-us/library/aa347875.aspx) which goes over the usage in greater detail. The example code from the article shows how a contract with an enum should look: ``` [DataContract] public class Car { [DataMember] public string model; [DataMember] public CarConditionEnum condition; } [DataContract(Name = "CarCondition")] public enum CarConditionEnum { [EnumMember] New, [EnumMember] Used, [EnumMember] Rental, Broken, Stolen } ``` Note that in their example (which I've included above) you can set just a subset of the enum values as part of the data contract if that's a requirement. In addition to this any property that is not tagged with the `DataMember` attribute will not serialize over the wire. This should be the checklist to ensure that serialization works for WCF: 1. Check that classes are marked with the `DataContract` attribute. 2. Check that properties are marked with the `DataMember` attribute. 3. Check that the individual enum values are marked with the `EnumMember` attribute.
53,458,186
if My table has this values i need to generate seqno column ``` ClientId clinetLocation seqno 001 Abc 1 001 BBc 2 001 ccd 3 002 Abc 1 002 BBc 2 003 ccd 1 ```
2018/11/24
[ "https://Stackoverflow.com/questions/53458186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6385653/" ]
You are looking for the `row_number()` function: ``` select ClientId, clinetLocation, row_number() over (partition by ClientId order by clinetLocation) as seqnum from t; ``` This is a standard function available in most databases.
One option would be counting the grouped rows with respect to those columns : ``` select count(1) over ( order by ClientId, ClientLocation ) as seqno, ClientId, ClientLocation from tab group by ClientId, ClientLocation; ``` *where `ClientId` & `ClientLocation` combination seems unique.* [***Rextester Demo***](https://rextester.com/ZPJ35367)
9,523,453
So I am trying to set my leftBarButtonItem to my navigation item via the following code: ``` UIBarButtonItem * leftSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; self.navigationItem.hidesBackButton = YES; leftSpacer.width = 10; self.navigationItem.leftBarButtonItem = leftSpacer; ``` However, it gives me a program received SIGABRT. Why is this?
2012/03/01
[ "https://Stackoverflow.com/questions/9523453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/721937/" ]
SQL server doesn't understand what `GO` is - only the query analyzer knows (eg. SSMS). If you need to execute multiple commands, simply execute them in the proper order, one at a time.
GO statements are not valid in ADO.net Do you need all of those other qualifying statements? You can break each into a separate command, and execute each command in turn with a single connection.
9,523,453
So I am trying to set my leftBarButtonItem to my navigation item via the following code: ``` UIBarButtonItem * leftSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; self.navigationItem.hidesBackButton = YES; leftSpacer.width = 10; self.navigationItem.leftBarButtonItem = leftSpacer; ``` However, it gives me a program received SIGABRT. Why is this?
2012/03/01
[ "https://Stackoverflow.com/questions/9523453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/721937/" ]
SQL server doesn't understand what `GO` is - only the query analyzer knows (eg. SSMS). If you need to execute multiple commands, simply execute them in the proper order, one at a time.
You cannot use go, you need to split the command in to multiple sets. <http://social.msdn.microsoft.com/Forums/ar/csharpgeneral/thread/2907541f-f1cf-40ea-8291-771734de55f2>
64,601,000
I have a class that extends the AppCompatDialogFragment. I want it to create a popup where the user can input their password. But I get this error every time I run the app. ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference ``` Here is my code for the class onCreateDialog method: ``` override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { //The popup val mBuilder = AlertDialog.Builder(activity) val mFlater = activity?.layoutInflater val mView =mFlater?.inflate(R.layout.activity_get_password, null) //Get the EditText val getPassword: EditText = mView!!.findViewById(R.id.getPassword) mBuilder.setPositiveButton("Ok"){ _, _ ->} //Set the view mBuilder.setView(mView) //Set the AlertDialog val alertDialog = mBuilder.create().apply { setCanceledOnTouchOutside(false) } //Set the clicklistener for the alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val password = getPassword.text.toString() if(password == db?.getPassword()) { //Send the password interfaces?.getPassword(password) //Close the alert dialog alertDialog.dismiss() } else //Wrong password? Toast.makeText(context, "Invalid Password!", Toast.LENGTH_LONG).show() } return alertDialog } ```
2020/10/30
[ "https://Stackoverflow.com/questions/64601000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13063308/" ]
We can use `base R` to do this. Loop over the rows with `apply` (`MARGIN = 1`) with the subset of columns i.e remove the 1st two columns (not needed), then we remove the `NA` in the row (`na.omit`), `if` the `length` of the resultant vector is 1, then create a `data.frame` with both columns as that value or `else`, remove the first and last value to create the 'Stop\_Area', 'Start\_Area'. The output will be a `list`. Then, we `rep`licate the rows of the original dataset based on the number of rows of this `list`, and the `cbind` it with the `list` `cbind`ed ``` lst1 <- apply(df1[-(1:2)], 1, function(x) { x1 <- na.omit(x) if(length(x1) == 1) data.frame(StartArea = x1, Stop_Area = x1) else data.frame(StartArea = x1[-length(x1)], Stop_Area = x1[-1]) }) out <- cbind(df1[1:2][rep(seq_len(nrow(df1)), sapply(lst1, nrow)),], do.call(rbind, lst1)) row.names(out) <- NULL ``` -output ``` out # ID Veh StartArea Stop_Area #1 1 Veh 1 Area A Area B #2 2 Veh 2 Area C Area C #3 3 Veh 3 Area D Area A #4 4 Veh 4 Area E Area F #5 4 Veh 4 Area F Area D #6 4 Veh 4 Area D Area A #7 5 Veh 5 Area H Area B #8 5 Veh 5 Area B Area C #9 6 Veh 6 Area J Area K #10 6 Veh 6 Area K Area A #11 6 Veh 6 Area A Area B ``` ### data ``` df1 <- structure(list(ID = 1:6, Veh = c("Veh 1", "Veh 2", "Veh 3", "Veh 4", "Veh 5", "Veh 6"), Area1 = c("Area A", "Area C", "Area D", "Area E", "Area H", "Area J"), Area2 = c("Area B", NA, "Area A", "Area F", "Area B", "Area K"), Area3 = c(NA, NA, NA, "Area D", "Area C", "Area A"), Area4 = c(NA, NA, NA, "Area A", NA, "Area B")), class = "data.frame", row.names = c(NA, -6L)) ```
*data.table* solution: ``` library(data.table) setDT(df1) melt(df1, id.vars=c("ID","Veh"))[!is.na(value)][ , if(.N == 1) .(start=value, stop=value) else .(start = value[-.N], stop = value[-1]), by=c("ID","Veh") ] # ID Veh start stop # 1: 1 Veh 1 Area A Area B # 2: 2 Veh 2 Area C Area C # 3: 3 Veh 3 Area D Area A # 4: 4 Veh 4 Area E Area F # 5: 4 Veh 4 Area F Area D # 6: 4 Veh 4 Area D Area A # 7: 5 Veh 5 Area H Area B # 8: 5 Veh 5 Area B Area C # 9: 6 Veh 6 Area J Area K #10: 6 Veh 6 Area K Area A #11: 6 Veh 6 Area A Area B ``` Which can be extended further if you want to jump straight to counting how many of each pair: ``` melt(df1, id.vars=c("ID","Veh"))[!is.na(value)][ , if(.N == 1) .(start=value, stop=value) else .(start = value[-.N], stop = value[-1]), by=c("ID","Veh") ][ , .(count = .N), by=c("start","stop") ] # start stop count #1: Area A Area B 2 #2: Area C Area C 1 #3: Area D Area A 2 #4: Area E Area F 1 #5: Area F Area D 1 #6: Area H Area B 1 #7: Area B Area C 1 #8: Area J Area K 1 #9: Area K Area A 1 ```
64,601,000
I have a class that extends the AppCompatDialogFragment. I want it to create a popup where the user can input their password. But I get this error every time I run the app. ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference ``` Here is my code for the class onCreateDialog method: ``` override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { //The popup val mBuilder = AlertDialog.Builder(activity) val mFlater = activity?.layoutInflater val mView =mFlater?.inflate(R.layout.activity_get_password, null) //Get the EditText val getPassword: EditText = mView!!.findViewById(R.id.getPassword) mBuilder.setPositiveButton("Ok"){ _, _ ->} //Set the view mBuilder.setView(mView) //Set the AlertDialog val alertDialog = mBuilder.create().apply { setCanceledOnTouchOutside(false) } //Set the clicklistener for the alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val password = getPassword.text.toString() if(password == db?.getPassword()) { //Send the password interfaces?.getPassword(password) //Close the alert dialog alertDialog.dismiss() } else //Wrong password? Toast.makeText(context, "Invalid Password!", Toast.LENGTH_LONG).show() } return alertDialog } ```
2020/10/30
[ "https://Stackoverflow.com/questions/64601000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13063308/" ]
We can use `base R` to do this. Loop over the rows with `apply` (`MARGIN = 1`) with the subset of columns i.e remove the 1st two columns (not needed), then we remove the `NA` in the row (`na.omit`), `if` the `length` of the resultant vector is 1, then create a `data.frame` with both columns as that value or `else`, remove the first and last value to create the 'Stop\_Area', 'Start\_Area'. The output will be a `list`. Then, we `rep`licate the rows of the original dataset based on the number of rows of this `list`, and the `cbind` it with the `list` `cbind`ed ``` lst1 <- apply(df1[-(1:2)], 1, function(x) { x1 <- na.omit(x) if(length(x1) == 1) data.frame(StartArea = x1, Stop_Area = x1) else data.frame(StartArea = x1[-length(x1)], Stop_Area = x1[-1]) }) out <- cbind(df1[1:2][rep(seq_len(nrow(df1)), sapply(lst1, nrow)),], do.call(rbind, lst1)) row.names(out) <- NULL ``` -output ``` out # ID Veh StartArea Stop_Area #1 1 Veh 1 Area A Area B #2 2 Veh 2 Area C Area C #3 3 Veh 3 Area D Area A #4 4 Veh 4 Area E Area F #5 4 Veh 4 Area F Area D #6 4 Veh 4 Area D Area A #7 5 Veh 5 Area H Area B #8 5 Veh 5 Area B Area C #9 6 Veh 6 Area J Area K #10 6 Veh 6 Area K Area A #11 6 Veh 6 Area A Area B ``` ### data ``` df1 <- structure(list(ID = 1:6, Veh = c("Veh 1", "Veh 2", "Veh 3", "Veh 4", "Veh 5", "Veh 6"), Area1 = c("Area A", "Area C", "Area D", "Area E", "Area H", "Area J"), Area2 = c("Area B", NA, "Area A", "Area F", "Area B", "Area K"), Area3 = c(NA, NA, NA, "Area D", "Area C", "Area A"), Area4 = c(NA, NA, NA, "Area A", NA, "Area B")), class = "data.frame", row.names = c(NA, -6L)) ```
Here is a base R option ``` do.call( rbind, c( make.row.names = FALSE, lapply(split(df, 1:nrow(df)), function(v) { if (length(u <- na.omit(unlist(v[-(1:2)]))) == 1) y <- rep(u, 2) else y <- embed(c(u), 2)[, 2:1] cbind(v[1:2], `colnames<-`(matrix(y, ncol = 2), c("startArea", "stopArea")), row.names = NULL) }) ) ) ``` which gives ``` ID Veh startArea stopArea 1 1 Veh 1 Area A Area B 2 2 Veh 2 Area C Area C 3 3 Veh 3 Area D Area A 4 4 Veh 4 Area E Area F 5 4 Veh 4 Area F Area D 6 4 Veh 4 Area D Area A 7 5 Veh 5 Area H Area B 8 5 Veh 5 Area B Area C 9 6 Veh 6 Area J Area K 10 6 Veh 6 Area K Area A 11 6 Veh 6 Area A Area B ```
64,601,000
I have a class that extends the AppCompatDialogFragment. I want it to create a popup where the user can input their password. But I get this error every time I run the app. ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference ``` Here is my code for the class onCreateDialog method: ``` override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { //The popup val mBuilder = AlertDialog.Builder(activity) val mFlater = activity?.layoutInflater val mView =mFlater?.inflate(R.layout.activity_get_password, null) //Get the EditText val getPassword: EditText = mView!!.findViewById(R.id.getPassword) mBuilder.setPositiveButton("Ok"){ _, _ ->} //Set the view mBuilder.setView(mView) //Set the AlertDialog val alertDialog = mBuilder.create().apply { setCanceledOnTouchOutside(false) } //Set the clicklistener for the alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val password = getPassword.text.toString() if(password == db?.getPassword()) { //Send the password interfaces?.getPassword(password) //Close the alert dialog alertDialog.dismiss() } else //Wrong password? Toast.makeText(context, "Invalid Password!", Toast.LENGTH_LONG).show() } return alertDialog } ```
2020/10/30
[ "https://Stackoverflow.com/questions/64601000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13063308/" ]
Here is a solution based on `tidyverse`. Create df target ---------------- Because `Area C` doesn't have a Stop Area clearly indicated between `Area2-3-4`, we need to replace the missing value in `Area2` with `Area1` when `Area2-3-4` are missing. Note we use `rowwise` and `c_across` to instruct our code to check row by row. At that point you just reshape your data with `pivot_longer` and you remove all NAs by specifying `values_drop_na = TRUE`. Last touch: you can define `StartArea` and `StopArea` for each `ID` and `Veh`. ``` library(tidyr) library(dplyr) df1 <- df1 %>% rowwise() %>% mutate(Area2 = if_else(all(is.na(c_across(c(Area2, Area3, Area4)))), Area1, Area2)) %>% pivot_longer(starts_with("Area"), values_drop_na = TRUE) %>% group_by(ID, Veh) %>% summarise(StartArea = value[-length(value)], StopArea = value[-1], .groups = "drop") df1 #> # A tibble: 11 x 4 #> ID Veh StartArea StopArea #> <int> <chr> <chr> <chr> #> 1 1 Veh 1 Area A Area B #> 2 2 Veh 2 Area C Area C #> 3 3 Veh 3 Area D Area A #> 4 4 Veh 4 Area E Area F #> 5 4 Veh 4 Area F Area D #> 6 4 Veh 4 Area D Area A #> 7 5 Veh 5 Area H Area B #> 8 5 Veh 5 Area B Area C #> 9 6 Veh 6 Area J Area K #> 10 6 Veh 6 Area K Area A #> 11 6 Veh 6 Area A Area B ``` --- Count ----- To count the frequency you can use `count`: ``` df1 %>% count(StartArea, StopArea) #> # A tibble: 9 x 3 #> StartArea StopArea n #> <chr> <chr> <int> #> 1 Area A Area B 2 #> 2 Area B Area C 1 #> 3 Area C Area C 1 #> 4 Area D Area A 2 #> 5 Area E Area F 1 #> 6 Area F Area D 1 #> 7 Area H Area B 1 #> 8 Area J Area K 1 #> 9 Area K Area A 1 ``` If you want to count the couples of Areas that are connected and you do not care about the direction, then you need to sort each row first. ``` df2 <- df1 %>% select(StartArea,StopArea) df2[] <- asplit(apply(df2, 1, sort), 1) # sort by row df2 %>% count(StartArea, StopArea) #> # A tibble: 9 x 3 #> StartArea StopArea n #> <chr> <chr> <int> #> 1 Area A Area B 2 #> 2 Area A Area D 2 #> 3 Area A Area K 1 #> 4 Area B Area C 1 #> 5 Area B Area H 1 #> 6 Area C Area C 1 #> 7 Area D Area F 1 #> 8 Area E Area F 1 #> 9 Area J Area K 1 ``` --- Data ---- ``` df1 <- structure(list(ID = 1:6, Veh = c("Veh 1", "Veh 2", "Veh 3", "Veh 4", "Veh 5", "Veh 6"), Area1 = c("Area A", "Area C", "Area D", "Area E", "Area H", "Area J"), Area2 = c("Area B", NA, "Area A", "Area F", "Area B", "Area K"), Area3 = c(NA, NA, NA, "Area D", "Area C", "Area A"), Area4 = c(NA, NA, NA, "Area A", NA, "Area B")), class = "data.frame", row.names = c(NA, -6L)) ```
*data.table* solution: ``` library(data.table) setDT(df1) melt(df1, id.vars=c("ID","Veh"))[!is.na(value)][ , if(.N == 1) .(start=value, stop=value) else .(start = value[-.N], stop = value[-1]), by=c("ID","Veh") ] # ID Veh start stop # 1: 1 Veh 1 Area A Area B # 2: 2 Veh 2 Area C Area C # 3: 3 Veh 3 Area D Area A # 4: 4 Veh 4 Area E Area F # 5: 4 Veh 4 Area F Area D # 6: 4 Veh 4 Area D Area A # 7: 5 Veh 5 Area H Area B # 8: 5 Veh 5 Area B Area C # 9: 6 Veh 6 Area J Area K #10: 6 Veh 6 Area K Area A #11: 6 Veh 6 Area A Area B ``` Which can be extended further if you want to jump straight to counting how many of each pair: ``` melt(df1, id.vars=c("ID","Veh"))[!is.na(value)][ , if(.N == 1) .(start=value, stop=value) else .(start = value[-.N], stop = value[-1]), by=c("ID","Veh") ][ , .(count = .N), by=c("start","stop") ] # start stop count #1: Area A Area B 2 #2: Area C Area C 1 #3: Area D Area A 2 #4: Area E Area F 1 #5: Area F Area D 1 #6: Area H Area B 1 #7: Area B Area C 1 #8: Area J Area K 1 #9: Area K Area A 1 ```
64,601,000
I have a class that extends the AppCompatDialogFragment. I want it to create a popup where the user can input their password. But I get this error every time I run the app. ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference ``` Here is my code for the class onCreateDialog method: ``` override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { //The popup val mBuilder = AlertDialog.Builder(activity) val mFlater = activity?.layoutInflater val mView =mFlater?.inflate(R.layout.activity_get_password, null) //Get the EditText val getPassword: EditText = mView!!.findViewById(R.id.getPassword) mBuilder.setPositiveButton("Ok"){ _, _ ->} //Set the view mBuilder.setView(mView) //Set the AlertDialog val alertDialog = mBuilder.create().apply { setCanceledOnTouchOutside(false) } //Set the clicklistener for the alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val password = getPassword.text.toString() if(password == db?.getPassword()) { //Send the password interfaces?.getPassword(password) //Close the alert dialog alertDialog.dismiss() } else //Wrong password? Toast.makeText(context, "Invalid Password!", Toast.LENGTH_LONG).show() } return alertDialog } ```
2020/10/30
[ "https://Stackoverflow.com/questions/64601000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13063308/" ]
Here is a solution based on `tidyverse`. Create df target ---------------- Because `Area C` doesn't have a Stop Area clearly indicated between `Area2-3-4`, we need to replace the missing value in `Area2` with `Area1` when `Area2-3-4` are missing. Note we use `rowwise` and `c_across` to instruct our code to check row by row. At that point you just reshape your data with `pivot_longer` and you remove all NAs by specifying `values_drop_na = TRUE`. Last touch: you can define `StartArea` and `StopArea` for each `ID` and `Veh`. ``` library(tidyr) library(dplyr) df1 <- df1 %>% rowwise() %>% mutate(Area2 = if_else(all(is.na(c_across(c(Area2, Area3, Area4)))), Area1, Area2)) %>% pivot_longer(starts_with("Area"), values_drop_na = TRUE) %>% group_by(ID, Veh) %>% summarise(StartArea = value[-length(value)], StopArea = value[-1], .groups = "drop") df1 #> # A tibble: 11 x 4 #> ID Veh StartArea StopArea #> <int> <chr> <chr> <chr> #> 1 1 Veh 1 Area A Area B #> 2 2 Veh 2 Area C Area C #> 3 3 Veh 3 Area D Area A #> 4 4 Veh 4 Area E Area F #> 5 4 Veh 4 Area F Area D #> 6 4 Veh 4 Area D Area A #> 7 5 Veh 5 Area H Area B #> 8 5 Veh 5 Area B Area C #> 9 6 Veh 6 Area J Area K #> 10 6 Veh 6 Area K Area A #> 11 6 Veh 6 Area A Area B ``` --- Count ----- To count the frequency you can use `count`: ``` df1 %>% count(StartArea, StopArea) #> # A tibble: 9 x 3 #> StartArea StopArea n #> <chr> <chr> <int> #> 1 Area A Area B 2 #> 2 Area B Area C 1 #> 3 Area C Area C 1 #> 4 Area D Area A 2 #> 5 Area E Area F 1 #> 6 Area F Area D 1 #> 7 Area H Area B 1 #> 8 Area J Area K 1 #> 9 Area K Area A 1 ``` If you want to count the couples of Areas that are connected and you do not care about the direction, then you need to sort each row first. ``` df2 <- df1 %>% select(StartArea,StopArea) df2[] <- asplit(apply(df2, 1, sort), 1) # sort by row df2 %>% count(StartArea, StopArea) #> # A tibble: 9 x 3 #> StartArea StopArea n #> <chr> <chr> <int> #> 1 Area A Area B 2 #> 2 Area A Area D 2 #> 3 Area A Area K 1 #> 4 Area B Area C 1 #> 5 Area B Area H 1 #> 6 Area C Area C 1 #> 7 Area D Area F 1 #> 8 Area E Area F 1 #> 9 Area J Area K 1 ``` --- Data ---- ``` df1 <- structure(list(ID = 1:6, Veh = c("Veh 1", "Veh 2", "Veh 3", "Veh 4", "Veh 5", "Veh 6"), Area1 = c("Area A", "Area C", "Area D", "Area E", "Area H", "Area J"), Area2 = c("Area B", NA, "Area A", "Area F", "Area B", "Area K"), Area3 = c(NA, NA, NA, "Area D", "Area C", "Area A"), Area4 = c(NA, NA, NA, "Area A", NA, "Area B")), class = "data.frame", row.names = c(NA, -6L)) ```
Here is a base R option ``` do.call( rbind, c( make.row.names = FALSE, lapply(split(df, 1:nrow(df)), function(v) { if (length(u <- na.omit(unlist(v[-(1:2)]))) == 1) y <- rep(u, 2) else y <- embed(c(u), 2)[, 2:1] cbind(v[1:2], `colnames<-`(matrix(y, ncol = 2), c("startArea", "stopArea")), row.names = NULL) }) ) ) ``` which gives ``` ID Veh startArea stopArea 1 1 Veh 1 Area A Area B 2 2 Veh 2 Area C Area C 3 3 Veh 3 Area D Area A 4 4 Veh 4 Area E Area F 5 4 Veh 4 Area F Area D 6 4 Veh 4 Area D Area A 7 5 Veh 5 Area H Area B 8 5 Veh 5 Area B Area C 9 6 Veh 6 Area J Area K 10 6 Veh 6 Area K Area A 11 6 Veh 6 Area A Area B ```
15,483,396
I have the following code to overplot three sets of data, count rate vs time, for three different sets of time ranges: ``` #!/usr/bin/env python from pylab import rc, array, subplot, zeros, savefig, ylim, xlabel, ylabel, errorbar, FormatStrFormatter, gca, axis from scipy import optimize, stats import numpy as np import pyfits, os, re, glob, sys rc('font',**{'family':'serif','serif':['Helvetica']}) rc('ps',usedistiller='xpdf') rc('text', usetex=True) #------------------------------------------------------ tmin=56200 tmax=56249 data=pyfits.open('http://heasarc.gsfc.nasa.gov/docs/swift/results/transients/weak/GX304-1.orbit.lc.fits') time = data[1].data.field(0)/86400. + data[1].header['MJDREFF'] + data[1].header['MJDREFI'] rate = data[1].data.field(1) error = data[1].data.field(2) data.close() cond = ((time > tmin-5) & (time < tmax)) time=time[cond] rate=rate[cond] error=error[cond] errorbar(time, rate, error, fmt='r.', capsize=0) gca().xaxis.set_major_formatter(FormatStrFormatter('%5.1f')) axis([tmin-10,tmax,-0.00,0.45]) xlabel('Time, MJD') savefig("sync.eps",orientation='portrait',papertype='a4',format='eps') ``` As, in this way, the plot is too much confusing, I thought to fit the curves. I tried with UnivariateSpline, but this completely messes up my data. Any advice please? Should I first define a function to fit those data? I also looked for "least-squared": is this the best solution to this problem?
2013/03/18
[ "https://Stackoverflow.com/questions/15483396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2107030/" ]
This is how I solved: ``` #!/usr/bin/env python import pyfits, os, re, glob, sys from scipy.optimize import leastsq from numpy import * from pylab import * from scipy import * rc('font',**{'family':'serif','serif':['Helvetica']}) rc('ps',usedistiller='xpdf') rc('text', usetex=True) #------------------------------------------------------ tmin = 56200 tmax = 56249 pi = 3.14 data=pyfits.open('http://heasarc.gsfc.nasa.gov/docs/swift/results/transients/weak/GX304-1.orbit.lc.fits') time = data[1].data.field(0)/86400. + data[1].header['MJDREFF'] + data[1].header['MJDREFI'] rate = data[1].data.field(1) error = data[1].data.field(2) data.close() cond = ((time > tmin-5) & (time < tmax)) time=time[cond] rate=rate[cond] error=error[cond] gauss_fit = lambda p, x: p[0]*(1/(2*pi*(p[2]**2))**(1/2))*exp(-(x-p[1])**2/(2*p[2]**2))+p[3]*(1/sqrt(2*pi*(p[5]**2)))*exp(-(x-p[4])**2/(2*p[5]**2)) #1d Gaussian func e_gauss_fit = lambda p, x, y: (gauss_fit(p, x) -y) #1d Gaussian fit v0= [0.20, 56210.0, 1, 0.40, 56234.0, 1] #inital guesses for Gaussian Fit, just do it around the peaks out = leastsq(e_gauss_fit, v0[:], args=(time, rate), maxfev=100000, full_output=1) #Gauss Fit v = out[0] #fit parameters out xxx = arange(min(time), max(time), time[1] - time[0]) ccc = gauss_fit(v, xxx) # this will only work if the units are pixel and not wavelength fig = figure(figsize=(9, 9)) #make a plot ax1 = fig.add_subplot(111) ax1.plot(time, rate, 'g.') #spectrum ax1.plot(xxx, ccc, 'b-') #fitted spectrum savefig("plotfitting.png") axis([tmin-10,tmax,-0.00,0.45]) ``` From [here](http://www.krioma.net/wp/blog/2011/12/multiple-gaussian-fitting-in-python.php). What about if I would like to fit with different functions the raising and the decaying part of the curves?
I use this for fitting. It is adapted from somewhere on the internet, but I forgot where. ``` from __future__ import print_function from __future__ import division from __future__ import absolute_import import numpy from scipy.optimize.minpack import leastsq ### functions ### def eq_cos(A, t): """ 4 parameters function: A[0] + A[1] * numpy.cos(2 * numpy.pi * A[2] * t + A[3]) A[0]: offset A[1]: amplitude A[2]: frequency A[3]: phase """ return A[0] + A[1] * numpy.cos(2 * numpy.pi * A[2] * t + numpy.pi*A[3]) def linear(A, t): """ A[0]: y-offset A[1]: slope """ return A[0] + A[1] * t ### fitting routines ### def minimize(A, t, y0, function): """ Needed for fit """ return y0 - function(A, t) def fit(x_array, y_array, function, A_start): """ Fit data 20101209/RB: started 20130131/RB: added example to doc-string INPUT: x_array: the array with time or something y-array: the array with the values that have to be fitted function: one of the functions, in the format as in the file "Equations" A_start: a starting point for the fitting OUTPUT: A_final: the final parameters of the fitting EXAMPLE: Fit some data to this function above def linear(A, t): return A[0] + A[1] * t ### x = x-axis y = some data A = [0,1] # initial guess A_final = fit(x, y, linear, A) ### WARNING: Always check the result, it might sometimes be sensitive to a good starting point. """ param = (x_array, y_array, function) A_final, cov_x, infodict, mesg, ier = leastsq(minimize, A_start, args=param, full_output = True) return A_final if __name__ == '__main__': # data x = numpy.arange(10) y = x + numpy.random.rand(10) # values between 0 and 1 # initial guesss A = [0,0.5] # fit A_final = fit(x, y, linear, A) # result is linear with a little offset print(A_final) ```
28,367,729
I want to generate an array of all the permutations for a time-series. Suppose the numbers can be 0, 5, 10, 25 and the first permutation is [0,0,0,0,0,0,0]. The next permutation can be [0,0,0,0,0,0,5] and so on up until [25,25,25,25,25,25,25]. There should be 4^6 = 4096 permutations in this case because there are 4 numbers and 7 slots. Can someone please help me understand how to get started on this problem? I want to write this in javascript. Thanks for your consideration.
2015/02/06
[ "https://Stackoverflow.com/questions/28367729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814381/" ]
See the attached script, something i just put together. It should work in your case. I've limited to 4 permutations, but it should be easy to expand to 7. I hope you see the pattern. ```js var array = new Array(); var values = [0,5,10,25]; for(var i = 0; i < Math.pow(4,4); i++) { // calculate which indexes to retrieve value from loops through 1..4 var entry = [ Math.floor(i / Math.pow(4,0)) % 4, // increment this with every i Math.floor(i / Math.pow(4,1)) % 4, // increment this with every 4 * i Math.floor(i / Math.pow(4,2)) % 4, // increment this with every 16 * i Math.floor(i / Math.pow(4,3)) % 4 // increment this with every 64 * i etc ]; array.push([values[entry[0]], values[entry[1]], values[entry[2]],values[entry[3]]]); } document.write(JSON.stringify(array)); ```
Below, I created a loop to generate all permutations. It is an iterative solution. **Update**: I have reduced my code down to the following: ``` function permutations(series, size) { return zeroFill(Math.pow(series.length,size)).map(function(r,i) { return zeroFill(size).map(function(c,j) { return series[Math.floor(i/Math.pow(series.length,j))%series.length]; }).reverse(); }); } function zeroFill(n) { return new Array(n+1).join('0').split(''); } ``` Since this is a very memory intensive process, I remove `25` from the list and reduced each processed entry to a length of `5`. ```js var out = document.getElementById('output'); var permutations = generate([0, 5, 10], 5); printResults(permutations); // Generate permutations. function generate(series, size) { var result = []; var len = series.length; var limit = Math.pow(len, size); for (var i = 0; i < limit; i++) { var entry = []; for (var j = 0; j < size; j++) { entry[size-j] = series[Math.floor(i / Math.pow(len, j)) % len]; } result.push(entry); } return result; } // Utility Functions - These are for display purposes. function printResults(list) { var width = ('' + list.length).length; list.forEach(function(list, index) { print('[' + FormatNumberLength(index, width) + '] ' + numberJoin(list, 3)); }); } function print(text) { out.innerHTML += text + '<br />'; } function numberJoin(intList, width) { return intList.map(function(value) { return FormatNumberLength(value, width); }).join(' '); } function FormatNumberLength(num, length, useZero) { var c = useZero ? '0' : ' '; var r = "" + num; while (r.length < length) r = c + r; return r; } ``` ```css #output { font-family: monospace; white-space: pre; } ``` ```html <div id="output"></div> ``` Expected result ``` [ 0] 0 0 0 0 0 [ 1] 0 0 0 0 5 [ 2] 0 0 0 0 10 [ 3] 0 0 0 5 0 [ 4] 0 0 0 5 5 [ 5] 0 0 0 5 10 [ 6] 0 0 0 10 0 [ 7] 0 0 0 10 5 [ 8] 0 0 0 10 10 [ 9] 0 0 5 0 0 [ 10] 0 0 5 0 5 [ 11] 0 0 5 0 10 [ 12] 0 0 5 5 0 [ 13] 0 0 5 5 5 [ 14] 0 0 5 5 10 [ 15] 0 0 5 10 0 [ 16] 0 0 5 10 5 [ 17] 0 0 5 10 10 [ 18] 0 0 10 0 0 [ 19] 0 0 10 0 5 [ 20] 0 0 10 0 10 [ 21] 0 0 10 5 0 [ 22] 0 0 10 5 5 [ 23] 0 0 10 5 10 [ 24] 0 0 10 10 0 [ 25] 0 0 10 10 5 [ 26] 0 0 10 10 10 [ 27] 0 5 0 0 0 [ 28] 0 5 0 0 5 [ 29] 0 5 0 0 10 [ 30] 0 5 0 5 0 [ 31] 0 5 0 5 5 [ 32] 0 5 0 5 10 [ 33] 0 5 0 10 0 [ 34] 0 5 0 10 5 [ 35] 0 5 0 10 10 [ 36] 0 5 5 0 0 [ 37] 0 5 5 0 5 [ 38] 0 5 5 0 10 [ 39] 0 5 5 5 0 [ 40] 0 5 5 5 5 [ 41] 0 5 5 5 10 [ 42] 0 5 5 10 0 [ 43] 0 5 5 10 5 [ 44] 0 5 5 10 10 [ 45] 0 5 10 0 0 [ 46] 0 5 10 0 5 [ 47] 0 5 10 0 10 [ 48] 0 5 10 5 0 [ 49] 0 5 10 5 5 [ 50] 0 5 10 5 10 [ 51] 0 5 10 10 0 [ 52] 0 5 10 10 5 [ 53] 0 5 10 10 10 [ 54] 0 10 0 0 0 [ 55] 0 10 0 0 5 [ 56] 0 10 0 0 10 [ 57] 0 10 0 5 0 [ 58] 0 10 0 5 5 [ 59] 0 10 0 5 10 [ 60] 0 10 0 10 0 [ 61] 0 10 0 10 5 [ 62] 0 10 0 10 10 [ 63] 0 10 5 0 0 [ 64] 0 10 5 0 5 [ 65] 0 10 5 0 10 [ 66] 0 10 5 5 0 [ 67] 0 10 5 5 5 [ 68] 0 10 5 5 10 [ 69] 0 10 5 10 0 [ 70] 0 10 5 10 5 [ 71] 0 10 5 10 10 [ 72] 0 10 10 0 0 [ 73] 0 10 10 0 5 [ 74] 0 10 10 0 10 [ 75] 0 10 10 5 0 [ 76] 0 10 10 5 5 [ 77] 0 10 10 5 10 [ 78] 0 10 10 10 0 [ 79] 0 10 10 10 5 [ 80] 0 10 10 10 10 [ 81] 5 0 0 0 0 [ 82] 5 0 0 0 5 [ 83] 5 0 0 0 10 [ 84] 5 0 0 5 0 [ 85] 5 0 0 5 5 [ 86] 5 0 0 5 10 [ 87] 5 0 0 10 0 [ 88] 5 0 0 10 5 [ 89] 5 0 0 10 10 [ 90] 5 0 5 0 0 [ 91] 5 0 5 0 5 [ 92] 5 0 5 0 10 [ 93] 5 0 5 5 0 [ 94] 5 0 5 5 5 [ 95] 5 0 5 5 10 [ 96] 5 0 5 10 0 [ 97] 5 0 5 10 5 [ 98] 5 0 5 10 10 [ 99] 5 0 10 0 0 [100] 5 0 10 0 5 [101] 5 0 10 0 10 [102] 5 0 10 5 0 [103] 5 0 10 5 5 [104] 5 0 10 5 10 [105] 5 0 10 10 0 [106] 5 0 10 10 5 [107] 5 0 10 10 10 [108] 5 5 0 0 0 [109] 5 5 0 0 5 [110] 5 5 0 0 10 [111] 5 5 0 5 0 [112] 5 5 0 5 5 [113] 5 5 0 5 10 [114] 5 5 0 10 0 [115] 5 5 0 10 5 [116] 5 5 0 10 10 [117] 5 5 5 0 0 [118] 5 5 5 0 5 [119] 5 5 5 0 10 [120] 5 5 5 5 0 [121] 5 5 5 5 5 [122] 5 5 5 5 10 [123] 5 5 5 10 0 [124] 5 5 5 10 5 [125] 5 5 5 10 10 [126] 5 5 10 0 0 [127] 5 5 10 0 5 [128] 5 5 10 0 10 [129] 5 5 10 5 0 [130] 5 5 10 5 5 [131] 5 5 10 5 10 [132] 5 5 10 10 0 [133] 5 5 10 10 5 [134] 5 5 10 10 10 [135] 5 10 0 0 0 [136] 5 10 0 0 5 [137] 5 10 0 0 10 [138] 5 10 0 5 0 [139] 5 10 0 5 5 [140] 5 10 0 5 10 [141] 5 10 0 10 0 [142] 5 10 0 10 5 [143] 5 10 0 10 10 [144] 5 10 5 0 0 [145] 5 10 5 0 5 [146] 5 10 5 0 10 [147] 5 10 5 5 0 [148] 5 10 5 5 5 [149] 5 10 5 5 10 [150] 5 10 5 10 0 [151] 5 10 5 10 5 [152] 5 10 5 10 10 [153] 5 10 10 0 0 [154] 5 10 10 0 5 [155] 5 10 10 0 10 [156] 5 10 10 5 0 [157] 5 10 10 5 5 [158] 5 10 10 5 10 [159] 5 10 10 10 0 [160] 5 10 10 10 5 [161] 5 10 10 10 10 [162] 10 0 0 0 0 [163] 10 0 0 0 5 [164] 10 0 0 0 10 [165] 10 0 0 5 0 [166] 10 0 0 5 5 [167] 10 0 0 5 10 [168] 10 0 0 10 0 [169] 10 0 0 10 5 [170] 10 0 0 10 10 [171] 10 0 5 0 0 [172] 10 0 5 0 5 [173] 10 0 5 0 10 [174] 10 0 5 5 0 [175] 10 0 5 5 5 [176] 10 0 5 5 10 [177] 10 0 5 10 0 [178] 10 0 5 10 5 [179] 10 0 5 10 10 [180] 10 0 10 0 0 [181] 10 0 10 0 5 [182] 10 0 10 0 10 [183] 10 0 10 5 0 [184] 10 0 10 5 5 [185] 10 0 10 5 10 [186] 10 0 10 10 0 [187] 10 0 10 10 5 [188] 10 0 10 10 10 [189] 10 5 0 0 0 [190] 10 5 0 0 5 [191] 10 5 0 0 10 [192] 10 5 0 5 0 [193] 10 5 0 5 5 [194] 10 5 0 5 10 [195] 10 5 0 10 0 [196] 10 5 0 10 5 [197] 10 5 0 10 10 [198] 10 5 5 0 0 [199] 10 5 5 0 5 [200] 10 5 5 0 10 [201] 10 5 5 5 0 [202] 10 5 5 5 5 [203] 10 5 5 5 10 [204] 10 5 5 10 0 [205] 10 5 5 10 5 [206] 10 5 5 10 10 [207] 10 5 10 0 0 [208] 10 5 10 0 5 [209] 10 5 10 0 10 [210] 10 5 10 5 0 [211] 10 5 10 5 5 [212] 10 5 10 5 10 [213] 10 5 10 10 0 [214] 10 5 10 10 5 [215] 10 5 10 10 10 [216] 10 10 0 0 0 [217] 10 10 0 0 5 [218] 10 10 0 0 10 [219] 10 10 0 5 0 [220] 10 10 0 5 5 [221] 10 10 0 5 10 [222] 10 10 0 10 0 [223] 10 10 0 10 5 [224] 10 10 0 10 10 [225] 10 10 5 0 0 [226] 10 10 5 0 5 [227] 10 10 5 0 10 [228] 10 10 5 5 0 [229] 10 10 5 5 5 [230] 10 10 5 5 10 [231] 10 10 5 10 0 [232] 10 10 5 10 5 [233] 10 10 5 10 10 [234] 10 10 10 0 0 [235] 10 10 10 0 5 [236] 10 10 10 0 10 [237] 10 10 10 5 0 [238] 10 10 10 5 5 [239] 10 10 10 5 10 [240] 10 10 10 10 0 [241] 10 10 10 10 5 [242] 10 10 10 10 10 ```
2,838,424
The general formula for finding this is provided in [this question](https://math.stackexchange.com/q/1543081/470240) (the same formula is given in my book, too, but without proof) which asked for a proof of the same. After reading the proof in the accepted answer, my brain is all factorised and broken up into pieces. Please help! Please see my reasoning in the comments of @CambridgeGrad 's answer. Can you extend that reasoning to find the no. of ways in which a number can be expressed as a product of $n$ factors?
2018/07/02
[ "https://math.stackexchange.com/questions/2838424", "https://math.stackexchange.com", "https://math.stackexchange.com/users/470240/" ]
Let the unique prime factorisation of $N=p\_1^{a\_1}p\_2^{a\_2}\dotsm p\_k^{a\_k}$. The divisors of $N$ are precisely the numbers of the form, $$ d=p\_1^{b\_1}p\_2^{b\_2}\dotsm p\_k^{b\_k} $$ where $0\le b\_i\le a\_i$ for $1\le i\le k$. This gives $a\_i+1$ choices for the exponent of $p\_i$, and so $$c=(a\_1+1)(a\_2+1)\dotsm(a\_k+1)$$ choices in total for divisors $d$. Your question resolves into how many ways you can form two factors out of $N$ such that their product is $N$. This is clearly of the form $N=d\cdot\frac{N}{d}$. One thing to note is that $d=\frac{N}{d}$ if and only if $N=d^2$. Now if $N$ is not a perfect square the choices for $d$ run through $c$ choices, and also the number of choices for $\frac{N}{d}$ is also $c$; you can think of $N=d\cdot\frac{N}{d}$, and also $N=\frac{N}{d}\cdot d$ both occurring as we run through the $c$ choices for $d$ and $\frac{N}{d}$, so the number of distinct factorisations without regard to order is thus $\frac12 c$. Now if $N$ is a perfect square, say $N=m^2$, we have that $m=\sqrt{N}$ is *one* divisor from our $c$ amount of choices, but gives rise to an *extra* product from the non-square case, this leads to two cases giving the same product, i.e., one where $\left(d,\frac{N}{d}\right)=(m,m)$ and one where $\left(\frac{N}{d},d\right)=(m,m)$, so this same product $m\cdot m$ gets counted twice and we thus have to half. Now we have a $c-1$ amount of the divisors distinct from $m$, and as before this leads to $\frac12 (c-1)$ amount of choices of these $c-1$ divisors as products. Now adding for the $m\cdot m$ product we have $\frac12 ((c-1)+2)=\frac12 (c+1)$ number if $N$ is a perfect square.
So suppose your number is $N=p\_1^{\alpha\_1}p\_2^{\alpha\_2}...p\_k^{\alpha\_k}$, as they did in the other answer. Now, by unique factorisation into primes, the factors of $N$ are precisely the numbers of the form $$ m=p\_1^{\beta\_1}p\_2^{\beta\_2}...p\_k^{\beta\_k} $$ where $\beta\_i\le\alpha\_i$ for all i. There are $\alpha\_1+1$ choices for the exponent of $p\_1$ (remembering to include 0), $\alpha\_2+1$ choices for the exponent of $p\_2$, etc. So this gives exactly $$l=(\alpha\_1+1)(\alpha\_2+1)...(\alpha\_k+1)$$ factors of $N$. If $N$ is not a prefect square, any factorisation must be of the form $N=mn$ where $m\neq n$. Hence we get $\frac{1}{2}l$ factorisations into 2 numbers. On the other hand, if $N$ is a perfect square, then for all the $l-1$ factors not equal to $\sqrt{N}$, we get a pair as before giving $\frac{1}{2}(l-1)$ factorisations, and then the factorisation $N=\sqrt{N}\sqrt{N}$ means we have $$\frac{1}{2}(l-1)+1=\frac{1}{2}(l+1)$$ in total. Hope that helps clear it up.
23,246,077
From everything I've seen everywhere on teh Googles, this appears to be a problem. I have some code (posted below) which works fine for any smaller report, but once there are ~5K or more records returned, it refuses to export. Anyone got any ideas? Due to corporate restrictions, we can't use any 3rd party tools or add-ins that are not standard in VS2010. **My code:** Just before I bind the datasource to the gridview when I run the report, I fill a session variable with the datasource: ``` var adapter = new SqlDataAdapter(cmd2); var ds = new DataSet(); adapter.Fill(ds, "MyTableName"); // Add this to a session variable so the datagrid won't get NULLed out on repost Session["SSRptMenu"] = ds; ``` I do this because the user may or may not choose to export it once it's done running. If they choose to export it, it's quicker to use the session variable to re-fill the gridview. Then, I have a separate function that is responsible for exporting the report. I have to refill the gridview, so I use the session variable to do so: ``` private void ExportGridView() { // Exports the data in the GridView to Excel // First, fill the datagrid with the results of the session variable DataSet gridDataSource = (DataSet)Session["SSRptMenu"]; GridView_Reports.Visible = true; GridView_Reports.DataSource = gridDataSource; GridView_Reports.DataBind(); // Exports the data in the GridView to Excel string attachment = "attachment; filename=RingMaster.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView_Reports.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } ``` Like I said, this works flawlessly on smaller reports, but exports nothing but a blank sheet when you get around 5K or more records.
2014/04/23
[ "https://Stackoverflow.com/questions/23246077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2174085/" ]
Try setting `<httpRuntime maxRequestLength="1048576"/>` in your config file (or some other number to accommodate your needs). By default, [maxRequestLength](http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx) only allows for 4MB of data.
Check the Response buffer limit. The default is only set to 4MB. Instruction to [Edit ASP Settings (IIS 7)](http://technet.microsoft.com/en-us/library/cc730855%28v=ws.10%29.aspx)
23,246,077
From everything I've seen everywhere on teh Googles, this appears to be a problem. I have some code (posted below) which works fine for any smaller report, but once there are ~5K or more records returned, it refuses to export. Anyone got any ideas? Due to corporate restrictions, we can't use any 3rd party tools or add-ins that are not standard in VS2010. **My code:** Just before I bind the datasource to the gridview when I run the report, I fill a session variable with the datasource: ``` var adapter = new SqlDataAdapter(cmd2); var ds = new DataSet(); adapter.Fill(ds, "MyTableName"); // Add this to a session variable so the datagrid won't get NULLed out on repost Session["SSRptMenu"] = ds; ``` I do this because the user may or may not choose to export it once it's done running. If they choose to export it, it's quicker to use the session variable to re-fill the gridview. Then, I have a separate function that is responsible for exporting the report. I have to refill the gridview, so I use the session variable to do so: ``` private void ExportGridView() { // Exports the data in the GridView to Excel // First, fill the datagrid with the results of the session variable DataSet gridDataSource = (DataSet)Session["SSRptMenu"]; GridView_Reports.Visible = true; GridView_Reports.DataSource = gridDataSource; GridView_Reports.DataBind(); // Exports the data in the GridView to Excel string attachment = "attachment; filename=RingMaster.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView_Reports.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } ``` Like I said, this works flawlessly on smaller reports, but exports nothing but a blank sheet when you get around 5K or more records.
2014/04/23
[ "https://Stackoverflow.com/questions/23246077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2174085/" ]
Try setting `<httpRuntime maxRequestLength="1048576"/>` in your config file (or some other number to accommodate your needs). By default, [maxRequestLength](http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx) only allows for 4MB of data.
You're allowed to use jQuery right? as that's included as standard in VS2010...? There is a plugin for jQuery that will upload an unlimited size file, by splitting it into smaller chunks. The link is <https://github.com/blueimp/jQuery-File-Upload> I understand that you can't use this directly due to your limitation on the use of 3rd party code, but you can still look at the source and maybe get some ideas of how to do this yourself with your own code.
23,246,077
From everything I've seen everywhere on teh Googles, this appears to be a problem. I have some code (posted below) which works fine for any smaller report, but once there are ~5K or more records returned, it refuses to export. Anyone got any ideas? Due to corporate restrictions, we can't use any 3rd party tools or add-ins that are not standard in VS2010. **My code:** Just before I bind the datasource to the gridview when I run the report, I fill a session variable with the datasource: ``` var adapter = new SqlDataAdapter(cmd2); var ds = new DataSet(); adapter.Fill(ds, "MyTableName"); // Add this to a session variable so the datagrid won't get NULLed out on repost Session["SSRptMenu"] = ds; ``` I do this because the user may or may not choose to export it once it's done running. If they choose to export it, it's quicker to use the session variable to re-fill the gridview. Then, I have a separate function that is responsible for exporting the report. I have to refill the gridview, so I use the session variable to do so: ``` private void ExportGridView() { // Exports the data in the GridView to Excel // First, fill the datagrid with the results of the session variable DataSet gridDataSource = (DataSet)Session["SSRptMenu"]; GridView_Reports.Visible = true; GridView_Reports.DataSource = gridDataSource; GridView_Reports.DataBind(); // Exports the data in the GridView to Excel string attachment = "attachment; filename=RingMaster.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView_Reports.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } ``` Like I said, this works flawlessly on smaller reports, but exports nothing but a blank sheet when you get around 5K or more records.
2014/04/23
[ "https://Stackoverflow.com/questions/23246077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2174085/" ]
Try setting `<httpRuntime maxRequestLength="1048576"/>` in your config file (or some other number to accommodate your needs). By default, [maxRequestLength](http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx) only allows for 4MB of data.
``` Please try the code after HttpContext.Current.Response.Write(tw.ToString()); and place your HttpContext.Current.Response.End(); after the catch. #region " Summary - Excel Upload " private void fnExcelUpload() { try { dgDashboard.AllowPaging = false; dgDashboard.Columns[0].Visible = false; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename = ExcelExport.xls"); Response.Charset = ""; Response.Buffer = true; this.EnableViewState = false; StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); fillDashboard(); dgDashboard.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.ApplicationInstance.CompleteRequest(); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.End(); } catch (Exception Ex) { ErrorLog obj = new ErrorLog(Session["PROGRAMCODE"].ToString(), Ex.Message, Ex.StackTrace, this.Page.ToString(), new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, System.Net.Dns.GetHostEntry(Context.Request.ServerVariables["REMOTE_HOST"]).HostName.ToString(), Session["EMPNUMBER"].ToString(), HttpContext.Current.User.Identity.Name.ToString()); } HttpContext.Current.Response.End(); } protected void imgExcelExport_Click(object sender, ImageClickEventArgs e) { fnExcelUpload(); } #endregion #region " Summary - Excel Upload " private void fnExcelUpload() { try { dgDashboard.AllowPaging = false; dgDashboard.Columns[0].Visible = false; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename = ExcelExport.xls"); Response.Charset = ""; Response.Buffer = true; this.EnableViewState = false; StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); fillDashboard(); dgDashboard.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.ApplicationInstance.CompleteRequest(); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.End(); } catch (Exception Ex) { ErrorLog obj = new ErrorLog(Session["PROGRAMCODE"].ToString(), Ex.Message, Ex.StackTrace, this.Page.ToString(), new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, System.Net.Dns.GetHostEntry(Context.Request.ServerVariables["REMOTE_HOST"]).HostName.ToString(), Session["EMPNUMBER"].ToString(), HttpContext.Current.User.Identity.Name.ToString()); } HttpContext.Current.Response.End(); } protected void imgExcelExport_Click(object sender, ImageClickEventArgs e) { fnExcelUpload(); } #endregion ```
24,762,394
I'm trying to get the current fragment from a Service but I'm getting null. Service: ``` MainActivity mainActivity=new MainActivity(); FragmentManager fm= mainActivity.getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentByTag("myFragment"); if (currentFragment.isVisible()){ // send some stuff } else { // create notification } ``` Basically I need it to send some values if it's visible or if it's not visible to create a notification. Both are working but when I put my logic in there I get null value for the currentFragment. Thanks.
2014/07/15
[ "https://Stackoverflow.com/questions/24762394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1115299/" ]
First of all, if I were you I would move that piece of code to `MainActivity`. Then, there is several design patterns how you could communicate between Activity and Service: 1. Using Intents 2. [Bind to Services](http://developer.android.com/guide/components/bound-services.html) 3. Using Service object itself (Singleton pattern) In your case, I would choose 2 or 3 options. Secondly, implement [Observer pattern](http://www.vogella.com/tutorials/DesignPatternObserver/article.html) there Activity should be `observer` and Service could be `subject`. Finally, in `onCreate()` method register as to Service as a observer in order to get messages as method calls from service. How to register depends on what option you will choose. P.S. I think it is obvious that you get no fragments by just creating Activity object because fragments creates on some lifecycle methods which is called by Android OS.
I would first debug by checking all the fragment names: ``` List<Fragment> fragmentList = fragmentManager.getFragments(); Log.d("MyClass", "fragmentList count: " + fragmentManager.getBackStackEntryCount()); for (Fragment fragment : fragmentList) { Log.d("MyClass", "fragmentList: " + fragment.getId() + " : "+ fragment.getTag()); } ```
24,762,394
I'm trying to get the current fragment from a Service but I'm getting null. Service: ``` MainActivity mainActivity=new MainActivity(); FragmentManager fm= mainActivity.getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentByTag("myFragment"); if (currentFragment.isVisible()){ // send some stuff } else { // create notification } ``` Basically I need it to send some values if it's visible or if it's not visible to create a notification. Both are working but when I put my logic in there I get null value for the currentFragment. Thanks.
2014/07/15
[ "https://Stackoverflow.com/questions/24762394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1115299/" ]
I would first debug by checking all the fragment names: ``` List<Fragment> fragmentList = fragmentManager.getFragments(); Log.d("MyClass", "fragmentList count: " + fragmentManager.getBackStackEntryCount()); for (Fragment fragment : fragmentList) { Log.d("MyClass", "fragmentList: " + fragment.getId() + " : "+ fragment.getTag()); } ```
Ok, Here's how I could do it: MainActivity: ``` Static Context context; ... context=this; ``` Service: ``` FragmentManager fm = ((FragmentActivity) MainActivity.context).getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentByTag("myFragment"); if (currentFragment.isVisible()){ // send some stuff } else { // create notification } ``` Edit1: With the help of LordRaydenMK I've just made it easier. Don't know how I didn't remember to do this way sooner. Fragment: ``` static boolean visible; OnResume visible=true; OnPause visible=false; ``` Service: ``` if (MyFragment.visible()){ // send some stuff } else { // create notification } ```
24,762,394
I'm trying to get the current fragment from a Service but I'm getting null. Service: ``` MainActivity mainActivity=new MainActivity(); FragmentManager fm= mainActivity.getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentByTag("myFragment"); if (currentFragment.isVisible()){ // send some stuff } else { // create notification } ``` Basically I need it to send some values if it's visible or if it's not visible to create a notification. Both are working but when I put my logic in there I get null value for the currentFragment. Thanks.
2014/07/15
[ "https://Stackoverflow.com/questions/24762394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1115299/" ]
First of all, if I were you I would move that piece of code to `MainActivity`. Then, there is several design patterns how you could communicate between Activity and Service: 1. Using Intents 2. [Bind to Services](http://developer.android.com/guide/components/bound-services.html) 3. Using Service object itself (Singleton pattern) In your case, I would choose 2 or 3 options. Secondly, implement [Observer pattern](http://www.vogella.com/tutorials/DesignPatternObserver/article.html) there Activity should be `observer` and Service could be `subject`. Finally, in `onCreate()` method register as to Service as a observer in order to get messages as method calls from service. How to register depends on what option you will choose. P.S. I think it is obvious that you get no fragments by just creating Activity object because fragments creates on some lifecycle methods which is called by Android OS.
Ok, Here's how I could do it: MainActivity: ``` Static Context context; ... context=this; ``` Service: ``` FragmentManager fm = ((FragmentActivity) MainActivity.context).getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentByTag("myFragment"); if (currentFragment.isVisible()){ // send some stuff } else { // create notification } ``` Edit1: With the help of LordRaydenMK I've just made it easier. Don't know how I didn't remember to do this way sooner. Fragment: ``` static boolean visible; OnResume visible=true; OnPause visible=false; ``` Service: ``` if (MyFragment.visible()){ // send some stuff } else { // create notification } ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
the problem is that in some cases `$errors` variable isn't created. Use `if(isset($errors) && $errors))` actually in the view all you need is `<?php echo validation_errors(); ?>`, no need to assign it to a variable take a look at <http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html> for more about how to show errors
Change this: ``` <?php if(isset($errors)){ ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <? } ?> ``` **UPDATE:** But you have a lot of other problems in your code. You need to clear it. For example: You didn't load the errors. And you let to create user without validation.
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
Change this: ``` <?php if(isset($errors)){ ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <? } ?> ``` **UPDATE:** But you have a lot of other problems in your code. You need to clear it. For example: You didn't load the errors. And you let to create user without validation.
Please try this ``` <?php if(isset($errors) && $errors!=''){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
You didn't post `$data` to view. You should use like this: ``` $this->load->view('register_user', $data); ```
Change this: ``` <?php if(isset($errors)){ ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <? } ?> ``` **UPDATE:** But you have a lot of other problems in your code. You need to clear it. For example: You didn't load the errors. And you let to create user without validation.
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
Change this: ``` <?php if(isset($errors)){ ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <? } ?> ``` **UPDATE:** But you have a lot of other problems in your code. You need to clear it. For example: You didn't load the errors. And you let to create user without validation.
or you can try this: ``` <?php if(isset($errors) && ('' != $errors) && (null != $errors)): ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <?php endif; ?> ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
the problem is that in some cases `$errors` variable isn't created. Use `if(isset($errors) && $errors))` actually in the view all you need is `<?php echo validation_errors(); ?>`, no need to assign it to a variable take a look at <http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html> for more about how to show errors
Please try this ``` <?php if(isset($errors) && $errors!=''){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
the problem is that in some cases `$errors` variable isn't created. Use `if(isset($errors) && $errors))` actually in the view all you need is `<?php echo validation_errors(); ?>`, no need to assign it to a variable take a look at <http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html> for more about how to show errors
or you can try this: ``` <?php if(isset($errors) && ('' != $errors) && (null != $errors)): ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <?php endif; ?> ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
You didn't post `$data` to view. You should use like this: ``` $this->load->view('register_user', $data); ```
Please try this ``` <?php if(isset($errors) && $errors!=''){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ```
18,042,383
I have this error on my view and i can't find where is the problem > > A PHP Error was encountered > > > Severity: Notice > > > Message: Undefined variable: errors > > > Filename: views/register\_user.php > > > Line Number: 5 > > > view: ``` <?php if($errors){ ?> <div style="background:red,color:white;"> <?=$errors?> </div> <? } ?> ``` and here controller ``` function register(){ if($_POST){ $config=array( array( 'field'=>'username', 'label'=>'Username', 'rules'=>'trim|required|min_length[3]|is_unique[users.username]' ), array( 'field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|min_length[5]|max_length[15]' ), array( 'field'=>'password2', 'label'=>'Password Confirmed', 'rules'=>'trim|required|min_length[5]|matches[password]' ), array( 'field'=>'user_type', 'label'=>'User Type', 'rules'=>'required' ), array( 'field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|is_unique[users.email]|valid_email' ) ); $this->load->library('form_validation'); $this->form_validation->set_rules($config); if($this->form_validation->run() == FALSE){ $data['errors']=validation_errors(); } else { $data=array( 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'user_type'=>$_POST['user_type'] ); $this->load->model('user'); $userid=$this->user->create_user($data); $this->session->set_userdata('userID',$userid); $this->session->set_userdata('user_type',$_POST['user_type']); redirect(base_url().'posts'); } } $this->load->helper('form'); $this->load->view('header'); $this->load->view('register_user'); $this->load->view('footer'); } ``` i'm starting using Codeigniter and i can't find the problem...
2013/08/04
[ "https://Stackoverflow.com/questions/18042383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583900/" ]
You didn't post `$data` to view. You should use like this: ``` $this->load->view('register_user', $data); ```
or you can try this: ``` <?php if(isset($errors) && ('' != $errors) && (null != $errors)): ?> <div style="background:red,color:white;"> <?php echo $errors; ?> </div> <?php endif; ?> ```
52,210,530
Suppose that we have a shopping cart in the site, we have specified number of a good in database. Whenever the user wants to validate his/her cart and finalize it, I want to subtract the number of goods that the user purchased from total count of the product. How can I do that? ``` router.post('/done', (req, res) => { // substract from the count for (var i = 0; i < req.body.cart.length; i++){ Product.findOne({_id: req.body.cart[i]._id}).exec((err, result) => { result.count = result.count - req.body.cart[i].count; // update the value of result.count and save it on database }) } }) ```
2018/09/06
[ "https://Stackoverflow.com/questions/52210530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7310077/" ]
You just need to save, and also check for errors. ``` router.post('/done', (req, res) => { // substract from the count for (var i = 0; i < req.body.cart.length; i++){ Product.findOne({_id: req.body.cart[i]._id}).exec((err, result) => { if(result) { result.count = result.count - req.body.cart[i].count; result.save((err) => { if (err) // do something }); } //If you don't find the product for some reason, do something }) } }) ```
You can use mongoose's [findOneAndUpdate()](https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate) and `$inc` reference operator [with a negative value](https://docs.mongodb.com/manual/reference/operator/update/inc/) to decrement the count. **Docs** > > The following update() operation uses the $inc operator to decrease the quantity field by 2 (i.e. increase by -2) and increase the "metrics.orders" field by 1: > > > ``` db.products.update( { sku: "abc123" }, { $inc: { quantity: -2, "metrics.orders": 1 } } ) ``` Making those changes ``` 'use strict'; router.post('/done', (req, res) => { let {cart} = req.body; if (!Array.isArray(cart) || cart.length === 0) { return res.status(400).send({ msg: 'Empty cart' }); } let updates = cart.map(item => { return Product.findOneAndUpdate({ _id: item._id }, { $inc: { count: -1 * item.count } }, { upsert: false }); }); Promise.all(updates).then(() => { return res.status(200).send({ msg: 'inventory updated' }); }).catch(err => { console.log('err', err.stack); return res.status(500).send({ msg: 'inventory update failed!' }); }); }); ```
994,245
Ruby doesn't seem to have a facility for defining a protected/private block like so: ``` protected do def method end end ``` This would be nice compared to ``` protected def method end public ``` where you might forget to "public" after the protected methods. It seems possible to implement this using metaprogramming. Any ideas how?
2009/06/15
[ "https://Stackoverflow.com/questions/994245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65925/" ]
Since you want to group by functionality you can declare all your methods, and then declare which ones are protected and private by using protected followed by the symbols of the methods you want to be protected, and the same for private. The following class shows what I mean. In this class all methods are public except bar\_protected and bar\_private which are declared protected and private at the end. ``` class Foo def bar_public print "This is public" end def bar_protected print "This is protected" end def bar_private print "This is private" end def call_protected bar_protected end def call_private bar_private end protected :bar_protected private :bar_private end ```
I actually endorse bodnarbm's solution and do not recommend doing this, but since I can't pass up a metaprogramming challenge, here's a hack that will accomplish this: ``` class Module def with_protected alias_if_needed = lambda do |first, second| alias_method first, second if instance_methods.include? second end metaclass = class<<self; self end metaclass.module_eval {|m| alias_if_needed[:__with_protected_old__, :method_added]} def self.method_added(method) protected method send :__with_protected_old__ if respond_to? :__with_protected_old__ end yield metaclass.module_eval do |m| remove_method :method_added alias_if_needed[:method_added, :__with_protected_old__] end end end ```
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
Use `str.split()` to split your string at spaces, then apply `int` to every element: ``` s = '2 -5 7 8 10 -205' nums = [int(num) for num in s.split()] ```
If your string looks like this: ``` s = '2 -5 7 8 10 -205' ``` You can create a list of ints by using a list comprehension. First you will split the string on whitespace, and parse each entry individually: ``` >>> [int(x) for x in s.split(' ')] [2, -5, 7, 8, 10, -205] ## list of ints ```
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
Use `str.split()` to split your string at spaces, then apply `int` to every element: ``` s = '2 -5 7 8 10 -205' nums = [int(num) for num in s.split()] ```
You could do this with a list comprehension: ``` data = ('2 -5 7 8 10 -205') l = [int(i) for i in data.split()] print(l) [2, -5, 7, 8, 10, -205] ``` Or alternatively you could use the `map` function: ``` list(map(int, data.split())) [2, -5, 7, 8, 10, -205] ``` **Benchmarking**: ``` In [725]: %timeit list(map(int, data.split())) 100000 loops, best of 3: 2.1 µs per loop In [726]: %timeit [int(i) for i in data.split()] 100000 loops, best of 3: 2.54 µs per loop ``` So with map it works faster *Note*: `list` is added to map because I'm using python 3.x. If you're using python 2.x you don't need that.
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
Use `str.split()` to split your string at spaces, then apply `int` to every element: ``` s = '2 -5 7 8 10 -205' nums = [int(num) for num in s.split()] ```
You should try to split the task into 2 subtasks: 1. Split the numbers in the string into list of numbers using [split](https://docs.python.org/2/library/stdtypes.html#str.split) 2. Convert each of the strings in the list to a regular integer using map [map](https://docs.python.org/2/library/functions.html#map) As a general advise - you should also read the documentation so that you can figure out how much of the hard work could be saved by just chaining the output of one function as an input of the next function.
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
Use `str.split()` to split your string at spaces, then apply `int` to every element: ``` s = '2 -5 7 8 10 -205' nums = [int(num) for num in s.split()] ```
Built-in method would do the job as well: ``` >>> s = '2 -5 7 8 10 -205' >>> map(int, s.split()) [2, -5, 7, 8, 10, -205] ``` If Python 3+: ``` >>> s = '2 -5 7 8 10 -205' >>> list(map(int, s.split())) [2, -5, 7, 8, 10, -205] ```
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
If your string looks like this: ``` s = '2 -5 7 8 10 -205' ``` You can create a list of ints by using a list comprehension. First you will split the string on whitespace, and parse each entry individually: ``` >>> [int(x) for x in s.split(' ')] [2, -5, 7, 8, 10, -205] ## list of ints ```
You should try to split the task into 2 subtasks: 1. Split the numbers in the string into list of numbers using [split](https://docs.python.org/2/library/stdtypes.html#str.split) 2. Convert each of the strings in the list to a regular integer using map [map](https://docs.python.org/2/library/functions.html#map) As a general advise - you should also read the documentation so that you can figure out how much of the hard work could be saved by just chaining the output of one function as an input of the next function.
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
You could do this with a list comprehension: ``` data = ('2 -5 7 8 10 -205') l = [int(i) for i in data.split()] print(l) [2, -5, 7, 8, 10, -205] ``` Or alternatively you could use the `map` function: ``` list(map(int, data.split())) [2, -5, 7, 8, 10, -205] ``` **Benchmarking**: ``` In [725]: %timeit list(map(int, data.split())) 100000 loops, best of 3: 2.1 µs per loop In [726]: %timeit [int(i) for i in data.split()] 100000 loops, best of 3: 2.54 µs per loop ``` So with map it works faster *Note*: `list` is added to map because I'm using python 3.x. If you're using python 2.x you don't need that.
You should try to split the task into 2 subtasks: 1. Split the numbers in the string into list of numbers using [split](https://docs.python.org/2/library/stdtypes.html#str.split) 2. Convert each of the strings in the list to a regular integer using map [map](https://docs.python.org/2/library/functions.html#map) As a general advise - you should also read the documentation so that you can figure out how much of the hard work could be saved by just chaining the output of one function as an input of the next function.
34,581,137
I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be ``` ('2 -5 7 8 10 -205') ``` What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code. n is the length of the string of numbers num is the empty string I add the numbers to. Originally num="" ``` while i<n: if temps[i]!=' ': num=num+temps[i] elif temps[i]==' ': print type(num) x=int(num) ``` The problem is that when it runs I get an error for the line with x=int(num) saying ``` ValueError: invalid literal for int() with base 10: '' ``` when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask. Thanks
2016/01/03
[ "https://Stackoverflow.com/questions/34581137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5741328/" ]
Built-in method would do the job as well: ``` >>> s = '2 -5 7 8 10 -205' >>> map(int, s.split()) [2, -5, 7, 8, 10, -205] ``` If Python 3+: ``` >>> s = '2 -5 7 8 10 -205' >>> list(map(int, s.split())) [2, -5, 7, 8, 10, -205] ```
You should try to split the task into 2 subtasks: 1. Split the numbers in the string into list of numbers using [split](https://docs.python.org/2/library/stdtypes.html#str.split) 2. Convert each of the strings in the list to a regular integer using map [map](https://docs.python.org/2/library/functions.html#map) As a general advise - you should also read the documentation so that you can figure out how much of the hard work could be saved by just chaining the output of one function as an input of the next function.
86,622
I submitted a paper to elsevier and it got major revision. I proceeded as per the suggestions and submitted revision. After few days the status changed to "Under Review". Now the status is still under Review even after 45 days. Can I ask the editor for a status update or should I wait further?
2017/03/17
[ "https://academia.stackexchange.com/questions/86622", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/36444/" ]
Depending on the field, "Under Review" can also be 6 months. The reviewers review in their spare time. If they don't have spare time or are unorganised reviews take very long time.
-By checking the policies of Reed Elsevier, sometimes revision takes 2-4 weeks and the author will be informed directly about the situation whenever it obtained. It depends on several factors such as how many reviewers they have this term and how many submitted papers they have on their system waiting to be evaluated and which field your paper in. * If you in hurry, there will be no harm if you send a kind email asking about the progress of reviewing your paper.
86,622
I submitted a paper to elsevier and it got major revision. I proceeded as per the suggestions and submitted revision. After few days the status changed to "Under Review". Now the status is still under Review even after 45 days. Can I ask the editor for a status update or should I wait further?
2017/03/17
[ "https://academia.stackexchange.com/questions/86622", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/36444/" ]
Depending on the field, "Under Review" can also be 6 months. The reviewers review in their spare time. If they don't have spare time or are unorganised reviews take very long time.
I think the best advise would be to go to the journal's homepage and browse recently published articles. Each such article has information about when it was (1) received, (2) received in revised form and (3) accepted for publication. From this, you can easily infer average time that is under revision. Keep also in mind that for many papers there is minor revision so the time interval from (2) -> (3) might be small. You should check towards the higher end of that interval to get some estimation. If you think the time spend under review is unreasonably large, you can send a message to the editor asking about the status. But you should not hurry.
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
I would use [Briss](http://sourceforge.net/projects/briss/). It lets you select various regions of each page, each of which to turn into a new page. ![enter image description here](https://i.stack.imgur.com/DYYPB.jpg)
You could use okular or any pdf reader and then use print to file and select options and copies-> pages . Select your interested pages and then give print. It will cut the selected pages . Simple and easy !!
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
Try **Gscan2pdf**, which you can download from the Software Centre or which you can install from command line `sudo apt-get install gscan2pdf`. Open Gscan2Pdf: 1. *file > import* your PDF file; ![import](https://i.stack.imgur.com/oUV5Y.png) Now you have a single page (see the left column): ![single](https://i.stack.imgur.com/rQlF2.png) 2. then *tools > Clean up*; ![clean up](https://i.stack.imgur.com/vWmq3.png) 3. select *double* as layout and #output pages as *2*, then click *OK*; ![split](https://i.stack.imgur.com/Dw3Xx.png) 4. Gscan2pdf splits your document (among other things, it will also clean it up and deskew it etc.) Now you have two pages: ![double](https://i.stack.imgur.com/AaB3D.png) 5. Save your PDF file if you're satisfied with the result.
I would use [Briss](http://sourceforge.net/projects/briss/). It lets you select various regions of each page, each of which to turn into a new page. ![enter image description here](https://i.stack.imgur.com/DYYPB.jpg)
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
You can use `mutool`, a [MuPDF](https://www.mupdf.com/) command-line tool (`sudo apt-get install mupdf-tools`): ``` mutool poster -x 2 input.pdf output.pdf ``` You can also use `-y` if you want to perform a vertical split.
I would use [Briss](http://sourceforge.net/projects/briss/). It lets you select various regions of each page, each of which to turn into a new page. ![enter image description here](https://i.stack.imgur.com/DYYPB.jpg)
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
**A command line solution using ImageMagick:** 1. Split the PDF into individual images, here at 300 dpi resolution: ``` convert -density 300 orig.pdf page.png ``` 2. Split each page image into a left and right image: ``` for file in page-*.png; do convert "$file" -crop 50%x100% "$file-split.png"; done ``` 3. Rename the `page-###-split-#.png` files to just `001.png`, `002.png` etc.: ``` ls page-*-split-*.png | cat -n | while read n f; do mv "$f" $(printf "%03d.png" $n); done ``` 4. Combine the resulting page images into a PDF again: ``` convert [0-9][0-9][0-9].png result.pdf ``` **Sources, variations and further tips:** * [Crop and split book scan in 3 commands](http://www.edison23.net/crop-and-split-book-scan-in-3-commands/), here modified to use a `for` loop command to prevent memory issues. * [Answer: Renaming files in a folder to sequential numbers](https://stackoverflow.com/a/34153342), together with [this comment](https://stackoverflow.com/questions/3211595#comment68768831_34153342) * [Answer: ImageMagick: convert quits after some pages](https://superuser.com/a/1208170), in case you are running into ImageMagick memory limits (which I did).
Sejda can do that either using its [web interface](https://www.sejda.com/split-pdf-down-the-middle) or [command line interface](http://www.sejda.org/shell-interface/tutorial/) (open source). The task is called `splitdownthemiddle`
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
Try **Gscan2pdf**, which you can download from the Software Centre or which you can install from command line `sudo apt-get install gscan2pdf`. Open Gscan2Pdf: 1. *file > import* your PDF file; ![import](https://i.stack.imgur.com/oUV5Y.png) Now you have a single page (see the left column): ![single](https://i.stack.imgur.com/rQlF2.png) 2. then *tools > Clean up*; ![clean up](https://i.stack.imgur.com/vWmq3.png) 3. select *double* as layout and #output pages as *2*, then click *OK*; ![split](https://i.stack.imgur.com/Dw3Xx.png) 4. Gscan2pdf splits your document (among other things, it will also clean it up and deskew it etc.) Now you have two pages: ![double](https://i.stack.imgur.com/AaB3D.png) 5. Save your PDF file if you're satisfied with the result.
**A command line solution using ImageMagick:** 1. Split the PDF into individual images, here at 300 dpi resolution: ``` convert -density 300 orig.pdf page.png ``` 2. Split each page image into a left and right image: ``` for file in page-*.png; do convert "$file" -crop 50%x100% "$file-split.png"; done ``` 3. Rename the `page-###-split-#.png` files to just `001.png`, `002.png` etc.: ``` ls page-*-split-*.png | cat -n | while read n f; do mv "$f" $(printf "%03d.png" $n); done ``` 4. Combine the resulting page images into a PDF again: ``` convert [0-9][0-9][0-9].png result.pdf ``` **Sources, variations and further tips:** * [Crop and split book scan in 3 commands](http://www.edison23.net/crop-and-split-book-scan-in-3-commands/), here modified to use a `for` loop command to prevent memory issues. * [Answer: Renaming files in a folder to sequential numbers](https://stackoverflow.com/a/34153342), together with [this comment](https://stackoverflow.com/questions/3211595#comment68768831_34153342) * [Answer: ImageMagick: convert quits after some pages](https://superuser.com/a/1208170), in case you are running into ImageMagick memory limits (which I did).
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
Another option is **ScanTailor**. This program is particularly well suited to processing several scans at a time. `apt-get install scantailor` It unfortunately only works on image file inputs, but it's simple enough to convert a scanned PDF to a jpg. Here's a one-liner that I used for converting a whole directory of PDFs into jpgs. If a PDF has *n* pages, it makes *n* jpg files. `for f in ./*.pdf; do gs -q -dSAFER -dBATCH -dNOPAUSE -r300 -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -sDEVICE=png16m "-sOutputFile=$f%02d.png" "$f" -c quit; done;` I had screenshots ready to share, but I don't have enough rep to post them. ScanTailor outputs to tif, so if you want the files back in PDF you can use this to make a PDF for each page. `for f in ./*.tif; do tiff2pdf "$f" -o "$f".pdf -p letter -F; done;` Then you can use this one-liner, or an application like PDFShuffler to merge any or all files into one PDF. `gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf *.pdf`
You could use okular or any pdf reader and then use print to file and select options and copies-> pages . Select your interested pages and then give print. It will cut the selected pages . Simple and easy !!
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
Try **Gscan2pdf**, which you can download from the Software Centre or which you can install from command line `sudo apt-get install gscan2pdf`. Open Gscan2Pdf: 1. *file > import* your PDF file; ![import](https://i.stack.imgur.com/oUV5Y.png) Now you have a single page (see the left column): ![single](https://i.stack.imgur.com/rQlF2.png) 2. then *tools > Clean up*; ![clean up](https://i.stack.imgur.com/vWmq3.png) 3. select *double* as layout and #output pages as *2*, then click *OK*; ![split](https://i.stack.imgur.com/Dw3Xx.png) 4. Gscan2pdf splits your document (among other things, it will also clean it up and deskew it etc.) Now you have two pages: ![double](https://i.stack.imgur.com/AaB3D.png) 5. Save your PDF file if you're satisfied with the result.
There is a wonderful program scankromsator. It is free and works quite well through wine. More information [here](http://www.djvu-soft.narod.ru/kromsator/eng.htm).
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
I would use [Briss](http://sourceforge.net/projects/briss/). It lets you select various regions of each page, each of which to turn into a new page. ![enter image description here](https://i.stack.imgur.com/DYYPB.jpg)
Another option is **ScanTailor**. This program is particularly well suited to processing several scans at a time. `apt-get install scantailor` It unfortunately only works on image file inputs, but it's simple enough to convert a scanned PDF to a jpg. Here's a one-liner that I used for converting a whole directory of PDFs into jpgs. If a PDF has *n* pages, it makes *n* jpg files. `for f in ./*.pdf; do gs -q -dSAFER -dBATCH -dNOPAUSE -r300 -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -sDEVICE=png16m "-sOutputFile=$f%02d.png" "$f" -c quit; done;` I had screenshots ready to share, but I don't have enough rep to post them. ScanTailor outputs to tif, so if you want the files back in PDF you can use this to make a PDF for each page. `for f in ./*.tif; do tiff2pdf "$f" -o "$f".pdf -p letter -F; done;` Then you can use this one-liner, or an application like PDFShuffler to merge any or all files into one PDF. `gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf *.pdf`
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
Here is a python script for this. <https://gist.github.com/tshrinivasan/23d8e4986cbae49b8a8c>
Sejda can do that either using its [web interface](https://www.sejda.com/split-pdf-down-the-middle) or [command line interface](http://www.sejda.org/shell-interface/tutorial/) (open source). The task is called `splitdownthemiddle`
56,853
I have a PDF file that was the result of the scan of a book. In this file 2 pages of the book correspond to 1 in the PDF. So when I see a page in the PDF file I'm actually seeing 2 pages of the book. ![enter image description here](https://i.stack.imgur.com/gbfn0.png) ([original](http://dl.dropbox.com/u/3905170/Kennan%20Kent%20-%20Counterpoint%20%5BPage%203%5D.pdf)) I would like to know if there's any way to convert this file to another PDF where 1 page of the book corresponds to 1 page of the PDF i.e. the normal situation.
2011/08/12
[ "https://askubuntu.com/questions/56853", "https://askubuntu.com", "https://askubuntu.com/users/15198/" ]
I would use [Briss](http://sourceforge.net/projects/briss/). It lets you select various regions of each page, each of which to turn into a new page. ![enter image description here](https://i.stack.imgur.com/DYYPB.jpg)
There is a wonderful program scankromsator. It is free and works quite well through wine. More information [here](http://www.djvu-soft.narod.ru/kromsator/eng.htm).
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
This will be safe, but exposes you to additional risks compared to not putting your password store in a public place. * Accidental upload of unencrypted passwords (you won't do that on purpose, but sure it might not happen by accident, or because of some software bug?) * Unknown weaknesses in RSA or the symmetric encryption in use * Usage patterns revealed (statistics is powerful) * Accidental release of your access token results in public data; if you'd additionally kept that private, you're much safer * Worst case is your whole password store *history* is revealed, compared to only the current one With other words: if you do not do mistakes, trust the software and the math behind the encryption algorithm stays secure publicly storing the encrypted password store is fine. If you have doubt in any of those (and personally, my trust would be in exactly this order, with lost trust in myself as a user with high confidentiality in the math behind), keep the store private. Ever posted a private passphrase in some chat window by accident that popped up? I know a bunch of people that did, including myself.
This is a good question, since it has been a problem in the past where someone put a private password in a public repository. Think of it this way, it's good practice to not store that file (along with any other sensitive files) in a public repository, even if it's private. It is good to back it up somewhere, but if lets say your password was retrieved somehow (third party site for example), they could access your github and still retrieve the password. Worst case, but it is still possible. I would usually suggest having some kind of file stored on an external hard drive, and possibly store the hard drive somewhere in-case there's a fire. If you really want to use a repository or cloud to store it, just do everything you can to keep it safe. Overall it's not the best idea. It's not the worst, but it's best to think of the "what would happen if?" scenarios. It may never happen to you, but if it did, is it worth the trouble? Edit: I was thinking of programs in some of my post, so i trimmed it up for you to answer your question better.
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
Terse answer ============ It's ok to put a pass repo github. Verbose Answer ============== Your pass repo is GPG encrypted using whatever private key you've selected, so it's as bullet proof as the key you've chosen. Furthermore, your private key **is not** stored in your pass repo. This means that the private vs. public location of your *encrypted* password files is not the weak link in your password manager's security. Rather, it's the private key that you've encrypted them with that you have to worry about. Make sure it's a good key (like the one you've mentioned) and don't expose it to anyone because they won't have to crack that big ol' key to use it. They'll just have to bork your password, and, let's face it, it's really tough to be certain your password is good enough to stop *everyone*. So don't let anyone else see your key. If you move your private key to each of your computers that use pass, then you can just pull your pass repo from github and use the private key stored on those computers individually. Now they'll all stay synced and safe. ### Two More Things To Consider The whole point of pass is to keep your passwords encrypted. If you're not ok with them being on github.com, then what you're really relying on is their private location and not their encrypted state. If that's the case, then why encrypt them at all? You could just use the same flat files that pass uses, and not bother encrypting them. That'd be pretty convenient! Also, keep in mind that making your password manager easier to use means you're less likely to want/need to subvert it. Any time you have to do pass's job for it (e.g. resetting a password on an account because the nice secure one was generated on a different computer and you haven't manually synced yet, but you have to get in right now) you're gonna reduce the security it provides.
This is a good question, since it has been a problem in the past where someone put a private password in a public repository. Think of it this way, it's good practice to not store that file (along with any other sensitive files) in a public repository, even if it's private. It is good to back it up somewhere, but if lets say your password was retrieved somehow (third party site for example), they could access your github and still retrieve the password. Worst case, but it is still possible. I would usually suggest having some kind of file stored on an external hard drive, and possibly store the hard drive somewhere in-case there's a fire. If you really want to use a repository or cloud to store it, just do everything you can to keep it safe. Overall it's not the best idea. It's not the worst, but it's best to think of the "what would happen if?" scenarios. It may never happen to you, but if it did, is it worth the trouble? Edit: I was thinking of programs in some of my post, so i trimmed it up for you to answer your question better.
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
This is a good question, since it has been a problem in the past where someone put a private password in a public repository. Think of it this way, it's good practice to not store that file (along with any other sensitive files) in a public repository, even if it's private. It is good to back it up somewhere, but if lets say your password was retrieved somehow (third party site for example), they could access your github and still retrieve the password. Worst case, but it is still possible. I would usually suggest having some kind of file stored on an external hard drive, and possibly store the hard drive somewhere in-case there's a fire. If you really want to use a repository or cloud to store it, just do everything you can to keep it safe. Overall it's not the best idea. It's not the worst, but it's best to think of the "what would happen if?" scenarios. It may never happen to you, but if it did, is it worth the trouble? Edit: I was thinking of programs in some of my post, so i trimmed it up for you to answer your question better.
> > One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo > > > I think it no safe. For all your account(directory structure) is not encrypted. Only password had been protected by gpg. > > (pass even provides that ability) > > > If do it using pass's ability. Maybe it is more safe. But you need rebuild your store using "pass git init".
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
Terse answer ============ It's ok to put a pass repo github. Verbose Answer ============== Your pass repo is GPG encrypted using whatever private key you've selected, so it's as bullet proof as the key you've chosen. Furthermore, your private key **is not** stored in your pass repo. This means that the private vs. public location of your *encrypted* password files is not the weak link in your password manager's security. Rather, it's the private key that you've encrypted them with that you have to worry about. Make sure it's a good key (like the one you've mentioned) and don't expose it to anyone because they won't have to crack that big ol' key to use it. They'll just have to bork your password, and, let's face it, it's really tough to be certain your password is good enough to stop *everyone*. So don't let anyone else see your key. If you move your private key to each of your computers that use pass, then you can just pull your pass repo from github and use the private key stored on those computers individually. Now they'll all stay synced and safe. ### Two More Things To Consider The whole point of pass is to keep your passwords encrypted. If you're not ok with them being on github.com, then what you're really relying on is their private location and not their encrypted state. If that's the case, then why encrypt them at all? You could just use the same flat files that pass uses, and not bother encrypting them. That'd be pretty convenient! Also, keep in mind that making your password manager easier to use means you're less likely to want/need to subvert it. Any time you have to do pass's job for it (e.g. resetting a password on an account because the nice secure one was generated on a different computer and you haven't manually synced yet, but you have to get in right now) you're gonna reduce the security it provides.
This will be safe, but exposes you to additional risks compared to not putting your password store in a public place. * Accidental upload of unencrypted passwords (you won't do that on purpose, but sure it might not happen by accident, or because of some software bug?) * Unknown weaknesses in RSA or the symmetric encryption in use * Usage patterns revealed (statistics is powerful) * Accidental release of your access token results in public data; if you'd additionally kept that private, you're much safer * Worst case is your whole password store *history* is revealed, compared to only the current one With other words: if you do not do mistakes, trust the software and the math behind the encryption algorithm stays secure publicly storing the encrypted password store is fine. If you have doubt in any of those (and personally, my trust would be in exactly this order, with lost trust in myself as a user with high confidentiality in the math behind), keep the store private. Ever posted a private passphrase in some chat window by accident that popped up? I know a bunch of people that did, including myself.
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
This will be safe, but exposes you to additional risks compared to not putting your password store in a public place. * Accidental upload of unencrypted passwords (you won't do that on purpose, but sure it might not happen by accident, or because of some software bug?) * Unknown weaknesses in RSA or the symmetric encryption in use * Usage patterns revealed (statistics is powerful) * Accidental release of your access token results in public data; if you'd additionally kept that private, you're much safer * Worst case is your whole password store *history* is revealed, compared to only the current one With other words: if you do not do mistakes, trust the software and the math behind the encryption algorithm stays secure publicly storing the encrypted password store is fine. If you have doubt in any of those (and personally, my trust would be in exactly this order, with lost trust in myself as a user with high confidentiality in the math behind), keep the store private. Ever posted a private passphrase in some chat window by accident that popped up? I know a bunch of people that did, including myself.
> > One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo > > > I think it no safe. For all your account(directory structure) is not encrypted. Only password had been protected by gpg. > > (pass even provides that ability) > > > If do it using pass's ability. Maybe it is more safe. But you need rebuild your store using "pass git init".
981,297
I am using [pass](http://www.passwordstore.org/) to handle all my passwords. They are encrypted using GPG with a 4096 bits key, using the SHA256 algorithm. I am using a different password for every login in my password store. One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo (pass even provides that ability). I would like to have my password store up to date on all my computers. Is it then safe to push the pass git repository to a private GitHub repository? If not, what's the weak link?
2015/10/02
[ "https://superuser.com/questions/981297", "https://superuser.com", "https://superuser.com/users/428375/" ]
Terse answer ============ It's ok to put a pass repo github. Verbose Answer ============== Your pass repo is GPG encrypted using whatever private key you've selected, so it's as bullet proof as the key you've chosen. Furthermore, your private key **is not** stored in your pass repo. This means that the private vs. public location of your *encrypted* password files is not the weak link in your password manager's security. Rather, it's the private key that you've encrypted them with that you have to worry about. Make sure it's a good key (like the one you've mentioned) and don't expose it to anyone because they won't have to crack that big ol' key to use it. They'll just have to bork your password, and, let's face it, it's really tough to be certain your password is good enough to stop *everyone*. So don't let anyone else see your key. If you move your private key to each of your computers that use pass, then you can just pull your pass repo from github and use the private key stored on those computers individually. Now they'll all stay synced and safe. ### Two More Things To Consider The whole point of pass is to keep your passwords encrypted. If you're not ok with them being on github.com, then what you're really relying on is their private location and not their encrypted state. If that's the case, then why encrypt them at all? You could just use the same flat files that pass uses, and not bother encrypting them. That'd be pretty convenient! Also, keep in mind that making your password manager easier to use means you're less likely to want/need to subvert it. Any time you have to do pass's job for it (e.g. resetting a password on an account because the nice secure one was generated on a different computer and you haven't manually synced yet, but you have to get in right now) you're gonna reduce the security it provides.
> > One of pass's cool feature is that everything holds in a folder with a nice hierarchy, which is perfect for setting up a git repo > > > I think it no safe. For all your account(directory structure) is not encrypted. Only password had been protected by gpg. > > (pass even provides that ability) > > > If do it using pass's ability. Maybe it is more safe. But you need rebuild your store using "pass git init".
38,920,892
I am tring to load some .dll files from a folder: ``` var fileNames = Directory .GetFiles(path, "*.dll", searchOption); var assemblyNames = fileNames .Select(AssemblyLoadContext.GetAssemblyName); List<Assembly> assemblies = new List<Assembly>(); foreach (AssemblyName assemblyName in assemblyNames) { assemblies.Add(Assembly.Load(assemblyName)); } ``` But somehow the assembly cannot be loaded: `FileNotFoundException, Could not load file or assembly [...] The system cannot find the file specified.` How is this possible, because the file is definitely there? I can provide additional information, if you need more background.
2016/08/12
[ "https://Stackoverflow.com/questions/38920892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868471/" ]
With these using statements: ``` using System.Reflection; using System.Runtime.Loader; ``` Try this: ``` var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(pathTodll); ```
To load a assembly from a file it is easier to use the Assembly.LoadFrom() function. In your application is would look like: ``` var fileNames = Directory.GetFiles(path, "*.dll", searchOption); ``` `List<Assembly> assemblies = new List<Assembly>(); foreach (string fileName in fileNames) { assemblies.Add(Assembly.LoadFrom(fileName)); }` [Edit] If you are attempting to load the assemblies for later use in the application (e.g. you have reference to the assembly in Visual Studio), it is recommend that you implement the AppDomain.AssemblyResolve event. The AppDomain.AssemblyResolve event will fire when an assembly cannot be found and needs to be loaded. At that time you can provide the AppDomain an assembly in a different file location.
23,350,378
guys, once again I come begging for help. I can't get my head around this - all I need is update the name attribute's indexes of texts in my form. I want to show to the user one line in the table and, as he/she clicks on the plus sign, another line is added. For my form to work on the server side, I need do reindex the name parameter. That's how I'm trying to do it: ``` function reindex () { $("table").find("tr.faixa").each(function(index, value) { value.find("input.faixa_min").attr("name", "data[" + index + "][BonusRecarga][faixa_min]"); // <- here's where I get the error value.find("input.faixa_max").attr("name", "data[" + index + "][BonusRecarga][faixa_max]"); value.find("input.valor_bonus").attr("name", "data[" + index + "][BonusRecarga][valor_bonus]"); value.find("input.perc_bonus").attr("name", "data[" + index + "][BonusRecarga][perc_bonus]"); }); } ``` And here's a fragment of the form: ``` <tr class="faixa"> <td> <input name="data[0][BonusRecarga][faixa_min]" class="faixa_min" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][faixa_max]" class="faixa_max" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][valor_bonus]" class="valor_bonus" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][perc_bonus]" class="perc_bonus input-small" type="text" required="required"/> </td> <td> <span class="help-inline"><i class="icon-plus" style="cursor: pointer"></i></span> <span class="help-inline"><i class="icon-minus" style="cursor: pointer"></i></span> </td> </tr> ``` I have also tried using a common for(var i = 0; i < $(".faixa").lenght; i++), but I always get the "undefined is not a function" in the first value.find(...). It looks like "value" doesn't have the find() method, but when I log it, it shows me a regular ".... Do you know why the find() method is not working on the "value" variable? Thanks in advance.
2014/04/28
[ "https://Stackoverflow.com/questions/23350378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2062019/" ]
`value` is a DOM Element object while `.find()` is a jQuery method. You need to create a jquery object : ``` var $value = $(value); //Then use $value.find() ```
A much faster result for jquery would be to use the EQ function and append. <https://api.jquery.com/eq/> if EQ is not what your looking for leave a comment and ill look further into your issue.
23,350,378
guys, once again I come begging for help. I can't get my head around this - all I need is update the name attribute's indexes of texts in my form. I want to show to the user one line in the table and, as he/she clicks on the plus sign, another line is added. For my form to work on the server side, I need do reindex the name parameter. That's how I'm trying to do it: ``` function reindex () { $("table").find("tr.faixa").each(function(index, value) { value.find("input.faixa_min").attr("name", "data[" + index + "][BonusRecarga][faixa_min]"); // <- here's where I get the error value.find("input.faixa_max").attr("name", "data[" + index + "][BonusRecarga][faixa_max]"); value.find("input.valor_bonus").attr("name", "data[" + index + "][BonusRecarga][valor_bonus]"); value.find("input.perc_bonus").attr("name", "data[" + index + "][BonusRecarga][perc_bonus]"); }); } ``` And here's a fragment of the form: ``` <tr class="faixa"> <td> <input name="data[0][BonusRecarga][faixa_min]" class="faixa_min" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][faixa_max]" class="faixa_max" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][valor_bonus]" class="valor_bonus" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][perc_bonus]" class="perc_bonus input-small" type="text" required="required"/> </td> <td> <span class="help-inline"><i class="icon-plus" style="cursor: pointer"></i></span> <span class="help-inline"><i class="icon-minus" style="cursor: pointer"></i></span> </td> </tr> ``` I have also tried using a common for(var i = 0; i < $(".faixa").lenght; i++), but I always get the "undefined is not a function" in the first value.find(...). It looks like "value" doesn't have the find() method, but when I log it, it shows me a regular ".... Do you know why the find() method is not working on the "value" variable? Thanks in advance.
2014/04/28
[ "https://Stackoverflow.com/questions/23350378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2062019/" ]
Try using `$(this).find('input...')...` . it works, and is better inside `each`.
A much faster result for jquery would be to use the EQ function and append. <https://api.jquery.com/eq/> if EQ is not what your looking for leave a comment and ill look further into your issue.
23,350,378
guys, once again I come begging for help. I can't get my head around this - all I need is update the name attribute's indexes of texts in my form. I want to show to the user one line in the table and, as he/she clicks on the plus sign, another line is added. For my form to work on the server side, I need do reindex the name parameter. That's how I'm trying to do it: ``` function reindex () { $("table").find("tr.faixa").each(function(index, value) { value.find("input.faixa_min").attr("name", "data[" + index + "][BonusRecarga][faixa_min]"); // <- here's where I get the error value.find("input.faixa_max").attr("name", "data[" + index + "][BonusRecarga][faixa_max]"); value.find("input.valor_bonus").attr("name", "data[" + index + "][BonusRecarga][valor_bonus]"); value.find("input.perc_bonus").attr("name", "data[" + index + "][BonusRecarga][perc_bonus]"); }); } ``` And here's a fragment of the form: ``` <tr class="faixa"> <td> <input name="data[0][BonusRecarga][faixa_min]" class="faixa_min" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][faixa_max]" class="faixa_max" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][valor_bonus]" class="valor_bonus" type="text" required="required"/> </td> <td> <input name="data[0][BonusRecarga][perc_bonus]" class="perc_bonus input-small" type="text" required="required"/> </td> <td> <span class="help-inline"><i class="icon-plus" style="cursor: pointer"></i></span> <span class="help-inline"><i class="icon-minus" style="cursor: pointer"></i></span> </td> </tr> ``` I have also tried using a common for(var i = 0; i < $(".faixa").lenght; i++), but I always get the "undefined is not a function" in the first value.find(...). It looks like "value" doesn't have the find() method, but when I log it, it shows me a regular ".... Do you know why the find() method is not working on the "value" variable? Thanks in advance.
2014/04/28
[ "https://Stackoverflow.com/questions/23350378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2062019/" ]
`value` is a DOM Element object while `.find()` is a jQuery method. You need to create a jquery object : ``` var $value = $(value); //Then use $value.find() ```
Try using `$(this).find('input...')...` . it works, and is better inside `each`.
68,049,688
I'm trying to insert some values into the database using reflection. Here is my code, query works well, but how to pass values? I don't know what went wrong: ``` public class MyORM<T> where T : IData { public void Insert(T item) { var sql = new StringBuilder("Insert into "); var type = item.GetType(); var properties = type.GetProperties(); sql.Append(type.Name); sql.Append(" ("); foreach (var property in properties) { sql.Append(property.Name); sql.Append(", "); } sql.Remove(sql.Length - 1, 1); sql.Append(") values ("); foreach (var property in properties) { sql.Append('@').Append(property.Name).Append(','); } sql.Remove(sql.Length - 1, 1); sql.Append(");"); var query = sql.ToString(); var command = new SqlCommand(query, _sqlConnection); foreach (var property in properties) { command.Parameters.Add(property.Name); } } } ```
2021/06/19
[ "https://Stackoverflow.com/questions/68049688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15581952/" ]
``` public void DBInsertNewRecordIntoTable(DatabaseTableObject databaseTableObject, string tableName) { string connectMe = "Server=localhost;User ID=root;Database=test"; string sqlCommand = string.Concat("SELECT * FROM ", tableName, " LIMIT 0;"); //1. Get an instance of MySqlAdapter MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sqlCommand, connectMe); //2. Retrieve schema from tableName and store it in DataSet DataSet dataSet = new DataSet(string.Concat(tableName, "DataSet")); mySqlDataAdapter.FillSchema(dataSet, SchemaType.Source, tableName); //5. Get dataTable from dataSet DataTable dataTable = dataSet.Tables[tableName]; //6. Add new row data DataRow dataRow = dataTable.NewRow(); //6.1 Get a list of the properties in the databaseTableObject and store it into an array PropertyInfo[] properties = databaseTableObject.GetType().GetProperties(); //6.2 Loop through all properties in databaseTableObject and assign their values to dataRow accordingly foreach (var property in properties) { //6.3 Getting property value var propertyValue = databaseTableObject.GetType().GetProperty(property.Name).GetValue(databaseTableObject, null); //6.4 Only assign value to dataRow if databaseTableObject's property's value is not null if (propertyValue != null) dataRow[property.Name] = propertyValue; } //7. Add dataRow data to local table dataTable.Rows.Add(dataRow); //8. Apply the change to remote table _ = new MySqlCommandBuilder(mySqlDataAdapter); mySqlDataAdapter.Update(dataSet, tableName); Console.WriteLine("Successfully updated the remote table"); } ``` --- ``` interface DatabaseTableObject { } public class DatabaseTableObjectEmployee: DatabaseTableObject { private string name; private int? age = null; private int? salary = null; public int? Age { get => age; set => age = value; } public int? Salary { get => salary; set => salary = value; } public string Name { get => name; set => name = value; } } ```
You can add `property.GetValue(entity)` in your iteration to get value and store it in a dictionary to pass it and use it as a parameter.Here my code.I have implemented it.Hope this will help. ``` public void Insert(TEntity entity) { if (entity == null) return; Type type = entity.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(); ` string s1 = "", s2 = ""; bool flag = false; `Dictionary<string, object> dic = new Dictionary<string, object>();` foreach (var property in propertyInfos) { Type type1 = property .GetType(); if (!flag) flag = true; else { s1 += ","; s2 += ","; } s1 += property .Name; s2 += "@" + property .Name; dic.Add(property .Name, property.GetValue(entity));//Here getting value } ` `string sql = "Insert into " + type.Name + " (" + s1 + ") Values (" + s2 + ");";` ` ExecuteCommand(sql, dic);` }``` //`Database Execution portion` `public void ExecuteCommand(string command, Dictionary<string, object> parameters)` { using(SqlConnection connection = new SqlConnection(_conncectionstring)) { using(SqlCommand sqlcommand = new SqlCommand(command, connection)) { try { if (connection.State != ConnectionState.Open) { connection.Open(); } if (parameters != null) { foreach (var item in parameters) { sqlcommand.Parameters.Add(new SqlParameter(item.Key, item.Value)); } } sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { } } } }` ```
68,049,688
I'm trying to insert some values into the database using reflection. Here is my code, query works well, but how to pass values? I don't know what went wrong: ``` public class MyORM<T> where T : IData { public void Insert(T item) { var sql = new StringBuilder("Insert into "); var type = item.GetType(); var properties = type.GetProperties(); sql.Append(type.Name); sql.Append(" ("); foreach (var property in properties) { sql.Append(property.Name); sql.Append(", "); } sql.Remove(sql.Length - 1, 1); sql.Append(") values ("); foreach (var property in properties) { sql.Append('@').Append(property.Name).Append(','); } sql.Remove(sql.Length - 1, 1); sql.Append(");"); var query = sql.ToString(); var command = new SqlCommand(query, _sqlConnection); foreach (var property in properties) { command.Parameters.Add(property.Name); } } } ```
2021/06/19
[ "https://Stackoverflow.com/questions/68049688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15581952/" ]
`command.Parameters.AddWithValue(property.Name, property.GetValue(item));` This line will solve your problem and will be able to pass the value.
You can add `property.GetValue(entity)` in your iteration to get value and store it in a dictionary to pass it and use it as a parameter.Here my code.I have implemented it.Hope this will help. ``` public void Insert(TEntity entity) { if (entity == null) return; Type type = entity.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(); ` string s1 = "", s2 = ""; bool flag = false; `Dictionary<string, object> dic = new Dictionary<string, object>();` foreach (var property in propertyInfos) { Type type1 = property .GetType(); if (!flag) flag = true; else { s1 += ","; s2 += ","; } s1 += property .Name; s2 += "@" + property .Name; dic.Add(property .Name, property.GetValue(entity));//Here getting value } ` `string sql = "Insert into " + type.Name + " (" + s1 + ") Values (" + s2 + ");";` ` ExecuteCommand(sql, dic);` }``` //`Database Execution portion` `public void ExecuteCommand(string command, Dictionary<string, object> parameters)` { using(SqlConnection connection = new SqlConnection(_conncectionstring)) { using(SqlCommand sqlcommand = new SqlCommand(command, connection)) { try { if (connection.State != ConnectionState.Open) { connection.Open(); } if (parameters != null) { foreach (var item in parameters) { sqlcommand.Parameters.Add(new SqlParameter(item.Key, item.Value)); } } sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { } } } }` ```
68,049,688
I'm trying to insert some values into the database using reflection. Here is my code, query works well, but how to pass values? I don't know what went wrong: ``` public class MyORM<T> where T : IData { public void Insert(T item) { var sql = new StringBuilder("Insert into "); var type = item.GetType(); var properties = type.GetProperties(); sql.Append(type.Name); sql.Append(" ("); foreach (var property in properties) { sql.Append(property.Name); sql.Append(", "); } sql.Remove(sql.Length - 1, 1); sql.Append(") values ("); foreach (var property in properties) { sql.Append('@').Append(property.Name).Append(','); } sql.Remove(sql.Length - 1, 1); sql.Append(");"); var query = sql.ToString(); var command = new SqlCommand(query, _sqlConnection); foreach (var property in properties) { command.Parameters.Add(property.Name); } } } ```
2021/06/19
[ "https://Stackoverflow.com/questions/68049688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15581952/" ]
`command.Parameters.AddWithValue(property.Name, property.GetValue(item));` This line will solve your problem and will be able to pass the value.
``` public void DBInsertNewRecordIntoTable(DatabaseTableObject databaseTableObject, string tableName) { string connectMe = "Server=localhost;User ID=root;Database=test"; string sqlCommand = string.Concat("SELECT * FROM ", tableName, " LIMIT 0;"); //1. Get an instance of MySqlAdapter MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sqlCommand, connectMe); //2. Retrieve schema from tableName and store it in DataSet DataSet dataSet = new DataSet(string.Concat(tableName, "DataSet")); mySqlDataAdapter.FillSchema(dataSet, SchemaType.Source, tableName); //5. Get dataTable from dataSet DataTable dataTable = dataSet.Tables[tableName]; //6. Add new row data DataRow dataRow = dataTable.NewRow(); //6.1 Get a list of the properties in the databaseTableObject and store it into an array PropertyInfo[] properties = databaseTableObject.GetType().GetProperties(); //6.2 Loop through all properties in databaseTableObject and assign their values to dataRow accordingly foreach (var property in properties) { //6.3 Getting property value var propertyValue = databaseTableObject.GetType().GetProperty(property.Name).GetValue(databaseTableObject, null); //6.4 Only assign value to dataRow if databaseTableObject's property's value is not null if (propertyValue != null) dataRow[property.Name] = propertyValue; } //7. Add dataRow data to local table dataTable.Rows.Add(dataRow); //8. Apply the change to remote table _ = new MySqlCommandBuilder(mySqlDataAdapter); mySqlDataAdapter.Update(dataSet, tableName); Console.WriteLine("Successfully updated the remote table"); } ``` --- ``` interface DatabaseTableObject { } public class DatabaseTableObjectEmployee: DatabaseTableObject { private string name; private int? age = null; private int? salary = null; public int? Age { get => age; set => age = value; } public int? Salary { get => salary; set => salary = value; } public string Name { get => name; set => name = value; } } ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
**UPDATE:** This is my implementation for feature names starting with an uppercase letter like in the example: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String featureName = "Feature "; String rawFeatureName = scenario.getId().split(";")[0].replace("-"," "); featureName = featureName + rawFeatureName.substring(0, 1).toUpperCase() + rawFeatureName.substring(1); return featureName; } ``` **ORIGINAL:** I don't know if this is useful for you, but I would suggest to use `scenario.getId()` This will give you the feature file name and scenario name, for example: ``` Feature: Login to the app Scenario: Login to the app with password Given I am on the login screen When I enter my passcode Then I press the ok button ``` with scenario.getId() you would get the following: > > login-to-the-app;login-to-the-app-with-password > > > Hope this helps you!
maybe like this, its return only filename: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String[] tab = scenario.getId().split("/"); int rawFeatureNameLength = tab.length; String featureName = tab[rawFeatureNameLength - 1].split(":")[0]; System.out.println("featureName: " + featureName); return featureName; } ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
There is an easier way to extract the feature name (without *.feature* postfix) from Scenario if you can add Apache *commons-io* on your classpath: ``` String featureName = FilenameUtils.getBaseName(scenario.getUri().toString()); ``` If you need the full feature file name with postfix you should use the *getName(...)* method instead: ``` String fullFeatureName = FilenameUtils.getName(scenario.getUri().toString()); ```
You can use Reporter to get the current running instance and then extract our the actual feature name from the feature file like so: ``` Object[] paramNames = Reporter.getCurrentTestResult().getParameters(); String featureName = paramNames[1].toString().replaceAll("^\"+|\"+$", ""); System.out.println("Feature file name: " + featureName); ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
**UPDATE:** This is my implementation for feature names starting with an uppercase letter like in the example: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String featureName = "Feature "; String rawFeatureName = scenario.getId().split(";")[0].replace("-"," "); featureName = featureName + rawFeatureName.substring(0, 1).toUpperCase() + rawFeatureName.substring(1); return featureName; } ``` **ORIGINAL:** I don't know if this is useful for you, but I would suggest to use `scenario.getId()` This will give you the feature file name and scenario name, for example: ``` Feature: Login to the app Scenario: Login to the app with password Given I am on the login screen When I enter my passcode Then I press the ok button ``` with scenario.getId() you would get the following: > > login-to-the-app;login-to-the-app-with-password > > > Hope this helps you!
I used the below method at Hooks class ``` @Before public void beforeScenario(Scenario scenario){ // scenarioId = "file:///**/src/test/resources/features/namefeature.feature:99" String scenarioId=scenario.getId(); int start=scenarioId.indexOf(File.separator+"features"+File.separator); int end=scenarioId.indexOf("."); String[] featureName=scenarioId.substring(start,end).split(File.separator+"features"+File.separator); System.out.println("featureName ="+featureName[1]); } ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
Kotlin 1.5, cucumber-java 6.10.0: ``` @Before fun beforeScenario(scenario: Scenario) { println(scenario.uri) } ``` In my case prints: ``` file:///C:/Users/K.H/git/JvmClient/src/jvmTest/resources/features/C197544.feature ```
Create a listener as below ``` import io.cucumber.plugin.ConcurrentEventListener; import io.cucumber.plugin.event.EventHandler; import io.cucumber.plugin.event.EventPublisher; import io.cucumber.plugin.event.TestCaseStarted; public class Listener implements ConcurrentEventListener { @Override public void setEventPublisher(EventPublisher eventPublisher) { eventPublisher.registerHandlerFor(TestCaseStarted.class, testCaseStartedEventHandler); } private final EventHandler<TestCaseStarted> testCaseStartedEventHandler = event -> { System.out.println("Current file fame : " + event.getTestCase().getUri().toString()); }; } ``` And then supply your listener to cucumber as below `"-p", "com.myProject.listener.Listener"` This will give you feature file name !
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
There is an easier way to extract the feature name (without *.feature* postfix) from Scenario if you can add Apache *commons-io* on your classpath: ``` String featureName = FilenameUtils.getBaseName(scenario.getUri().toString()); ``` If you need the full feature file name with postfix you should use the *getName(...)* method instead: ``` String fullFeatureName = FilenameUtils.getName(scenario.getUri().toString()); ```
I used the below method at Hooks class ``` @Before public void beforeScenario(Scenario scenario){ // scenarioId = "file:///**/src/test/resources/features/namefeature.feature:99" String scenarioId=scenario.getId(); int start=scenarioId.indexOf(File.separator+"features"+File.separator); int end=scenarioId.indexOf("."); String[] featureName=scenarioId.substring(start,end).split(File.separator+"features"+File.separator); System.out.println("featureName ="+featureName[1]); } ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
**UPDATE:** This is my implementation for feature names starting with an uppercase letter like in the example: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String featureName = "Feature "; String rawFeatureName = scenario.getId().split(";")[0].replace("-"," "); featureName = featureName + rawFeatureName.substring(0, 1).toUpperCase() + rawFeatureName.substring(1); return featureName; } ``` **ORIGINAL:** I don't know if this is useful for you, but I would suggest to use `scenario.getId()` This will give you the feature file name and scenario name, for example: ``` Feature: Login to the app Scenario: Login to the app with password Given I am on the login screen When I enter my passcode Then I press the ok button ``` with scenario.getId() you would get the following: > > login-to-the-app;login-to-the-app-with-password > > > Hope this helps you!
Kotlin 1.5, cucumber-java 6.10.0: ``` @Before fun beforeScenario(scenario: Scenario) { println(scenario.uri) } ``` In my case prints: ``` file:///C:/Users/K.H/git/JvmClient/src/jvmTest/resources/features/C197544.feature ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
**UPDATE:** This is my implementation for feature names starting with an uppercase letter like in the example: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String featureName = "Feature "; String rawFeatureName = scenario.getId().split(";")[0].replace("-"," "); featureName = featureName + rawFeatureName.substring(0, 1).toUpperCase() + rawFeatureName.substring(1); return featureName; } ``` **ORIGINAL:** I don't know if this is useful for you, but I would suggest to use `scenario.getId()` This will give you the feature file name and scenario name, for example: ``` Feature: Login to the app Scenario: Login to the app with password Given I am on the login screen When I enter my passcode Then I press the ok button ``` with scenario.getId() you would get the following: > > login-to-the-app;login-to-the-app-with-password > > > Hope this helps you!
You can use Reporter to get the current running instance and then extract our the actual feature name from the feature file like so: ``` Object[] paramNames = Reporter.getCurrentTestResult().getParameters(); String featureName = paramNames[1].toString().replaceAll("^\"+|\"+$", ""); System.out.println("Feature file name: " + featureName); ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
**UPDATE:** This is my implementation for feature names starting with an uppercase letter like in the example: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String featureName = "Feature "; String rawFeatureName = scenario.getId().split(";")[0].replace("-"," "); featureName = featureName + rawFeatureName.substring(0, 1).toUpperCase() + rawFeatureName.substring(1); return featureName; } ``` **ORIGINAL:** I don't know if this is useful for you, but I would suggest to use `scenario.getId()` This will give you the feature file name and scenario name, for example: ``` Feature: Login to the app Scenario: Login to the app with password Given I am on the login screen When I enter my passcode Then I press the ok button ``` with scenario.getId() you would get the following: > > login-to-the-app;login-to-the-app-with-password > > > Hope this helps you!
There is an easier way to extract the feature name (without *.feature* postfix) from Scenario if you can add Apache *commons-io* on your classpath: ``` String featureName = FilenameUtils.getBaseName(scenario.getUri().toString()); ``` If you need the full feature file name with postfix you should use the *getName(...)* method instead: ``` String fullFeatureName = FilenameUtils.getName(scenario.getUri().toString()); ```
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
There is an easier way to extract the feature name (without *.feature* postfix) from Scenario if you can add Apache *commons-io* on your classpath: ``` String featureName = FilenameUtils.getBaseName(scenario.getUri().toString()); ``` If you need the full feature file name with postfix you should use the *getName(...)* method instead: ``` String fullFeatureName = FilenameUtils.getName(scenario.getUri().toString()); ```
Create a listener as below ``` import io.cucumber.plugin.ConcurrentEventListener; import io.cucumber.plugin.event.EventHandler; import io.cucumber.plugin.event.EventPublisher; import io.cucumber.plugin.event.TestCaseStarted; public class Listener implements ConcurrentEventListener { @Override public void setEventPublisher(EventPublisher eventPublisher) { eventPublisher.registerHandlerFor(TestCaseStarted.class, testCaseStartedEventHandler); } private final EventHandler<TestCaseStarted> testCaseStartedEventHandler = event -> { System.out.println("Current file fame : " + event.getTestCase().getUri().toString()); }; } ``` And then supply your listener to cucumber as below `"-p", "com.myProject.listener.Listener"` This will give you feature file name !
41,394,810
I am finding some difficulties trying to implement a factory class in Java that build a **RoomTipology** object selecting a random value from an **enum**. So I have the following situation: ``` public class RoomTipologyMockFactory { private RoomTipology roomTipology; private static enum RoomTipologyEnum { MATRIMONIALE, MATRIMONILAE_SUPERIOR, QUADRUPLA, TRIPLA, SINGOLA; private static final List<RoomTipologyEnum> VALUES = Collections.unmodifiableList(Arrays.asList(values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } } public static RoomTipology getRandomRoomTipology() { List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); RoomTipology result = new RoomTipology(); switch (roomTipology) { case MATRIMONIALE: result.setName("Matrimoniale"); result.setDescription("Camera matrimoniale con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case MATRIMONILAE_SUPERIOR: result.setName("Matrimoniale Superior"); result.setDescription("Camera con bagno dotata di piccolo angolo soggiorno completo di divano e " + "scrivania, molto luminosa, pavimenti in parquet, riscaldamento e aria condizionata, " + "armadio/guardaroba, TV a schermo piatto dotata di canali satellitari, connessione Wi-Fi " + "gratuita, bollitore e selezione di tè e tisane."); result.setMaxPeople(2); result.setTimeStamp(new Date()); break; case QUADRUPLA: result.setName("Camera Quadruola"); result.setDescription("Camera per quattro persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(4); result.setTimeStamp(new Date()); break; case TRIPLA: result.setName("Camera Tripla"); result.setDescription("Camera per tre persone con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(3); result.setTimeStamp(new Date()); break; case SINGOLA: result.setName("Camera Singola"); result.setDescription("Camera singola persona con bagno interno, Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " + "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " + "pellentesque eu, pretium quis, sem."); result.setMaxPeople(1); result.setTimeStamp(new Date()); break; } return result; } } ``` As you can see in the previous code I have an external **RoomTipologyMockFactory** that is used to create mocks instances of the **RoomTipology** class. Every time tht the **getRandomRoomTipology()** method is called have to be selected a random possible value of the **RoomTipologyEnum** enum and so it use it to build a specific mock of the **RoomTipology** class. So, inside the enum definition, I have created the **getRandomRoomTipologyValue()** method that returns a random value form the enum public static RoomTipologyEnum getRandomRoomTipologyValue() { return VALUES.get(RANDOM.nextInt(SIZE)); } I have to use this value into the **getRandomRoomTipology** to return a specific **RoomTipology** mock instance. I have 2 problems: 1) I have declared this enum as **private static** (so it is a class level and, in theory I have not to build it with new() because I take it from the current **RoomTipologyMockFactory** instance. But I can't do: ``` List<Object> value = RoomTipologyEnum.getRandomRoomTipology(); ``` it seems that can't resolve to the **getRandomRoomTipology()** method. 2) I have no more to switch on the enum but I think on the returned value. What is wrong? What am I missing? How can I fix this issue?
2016/12/30
[ "https://Stackoverflow.com/questions/41394810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
There is an easier way to extract the feature name (without *.feature* postfix) from Scenario if you can add Apache *commons-io* on your classpath: ``` String featureName = FilenameUtils.getBaseName(scenario.getUri().toString()); ``` If you need the full feature file name with postfix you should use the *getName(...)* method instead: ``` String fullFeatureName = FilenameUtils.getName(scenario.getUri().toString()); ```
maybe like this, its return only filename: ``` private String getFeatureFileNameFromScenarioId(Scenario scenario) { String[] tab = scenario.getId().split("/"); int rawFeatureNameLength = tab.length; String featureName = tab[rawFeatureNameLength - 1].split(":")[0]; System.out.println("featureName: " + featureName); return featureName; } ```
28,502,134
I'm implementing a custom widget to use it as a title bar on a dockable window. My problem arises only on Windows, namely, the window border disappears when the dock window is afloat. Seems the problem is that, on Windows only, the window flags are changed. I.e. when I do this: ``` print dock_window.windowFlags() dock_window.setTitleBarWidget(title_bar) print dock_window.windowFlags() ``` it prints out different setting for the flags before and after. However, it stays the same on linux and the borders remain unchanged. My question is, how to restore the window border? UPDATE: Since the custom title bar overrides the flags for the border when the dock window is floating, how can I edit the dock window so it has some kind of border? (It is crucial for the dock window to have a custom title bar when floating.)
2015/02/13
[ "https://Stackoverflow.com/questions/28502134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505165/" ]
The reason Java wants you to cast the result is that `T` returned from `makeInstance` method is not guaranteed to be the same as `T` of `freshen` method. The reason for it is that `getClass()` does not return `Class<T>`. Instead, it returns `Class<? extends X>`, where `X` is the erasure of the static type of `instance`, i.e. `Object`. That's where the compiler's chain of inference stops: it cannot infer from that call that the return type would be `T`, requiring you to do the cast. An alternative to casting the instance would be casting the class, like this: ``` return makeInstance((Class<T>)instance.getClass()); ```
You can solve this problem using following. ``` public class Scratch<T extends Base> { public T freshen(T instance) { // No need to cast this to T return makeInstance(instance.getClass()); } public T makeInstance(Class<T> type) { try { return type.newInstance(); } catch (InstantiationException ex) { Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static final class Base { } } ``` Hope this helps.
28,502,134
I'm implementing a custom widget to use it as a title bar on a dockable window. My problem arises only on Windows, namely, the window border disappears when the dock window is afloat. Seems the problem is that, on Windows only, the window flags are changed. I.e. when I do this: ``` print dock_window.windowFlags() dock_window.setTitleBarWidget(title_bar) print dock_window.windowFlags() ``` it prints out different setting for the flags before and after. However, it stays the same on linux and the borders remain unchanged. My question is, how to restore the window border? UPDATE: Since the custom title bar overrides the flags for the border when the dock window is floating, how can I edit the dock window so it has some kind of border? (It is crucial for the dock window to have a custom title bar when floating.)
2015/02/13
[ "https://Stackoverflow.com/questions/28502134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505165/" ]
The reason Java wants you to cast the result is that `T` returned from `makeInstance` method is not guaranteed to be the same as `T` of `freshen` method. The reason for it is that `getClass()` does not return `Class<T>`. Instead, it returns `Class<? extends X>`, where `X` is the erasure of the static type of `instance`, i.e. `Object`. That's where the compiler's chain of inference stops: it cannot infer from that call that the return type would be `T`, requiring you to do the cast. An alternative to casting the instance would be casting the class, like this: ``` return makeInstance((Class<T>)instance.getClass()); ```
The root cause for your problem is "type erasure": when the Java compiler compiles the body of the `freshen()` method it essentially replaces the `T` type with its upper bound, namely: `Base`. So here's the reasoning the compiler is doing: - `instance` is of type `Base` (as I said, `T` was replaced with `Base`) - `.getClass()` is invoked on a variable of type `Base` so the return value of this call is `Class<? extends Base`> - the parameter that is passed to `makeInstance()` is therefore, from the compiler's point of view, of type `Class<? extends Base>`. Consequently the `T` inside `makeInstance()` is also `Base` => the method returns `Base`
28,502,134
I'm implementing a custom widget to use it as a title bar on a dockable window. My problem arises only on Windows, namely, the window border disappears when the dock window is afloat. Seems the problem is that, on Windows only, the window flags are changed. I.e. when I do this: ``` print dock_window.windowFlags() dock_window.setTitleBarWidget(title_bar) print dock_window.windowFlags() ``` it prints out different setting for the flags before and after. However, it stays the same on linux and the borders remain unchanged. My question is, how to restore the window border? UPDATE: Since the custom title bar overrides the flags for the border when the dock window is floating, how can I edit the dock window so it has some kind of border? (It is crucial for the dock window to have a custom title bar when floating.)
2015/02/13
[ "https://Stackoverflow.com/questions/28502134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505165/" ]
The root cause for your problem is "type erasure": when the Java compiler compiles the body of the `freshen()` method it essentially replaces the `T` type with its upper bound, namely: `Base`. So here's the reasoning the compiler is doing: - `instance` is of type `Base` (as I said, `T` was replaced with `Base`) - `.getClass()` is invoked on a variable of type `Base` so the return value of this call is `Class<? extends Base`> - the parameter that is passed to `makeInstance()` is therefore, from the compiler's point of view, of type `Class<? extends Base>`. Consequently the `T` inside `makeInstance()` is also `Base` => the method returns `Base`
You can solve this problem using following. ``` public class Scratch<T extends Base> { public T freshen(T instance) { // No need to cast this to T return makeInstance(instance.getClass()); } public T makeInstance(Class<T> type) { try { return type.newInstance(); } catch (InstantiationException ex) { Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static final class Base { } } ``` Hope this helps.
3,061,203
Conside the following code: ``` int main() { signed char a = 10; a += a; // Line 5 a = a + a; return 0; } ``` I am getting this warning at Line 5: > > d:\codes\operator cast\operator > cast\test.cpp(5) : warning C4244: '+=' > : conversion from 'int' to 'signed > char', possible loss of data > > > Does this mean that += operator makes an implicit cast of the right hand operator to `int`? P.S: I am using Visual studio 2005 **Edit**: This issue occurs only when the warning level is set to 4
2010/06/17
[ "https://Stackoverflow.com/questions/3061203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139909/" ]
What you are seeing is the result of *integral promotion*. *Integral promotion* is applied to both arguments to most binary expressions involving integer types. This means that anything of integer type that is narrower than an `int` is promoted to an `int` (or possibly `unsigned int`) before the operation is performed. This means that `a += a` is performed as an `int` calculation but because the result is stored back into `a` which is a `char` the result has to undergo a narrowing conversion, hence the warning.
Really, there shouldn't be any warning for this line. the operator += is very well defined for all basic types. I would place that as a small bug of VC++ 2005.
59,867
This is a tool (probably) in on an ultralight airplane. Initially I guessed that it is a tilting meter (to level between right and left), but seems it is not as it just a vertical tube filled up with something like liquid. So, what is that and how does it work? ![enter image description here](https://i.stack.imgur.com/CVRnn.png)
2019/02/06
[ "https://aviation.stackexchange.com/questions/59867", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34998/" ]
It's an airspeed indicator for ultralights. The pitot inlet is at the bottom and the pitot air pushes a little red plastic disc up and down on a central rod, with a calibrated clearance between the edge of the disc and the walls of the tube. They are very sensitive and are good down to 10 MPH or less. You'll also see them on hang gliders. See here: <https://www.aircraftspruce.com/catalog/inpages/hallwindmeter.php?clickkey=5468>
I don't see an ASI in the panel. I am unable to confirm this guess, but it could be an airspeed indicator (ASI). Google Dwyer Wind Speed Indicator. The Dwyer is plastic, wider at the bottom, and works by having the wind push a ball up a tube that gets progressively wider near the top. As the airflow pushes the ball up, more air can leak around the ball. Where the ball reaches equilibrium indicates the speed. Edit: @John K beat me to it! Thanks, John!
59,867
This is a tool (probably) in on an ultralight airplane. Initially I guessed that it is a tilting meter (to level between right and left), but seems it is not as it just a vertical tube filled up with something like liquid. So, what is that and how does it work? ![enter image description here](https://i.stack.imgur.com/CVRnn.png)
2019/02/06
[ "https://aviation.stackexchange.com/questions/59867", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34998/" ]
It's an airspeed indicator for ultralights. The pitot inlet is at the bottom and the pitot air pushes a little red plastic disc up and down on a central rod, with a calibrated clearance between the edge of the disc and the walls of the tube. They are very sensitive and are good down to 10 MPH or less. You'll also see them on hang gliders. See here: <https://www.aircraftspruce.com/catalog/inpages/hallwindmeter.php?clickkey=5468>
It's indeed an airspeed indicator. Here's one at Oshkosh 2018, with me blowing about 27 knots into it.[![ASI on ultralight](https://i.stack.imgur.com/F6UBw.jpg)](https://i.stack.imgur.com/F6UBw.jpg) [![blowing into intake](https://i.stack.imgur.com/DFSsU.jpg)](https://i.stack.imgur.com/DFSsU.jpg)
45,339,092
this is my code: ``` final ImageView imageView1 = (ImageView) findViewById(R.id.imageView8); imageView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); } }); ``` by this code when i click on my ImageView i can see it in fullScreen. Now i have a question: when I see imageView in fullscreen I want when I press Back, this imageView close and back to previous situation and my app doesn't back to previous activity
2017/07/26
[ "https://Stackoverflow.com/questions/45339092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8372932/" ]
I would change the 'th' to a 'tr' because I'm pretty sure react will give you a warning if you add 'th' inside 'tbody' ``` let finalList = [] this.state.categories.forEach( (cat, index) => { finalList.push(<tr...>{this.state.category}</tr>) this.state.data.forEach( (row, index) => { if(row.category === cat){ finalList.push( <tr key={i}> <td className="col-lg-2 text-center">{row.name}</td> <td className="col-lg-2 text-center">{row.alias}</td> <td className="col-lg-2 text-center">{row.description}</td> <td className="col-lg-1 text-center">{row.default_value}</td> <td className="col-lg-1 text-center">{row.min_value}</td> <td className="col-lg-1 text-center">{row.max_value}</td> <td className="col-lg-1 text-center">Action</td> </tr> ) } }) }) ``` Word of warning I would avoid using tables checkout css grids their a lot more flexible and pretty well supported
**EDIT: From version 16.0.0** onwards in react, you could make use of React.Fragment to return multiple elements from render ``` <tbody> { this.state.categories.map((category, index) => { var innerData = this.state.data.map((row, i) => { if (row.category === category) { return ( <tr key={i}> <td className="col-lg-2 text-center">{row.name}</td> <td className="col-lg-2 text-center">{row.alias}</td> <td className="col-lg-2 text-center">{row.description}</td> <td className="col-lg-1 text-center">{row.default_value}</td> <td className="col-lg-1 text-center">{row.min_value}</td> <td className="col-lg-1 text-center">{row.max_value}</td> <td className="col-lg-1 text-center">Action</td> </tr> ) } return null }) return ( <React.Fragment> <th colSpan="7" key={index} style={{ 'textAlign': 'left', 'paddingLeft': '5px', 'backgroundColor': '#D3D0CF' }}>{this.state.category}</th>, {innerData} </React.Fragment> ) }) } </tbody> ``` --- **Before v16** With the help of `JSX syntactic sugar` it is possible to return multiple elements from within a component, by writing them as comma separated elements in an array like ``` <tbody> { this.state.categories.map((category, index) => { var innerData = this.state.data.map((row, i) => { if (row.category === category) { return ( <tr key={i}> <td className="col-lg-2 text-center">{row.name}</td> <td className="col-lg-2 text-center">{row.alias}</td> <td className="col-lg-2 text-center">{row.description}</td> <td className="col-lg-1 text-center">{row.default_value}</td> <td className="col-lg-1 text-center">{row.min_value}</td> <td className="col-lg-1 text-center">{row.max_value}</td> <td className="col-lg-1 text-center">Action</td> </tr> ) } return null }) return ([ <th colSpan="7" key={index} style={{ 'textAlign': 'left', 'paddingLeft': '5px', 'backgroundColor': '#D3D0CF' }}>{this.state.category}</th>, [...innerData] ]) }) } </tbody> ``` Also when you make use of if statements within a map function, you need to have them outside of the return statement, now if you do `{this.state.categories.map((category, index) => <tr>...` it means that whatever is after the arrow is considered to be part of the return and hence you inner map's if statement will give you an error. There is an **[issue](https://github.com/facebook/react/issues/2127)** on react github page for returning multiple elements. Read through it for more details.
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You'll want to set up your letters like this: ``` var alphabet = { a: 1, b: 2, c: 3 } var word = "love"; var total = 0; for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ``` [**DEMO**](http://jsfiddle.net/QC3gQ/) --- **EDIT** `@am not i am` claims that IE8 won't index strings like that, and she's usually right, so, to be friendly to junk browsers you can do ``` for (var i = 0; i < word.length; i++) total += alphabet[word.charAt(i)]; ``` instead of ``` for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ```
You don't need to create the mapping array, assuming your word is all lowercase letters you can use: ``` var word = 'love', total = 0, codeA='a'.charCodeAt(); for ( var i = 0; i < word.length; i++ ) { total += word.charCodeAt( i ) - codeA + 1; } ``` charCodeAt() returns the Unicode value of a character, for the latin alphabet this is equal to its ASCII code which is sequential for letters
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You can use the ascii code of the characters in the string, which does not require the long array at all: ``` function sum(str) { var i, sum = 0, a = 'a'.charCodeAt(0) - 1; for (i = 0 ; i < str.length ; i++) { sum += str.charCodeAt(i) - a; } } alert(sum('love')); ```
1. **Using closure** with *RegEx* ``` (function(w){ var c=0; w.toLowerCase().replace(/[a-z]{1}/g,function(a){c+=a.charCodeAt(0)-97+1}); return c; })("love") ``` 2. **Trivial** solution. ``` var c=0; var str="love" var istr=str.toLowerCase() for(var i=0;i<istr.length;i++){ c+=istr.charCodeAt(i)-"a".charCodeAt(0)+1 } ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
1. **Using closure** with *RegEx* ``` (function(w){ var c=0; w.toLowerCase().replace(/[a-z]{1}/g,function(a){c+=a.charCodeAt(0)-97+1}); return c; })("love") ``` 2. **Trivial** solution. ``` var c=0; var str="love" var istr=str.toLowerCase() for(var i=0;i<istr.length;i++){ c+=istr.charCodeAt(i)-"a".charCodeAt(0)+1 } ```
Letters already have numerical assignments - ASCII value. A = 65, so just subtract the offset. ``` var phrase="abcd".toUpperCase(); var sum = 0 for(x=0;x<phrase.length;x++) { sum = sum + phrase.charCodeAt(x)-64; } alert(sum) ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You can use the ascii code of the characters in the string, which does not require the long array at all: ``` function sum(str) { var i, sum = 0, a = 'a'.charCodeAt(0) - 1; for (i = 0 ; i < str.length ; i++) { sum += str.charCodeAt(i) - a; } } alert(sum('love')); ```
This will work for what you want (notice the first element of alphabet is empty because we want a = 1, not 0) ``` var alphabet = ['','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] , word = 'love' , letters = word.split('') , sum = 0 letters.forEach(function(letter){ sum += alphabet.indexOf(letter) }) ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You don't need to create the mapping array, assuming your word is all lowercase letters you can use: ``` var word = 'love', total = 0, codeA='a'.charCodeAt(); for ( var i = 0; i < word.length; i++ ) { total += word.charCodeAt( i ) - codeA + 1; } ``` charCodeAt() returns the Unicode value of a character, for the latin alphabet this is equal to its ASCII code which is sequential for letters
Actually, It is not required to do all this stuff. I have a simple trick here.... ``` var word="Love"; var total=0; for(i=0;i<word.length;i++){ total+=((word[i].toLowerCase()).charCodeAt(0)-96); } alert(total); // aleters 54 ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You'll want to set up your letters like this: ``` var alphabet = { a: 1, b: 2, c: 3 } var word = "love"; var total = 0; for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ``` [**DEMO**](http://jsfiddle.net/QC3gQ/) --- **EDIT** `@am not i am` claims that IE8 won't index strings like that, and she's usually right, so, to be friendly to junk browsers you can do ``` for (var i = 0; i < word.length; i++) total += alphabet[word.charAt(i)]; ``` instead of ``` for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ```
Actually, It is not required to do all this stuff. I have a simple trick here.... ``` var word="Love"; var total=0; for(i=0;i<word.length;i++){ total+=((word[i].toLowerCase()).charCodeAt(0)-96); } alert(total); // aleters 54 ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
1. **Using closure** with *RegEx* ``` (function(w){ var c=0; w.toLowerCase().replace(/[a-z]{1}/g,function(a){c+=a.charCodeAt(0)-97+1}); return c; })("love") ``` 2. **Trivial** solution. ``` var c=0; var str="love" var istr=str.toLowerCase() for(var i=0;i<istr.length;i++){ c+=istr.charCodeAt(i)-"a".charCodeAt(0)+1 } ```
This will work for what you want (notice the first element of alphabet is empty because we want a = 1, not 0) ``` var alphabet = ['','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] , word = 'love' , letters = word.split('') , sum = 0 letters.forEach(function(letter){ sum += alphabet.indexOf(letter) }) ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You'll want to set up your letters like this: ``` var alphabet = { a: 1, b: 2, c: 3 } var word = "love"; var total = 0; for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ``` [**DEMO**](http://jsfiddle.net/QC3gQ/) --- **EDIT** `@am not i am` claims that IE8 won't index strings like that, and she's usually right, so, to be friendly to junk browsers you can do ``` for (var i = 0; i < word.length; i++) total += alphabet[word.charAt(i)]; ``` instead of ``` for (var i = 0; i < word.length; i++) total += alphabet[word[i]]; ```
1. **Using closure** with *RegEx* ``` (function(w){ var c=0; w.toLowerCase().replace(/[a-z]{1}/g,function(a){c+=a.charCodeAt(0)-97+1}); return c; })("love") ``` 2. **Trivial** solution. ``` var c=0; var str="love" var istr=str.toLowerCase() for(var i=0;i<istr.length;i++){ c+=istr.charCodeAt(i)-"a".charCodeAt(0)+1 } ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You don't need to create the mapping array, assuming your word is all lowercase letters you can use: ``` var word = 'love', total = 0, codeA='a'.charCodeAt(); for ( var i = 0; i < word.length; i++ ) { total += word.charCodeAt( i ) - codeA + 1; } ``` charCodeAt() returns the Unicode value of a character, for the latin alphabet this is equal to its ASCII code which is sequential for letters
This will work for what you want (notice the first element of alphabet is empty because we want a = 1, not 0) ``` var alphabet = ['','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] , word = 'love' , letters = word.split('') , sum = 0 letters.forEach(function(letter){ sum += alphabet.indexOf(letter) }) ```
8,914,579
if anyone can give me some idea to begin with...at the end there. i was looking input a word like e.g. "love" and get the sum of the numbers corresponding to each letter answer = 54 ``` var a = 1;var b = 2;var c = 3;var d = 4;var e = 5;var f = 6;var g = 7; var h = 8;var i = 9;var j = 10;var k = 11;var l = 12;var m = 13; var n = 14;var o = 15;var p = 16;var q = 17;var r = 18;var s = 19;var t = 20; var u = 21;var v = 22;var w = 23;var x = 24;var y = 25;var z = 26; var addLetters = new Array(1); addLetters[1] = "love"; var square01 = 12 + 15 + 22 + 5 ; function (){ document.getElementById(square01).innerHTML;}} ``` thanks to everyone for their help.
2012/01/18
[ "https://Stackoverflow.com/questions/8914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126121/" ]
You can use the ascii code of the characters in the string, which does not require the long array at all: ``` function sum(str) { var i, sum = 0, a = 'a'.charCodeAt(0) - 1; for (i = 0 ; i < str.length ; i++) { sum += str.charCodeAt(i) - a; } } alert(sum('love')); ```
Actually, It is not required to do all this stuff. I have a simple trick here.... ``` var word="Love"; var total=0; for(i=0;i<word.length;i++){ total+=((word[i].toLowerCase()).charCodeAt(0)-96); } alert(total); // aleters 54 ```
44,160,721
I am in the process of developing application in C# which analyse multiple files .csv files using some sort of queries or functions and it display results. So far, I have managed to create application which opens .csv file using excel but I have just found that Microsoft Excel won't read record of more than 104,000. In my case I have record of 705.000. So currently I am converting those .csv files in Microsoft Access database and from that using queries I have populated those results into my C# application. However, this process is long and I have to convert all the files into Access and then I can analyse the data. Is there any other way I can directly read multiple .csv files and filter what I am looking for? Any suggestions or help will be appreciated. Thanks, Harsh Panchal
2017/05/24
[ "https://Stackoverflow.com/questions/44160721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4740248/" ]
Depending upon what your analysis needs are you might find R with the ff package to be a useful tool. If you really must use c# for this task then is there some reason you cannot simply read the files one line at a time analyzing as you go?
You can try this. Untested. ``` //Read all lines into array in once. var tmparray = File.ReadAllLines("C:\YourFile.csv"); for (var i = 0; i < tmparray.Length; i += 1) { //Assuming ";" is your seperator. (or delimiter) subArray=tmparray[i].Split(';'); //Do anything with your subArray. } ```