id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
β | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
β | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
β | last_editor_display_name
stringlengths 2
29
β | last_editor_user_id
int64 -1
20M
β | owner_display_name
stringlengths 1
29
β | owner_user_id
int64 1
20M
β | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46,707,339 | How to filter column on values in list in pyspark? | <p>I have a dataframe rawdata on which i have to apply filter condition on column X with values CB,CI and CR. So I used the below code:</p>
<pre><code>df = dfRawData.filter(col("X").between("CB","CI","CR"))
</code></pre>
<p>But I am getting the following error:</p>
<blockquote>
<p>between() takes exactly 3 arguments (4 given)</p>
</blockquote>
<p>Please let me know how I can resolve this issue.</p> | 46,707,814 | 1 | 1 | null | 2017-10-12 10:30:13.277 UTC | 3 | 2022-09-15 10:14:56.98 UTC | 2022-09-15 10:14:56.98 UTC | null | 2,753,501 | null | 7,861,979 | null | 1 | 19 | apache-spark|pyspark|apache-spark-sql | 64,838 | <p>The function <code>between</code> is used to check if the value is between two values, the input is a lower bound and an upper bound. It can not be used to check if a column value is in a list. To do that, use <code>isin</code>:</p>
<pre><code>import pyspark.sql.functions as f
df = dfRawData.where(f.col("X").isin(["CB", "CI", "CR"]))
</code></pre> |
28,020,001 | Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection<int> in mvc controller | <pre><code>public ActionResult addstandardpackage1(ICollection<int> SingleStay,ICollection<int> DOUBLESTAY,ICollection<int> TRIBLESTAY,ICollection<int> FAMILYSTAY,ICollection<int> EXTRABED)
{
var s = SingleStay;
for (int i = 0; i < SingleStay.Count; i++ )
{
var cal = SingleStay[i];
}
foreach (var key in SingleStay)
{
var value = key;
}
}
</code></pre>
<p>In for Loop i am get the error like Cannot apply indexing with [] to an expression of type But i need in for loop , in for each i am getting . because based on for loop i will bind the details with other collection lists. Please Help me.</p>
<p>I am getting error in <code>var cal=Singlestay[i]</code>.</p> | 28,020,042 | 3 | 0 | null | 2015-01-19 07:47:47.11 UTC | 2 | 2019-10-17 18:26:58.307 UTC | 2017-08-28 15:22:50.403 UTC | user2160375 | 1,912,756 | null | 3,643,560 | null | 1 | 23 | c#|model-view-controller | 41,436 | <p>Just convert it to an array:</p>
<pre><code>var s = SingleStay.ToArray();
</code></pre>
<p>note that this will consume additional memory though.</p>
<p>Better way would be to get an Array or any other collection-form that supports indexer in the first place.</p>
<p>Yet another way would be to implement it with an index variable:</p>
<pre><code> var s = SingleStay;
int i = 0;
foreach (var cal in s)
{
//do your stuff (Note: if you use 'continue;' here increment i before)
i++;
}
</code></pre> |
51,700,425 | what is the relation and difference between ipython and jupyter console | <p>After the ipython notebook project renamed to jupyter, I always think that <code>ipython notebook</code> is the same as <code>jupyter notebook</code> and <code>ipython</code> shell is just an alias of <code>jupyter console</code>. Today I realize that <code>ipython</code> does not have <code>connect_info</code> magic defined and therefore is not able to be connected to from different backends. </p>
<p>I have the following component installed in my conda:</p>
<pre><code>ipython 6.1.0 py36_0 defaults
jupyter 1.0.0 py36_4 defaults
jupyter_client 5.2.3 py36_0 defaults
jupyter_console 5.2.0 py36he59e554_1 defaults
jupyter_contrib_core 0.3.3 py36_1 conda-forge
jupyter_contrib_nbextensions 0.5.0 py36_0 conda-forge
jupyter_core 4.4.0 py36h7c827e3_0 defaults
</code></pre>
<p>I have the following questions:</p>
<ol>
<li>What is the relation between the <code>ipython</code> of this version and <code>jupyter console</code> of this version? </li>
<li>Does the <code>ipython notebook</code> (deprecated as in <code>ipython 6.1.0</code>) another share some components with <code>jupyter</code> libraries; or <code>ipython notebook</code> is still self-contained?</li>
<li>Do <code>ipython</code> and <code>jupyter</code> have any dependencies? </li>
</ol> | 51,703,852 | 1 | 0 | null | 2018-08-06 04:05:12.997 UTC | 12 | 2020-11-19 14:19:10.293 UTC | null | null | null | null | 7,026,980 | null | 1 | 38 | python|ipython|jupyter | 14,754 | <p><a href="https://jupyter.readthedocs.io/en/latest/projects/architecture/content-architecture.html" rel="noreferrer">Architecture Guides β Jupyter Documentation</a> has the authoritative info on how IPython and Jupyter are connected and related.</p>
<p>Specifically, as per <a href="https://jupyter.readthedocs.io/en/latest/use/advanced/migrating.html" rel="noreferrer">Migrating from IPython Notebook β Jupyter Documentation</a>:</p>
<blockquote>
<p><a href="https://blog.jupyter.org/the-big-split-9d7b88a031a7" rel="noreferrer">The Big Split</a> moved IPythonβs various language-agnostic components under the Jupyter umbrella. Going forward, Jupyter will contain the language-agnostic projects that serve many languages. IPython will continue to focus on Python and its use with Jupyter.</p>
</blockquote>
<p><a href="https://test-jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html" rel="noreferrer">Jupyter's architecture</a> includes frontends (web or console) and backends (kernels for various languages). IPython console is only about Python and terminal. "IPython Notebook", if it's still a thing (it doesn't work out of the box if I <code>pip install ipython</code> as of IPython 5.5.0), is probably a rudiment of the moved components for backward compatibility.</p>
<p>IPython is a dependency of Jupyter:</p>
<pre><code>> pip show jupyter
<...>
Requires: ipywidgets, qtconsole, nbconvert, notebook, jupyter-console, ipykernel
> pip show ipython
<...>
Required-by: jupyter-console, ipywidgets, ipykernel
</code></pre> |
8,394,357 | What exactly are Delay signing and strong names in .net? | <p>I have seen in many article it is written that
Delay signing and strong name for an assembly prevents it from hi-jacked.</p>
<p>What does that mean?</p>
<p>The only thing that i know is without a strong name you can not install an assembly in GAC.
So suppose i have an assembly without a strong name, Can it be hi-jacked?</p>
<p>Someone please clarify my doubt.</p> | 8,394,506 | 1 | 0 | null | 2011-12-06 01:47:58.76 UTC | 10 | 2014-06-24 10:43:08.687 UTC | 2011-12-06 03:15:29.243 UTC | null | 241,753 | null | 275,846 | null | 1 | 25 | c#|.net|delay-sign | 14,420 | <p>There is plenty of information about this on MSDN; for example: <a href="http://msdn.microsoft.com/en-us/library/xwb8f617.aspx">Strong Naming</a>, and <a href="http://msdn.microsoft.com/en-us/library/t07a3dye%28v=VS.100%29.aspx">Delay Signing</a></p>
<p>To summarize the basic idea:</p>
<p>Strong naming is a way of stamping your assembly with a simple identification mark, that can be used later to validate that it has not been modified since it was deployed. The strong name is basically a hash of the assembly's name, version, and a "strong-name key" unique to the developer. References to strong name assemblies go through stricter validation that reference to non-strongly-named ones; in particular, strong-named references must match version numbers, and the strong name hash must match.</p>
<p>This helps avoid two common sources of potential security vulnerabilities in your programs:</p>
<ol>
<li>A malicious user replaces an assembly in your program with a different assembly with the same file name, but which contains malicious code, and convinces your program to load and execute it.</li>
<li>A malicious user replaces an assembly in your program with a different version of the same assembly, but which has known bugs that have since been fixed.</li>
</ol>
<p>The strong name process will reject both of these actions because the strong name data will not match. This is why assemblies in the GAC must be strong named: they are uses so ubiquitously, they would otherwise make major targets for this kind of hijacking.</p>
<p>Note, however, that strong names <strong>do absolutely nothing to verify the identity of the publisher</strong>. Anyone can publish a strongly-named assembly claiming to be Microsoft and there's nothing in the strong name to refute that assertion. Verifying identify is the job of Authenticode digital signatures, which are different from strong naming. The two are often used together, but they are orthogonal concepts.</p>
<p>Delay signing is a technique for signing assemblies outside of the build process. The idea here is, your company might have policies that don't allow the strong name keys from being available at build time (perhaps they are kept offline, or secured behind a password.) A delay signed assembly is marked with a blank strong-name key: it basically reserves space for the key to be added later, by an authorized user. In the mean time, a partial strong-name key is included -- just enough information for other assemblies to make a strong reference, but not enough to detect changes or modifications.</p> |
8,818,119 | How can I run a function from a script in command line? | <p>I have a script that has some functions.</p>
<p>Can I run one of the function directly from command line?</p>
<p>Something like this?</p>
<pre><code>myScript.sh func()
</code></pre> | 8,818,150 | 10 | 0 | null | 2012-01-11 11:01:08.57 UTC | 53 | 2022-03-21 15:28:00.77 UTC | 2017-02-14 23:36:59.257 UTC | null | 3,266,847 | null | 726,706 | null | 1 | 176 | linux|bash|scripting | 221,331 | <p>If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the <code>source</code> or <code>.</code> command and then simply call the function. See <code>help source</code> for more information.</p> |
48,253,103 | How to get input text value in ionic | <p>I'm trying to get <code>input</code> text value and store it in a variable named <code>input</code> in <code>ionic</code>. But I tried and failed. Can anyone please tell me what I have faulty done?</p>
<p>This is my <code>HTML</code></p>
<pre><code> <ion-content>
<ion-list>
<ion-item>
<ion-label stacked>display</ion-label>
<ion-input type="text" text-right id="input" ></ion-input>
</ion-item>
</ion-list>
</ion-content>
</code></pre>
<p>and this is my <code>home.ts</code> in ionic</p>
<pre><code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController) {
var input=document.getElementById('input').nodeValue;
document.getElementById('seven').innerHTML=input;
}
}
</code></pre> | 48,253,114 | 3 | 0 | null | 2018-01-14 19:01:51.393 UTC | 2 | 2021-06-04 12:32:21.303 UTC | 2021-06-04 12:32:21.303 UTC | null | 5,486,116 | null | 8,794,865 | null | 1 | 19 | html|angular|ionic-framework | 64,663 | <p>Actually you seems to be using angular not angularjs, use [(ngModel)]</p>
<pre><code> <ion-input type="text" [(ngModel)]="name" text-right id="input" ></ion-input>
</code></pre>
<p>and inside the component,</p>
<p><strong><code>name:string;</code></strong></p>
<p>so whenever you need the value , you can use.</p>
<p><strong><code>console.log(this.name);</code></strong></p> |
53,851,828 | TS2740 Type is missing the following properties from ReadOnly<MyInterface> error in React Native with TypeScript app | <p>Since <code>StatelessComponent</code> is deprecated, I am trying to turn all the components into classes.</p>
<p>I have an interface, for example: </p>
<pre><code>interface MyInterface{
prop1: number;
prop2: boolean;
}
</code></pre>
<p>And I use it in the class:</p>
<pre><code>class MyComponent extends React.Component<MyInterface> {
...
public render(){...}
}
</code></pre>
<p>And when I try to use <code>MyComponent</code> like this:</p>
<pre><code><MyComponent
prop1={3}
prop2={false}
/>
</code></pre>
<p>I get this error: </p>
<blockquote>
<p>TS2740: Type {prop1: 3, prop2: false} is missing the following properties from type ReadOnly: render, context, setState, forceUpdate, and 3 more.</p>
</blockquote>
<p>Is there any workaround to this?</p> | 53,854,058 | 4 | 4 | null | 2018-12-19 13:01:15.153 UTC | 2 | 2020-04-08 22:50:29.92 UTC | 2018-12-19 13:26:12.433 UTC | null | 6,662,393 | null | 6,662,393 | null | 1 | 6 | typescript|react-native | 45,905 | <p>I finally solved the problem by changing the declaration of the class to <code>class MyComponent extends React.Component<any, MyInterface></code>.</p> |
30,739,244 | Python Flask shutdown event handler | <p>I'm using Flask as a REST endpoint which adds an application request to a queue. The queue is then consumed by a second thread. </p>
<p><code>server.py</code></p>
<pre><code>def get_application():
global app
app.debug = True
app.queue = client.Agent()
app.queue.start()
return app
@app.route("/api/v1/test/", methods=["POST"])
def test():
if request.method == "POST":
try:
#add the request parameters to queue
app.queue.add_to_queue(req)
except Exception:
return "All the parameters must be provided" , 400
return "", 200
return "Resource not found",404
</code></pre>
<p><code>client.py</code></p>
<pre><code>class Agent(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.active = True
self.queue = Queue.Queue(0)
def run(self):
while self.active:
req = self.queue.get()
#do something
def add_to_queue(self,request):
self.queue.put(request)
</code></pre>
<p>Is there a shutdown event handler in flask so that I can cleanly shutdown the consumer thread whenever the flask app is shutdown (like when the apache service is restarted)?</p> | 30,739,397 | 2 | 0 | null | 2015-06-09 17:46:54.363 UTC | 4 | 2022-04-12 16:18:55.753 UTC | null | null | null | null | 2,912,843 | null | 1 | 28 | python|multithreading|flask | 31,885 | <p>There is no <code>app.stop()</code> if that is what you are looking for, however using module <code>atexit</code> you can do something similar:</p>
<p><a href="https://docs.python.org/2/library/atexit.html" rel="nofollow noreferrer">https://docs.python.org/2/library/atexit.html</a></p>
<p>Consider this:</p>
<pre><code>import atexit
#defining function to run on shutdown
def close_running_threads():
for thread in the_threads:
thread.join()
print "Threads complete, ready to finish"
#Register the function to be called on exit
atexit.register(close_running_threads)
#start your process
app.run()
</code></pre>
<p>Also of note-<code>atexit</code> will not be called if you force your server down using Ctrl-C.</p>
<p>For that there is another module- <code>signal</code>.</p>
<p><a href="https://docs.python.org/2/library/signal.html" rel="nofollow noreferrer">https://docs.python.org/2/library/signal.html</a></p> |
1,236,485 | How to access elements of a C++ map from a pointer? | <p>Simple question but difficult to formulate for a search engine: if I make a pointer to a map object, how do I access and set its elements? The following code does not work.</p>
<pre><code>map<string, int> *myFruit;
myFruit["apple"] = 1;
myFruit["pear"] = 2;
</code></pre> | 1,236,492 | 3 | 0 | null | 2009-08-06 00:59:45.953 UTC | 6 | 2009-08-06 01:02:46.887 UTC | null | null | null | user123003 | null | null | 1 | 34 | c++ | 44,364 | <p>You can do this:</p>
<pre><code>(*myFruit)["apple"] = 1;
</code></pre>
<p>or</p>
<pre><code>myFruit->operator[]("apple") = 1;
</code></pre>
<p>or</p>
<pre><code>map<string, int> &tFruit = *myFruit;
tFruit["apple"] = 1;
</code></pre> |
632,434 | LINQ to SQL Where Clause Optional Criteria | <p>I am working with a LINQ to SQL query and have run into an issue where I have 4 optional fields to filter the data result on. By optional, I mean has the choice to enter a value or not. Specifically, a few text boxes that could have a value or have an empty string and a few drop down lists that could have had a value selected or maybe not...</p>
<p>For example:</p>
<pre><code> using (TagsModelDataContext db = new TagsModelDataContext())
{
var query = from tags in db.TagsHeaders
where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
select tags;
this.Results = query.ToADOTable(rec => new object[] { query });
}
</code></pre>
<p>Now I need to add the following fields/filters, but only if they are supplied by the user.</p>
<ol>
<li>Product Number - Comes from another table that can be joined to TagsHeaders.</li>
<li>PO Number - a field within the TagsHeaders table.</li>
<li>Order Number - Similar to PO #, just different column.</li>
<li>Product Status - If the user selected this from a drop down, need to apply selected value here.</li>
</ol>
<p>The query I already have is working great, but to complete the function, need to be able to add these 4 other items in the where clause, just don't know how!</p> | 632,487 | 3 | 1 | null | 2009-03-10 21:50:08.82 UTC | 45 | 2010-06-11 19:34:18.207 UTC | 2009-09-30 04:42:08.543 UTC | RSolberg | 55,747 | RSolberg | 55,747 | null | 1 | 72 | c#|asp.net|linq|linq-to-sql | 93,342 | <p>You can code your original query:</p>
<pre><code>var query = from tags in db.TagsHeaders
where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
&& Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
select tags;
</code></pre>
<p>And then based on a condition, add additional where constraints.</p>
<pre><code>if(condition)
query = query.Where(i => i.PONumber == "ABC");
</code></pre>
<p>I am not sure how to code this with the query syntax but id does work with a lambda. Also works with query syntax for the initial query and a lambda for the secondary filter.</p>
<p>You can also include an extension method (below) that I coded up a while back to include conditional where statements. (Doesn't work well with the query syntax):</p>
<pre><code> var query = db.TagsHeaders
.Where(tags => tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()))
.Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE)
.Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE)
.WhereIf(condition1, tags => tags.PONumber == "ABC")
.WhereIf(condition2, tags => tags.XYZ > 123);
</code></pre>
<p>The extension method:</p>
<pre><code>public static IQueryable<TSource> WhereIf<TSource>(
this IQueryable<TSource> source, bool condition,
Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
</code></pre>
<p>Here is the same extension method for IEnumerables:</p>
<pre><code>public static IEnumerable<TSource> WhereIf<TSource>(
this IEnumerable<TSource> source, bool condition,
Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
</code></pre> |
39,512,260 | calculating Gini coefficient in Python/numpy | <p>i'm calculating <a href="https://en.wikipedia.org/wiki/Gini_coefficient" rel="noreferrer">Gini coefficient</a> (similar to: <a href="https://stackoverflow.com/questions/31416664/python-gini-coefficient-calculation-using-numpy">Python - Gini coefficient calculation using Numpy</a>) but i get an odd result. for a uniform distribution sampled from <code>np.random.rand()</code>, the Gini coefficient is 0.3 but I would have expected it to be close to 0 (perfect equality). what is going wrong here?</p>
<pre><code>def G(v):
bins = np.linspace(0., 100., 11)
total = float(np.sum(v))
yvals = []
for b in bins:
bin_vals = v[v <= np.percentile(v, b)]
bin_fraction = (np.sum(bin_vals) / total) * 100.0
yvals.append(bin_fraction)
# perfect equality area
pe_area = np.trapz(bins, x=bins)
# lorenz area
lorenz_area = np.trapz(yvals, x=bins)
gini_val = (pe_area - lorenz_area) / float(pe_area)
return bins, yvals, gini_val
v = np.random.rand(500)
bins, result, gini_val = G(v)
plt.figure()
plt.subplot(2, 1, 1)
plt.plot(bins, result, label="observed")
plt.plot(bins, bins, '--', label="perfect eq.")
plt.xlabel("fraction of population")
plt.ylabel("fraction of wealth")
plt.title("GINI: %.4f" %(gini_val))
plt.legend()
plt.subplot(2, 1, 2)
plt.hist(v, bins=20)
</code></pre>
<p>for the given set of numbers, the above code calculates the fraction of the total distribution's values that are in each percentile bin.</p>
<p>the result:</p>
<p><a href="https://i.stack.imgur.com/YKOUG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YKOUG.png" alt="enter image description here"></a></p>
<p>uniform distributions should be near "perfect equality" so the lorenz curve bending is off.</p> | 39,513,799 | 6 | 1 | null | 2016-09-15 13:26:21.98 UTC | 9 | 2022-03-29 15:46:26.307 UTC | 2017-05-23 10:33:51.72 UTC | null | -1 | null | 5,768,196 | null | 1 | 27 | python|numpy|statistics | 61,958 | <p>This is to be expected. A random sample from a uniform distribution does not result in uniform values (i.e. values that are all relatively close to each other). With a little calculus, it can be shown that the <em>expected</em> value (in the statistical sense) of the Gini coefficient of a sample from the uniform distribution on [0, 1] is 1/3, so getting values around 1/3 for a given sample is reasonable.</p>
<p>You'll get a lower Gini coefficient with a sample such as <code>v = 10 + np.random.rand(500)</code>. Those values are all close to 10.5; the <em>relative</em> variation is lower than the sample <code>v = np.random.rand(500)</code>.
In fact, the expected value of the Gini coefficient for the sample <code>base + np.random.rand(n)</code> is 1/(6*base + 3).</p>
<p>Here's a simple implementation of the Gini coefficient. It uses the fact that the Gini coefficient is half the <a href="https://en.wikipedia.org/wiki/Mean_absolute_difference#Relative_mean_absolute_difference" rel="nofollow noreferrer">relative mean absolute difference</a>.</p>
<pre><code>def gini(x):
# (Warning: This is a concise implementation, but it is O(n**2)
# in time and memory, where n = len(x). *Don't* pass in huge
# samples!)
# Mean absolute difference
mad = np.abs(np.subtract.outer(x, x)).mean()
# Relative mean absolute difference
rmad = mad/np.mean(x)
# Gini coefficient
g = 0.5 * rmad
return g
</code></pre>
<p>(For some more efficient implementations, see <a href="https://stackoverflow.com/questions/48999542/more-efficient-weighted-gini-coefficient-in-python">More efficient weighted Gini coefficient in Python</a>)</p>
<p>Here's the Gini coefficient for several samples of the form <code>v = base + np.random.rand(500)</code>:</p>
<pre><code>In [80]: v = np.random.rand(500)
In [81]: gini(v)
Out[81]: 0.32760618249832563
In [82]: v = 1 + np.random.rand(500)
In [83]: gini(v)
Out[83]: 0.11121487509454202
In [84]: v = 10 + np.random.rand(500)
In [85]: gini(v)
Out[85]: 0.01567937753659053
In [86]: v = 100 + np.random.rand(500)
In [87]: gini(v)
Out[87]: 0.0016594595244509495
</code></pre> |
6,976,944 | How does ArrowLoop work? Also, mfix? | <p>I'm fairly comfortable now with the rest of the arrow machinery, but I don't get how loop works. It seems magical to me, and that's bad for my understanding. I also have trouble understanding mfix. When I look at a piece of code that uses <code>rec</code> in a <code>proc</code> or <code>do</code> block, I get confused. With regular monadic or arrow code, I can step through the computation and keep an operational picture of what's going on in my head. When I get to <code>rec</code>, I don't know what picture to keep! I get stuck, and I can't reason about such code.</p>
<p>The example I'm trying to grok is from <a href="http://www.soi.city.ac.uk/~ross/papers/notation.html">Ross Paterson's paper on arrows</a>, the one about circuits.</p>
<pre><code>counter :: ArrowCircuit a => a Bool Int
counter = proc reset -> do
rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
returnA -< output
</code></pre>
<p>I assume that if I understand this example, I'll be able to understand loop in general, and it'll go a great way towards understanding mfix. They feel essentially the same to me, but perhaps there is a subtlety I'm missing? Anyway, what I would really prize is an <em>operational</em> picture of such pieces of code, so I can step through them in my head like 'regular' code.</p>
<p><strong>Edit</strong>: Thanks to Pigworker's answer, I have started thinking about rec and such as demands being fulfilled. Taking the <code>counter</code> example, the first line of the rec block demands a value called <code>output</code>. I imagine this operationally as creating a box, labelling it <code>output</code>, and asking the rec block to fill that box. In order to fill that box, we feed in a value to returnA, but that value itself demands another value, called <code>next</code>. In order to use this value, it must be demanded of another line in the rec block <em>but it doesn't matter where in the rec block it is demanded, for now</em>. </p>
<p>So we go to the next line, and we find the box labelled <code>next</code>, and we demand that another computation fill it. Now, this computation demands our first box! So we <em>give it the box</em>, but it has no value inside it, so if this computation demands the contents of <code>output</code>, we hit an infinite loop. Fortunately, delay takes the box, but produces a value without looking inside the box. This fills <code>next</code>, which then allows us to fill <code>output</code>. Now that <code>output</code> is filled, when the next input of this circuit is processed, the previous <code>output</code> box will have its value, ready to be demanded in order to produce the next <code>next</code>, and thus the next <code>output</code>.</p>
<p>How does that sound?</p> | 6,980,343 | 1 | 10 | null | 2011-08-08 01:11:36.92 UTC | 13 | 2014-08-05 19:12:56.537 UTC | 2014-08-05 19:12:56.537 UTC | null | 2,597,135 | null | 753,990 | null | 1 | 31 | haskell|monads|arrows | 2,802 | <p>In this code, they key piece is the <code>delay 0</code> arrow in the <code>rec</code> block. To see how it works, it helps to think of values as varying over time and time as chopped into slices. I think of the slices as ‘days’. The <code>rec</code> block explains how each day's computation works. It's organised by <em>value</em>, rather than by <em>causal order</em>, but we can still track causality if we're careful. Crucially, we must make sure (without any help from the <em>types</em>) that each day's work relies on the past but not the future. The one-day <code>delay 0</code> buys us time in that respect: it shifts its input signal one day later, taking care of the first day by giving the value 0. The delay's input signal is ‘tomorrow's <code>next</code>’.</p>
<pre><code>rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
</code></pre>
<p>So, looking at the arrows and their outputs, we're delivering <em>today's</em> <code>output</code> but <em>tomorrow's</em> <code>next</code>. Looking at the inputs, we're relying on <em>today's</em> <code>reset</code> and <code>next</code> values. It's clear that we can deliver those outputs from those inputs without time travel. The <code>output</code> is today's <code>next</code> number unless we <code>reset</code> to 0; tomorrow, the <code>next</code> number is the successor of today's <code>output</code>. Today's <code>next</code> value thus comes from yesterday, unless there was no yesterday, in which case it's 0.</p>
<p>At a lower level, this whole setup works because of Haskell's laziness. Haskell computes by a demand-driven strategy, so if there is a sequential order of tasks which respects causality, Haskell will find it. Here, the <code>delay</code> establishes such an order.</p>
<p>Be aware, though, that Haskell's type system gives you very little help in ensuring that such an order exists. You're free to use loops for utter nonsense! So your question is far from trivial. Each time you read or write such a program, you do need to think ‘how can this possibly work?’. You need to check that <code>delay</code> (or similar) is used appropriately to ensure that information is demanded only when it can be computed. Note that <em>constructors</em>, especially <code>(:)</code> can act like delays, too: it's not unusual to compute the tail of a list, apparently given the whole list (but being careful only to inspect the head). Unlike imperative programming, the lazy functional style allows you to organize your code around concepts other than the sequence of events, but it's a freedom that demands a more subtle awareness of time.</p> |
36,533,739 | Run function when an ionic 2 page has fully loaded | <p>Is there a way to determine when an ionic 2 page has fully loaded? I need to insert some html into the page when all of the page html has been loaded. Ideally I would like to have a function in my @page class that runs when the page has been loaded.</p>
<p>At the moment I am inserting an iframe containing a vine into a div container. I am experiencing, when running the app on an iPhone 5 running iOS 9, some peculiar behaviour where the same vine sometimes sizes to the container and sometimes doesn't. I am guessing that this might be due to timing (the source for the vine iframe is received as part of an http request).</p> | 36,534,687 | 2 | 1 | null | 2016-04-10 18:25:04.903 UTC | 2 | 2019-03-27 08:13:32.227 UTC | null | null | null | null | 1,726,579 | null | 1 | 12 | ios|iframe|ionic-framework|angular|ionic2 | 39,021 | <p>You can use the <code>ionViewDidLoad</code> method:</p>
<pre><code>@Page({
templateUrl: 'build/pages/somepage/somepage.html'
})
export class SomePage {
constructor() {
// ...
}
ionViewDidLoad() {
// Put here the code you want to execute
}
}
</code></pre>
<p>The lifecycle events as November 18, 2016 are:</p>
<ul>
<li>ionViewDidLoad</li>
<li>ionViewWillEnter</li>
<li>ionViewDidEnter</li>
<li>ionViewWillLeave</li>
<li>ionViewDidLeave</li>
<li>ionViewWillUnload</li>
<li>ionViewCanEnter</li>
</ul>
<p>Since Ionic 2 is in active development, things change all the time. If you would like to check the current lifecycle events, please refer to: <a href="https://ionicframework.com/docs/v2/api/navigation/NavController/#lifecycle-events" rel="noreferrer">https://ionicframework.com/docs/v2/api/navigation/NavController/#lifecycle-events</a> </p> |
28,420,724 | How to determine the intended frame-rate on an html video element | <p>Is there a way to determine the intended frame rate of content playing in the html video element?</p>
<p>Does the video element even know the intended FPS or frame count, or does it simply "guess" (maybe 24fps) and play at the guessed speed?</p>
<p>Here are my unsuccessful attempts:</p>
<ul>
<li><p>Look for a FPS or FrameCount property on the video element itself--Nope!</p></li>
<li><p>Look for cross-video-format header info about FPS or FrameCount--Nothing consistent!</p></li>
<li><p>Look for an event that is triggered upon frame changing--Nope!</p></li>
</ul>
<p>My next attempt is more complicated: Sample the video by capturing frames to a canvas element and count frames by determining when the pixels change.</p>
<p>Does anyone have a simpler answer before I do the complicated attempt?</p> | 28,455,790 | 3 | 2 | null | 2015-02-09 22:32:41.493 UTC | 11 | 2022-07-24 12:38:09.737 UTC | 2015-02-09 22:50:52.227 UTC | null | 411,591 | null | 411,591 | null | 1 | 23 | javascript|html|video|canvas | 25,413 | <p>Knowing the frame-rate of the video wouldn't be as useful as you might think.<br>
Browsers uses of some tricks to make a match between the frame-rate of the movie and the refresh-rate of the screen, so if you look at <code>currentTime</code> property, you'll see that the <em>actual</em> frame duration ( == <code>currentTime</code> - previous <code>currentTime</code>) is not a constant, it varies from frame to frame. </p>
<p>On this sample video : <a href="http://jsfiddle.net/3qs46n4z/3/" rel="noreferrer">http://jsfiddle.net/3qs46n4z/3/</a> the pattern is :<br>
4-1-5-1 :<br>
4 frames at 21.3 + 1 frame at 32 + 5 frames at 21.3 + 1 frame at 32.</p>
<p>So if you want to always display the latest frame on a canvas while avoiding overdraw, the solution might be to :<br>
- On each rAF, look at the current time of the video :<br>
β’ Same ? -> do nothing.<br>
β’ Changed ? -> update frame. </p>
<p>And whatever you want to do, comparing two currentTime === two numbers might be faster than comparing two imageDatas ;-) </p>
<p>Edit : looking into the specifications to find evidence of my saying, i found a nuance with this Note : </p>
<pre><code> Which frame in a video stream corresponds to a particular playback position is defined by the video stream's format.
</code></pre>
<p>(Note of 4.8.6 at <a href="http://www.w3.org/TR/2011/WD-html5-20110113/video.html" rel="noreferrer">http://www.w3.org/TR/2011/WD-html5-20110113/video.html</a> )</p>
<p>So strictly saying we can only say that (the current time is the same) implies (the frames are identical).<br>
I can only bet that the reciprocal is true => different time means different frame.<br>
In the example above, Chrome is trying to match the 24Hz of the movie on my 60Hz computer by trying to get 45 Hz ( = 60 / 2 + 60 / 4), the nearest from 48 = 2*24.
For the 21 created frames i don't know if it interpolates or merely duplicates the frames. It surely changes depending on browser/device (Gpu especially). I bet any recent desktop or powerful smartphone does interpolate.</p>
<p>Anyway given the high cost of checking with the imageData, you'd much better draw twice than check.</p>
<p>Rq1 : I wonder to which extent using Xor mode + testing against 0 32 bits at a time could boost the compare time. (getImageData <em>is</em> slow.)</p>
<p>Rq2 : I'm sure there's a hacky way to use the playback rate to 'sync' the video and the display, and to know which frame is a genuine ( == not interpolated ) frame. ( so two pass here 1) sync 2) rewind and retrieve frames).</p>
<p>Rq3 : If your purpose is to get each and every video frame <em>and only</em> the video's frame, a browser is not the way to go. As explained above, the (desktop) browsers do interpolate to match as closely as possible the display frame rate. Those frames were <em>not</em> in the original stream. There are even some high-end '3D' (2D+time) interpolation devices where the initial frames are not even meant to be displayed (! ).
On the other hand, if you are okay with the (interpolated) output stream, polling on rAF will provide <em>every</em> frames that you see (you can't miss a frame (except obviously your app is busy doing something else) . </p>
<p>Rq4 : interpolation ( == no duplicate frames ) is 99.99% likely on recent/decent GPU powered desktop. </p>
<p>Rq5 : Be sure to warm your functions (call them 100 times on start) and to create no garbage to avoid jit / gc pauses.</p> |
20,368,832 | Address family not supported by protocol | <p>The following code is a socket programming sample for a TCP client.</p>
<p>But when I run this, connect() is returned as Address family not supported by protocol.</p>
<p>I have heard, this problem will happen if the platform does not support ipv6.</p>
<p>But AF_INET I wrote is ipv4.</p>
<p>Also my server, that is CentOS6.4, is configured within an inet6 addr .</p>
<p>Does anyone know why?</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int
main(){
struct sockaddr_in server;
int sock;
char buf[32];
int n;
sock = socket(AF_INET,SOCK_STREAM,0);
perror("socket");
server.sin_family = AF_INET;
server.sin_port = htons(12345);
inet_pton(AF_INET,"127.0.0.1",&server,sizeof(server));
connect(sock,(struct sockaddr *)&server,sizeof(server));
perror("connect");
memset(buf,0,sizeof(buf));
n = read(sock,buf,sizeof(buf));
perror("read");
printf("%d,%s\n",n,buf);
close(sock);
return 0;
}
</code></pre> | 20,369,264 | 3 | 0 | null | 2013-12-04 06:46:59.26 UTC | 4 | 2021-07-08 19:04:00.423 UTC | 2021-07-08 19:04:00.423 UTC | null | 3,739,391 | null | 1,345,414 | null | 1 | 17 | c|sockets|centos|ipv6 | 116,880 | <p>The code passes the wrong destination address and wrong number of arguments to <code>inet_pton()</code>. (For the latter the compiler should have warned you about, btw)</p>
<p>This line</p>
<pre><code> inet_pton(AF_INET, "127.0.0.1", &server, sizeof(server));
</code></pre>
<p>should be</p>
<pre><code> inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
</code></pre>
<p>Verbatim from <a href="http://man7.org/linux/man-pages/man3/inet_pton.3.html" rel="noreferrer"><code>man inet_pton</code></a>:</p>
<blockquote>
<p><strong>int inet_pton(int af, const char *src, void *dst);</strong></p>
<p><strong>AF_INET</strong></p>
<p>[...] The address is converted to
a struct in_addr and copied to dst, which must be sizeof(struct in_addr) (4) bytes (32 bits) long.</p>
</blockquote>
<hr>
<p>Not related to the problem, but also an issue, is that <code>read()</code> returns <code>ssize_t</code> not <code>int</code>.</p>
<p>The following lines shall be adjusted:</p>
<pre><code>int n;
[...]
printf("%d, %s\n", n, buf);
</code></pre>
<p>to become:</p>
<pre><code>ssize_t n;
[...]
printf("%zd, %s\n", n, buf);
</code></pre> |
20,357,960 | Drawing selection box (rubberbanding, marching ants) in Cocoa, ObjectiveC | <p>I've currently implemented a simple selection box using mouse events and redrawing a rectangle on mouse drag. Here's my code:</p>
<pre><code>-(void)drawRect:(NSRect)dirtyRect
{
if (!NSEqualRects(self.draggingBox, NSZeroRect))
{
[[NSColor grayColor] setStroke];
[[NSBezierPath bezierPathWithRect:self.draggingBox] stroke];
}
}
#pragma mark Mouse Events
- (void)mouseDown:(NSEvent *)theEvent
{
NSPoint pointInView = [self convertPoint:[theEvent locationInWindow] fromView:nil];
self.draggingBox = NSMakeRect(pointInView.x, pointInView.y, 0, 0);
[self setNeedsDisplay:YES];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint pointInView = [self convertPoint:[theEvent locationInWindow] fromView:nil];
_draggingBox.size.width = pointInView.x - (self.draggingBox.origin.x);
_draggingBox.size.height = pointInView.y - (self.draggingBox.origin.y);
[self setNeedsDisplay:YES];
}
- (void)mouseUp:(NSEvent *)theEvent
{
self.draggingBox = NSZeroRect;
[self setNeedsDisplay:YES];
}
</code></pre>
<p>Ref: <a href="http://cocoadev.com/HowToCreateWalkingAnts">http://cocoadev.com/HowToCreateWalkingAnts</a></p>
<p><strong>Questions:</strong></p>
<p>Is this the most efficient way to do this? If the view was complex, would it be more efficient to draw a transparent view over the main view instead of continuously redrawing the view for the duration of the mouse drag (<a href="http://www.cocoabuilder.com/archive/cocoa/99877-drawing-selection-rectangle.html">http://www.cocoabuilder.com/archive/cocoa/99877-drawing-selection-rectangle.html</a>)? How is this done? I can't seem to find any examples.</p> | 20,359,552 | 4 | 0 | null | 2013-12-03 17:38:05 UTC | 13 | 2020-04-20 02:26:05.027 UTC | 2013-12-03 18:42:52.44 UTC | null | 959,476 | null | 959,476 | null | 1 | 13 | objective-c|macos|cocoa|nsview | 5,068 | <p>You can use QuartzCore to animate the "marching ants" for you, if you want. This gets you completely out of the world of manually drawing the rubber-banded selection box, too. You just define the path that defines that box, and let Core Animation take care of drawing the box, as well as animating it.</p>
<p>In the XIB's "View Effects" Inspector, turn on "Core Animation", and then you can do something like:</p>
<pre><code>#import <QuartzCore/QuartzCore.h>
#import "CustomView.h"
@interface CustomView ()
@property (nonatomic) NSPoint startPoint;
@property (nonatomic, strong) CAShapeLayer *shapeLayer;
@end
@implementation CustomView
#pragma mark Mouse Events
- (void)mouseDown:(NSEvent *)theEvent
{
self.startPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
// create and configure shape layer
self.shapeLayer = [CAShapeLayer layer];
self.shapeLayer.lineWidth = 1.0;
self.shapeLayer.strokeColor = [[NSColor blackColor] CGColor];
self.shapeLayer.fillColor = [[NSColor clearColor] CGColor];
self.shapeLayer.lineDashPattern = @[@10, @5];
[self.layer addSublayer:self.shapeLayer];
// create animation for the layer
CABasicAnimation *dashAnimation;
dashAnimation = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];
[dashAnimation setFromValue:@0.0f];
[dashAnimation setToValue:@15.0f];
[dashAnimation setDuration:0.75f];
[dashAnimation setRepeatCount:HUGE_VALF];
[self.shapeLayer addAnimation:dashAnimation forKey:@"linePhase"];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
// create path for the shape layer
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, self.startPoint.x, self.startPoint.y);
CGPathAddLineToPoint(path, NULL, self.startPoint.x, point.y);
CGPathAddLineToPoint(path, NULL, point.x, point.y);
CGPathAddLineToPoint(path, NULL, point.x, self.startPoint.y);
CGPathCloseSubpath(path);
// set the shape layer's path
self.shapeLayer.path = path;
CGPathRelease(path);
}
- (void)mouseUp:(NSEvent *)theEvent
{
[self.shapeLayer removeFromSuperlayer];
self.shapeLayer = nil;
}
@end
</code></pre>
<p>This way, Core Animation takes care of the marching ants for you.</p>
<p><img src="https://i.stack.imgur.com/5dDND.gif" alt="marching ants demo"></p> |
20,123,147 | Add line break to axis labels and ticks in ggplot | <p>I'm looking for a way to use long variable names on the x axis of a plot. Of course I could use a smaller font or rotate them a little but I would like keep them vertical and readable. </p>
<p>As an example:</p>
<pre><code>df <- data.frame(a=LETTERS[1:20], b=rnorm(20), c=rnorm(20), d=rnorm(20))
df_M <- melt(df, id="a")
plot <- ggplot(data=df_M,
aes(x=variable, y=a, fill=value)) +
geom_tile() +
scale_fill_gradient(low="green", high="red")
plot
</code></pre>
<p>here the x axis is just letters, but if I want to use the full name, the names use a disproportionate amount of space:</p>
<pre><code> plot +
theme(axis.text.x=element_text(angle=90)) +
scale_x_discrete(breaks=unique(df_M$variable),
labels=c("Ambystoma mexicanum",
"Daubentonia madagascariensis",
"Psychrolutes marcidus"))
</code></pre>
<p>So I would like to put a line break in the labels. Preferably in ggplot2 but other solutions are welcome of course.</p>
<p>Thanks!</p> | 20,123,502 | 5 | 0 | null | 2013-11-21 14:09:10.147 UTC | 16 | 2022-09-02 14:12:30.023 UTC | 2019-02-07 11:01:14.87 UTC | null | 1,951,485 | null | 2,997,794 | null | 1 | 34 | r|ggplot2 | 69,079 | <p>You can add your own formatter ( see <code>scales</code> package for more examples). Here I replace any space in your x labels by a new line.</p>
<pre><code>addline_format <- function(x,...){
gsub('\\s','\n',x)
}
myplot +
scale_x_discrete(breaks=unique(df_M$variable),
labels=addline_format(c("Ambystoma mexicanum",
"Daubentonia madagascariensis", "Psychrolutes marcidus")))
</code></pre>
<p><img src="https://i.stack.imgur.com/0Njda.png" alt="enter image description here"></p> |
5,634,097 | How can I change the description of a existing changelist in command line? | <p>The command "p4 change" prompts a editor and needs a form. But I want to do this in command line.</p>
<p>How can I achieve this?</p> | 5,634,141 | 3 | 2 | null | 2011-04-12 10:57:51.5 UTC | 1 | 2017-05-28 18:41:43.003 UTC | null | null | null | null | 238,118 | null | 1 | 12 | perforce | 38,884 | <p>There's always the <code>-i</code> command:</p>
<blockquote>
<p>Read a changelist description from standard input. Input must be in the same format used by the p4 change form.</p>
</blockquote>
<p>As Bryan points out in his comment the best approach is probably to run <code>change -o</code>, redirect the output to a file, process the file with other shell commands, and then send that file back to the server with <code>change -i</code>.</p>
<p><a href="http://www.perforce.com/perforce/doc.current/manuals/cmdref/change.html#1040665" rel="noreferrer">Source</a></p>
<p>But you can always change the description when you submit:</p>
<blockquote>
<p>p4 submit -d "description"</p>
</blockquote>
<p>This only works on the default change list.</p>
<p><a href="http://www.perforce.com/perforce/doc.current/manuals/cmdref/submit.html" rel="noreferrer">Source</a></p> |
6,258,556 | org.hibernate.hql.ast.QueryTranslatorImpl list ATTENTION: firstResult/maxResults specified with collection fetch; applying in memory | <p>I'm facing a problem, I have a query in JPA. as I have some collections I need to use left join fetch or inner join fetch</p>
<p>My problem is in using the <code>setFirstResult</code> and <code>setMaxResult</code> in order to bring back a precise number of result. every time i see the whole result is bring back AND only AFTER the maxResult is used.</p>
<p>Is there any way to make the maxResult before ? </p>
<p>Thanks a lot ! </p>
<p>here it is more information : </p>
<p>my problem is when i use that : </p>
<pre><code>startIndex = 0;
maxResults = 10;
query.setFirstResult(startIndex);
query.setMaxResults(maxResults);
</code></pre>
<p>I see this message in my log : </p>
<blockquote>
<p>7 juin 2011 09:52:37 org.hibernate.hql.ast.QueryTranslatorImpl list
ATTENTION: firstResult/maxResults specified with collection fetch;
applying in memory!</p>
</blockquote>
<p>I see the 200 result coming back (in log) and after in the HashSet i have finally the 10 result i ask.</p>
<p>its seems in memory is bring back the 200 result and after the maxResults is applied in memory.</p>
<p>I'm searching if there is any way to be able to fetch and limit the number of result. </p>
<p>I used a workaround, I make a first query to ask the id of my order , without any fetch, used the maxResult.
everything work perfectly it's used the limit instruction.
After I use my "big" query with the fetch and limit the result inside the list of id bring back in the first one.</p>
<p>here it is my full query without my workaround (notice that there is no limit generated as talk by @Bozho ):</p>
<pre class="lang-sql prettyprint-override"><code>select o from Order o
left join fetch o.notes note
left join fetch o.orderedBy orderedBy
left join fetch orderedBy.address addressOrdered
left join fetch orderedBy.language orderedByLg
left join fetch orderedByLg.translations orderedByLgTtrad
left join fetch o.deliveredTo deliveredTo
left join fetch deliveredTo.address addressDelivered
left join fetch deliveredTo.language deliveredToLg
left join fetch deliveredToLg.translations
left join fetch o.finalReceiptPlace finalReceiptPlace
left join fetch finalReceiptPlace.address addressFinalReceiptPlace
left join fetch finalReceiptPlace.language finalReceiptPlaceLg
left join fetch finalReceiptPlaceLg.translations
inner join fetch o.deliveryRoute delivery
left join fetch delivery.translations
inner join fetch o.type orderType
left join fetch orderType.translations
inner join fetch o.currency currency
left join fetch currency.translations
left join fetch o.attachments
left join fetch note.origin orig
left join fetch orig.translations
left join fetch o.supplier sup
left join fetch sup.department dep
left join fetch o.stateDetail stateD
inner join fetch stateD.state stat
where 1=1 and o.entryDate >= :startDat
</code></pre> | 10,727,653 | 3 | 4 | null | 2011-06-06 22:03:35.417 UTC | 10 | 2018-01-16 21:26:51.61 UTC | 2014-05-08 00:16:22.423 UTC | null | 1,391,249 | null | 359,281 | null | 1 | 13 | hibernate|jpa | 16,526 | <blockquote>
<p><strong>TL;DR</strong> Hibernate doesn't know how many rows of the flattened, joined query it needs to get the specified number of the Order objects, so it has to load the whole query in memory. See below for an explanation.</p>
</blockquote>
<p>To understand why Hibernate does this, you need to understand how Hibernate does the ORM (Object-Relational Mapping) involved for JPA Entities.</p>
<p>Consider a simplified set of Entities for your order. Class <code>Order</code> contains 2 fields: <code>number</code> and <code>customerId</code> and a list of order lines. Class <code>OrderLine</code> contains <code>productCode</code> and <code>quantity</code> fields, as well as a <code>uid</code> key and a reference to the parent Order.</p>
<p>These classes may be defined thus:</p>
<pre><code>@Entity
@Table(name = "ORDER")
public class Order {
@ID
@Column(name = "NUMBER")
private Integer number;
@Column(name = "CUSTOMER_ID")
private Integer customerId;
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
@OrderBy
private List<OrderLine> orderLineList;
.... // Rest of the class
}
@Entity
@Table(name = "ORDER_LINE")
public class OrderLine
{
@ID
@Column(name = "UID")
private Integer uid;
@Column(name = "PRODUCT_CODE")
private Integer productCode;
@Column(name = "QUANTITY")
private Integer quantity;
@Column(name = "ORDER_NUMBER")
private Integer orderNumber;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "ORDER_NUMBER", referencedColumnName = "NUMBER", insertable = false, updatable = false)
private Order order;
.... // Rest of the class
}
</code></pre>
<p>Now, if you performed the following JPQL query on these Entities:</p>
<pre><code>SELECT o FROM Order o LEFT JOIN FETCH o.orderLineList
</code></pre>
<p>then Hibernate performs this query as a 'flattened' SQL query similar to the following:</p>
<pre><code>SELECT o.number, o.customer_id, ol.uid, ol.product_code, ol.quantity, ol.order_number
FROM order o LEFT JOIN order_line ol ON order_line.order_number = order.number
</code></pre>
<p>which would give a result like this:</p>
<pre><code>| o.number | o.customer_id | ol.uid | ol.product_code | ol.quantity |
|==========|===============|========|=================|=============|
| 1 | 123 | 1 | 1111 | 5 |
| 1 | 123 | 2 | 1112 | 6 |
| 1 | 123 | 3 | 1113 | 1 |
| 2 | 123 | 4 | 1111 | 2 |
| 2 | 123 | 5 | 1112 | 7 |
| 3 | 123 | 6 | 1111 | 6 |
| 3 | 123 | 7 | 1112 | 5 |
| 3 | 123 | 8 | 1113 | 3 |
| 3 | 123 | 9 | 1114 | 2 |
| 3 | 123 | 10 | 1115 | 9 |
...etc
</code></pre>
<p>which Hibernate would use to 'reconstruct' <code>Order</code> objects with attached lists of <code>OrderLine</code> sub-objects.</p>
<p>However, since the number of order lines per order is random, there is no way for Hibernate to know how many rows of this query to take to get the specified maximum number of <code>Order</code> objects required. So it has to take the whole query and build up the objects in memory until it has the right amount, before discarding the rest of the result set. The log warning it produces alludes to this:</p>
<pre><code>ATTENTION: firstResult/maxResults specified with collection fetch; applying in memory!
</code></pre>
<p>We're only just discovering now that these queries can have a significant impact on server memory use, and we've had issues with our server falling over with out of memory errors when these queries are attempted.</p>
<p>By the way, I will say now that this is mostly just theory on my part and I have no idea how the actual Hibernate code works. Most of this you can glean from the logs when you have Hibernate logging the SQL statements it generates.</p>
<hr>
<p><strong>UPDATE:</strong>
Recently I have discovered a little 'gotcha' with the above.</p>
<p>Consider a third Entity called <code>Shipment</code> which is for one or more Lines of an Order.</p>
<p>The <code>Shipment</code> entity would have a <code>@ManyToOne</code> association to the <code>Order</code> entity.</p>
<p>Let's say you have 2 Shipments for the same Order which has 4 Lines.</p>
<p>If you perform a JPQL query for the following:</p>
<pre><code>SELECT s FROM Shipment s LEFT JOIN s.order o LEFT JOIN FETCH o.orderLineList
</code></pre>
<p>You would expect (or at least I did) to get 2 shipment objects back, each with a reference to the same Order object, which itself would contain the 4 Lines.</p>
<p>Nope, wrong again! In fact, you get 2 Shipment objects, each referring to the same Order object, which contains <strong><em>8</em></strong> Lines! Yes, the Lines get duplicated in the Order! And yes, that is even if you specify the DISTINCT clause.</p>
<p>If you research this issue here on SO or elsewhere (most notably the Hibernate forums), you'll find that this is actually a <em>feature</em> not a bug, according to the Hibernate powers that be. Some people actually <strong><em>want</em></strong> this behaviour!</p>
<p>Go figure.</p> |
5,768,316 | pop a specific element off a vector in c++ | <p>so suppose I have a vector called v and it has three elements: 1,2,3 </p>
<p>is there a way to specifically pop 2 from the vector so the resulting vector becomes</p>
<p>1,3 </p> | 5,768,347 | 4 | 0 | null | 2011-04-24 02:38:12.093 UTC | 4 | 2011-04-24 02:59:09.507 UTC | null | null | null | null | 380,714 | null | 1 | 24 | c++|vector | 62,909 | <p>Assuming you're looking for the element containing the value <code>2</code>, not the value at index <code>2</code>.</p>
<pre><code>#include<vector>
#include<algorithm>
int main(){
std::vector<int> a={1,2,3};
a.erase(std::find(a.begin(),a.end(),2));
}
</code></pre>
<p>(I used C++0x to avoid some boilerplate, but the actual use of <code>std::find</code> and <code>vector::erase</code> doesn't require C++0x)</p> |
5,664,345 | String to Binary in C# | <p>I have a function to convert string to hex as this,</p>
<pre><code>public static string ConvertToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
</code></pre>
<p>Could you please help me write another string to Binary function based on my sample function? </p>
<pre><code>public static string ConvertToBin(string asciiString)
{
string bin = "";
foreach (char c in asciiString)
{
int tmp = c;
bin += String.Format("{0:x2}", (uint)System.Convert.????(tmp.ToString()));
}
return bin;
}
</code></pre> | 5,664,400 | 4 | 3 | null | 2011-04-14 13:57:14.343 UTC | 10 | 2019-09-21 04:46:54.687 UTC | 2011-04-14 14:28:24.727 UTC | null | 6,461 | null | 159,818 | null | 1 | 28 | c#|string|binary|types | 128,042 | <p>Here you go:</p>
<pre><code>public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
</code></pre> |
6,178,366 | backbone.js fetch results cached | <p>I am using fetch in the index action of the following backbone.js controller:</p>
<pre><code>App.Controllers.PlanMembers = Backbone.Controller.extend({
routes: {
"": "index"
},
index: function () {
var planMembers = new App.Collections.PlanMembers();
planMembers.fetch({
success: function () {
var recoveryTeam = planMembers.select(function (planMember) {
return planMember.get("TeamMemberRole") == "RecoveryTeam";
});
var otherMembers = planMembers.select(function (planMember) {
return planMember.get("TeamMemberRole") == "Other";
});
new App.Views.Index({ collection: { name: "Team", members: recoveryTeam }, el: $('#recoveryTeam') });
new App.Views.Index({ collection: { name: "Team", members: otherMembers }, el: $('#otherTeam') });
},
error: function () {
alert('failure');
showErrorMessage("Error loading planMembers.");
}
});
}
});
</code></pre>
<p>The problem is that the results are being cached. It does not pick up database changes. Is there anyway to tell backbone.js not to cache the results?</p>
<p>I know I could override the url of the collection and append a timestamp but I am looking for something a bit cleaner than that.</p> | 6,188,929 | 4 | 1 | null | 2011-05-30 15:55:15.99 UTC | 12 | 2016-04-09 18:01:40.303 UTC | 2011-05-30 16:19:00.92 UTC | null | 489,560 | null | 11,755 | null | 1 | 41 | backbone.js | 25,235 | <p>This is a problem on IE usually and backbone has nothing to do with it. You have to go down to the jQuery ajax call and look at the doc. Backbone uses jquery ajax for its sync method. You can do something like this to force ajax call on all browsers:</p>
<pre><code>$.ajaxSetup({ cache: false });
</code></pre>
<p><a href="http://api.jquery.com/jQuery.ajaxSetup/">http://api.jquery.com/jQuery.ajaxSetup/</a></p> |
1,522,778 | maven-assembly plugin - how to create nested assemblies | <p>I have a project whereby I'm trying to create a distribution zip file, which contains (amongst other files) an executable jar with dependencies of my java project.</p>
<p>So I sort of want it to look like this:</p>
<pre><code>-wiki-search-1.0.0-dist.zip
-wiki-search.bat
-wiki-search-help.html
-wiki-search-1.0.0-jar-with-dependencies.jar
-jar content...
</code></pre>
<p>I'm using the assembly plugin, and the predefined descriptor "jar-with-dependencies" to create my executable jar file.</p>
<p>I'm specifying a separate assembly plugin entry in my pom, referencing a custom descriptor to try and build the distributable zip file.</p>
<p>So the part of my pom looks like this:</p>
<pre><code><plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>quicksearch.QuickSearchApp</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/main/assembly/dist.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
</code></pre>
<p>And my custom descriptor looks like this:</p>
<pre><code><assembly>
<id>dist</id>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<includes>
<include>${project.basedir}/target/wiki-search-0.0.1-SNAPSHOT-jar-with-dependencies.jar</include>
</includes>
<outputDirectory>.</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.basedir}/src/main/etc</directory>
<includes>
<include>*</include>
</includes>
<outputDirectory></outputDirectory>
</fileSet>
</fileSets>
</assembly>
</code></pre>
<p>Everything works fine. The jar-with-dependencies is being built. My dist zip file is being built. But the dist zip file does not contain the jar-with-dependencies file.</p> | 1,524,113 | 2 | 0 | null | 2009-10-05 22:40:25.347 UTC | 16 | 2015-07-03 11:28:16.6 UTC | 2015-07-03 11:28:16.6 UTC | null | 2,630,337 | null | 26,633 | null | 1 | 31 | maven-2 | 12,576 | <p>With your existing configuration, your two separate configurations for the assembly plugin will be merged, and the configurations will also be merged.</p>
<p>To achieve your goal you should define a single assembly-plugin configuration with multiple nested executions, then define the configuration for each execution inside it. The assembly plugin will then execute each assembly sequentially, so the <code>jar-with-dependencies</code> jar will be available for inclusion in the <code>dist</code> jar. Also note the <code>attached</code> goal is deprecated in favour of the <code>single</code> goal.</p>
<p>Also note that paths in the assembly are relative to the root, and to include a particular file you should use the <code><files></code> element rather than the <code><filesets></code> element. You can also specify properties in the assembly to make it less fragile to change.</p>
<p>The rearranged configuration and assembly below should do what you're after:</p>
<p>Assembly descriptor:</p>
<pre><code><assembly>
<id>dist</id>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>
target/${project.artifactId}-${project.version}-jar-with-dependencies.jar
</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
<fileSets>
<fileSet>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>*</include>
</includes>
<outputDirectory>/</outputDirectory>
</fileSet>
</fileSets>
</assembly>
</code></pre>
<p>Assembly plugin:</p>
<pre><code><plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>quicksearch.QuickSearchApp</mainClass>
</manifest>
</archive>
</configuration>
</execution>
<execution>
<id>dist</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/dist.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</code></pre> |
1,530,736 | How to print a null-terminated string with newlines without showing backslash escapes in gdb? | <p>I have a variable </p>
<pre><code>char* x = "asd\nqwe\n ... "
</code></pre>
<p>and I want to print it with newlines printed as newlines not <em>backslash n</em>.
Is it possible?</p> | 1,530,774 | 2 | 4 | null | 2009-10-07 10:23:42.11 UTC | 11 | 2015-07-21 11:41:58.503 UTC | 2015-06-23 09:25:24.687 UTC | null | 895,245 | null | 61,342 | null | 1 | 63 | c|debugging|gdb | 98,222 | <p>Update:
Why not just use the gdb <code>printf</code> command?</p>
<pre><code>(gdb) printf "%s", x
asd
qwe
...
(gdb)
</code></pre>
<hr>
<p>Old answer:
From within the debugger you can execute commands. Just call <code>printf</code></p>
<pre><code>(gdb) call printf("%s", x)
asd
qwe
...
(gdb)
</code></pre> |
59,606,449 | kubectl how to rename a context | <p>I have many contexts, one for staging, one for production, and many for dev clusters. Copy and pasting the default cluster names is tedious and hard, especially over time. How can I rename them to make context switching easier?</p> | 59,606,450 | 2 | 0 | null | 2020-01-06 03:48:37.727 UTC | 4 | 2021-06-17 12:59:52.5 UTC | null | null | null | null | 5,838,056 | null | 1 | 35 | kubectl | 16,573 | <p>Renaming contexts is easy!</p>
<pre><code>$ kubectl config rename-context old-name new-name
</code></pre>
<p>Confirm the change by </p>
<pre><code>$ kubectl config get-contexts
</code></pre> |
5,890,499 | PCM audio amplitude values? | <p>I am starting out with audio recording using my Android smartphone.</p>
<p>I successfully saved voice recordings to a PCM file. When I parse the data and print out the signed, 16-bit values, I can create a graph like the one below. <strong>However, I do not understand the amplitude values along the y-axis.</strong> </p>
<ol>
<li><p>What exactly are the units for the amplitude values? The values are signed 16-bit, so they must range from -32K to +32K. But what do these values represent? Decibels? </p></li>
<li><p>If I use 8-bit values, then the values must range from -128 to +128. How would that get mapped to the volume/"loudness" of the 16-bit values? Would you just use a 16-to-1 quantisation mapping?</p></li>
<li><p>Why are there negative values? I would think that complete silence would result in values of 0.</p></li>
</ol>
<p>If someone can point me to a website with information on what's being recorded, I would appreciate it. I found <a href="https://ccrma.stanford.edu/courses/422/projects/WaveFormat/" rel="noreferrer">webpages</a> on the PCM file format, but not what the data values are.</p>
<p><img src="https://i.stack.imgur.com/W6SL8.png" alt="enter image description here"></p> | 5,891,128 | 5 | 2 | null | 2011-05-04 22:14:55.4 UTC | 21 | 2014-04-11 14:01:09.613 UTC | 2011-05-05 01:50:00.65 UTC | null | 4,561,314 | null | 4,561,314 | null | 1 | 35 | iphone|android|audio|audio-recording|pcm | 17,732 | <p>Think of the surface of the microphone. When it's silent, the surface is motionless at position zero. When you talk, that causes the air around your mouth to vibrate. Vibrations are spring like, and have movement in both directions, as in back and forth, or up and down, or in and out. The vibrations in the air cause the microphone surface to vibrate as well, as in move up and down. When it moves down, that might be measured or sampled a positive value. When it moves up that might be sampled as a negative value. (Or it could be the opposite.) When you stop talking the surface settles back down to the zero position.</p>
<p>What numbers you get from your PCM recording data depend on the gain of the system. With common 16 bit samples, the range is from -32768 to 32767 for the largest possible excursion of a vibration that can be recorded without distortion, clipping or overflow. Usually the gain is set a bit lower so that the maximum values aren't right on the edge of distortion.</p>
<p>ADDED:</p>
<p>8-bit PCM audio is often an unsigned data type, with the range from 0..255, with a value of 128 indicating "silence". So you have to add/subtract this bias, as well as scale by about 256 to convert between 8-bit and 16-bit audio PCM waveforms.</p> |
6,309,472 | matplotlib: can I create AxesSubplot objects, then add them to a Figure instance? | <p>Looking at the <code>matplotlib</code> documentation, it seems the standard way to add an <code>AxesSubplot</code> to a <code>Figure</code> is to use <code>Figure.add_subplot</code>:</p>
<pre><code>from matplotlib import pyplot
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )
</code></pre>
<p>I would like to be able to create <code>AxesSubPlot</code>-like objects independently of the figure, so I can use them in different figures. Something like</p>
<pre><code>fig = pyplot.figure()
histoA = some_axes_subplot_maker.hist( some params ..... )
histoA = some_axes_subplot_maker.hist( some other params ..... )
# make one figure with both plots
fig.add_subaxes(histo1, 211)
fig.add_subaxes(histo1, 212)
fig2 = pyplot.figure()
# make a figure with the first plot only
fig2.add_subaxes(histo1, 111)
</code></pre>
<p>Is this possible in <code>matplotlib</code> and if so, how can I do this?</p>
<p><strong>Update:</strong> I have not managed to decouple creation of Axes and Figures, but following examples in the answers below, can easily re-use previously created axes in new or olf Figure instances. This can be illustrated with a simple function:</p>
<pre><code>def plot_axes(ax, fig=None, geometry=(1,1,1)):
if fig is None:
fig = plt.figure()
if ax.get_geometry() != geometry :
ax.change_geometry(*geometry)
ax = fig.axes.append(ax)
return fig
</code></pre> | 6,309,636 | 5 | 1 | null | 2011-06-10 16:38:43.09 UTC | 41 | 2020-12-20 18:35:38.283 UTC | 2011-06-12 08:13:14.627 UTC | null | 661,519 | null | 661,519 | null | 1 | 99 | python|matplotlib | 92,201 | <p>Typically, you just pass the axes instance to a function. </p>
<p>For example:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
def main():
x = np.linspace(0, 6 * np.pi, 100)
fig1, (ax1, ax2) = plt.subplots(nrows=2)
plot(x, np.sin(x), ax1)
plot(x, np.random.random(100), ax2)
fig2 = plt.figure()
plot(x, np.cos(x))
plt.show()
def plot(x, y, ax=None):
if ax is None:
ax = plt.gca()
line, = ax.plot(x, y, 'go')
ax.set_ylabel('Yabba dabba do!')
return line
if __name__ == '__main__':
main()
</code></pre>
<p>To respond to your question, you could always do something like this:</p>
<pre><code>def subplot(data, fig=None, index=111):
if fig is None:
fig = plt.figure()
ax = fig.add_subplot(index)
ax.plot(data)
</code></pre>
<p>Also, you can simply add an axes instance to another figure:</p>
<pre><code>import matplotlib.pyplot as plt
fig1, ax = plt.subplots()
ax.plot(range(10))
fig2 = plt.figure()
fig2.axes.append(ax)
plt.show()
</code></pre>
<p>Resizing it to match other subplot "shapes" is also possible, but it's going to quickly become more trouble than it's worth. The approach of just passing around a figure or axes instance (or list of instances) is much simpler for complex cases, in my experience...</p> |
5,978,510 | Regex to match Date | <p>I want to match dates with format mm/dd/yy or mm/dd/yyyy but it should not pick 23/09/2010 where month is 23 which is invalid nor some invalid date like 00/12/2020 or 12/00/2011.</p> | 5,978,549 | 7 | 2 | null | 2011-05-12 13:13:37.377 UTC | 9 | 2020-04-21 16:06:17.503 UTC | 2011-05-12 17:18:17.587 UTC | null | 405,017 | null | 422,543 | null | 1 | 17 | ruby|regex | 29,970 | <p>You'd better do a split on / and test all individual parts. But if you really want to use a regex you can try this one :</p>
<pre><code>#\A(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))\Z#
</code></pre>
<p>Explanation:</p>
<pre><code>\A # start of string
(?: # group without capture
# that match 31st of month 1,3,5,7,8,10,12
(?: # group without capture
(?: # group without capture
(?: # group without capture
0? # number 0 optionnal
[13578] # one digit either 1,3,5,7 or 8
) # end group
| # alternative
(1[02]) # 1 followed by 0 or 2
) # end group
/ # slash
31 # number 31
/ # slash
(19|20)? #numbers 19 or 20 optionnal
\d\d # 2 digits from 00 to 99
) # end group
|
(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)
|
(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))
|
(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d)
)
\Z
</code></pre>
<p>I've explained the first part, leaving the rest as an exercise.</p>
<p>This match one invalid date : 02/29/1900 but is correct for any other dates between 01/01/1900 and 12/31/2099</p> |
5,651,902 | Android plurals treatment of "zero" | <p>If have the following plural ressource in my strings.xml:</p>
<pre><code> <plurals name="item_shop">
<item quantity="zero">No item</item>
<item quantity="one">One item</item>
<item quantity="other">%d items</item>
</plurals>
</code></pre>
<p>I'm showing the result to the user using:</p>
<pre><code>textView.setText(getQuantityString(R.plurals.item_shop, quantity, quantity));
</code></pre>
<p>It's working well with 1 and above, but if quantity is 0 then I see "0 items".
Is "zero" value supported only in Arabic language as the documentation seems to indicate?
Or am I missing something?</p> | 5,671,704 | 7 | 4 | null | 2011-04-13 15:39:59.517 UTC | 28 | 2021-02-23 18:45:38.063 UTC | null | null | null | null | 565,798 | null | 1 | 102 | android | 24,442 | <p>The Android resource method of internationalisation is quite limited. I have had much better success using the standard <code>java.text.MessageFormat</code>.</p>
<p>Basically, all you have to do is use the standard string resource like this:</p>
<pre><code><resources>
<string name="item_shop">{0,choice,0#No items|1#One item|1&lt;{0} items}</string>
</resources>
</code></pre>
<p>Then, from the code all you have to do is the following:</p>
<pre><code>String fmt = getResources().getText(R.string.item_shop).toString();
textView.setText(MessageFormat.format(fmt, amount));
</code></pre>
<p>You can read more about the format strings in the <a href="http://download.oracle.com/javase/6/docs/api/java/text/MessageFormat.html" rel="noreferrer">javadocs for MessageFormat</a></p> |
39,019,094 | ReactJS - get json object data from an URL | <p>How do I get data from an URL into ReactJS.</p>
<p>The url is of the following type:
<a href="http://www.domain.com/api/json/x/a/search.php?s=category" rel="noreferrer">http://www.domain.com/api/json/x/a/search.php?s=category</a></p>
<p>which, if typed in a browser, will display a json object.</p>
<p>How do I load it to ReactJS.</p>
<p>To start with, I started by:</p>
<pre><code>const dUrl = "http://www.the....";
console.log(dUrl);
</code></pre>
<p>but obviously it displays the url not the content (which, I will be able to filter - it's just this initial step of loading it into an object that I don't know)</p>
<p>Edit: I'd rather not use jQuery.</p> | 39,019,646 | 5 | 1 | null | 2016-08-18 13:07:47.843 UTC | 2 | 2019-03-22 06:56:12.397 UTC | 2016-08-18 13:41:16.107 UTC | null | 1,945,363 | null | 1,945,363 | null | 1 | 16 | json|reactjs | 69,349 | <p>Edit: Use fetch for making API calls.</p>
<pre><code>fetch(http://www.example.com/api/json/x/a/search.php?s=category)
.then(response => response.json())
.then((jsonData) => {
// jsonData is parsed json object received from url
console.log(jsonData)
})
.catch((error) => {
// handle your errors here
console.error(error)
})
</code></pre>
<p>Fetch is available in all modern browsers.</p> |
44,077,630 | Ansible to check diskspace for mounts mentioned as variable | <p>I am new to ansible and currently working on a play which will see if disk space of remote machines has reached 70% threshold. If they have reached it should throw error. </p>
<p>i found a good example at : <a href="https://stackoverflow.com/questions/26981907/using-ansible-to-manage-disk-space">Using ansible to manage disk space</a></p>
<p>but at this example the mount names are hard coded. And my requirement is to pass them dynamically. So i wrote below code which seems to not work:</p>
<pre><code> name: test for available disk space
assert:
that:
- not {{ item.mount == '{{mountname}}' and ( item.size_available <
item.size_total - ( item.size_total|float * 0.7 ) ) }}
with_items: '{{ansible_mounts}}'
ignore_errors: yes
register: disk_free
name: Fail the play
fail: msg="disk space has reached 70% threshold"
when: disk_free|failed
</code></pre>
<p>This play works when i use:</p>
<pre><code>item.mount == '/var/app'
</code></pre>
<p>Is there any way to enter mountname dynamically ? and can i enter multiple mount names ??</p>
<p>I am using ansible 2.3 on rhel</p>
<p>Thanks in advance :)</p> | 44,078,311 | 3 | 0 | null | 2017-05-19 19:24:20.933 UTC | 4 | 2018-12-07 11:31:38.217 UTC | 2017-05-23 12:10:43.367 UTC | null | -1 | null | 5,374,696 | null | 1 | 7 | ansible | 39,827 | <p>Try this:</p>
<pre><code>name: Ensure that free space on {{ mountname }} is grater than 30%
assert:
that: mount.size_available > mount.size_total|float * 0.3
msg: disk space has reached 70% threshold
vars:
mount: "{{ ansible_mounts | selectattr('mount','equalto',mountname) | list | first }}"
</code></pre>
<ol>
<li><p><code>that</code> is a raw Jinja2 expression, don't use curly brackets in it.</p></li>
<li><p>why do you use separate <code>fail</code> task, if <code>assert</code> can fail with a message?</p></li>
</ol> |
24,912,173 | Django 1.7 - makemigrations not detecting changes | <p>As the title says, I can't seem to get migrations working.</p>
<p>The app was originally under 1.6, so I understand that migrations won't be there initially, and indeed if I run <code>python manage.py migrate</code> I get:</p>
<pre><code>Operations to perform:
Synchronize unmigrated apps: myapp
Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
No migrations to apply.
</code></pre>
<p>If I make a change to any models in <code>myapp</code>, it still says unmigrated, as expected.</p>
<p>But if I run <code>python manage.py makemigrations myapp</code> I get:</p>
<pre><code>No changes detected in app 'myapp'
</code></pre>
<p>Doesn't seem to matter what or how I run the command, it's never detecting the app as having changes, nor is it adding any migration files to the app.</p>
<p>Is there any way to force an app onto migrations and essentially say "This is my base to work with" or anything? Or am I missing something?</p>
<p>My database is a PostgreSQL one if that helps at all.</p> | 24,929,525 | 33 | 1 | null | 2014-07-23 13:44:54.297 UTC | 27 | 2022-09-13 07:11:32.98 UTC | 2014-07-28 11:36:30.34 UTC | null | 1,433,392 | null | 572,845 | null | 1 | 149 | python|django|django-1.7|django-migrations | 133,615 | <p>Ok, looks like I missed an obvious step, but posting this in case anyone else does the same.</p>
<p>When upgrading to 1.7, my models became unmanaged (<code>managed = False</code>) - I had them as <code>True</code> before but seems it got reverted.</p>
<p>Removing that line (To default to True) and then running <code>makemigrations</code> immediately made a migration module and now it's working. <code>makemigrations</code> will not work on unmanaged tables (Which is obvious in hindsight)</p> |
44,523,828 | Initialization from incompatible pointer type warning when assigning to a pointer | <p>GCC gives me an 'Initialization from incompatible pointer type' warning when I use this code (though the code works fine and does what it's supposed to do, which is print all the elements of the array).</p>
<pre><code>#include <stdio.h>
int main(void)
{
int arr[5] = {3, 0, 3, 4, 1};
int *p = &arr;
printf("%p\n%p\n\n", p);
for (int a = 0; a < 5; a++)
printf("%d ", *(p++));
printf("\n");
}
</code></pre>
<p>However no warning is given when I use this bit of code</p>
<pre><code>int main(void)
{
int arr[5] = {3, 0, 3, 4, 1};
int *q = arr;
printf("%p\n%p\n\n", q);
for (int a = 0; a < 5; a++)
printf("%d ", *(q++));
printf("\n");
}
</code></pre>
<p>The only difference between these two snippets is that I assign *p = &arr and *q = arr .</p>
<ul>
<li>Exactly what different is the & making ?</li>
<li>And why does the code execute and give the exact same output in both the cases ?</li>
</ul> | 44,524,152 | 5 | 2 | null | 2017-06-13 14:02:43.057 UTC | 2 | 2017-06-13 14:26:41.333 UTC | 2017-06-13 14:13:46.85 UTC | null | 7,609,016 | null | 7,609,016 | null | 1 | 17 | c|arrays|pointers | 48,364 | <ul>
<li><code>&arr</code> gives an <em>array pointer</em>, a special pointer type <code>int(*)[5]</code> which points at the array as whole.</li>
<li><code>arr</code>, when written in an expression such a <code>int *q = arr;</code>, "decays" into a pointer to the first element. Completely equivalent to <code>int *q = &arr[0];</code></li>
</ul>
<p>In the first case you try to assign a <code>int(*)[5]</code> to a <code>int*</code>. These are incompatible pointer types, hence the compiler diagnostic message.</p>
<p>As it turns out, the array pointer and the int pointer to the first element will very likely have the same representation and the same address internally. This is why the first example "works" even though it is not correct C.</p> |
21,585,326 | Implementing SearchView in action bar | <p>I need to create <code>SearchView</code> from my <code>arrayList<String></code> and show the suggestions in the drop-down list same this </p>
<p><a href="https://i.stack.imgur.com/y9ofu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y9oful.jpg" alt="enter image description here"></a></p>
<p>I look for tutorials that explain step by step how to build a <code>SearchView</code> in a action bar.</p>
<p>I have read <a href="http://developer.android.com/guide/topics/search/search-dialog.html" rel="noreferrer">the documentation</a> and following the example google but it was not useful to me.</p>
<p>I have created the search </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>`
</code></pre>
<p>But I do not know how to set the parameters of the array of strings.
I tried to retrieve the result in a different Activity but not work.</p> | 22,302,422 | 4 | 1 | null | 2014-02-05 18:21:37.94 UTC | 68 | 2019-10-23 10:53:43.2 UTC | 2016-05-26 17:35:30.79 UTC | null | 1,718,174 | null | 2,672,575 | null | 1 | 83 | android|android-actionbar|autocompletetextview|searchview | 195,508 | <p>It took a while to put together a solution for this, but have found this is the easiest way to get it to work in the way that you describe. There could be better ways to do this, but since you haven't posted your activity code I will have to improvise and assume you have a list like this at the start of your activity:</p>
<pre><code>private List<String> items = db.getItems();
</code></pre>
<p><em>ExampleActivity.java</em></p>
<pre><code>private List<String> items;
private Menu menu;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.example, menu);
this.menu = menu;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String query) {
loadHistory(query);
return true;
}
});
}
return true;
}
// History
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void loadHistory(String query) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Cursor
String[] columns = new String[] { "_id", "text" };
Object[] temp = new Object[] { 0, "default" };
MatrixCursor cursor = new MatrixCursor(columns);
for(int i = 0; i < items.size(); i++) {
temp[0] = i;
temp[1] = items.get(i);
cursor.addRow(temp);
}
// SearchView
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items));
}
}
</code></pre>
<p>Now you need to create an adapter extended from <code>CursorAdapter</code>:</p>
<p><em>ExampleAdapter.java</em></p>
<pre><code>public class ExampleAdapter extends CursorAdapter {
private List<String> items;
private TextView text;
public ExampleAdapter(Context context, Cursor cursor, List<String> items) {
super(context, cursor, false);
this.items = items;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
text.setText(items.get(cursor.getPosition()));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item, parent, false);
text = (TextView) view.findViewById(R.id.text);
return view;
}
}
</code></pre>
<p>A better way to do this is if your list data is from a database, you can pass the <code>Cursor</code> returned by database functions directly to <code>ExampleAdapter</code> and use the relevant column selector to display the column text in the <code>TextView</code> referenced in the adapter.</p>
<p>Please note: when you import <code>CursorAdapter</code> don't import the Android support version, import the standard <code>android.widget.CursorAdapter</code> instead.</p>
<p>The adapter will also require a custom layout:</p>
<p><em>res/layout/item.xml</em></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</code></pre>
<p>You can now customize list items by adding additional text or image views to the layout and populating them with data in the adapter.</p>
<p>This should be all, but if you haven't done this already you need a SearchView menu item:</p>
<p><em>res/menu/example.xml</em></p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/search"
android:title="@string/search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
</code></pre>
<p>Then create a searchable configuration:</p>
<p><em>res/xml/searchable.xml</em></p>
<pre><code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/search"
android:hint="@string/search" >
</searchable>
</code></pre>
<p>Finally add this inside the relevant activity tag in the manifest file:</p>
<p><em>AndroidManifest.xml</em></p>
<pre><code><intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value="com.example.ExampleActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</code></pre>
<p>Please note: The <code>@string/search</code> string used in the examples should be defined in <em>values/strings.xml</em>, also don't forget to update the reference to <code>com.example</code> for your project.</p> |
21,851,985 | Difference between np.int, np.int_, int, and np.int_t in cython? | <p>I am a bit struggled with so many <code>int</code> data types in cython.</p>
<p><code>np.int, np.int_, np.int_t, int</code></p>
<p>I guess <code>int</code> in pure python is equivalent to <code>np.int_</code>, then where does <code>np.int</code> come from? I cannot find the document from numpy? Also, why does <code>np.int_</code> exist given we do already have <code>int</code>?</p>
<p>In cython, I guess <code>int</code> becomes a C type when used as <code>cdef int</code> or <code>ndarray[int]</code>, and when used as <code>int()</code> it stays as the python caster?</p>
<p>Is <code>np.int_</code> equivalent to <code>long</code> in C? so <code>cdef long</code> is the identical to <code>cdef np.int_</code>?</p>
<p>Under what circumstances should I use <code>np.int_t</code> instead of <code>np.int</code>? e.g. <code>cdef np.int_t</code>, <code>ndarray[np.int_t]</code> ...</p>
<p>Can someone briefly explain how the wrong use of those types would affect the performance of compiled cython code?</p> | 46,416,257 | 3 | 1 | null | 2014-02-18 11:11:50.903 UTC | 29 | 2022-06-02 05:45:48.767 UTC | 2014-02-18 13:17:37.747 UTC | null | 691,867 | null | 691,867 | null | 1 | 55 | python|c|numpy|cython | 45,001 | <p>It's a bit complicated because the names have different meanings depending on the context.</p>
<h1><code>int</code></h1>
<ol>
<li><p>In Python</p>
<p>The <code>int</code> is normally just a Python type, it's of arbitrary precision, meaning that you can store any conceivable integer inside it (as long as you have enough memory).</p>
<pre><code>>>> int(10**50)
100000000000000000000000000000000000000000000000000
</code></pre></li>
<li><p>However, when you use it as <code>dtype</code> for a NumPy array it will be interpreted as <code>np.int_</code> <sup>1</sup>. Which is <strong>not</strong> of arbitrary precision, it will have the same size as C's <code>long</code>:</p>
<pre><code>>>> np.array(10**50, dtype=int)
OverflowError: Python int too large to convert to C long
</code></pre>
<p>That also means the following two are equivalent:</p>
<pre><code>np.array([1,2,3], dtype=int)
np.array([1,2,3], dtype=np.int_)
</code></pre></li>
<li><p>As Cython type identifier it has another meaning, here it stands for the <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> type <code>int</code>. It's of limited precision (typically 32bits). You can use it as Cython type, for example when defining variables with <code>cdef</code>:</p>
<pre><code>cdef int value = 100 # variable
cdef int[:] arr = ... # memoryview
</code></pre>
<p>As return value or argument value for <code>cdef</code> or <code>cpdef</code> functions:</p>
<pre><code>cdef int my_function(int argument1, int argument2):
# ...
</code></pre>
<p>As "generic" for <code>ndarray</code>:</p>
<pre><code>cimport numpy as cnp
cdef cnp.ndarray[int, ndim=1] val = ...
</code></pre>
<p>For type casting:</p>
<pre><code>avalue = <int>(another_value)
</code></pre>
<p>And probably many more.</p></li>
<li><p>In Cython but as Python type. You can still call <code>int</code> and you'll get a "Python int" (of arbitrary precision), or use it for <code>isinstance</code> or as <code>dtype</code> argument for <code>np.array</code>. Here the context is important, so converting to a Python <code>int</code> is different from converting to a C int:</p>
<pre><code>cdef object val = int(10) # Python int
cdef int val = <int>(10) # C int
</code></pre></li>
</ol>
<h1><code>np.int</code></h1>
<p>Actually this is very easy. It's just an alias for <code>int</code>:</p>
<pre><code>>>> int is np.int
True
</code></pre>
<p>So everything from above applies to <code>np.int</code> as well. However you can't use it as a type-identifier except when you use it on the <code>cimport</code>ed package. In that case it represents the Python integer type.</p>
<pre><code>cimport numpy as cnp
cpdef func(cnp.int obj):
return obj
</code></pre>
<p>This will expect <code>obj</code> to be a Python integer <strong>not a NumPy type</strong>:</p>
<pre><code>>>> func(np.int_(10))
TypeError: Argument 'obj' has incorrect type (expected int, got numpy.int32)
>>> func(10)
10
</code></pre>
<p>My advise regarding <code>np.int</code>: Avoid it whenever possible. In Python code it's equivalent to <code>int</code> and in Cython code it's also equivalent to Pythons <code>int</code> but if used as type-identifier it will probably confuse you and everyone who reads the code! It certainly confused me...</p>
<h1><code>np.int_</code></h1>
<p>Actually it only has one meaning: It's a <strong>Python type</strong> that represents a scalar NumPy type. You use it like Pythons <code>int</code>:</p>
<pre><code>>>> np.int_(10) # looks like a normal Python integer
10
>>> type(np.int_(10)) # but isn't (output may vary depending on your system!)
numpy.int32
</code></pre>
<p>Or you use it to specify the <code>dtype</code>, for example with <code>np.array</code>:</p>
<pre><code>>>> np.array([1,2,3], dtype=np.int_)
array([1, 2, 3])
</code></pre>
<p>But you cannot use it as type-identifier in Cython.</p>
<h1><code>cnp.int_t</code></h1>
<p>It's the type-identifier version for <code>np.int_</code>. That means you can't use it as dtype argument. But you can use it as type for <code>cdef</code> declarations:</p>
<pre><code>cimport numpy as cnp
import numpy as np
cdef cnp.int_t[:] arr = np.array([1,2,3], dtype=np.int_)
|---TYPE---| |---DTYPE---|
</code></pre>
<p>This example (hopefully) shows that the type-identifier with the trailing <code>_t</code> actually represents the type of an array using the <strong>dtype</strong> without the trailing <code>t</code>. You can't interchange them in Cython code!</p>
<h1>Notes</h1>
<p>There are several more numeric types in NumPy I'll include a list containing the NumPy dtype and Cython type-identifier and the C type identifier that could also be used in Cython here. But it's basically taken from <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types" rel="noreferrer">the NumPy documentation</a> and the <a href="https://github.com/cython/cython/blob/master/Cython/Includes/numpy/__init__.pxd" rel="noreferrer">Cython NumPy <code>pxd</code> file</a>:</p>
<pre><code>NumPy dtype Numpy Cython type C Cython type identifier
np.bool_ None None
np.int_ cnp.int_t long
np.intc None int
np.intp cnp.intp_t ssize_t
np.int8 cnp.int8_t signed char
np.int16 cnp.int16_t signed short
np.int32 cnp.int32_t signed int
np.int64 cnp.int64_t signed long long
np.uint8 cnp.uint8_t unsigned char
np.uint16 cnp.uint16_t unsigned short
np.uint32 cnp.uint32_t unsigned int
np.uint64 cnp.uint64_t unsigned long
np.float_ cnp.float64_t double
np.float32 cnp.float32_t float
np.float64 cnp.float64_t double
np.complex_ cnp.complex128_t double complex
np.complex64 cnp.complex64_t float complex
np.complex128 cnp.complex128_t double complex
</code></pre>
<p>Actually there are Cython types for <code>np.bool_</code>: <code>cnp.npy_bool</code> and <code>bint</code> but both they can't be used for NumPy arrays currently. For scalars <code>cnp.npy_bool</code> will just be an unsigned integer while <code>bint</code> will be a boolean. Not sure what's going on there...</p>
<hr>
<p><sup>1</sup> Taken From the <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.dtypes.html#specifying-and-constructing-data-types" rel="noreferrer">NumPy documentation "Data type objects"</a></p>
<blockquote>
<h2>Built-in Python types</h2>
<p>Several python types are equivalent to a corresponding array scalar when used to generate a dtype object:</p>
<pre><code>int np.int_
bool np.bool_
float np.float_
complex np.cfloat
bytes np.bytes_
str np.bytes_ (Python2) or np.unicode_ (Python3)
unicode np.unicode_
buffer np.void
(all others) np.object_
</code></pre>
</blockquote> |
9,041,976 | Recovering mysql database from data folder backup | <p>I have uninstalled the old XAMPP and deleted all of the content of <code>d:\xampp folder</code> and installed the new one. When I copy my backup folder (with the name of my database, containing all <code>.frm</code> and <code>.opt</code> files) to the <code>D:\xampp\mysql\data</code>, the database shows in the list in phpmyadmin but it has no tables and data. What I've done wrong?</p> | 9,047,289 | 13 | 0 | null | 2012-01-28 00:46:21.5 UTC | 12 | 2022-06-25 19:14:17.263 UTC | 2017-02-23 13:36:31.26 UTC | null | 5,866,279 | null | 603,200 | null | 1 | 21 | mysql|phpmyadmin | 79,119 | <p>I've searched a lot. There's a few other files that are needed for recovery. I think it's impossible to recover tables from the .frm files alone. I've re-created my database.</p> |
9,149,919 | No mapping exists from object type System.Collections.Generic.List when executing stored proc with parameters in EF 4.3 | <p>Lately I've been working on stored procedure and encountered 1 strange problem. </p>
<p>First, I was able to successfully call a stored procedure from the database via:</p>
<blockquote>
<p>IList<XXXViewModel> XXXList =
_context.Database.SqlQuery("spXXX").ToList();</p>
</blockquote>
<p>But when I needed to pass parameters it failed:</p>
<pre><code>var parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("param1", param1Value));
parameters.Add(new SqlParameter("param2", param2Value));
IList<XXXViewModel> XXXList =
_context.Database.SqlQuery<XXXViewModel>("spXXX @param1, @param2", parameters).ToList();
</code></pre>
<p>And I got the ff, error:</p>
<blockquote>
<p>No mapping exists from object type
System.Collections.Generic.List`1[[System.Data.SqlClient.SqlParameter,
System.Data, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]] to a known managed provider native
type.</p>
</blockquote>
<p>Note that I've also tried:</p>
<pre><code>_context.Database.ExecuteSqlCommand<EXEC XXXViewModel>("spXXX @param1, @param2", parameters).ToList();
</code></pre>
<p>But got the same result :-(.</p>
<p>Also I've tried calling, by specifying each of the parameters:</p>
<pre><code>IList<XXXResult> query = Context.Database.SqlQuery<XXXResult>("SP @paramA, @paramB, @paramC", new SqlParameter("paramA", "A"), new SqlParameter("paramB", "B"), new SqlParameter("paramC", "C")).ToList();
</code></pre>
<p>Anyone has any idea?</p> | 9,149,978 | 9 | 0 | null | 2012-02-05 14:14:36.347 UTC | 4 | 2022-03-16 05:55:17.53 UTC | 2012-02-05 15:24:50.663 UTC | null | 689,416 | null | 689,416 | null | 1 | 43 | entity-framework|entity-framework-4.1|ef-code-first | 48,671 | <p>You need to pass each parameter to the method (ie You can't pass a list)</p>
<pre><code>IList<XXXViewModel> XXXList =
_context.Database.SqlQuery<XXXViewModel>("spXXX @param1, @param2",
new SqlParameter("param1", param1Value),
new SqlParameter("param2", param2Value)).ToList();
</code></pre> |
10,336,899 | What is a Question Mark "?" and Colon ":" Operator Used for? | <p>Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.</p>
<pre><code>int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
</code></pre> | 10,336,927 | 7 | 1 | null | 2012-04-26 15:48:05.573 UTC | 65 | 2017-04-18 20:44:46.653 UTC | 2015-07-23 10:13:01.063 UTC | null | 1,816,580 | null | 1,214,163 | null | 1 | 145 | java|operators|ternary-operator|conditional-operator | 395,788 | <p>This is the <a href="https://en.wikipedia.org/wiki/%3F:" rel="noreferrer">ternary conditional operator</a>, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but <a href="https://stackoverflow.com/questions/2997028/other-ternary-operators-besides-ternary-conditional">it's not the only ternary operator</a>, just the most common one.</p>
<p>Here's a good example from Wikipedia demonstrating how it works:</p>
<blockquote>
<p>A traditional if-else construct in C, Java and JavaScript is written:</p>
<pre><code>if (a > b) {
result = x;
} else {
result = y;
}
</code></pre>
<p>This can be rewritten as the following statement:</p>
<pre><code>result = a > b ? x : y;
</code></pre>
</blockquote>
<p>Basically it takes the form:</p>
<pre><code>boolean statement ? true result : false result;
</code></pre>
<p>So if the boolean statement is true, you get the first part, and if it's false you get the second one.</p>
<p>Try these if that still doesn't make sense:</p>
<pre><code>System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
</code></pre> |
23,094,584 | Multiple Controller Types with same Route prefix ASP.NET Web Api | <p>Is it possible to separate GETs and POSTs into separate API Controller types and accessing them using the same Route Prefix?</p>
<p>Here are my controllers:</p>
<pre><code>[RoutePrefix("api/Books")]
public class BooksWriteController : EventStoreApiController
{
[Route("")]
public void Post([FromBody] CommandWrapper commandWrapper){...}
}
[RoutePrefix("api/Books")]
public class BooksReadController : MongoDbApiController
{
[Route("")]
public Book[] Get() {...}
[Route("{id:int}")]
public Book Get(int id) {...}
}
</code></pre> | 23,097,445 | 3 | 1 | null | 2014-04-15 21:09:29.423 UTC | 10 | 2020-12-03 18:41:24.377 UTC | 2020-12-03 18:41:24.377 UTC | null | 185,123 | null | 1,145,404 | null | 1 | 25 | c#|asp.net-web-api|asp.net-web-api-routing|attributerouting | 25,258 | <p>Web API (1.x-2.x) does not support multiple attribute routes with the same path on different controllers. The result is a 404, because all the route matches more than one controller and at that point Web API will consider the result ambiguous.</p>
<p>Note that <a href="https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc/" rel="noreferrer">MVC Core</a> does support this scenario note: MVC Core serves as both MVC & Web API.</p>
<p>If you choose to use Web API 2.11 (or newer) you can create a route constraint for the http method per controller and use it instead of the built in Route Attribute. The sample below shows that you can use RoutePrefix or directly Routes (like kmacdonald's answer).</p>
<pre><code>using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Routing;
public class BooksWriteController : ApiController
{
[PostRoute("api/Books")]
public void Post() { }
}
[RoutePrefix("api/books")]
public class BooksReadController : ApiController
{
[GetRoute]
public void Get() { }
[GetRoute("{id:int}")]
public void Get(int id) { }
}
</code></pre>
<p>These two classes simplify the use of the constraint route attribute</p>
<pre><code>class GetRouteAttribute : MethodConstraintedRouteAttribute
{
public GetRouteAttribute(string template) : base(template ?? "", HttpMethod.Get) { }
}
class PostRouteAttribute : MethodConstraintedRouteAttribute
{
public PostRouteAttribute(string template) : base(template ?? "", HttpMethod.Post) { }
}
</code></pre>
<p>This class allows adding constraints to the route generated</p>
<pre><code>class MethodConstraintedRouteAttribute : RouteFactoryAttribute
{
public MethodConstraintedRouteAttribute(string template, HttpMethod method)
: base(template)
{
Method = method;
}
public HttpMethod Method
{
get;
private set;
}
public override IDictionary<string, object> Constraints
{
get
{
var constraints = new HttpRouteValueDictionary();
constraints.Add("method", new MethodConstraint(Method));
return constraints;
}
}
}
</code></pre>
<p>This is just a standard route constraint, nit: you may want to cache the constraints object to reduce allocations.</p>
<pre><code>class MethodConstraint : IHttpRouteConstraint
{
public HttpMethod Method { get; private set; }
public MethodConstraint(HttpMethod method)
{
Method = method;
}
public bool Match(HttpRequestMessage request,
IHttpRoute route,
string parameterName,
IDictionary<string, object> values,
HttpRouteDirection routeDirection)
{
return request.Method == Method;
}
}
</code></pre> |
23,365,307 | java: TreeSet order | <p>With this code I get this output:</p>
<pre><code> TreeSet<String> t=new TreeSet<String>();
t.add("test 15");
t.add("dfd 2");
t.add("ersfd 20");
t.add("asdt 10");
Iterator<String> it=t.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
</code></pre>
<p>I get: </p>
<pre><code> asdt 10
dfd 2
ersfd 20
test 15
</code></pre>
<p>How can I get an order of this kind, based on the numbers, with TreeSet?</p>
<pre><code> dfd 2
asdt 10
test 15
ersfd 20
</code></pre> | 23,365,540 | 7 | 2 | null | 2014-04-29 12:56:23.203 UTC | 2 | 2019-11-14 02:03:37.847 UTC | null | null | null | null | 3,529,121 | null | 1 | 10 | java|treeset | 45,595 | <p>The TreeSet implementation is sorting by the lexicographic order of the string values you insert. If you want to sort by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator.</p>
<pre><code>Set<String> set = new TreeSet<String>(new Comparator<String>() {
public int compare(String one, String other) {
// implement
}
});
</code></pre>
<p>or</p>
<pre><code>public class MyClass implements Comparable {
private String key;
private int value;
public int compareTo(MyClass other) {
// implement
}
public boolean equals(MyClass other) {
// implement
}
// snip ...
}
Set<MyClass> set = new TreeSet<MyClass>();
</code></pre> |
31,728,837 | RecyclerView Grow Element From Right to Left | <p>i use RecyclerView in horizontal direction and New element is left to right. and scrolling is ltr. how to change this direction?</p>
<p><a href="https://i.stack.imgur.com/tPztM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tPztM.png" alt="enter image description here"></a></p>
<p>Xml Code:</p>
<pre><code> <android.support.v7.widget.RecyclerView
android:id="@+id/rc3"
android:layout_gravity="right"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</code></pre>
<p>And Java:</p>
<pre><code> RecyclerView rc1 = (RecyclerView) findViewById(R.id.rc1);
AdapterMainPrice mainPrice = new AdapterMainPrice(StructPrice.getThreePrice());
rc1.setHasFixedSize(false);
LinearLayoutManager llm = new LinearLayoutManager(G.context);
llm.setOrientation(LinearLayoutManager.HORIZONTAL);
rc1.setLayoutManager(llm);
rc1.setAdapter(mainPrice);
</code></pre>
<p>Adapter:</p>
<p>public class AdapterMainPrice extends RecyclerView.Adapter {</p>
<pre><code>private List<StructPrice> prices;
public AdapterMainPrice(List<StructPrice> catList) {
this.prices = catList;
}
@Override
public int getItemCount() {
return prices.size();
}
@Override
public void onBindViewHolder(NewsViewHolder ghazaViewHolder, int position) {
StructPrice price = prices.get(position);
ghazaViewHolder.vTitle.setText(price.getProductName());
Glide.with(G.context)
.load(price.getProductPic())
.placeholder(R.drawable.loading_spinner)
.crossFade()
.into(ghazaViewHolder.Vimg);
ghazaViewHolder.cardView.startAnimation(ghazaViewHolder.animation);
}
@Override
public NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.adapter_item_main, viewGroup, false);
return new NewsViewHolder(itemView);
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected ImageView Vimg;
protected Animation animation;
protected CardView cardView;
public NewsViewHolder(View v) {
super(v);
vTitle = (TextView) v.findViewById(R.id.mainRCtv);
Vimg = (ImageView) v.findViewById(R.id.mainRCimg);
animation = AnimationUtils.loadAnimation(G.context, R.anim.fadein);
cardView = (CardView) v.findViewById(R.id.mainRCCard);
}
}
</code></pre> | 33,389,274 | 9 | 1 | null | 2015-07-30 16:06:42.44 UTC | 5 | 2021-08-17 08:15:24.5 UTC | null | null | null | null | 2,383,176 | null | 1 | 30 | android|android-recyclerview|right-to-left | 28,732 | <p>it is pretty simple, just call setReverseLayout(true) for your LayoutManager :</p>
<pre><code>LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true);
layoutManager.setReverseLayout(true);
</code></pre>
<p>it is explained in its documentation :</p>
<pre><code> /**
* Used to reverse item traversal and layout order.
* This behaves similar to the layout change for RTL views. When set to true, first item is
* laid out at the end of the UI, second item is laid out before it etc.
*
* For horizontal layouts, it depends on the layout direction.
* When set to true, If {@link android.support.v7.widget.RecyclerView} is LTR, than it will
* layout from RTL, if {@link android.support.v7.widget.RecyclerView}} is RTL, it will layout
* from LTR.
*
* If you are looking for the exact same behavior of
* {@link android.widget.AbsListView#setStackFromBottom(boolean)}, use
* {@link #setStackFromEnd(boolean)}
*/
public void setReverseLayout(boolean reverseLayout) {
assertNotInLayoutOrScroll(null);
if (reverseLayout == mReverseLayout) {
return;
}
mReverseLayout = reverseLayout;
requestLayout();
}
</code></pre> |
13,582,000 | select all the employee in all departments which are having highest salary in that department | <p>In one of the interviews one person asked me below question</p>
<p>"Write a query to find out all employee in all departments which are having highest salary in that department with department name,employee name and his salary"</p>
<p>It means that there are 100 records in employee table and 10 records in department table.
So it needs to give me 10 records from query plus if there is no employee in any department it still needs to show that department name.</p>
<p>Thanks</p> | 13,582,474 | 6 | 1 | null | 2012-11-27 10:18:44.443 UTC | 2 | 2017-03-03 01:10:31.95 UTC | null | null | null | null | 1,817,490 | null | 1 | 1 | mysql | 63,991 | <p>This query gives you a list of departments, with that department's highest paid salary, if exists, or null otherwise. In this case, selecting the employee names do not give you the right name and just return the first employee in the linked department! </p>
<pre><code>SELECT
d.name,
MAX(e.salary)
FROM
department d
LEFT OUTER JOIN employee e ON (e.department_id = d.id)
GROUP BY d.id
</code></pre>
<p>See on <a href="http://sqlfiddle.com/#!9/c18e7/51" rel="nofollow noreferrer">SQL Fiddle</a></p>
<p>If you wish a list of departments with the highest salary and employee name:</p>
<pre><code>SELECT
d.name,
e.name, e.salary
FROM
department d
LEFT OUTER JOIN employee e ON (e.department_id = d.id)
WHERE e.salary IN (
SELECT MAX(em.salary) FROM employee em
WHERE em.department_id = d.id
);
</code></pre>
<p>See on <a href="http://sqlfiddle.com/#!9/c18e7/15" rel="nofollow noreferrer">SQL Fiddle</a></p> |
13,607,854 | ORACLE 11G UTL_FILE + UTL_FILE_DIR - Invalid Directory | <p>Hi I am running Oracle 11 and I am trying to write to a directory on the server box using UTL_FILE.FOPEN.</p>
<p>To test this I am using the following script (output included):</p>
<pre><code>SQL> @D:\test.sql
declare
l_file_handle UTL_FILE.FILE_TYPE;
begin
l_file_handle := UTL_FILE.FOPEN('/appl/mydir',
'/appl/mydir/filename',
'W');
UTL_FILE.FCLOSE(l_file_handle);
DBMS_OUTPUT.PUT_LINE('FINISHED');
end;
ORA-29280: invalid directory path
ORA-06512: at "SYS.UTL_FILE", line 41
ORA-06512: at "SYS.UTL_FILE", line 478
ORA-06512: at line 7
SQL>
</code></pre>
<p>I have the /appl/mydir added to the UTL_FILE parameter:</p>
<pre><code>SELECT value
FROM V$PARAMETER
WHERE NAME = 'utl_file_dir';
/appl/mydir, /appl/mydir2, /appl/mydir3
</code></pre>
<p>The UNIX directory is writable by all on UNIX:</p>
<pre><code>$ ls -l /appl/mydir
total 0
drwxrwsrwx 2 user userc 363968 Nov 27 13:46 mydir
</code></pre>
<p>Using oracle Directory object is not an option and I am aware of the disadvantages of using the UTL_FILE_DIR implementation.</p>
<p>Any ideas why the above script is failing?</p> | 13,609,023 | 4 | 5 | null | 2012-11-28 14:50:14.503 UTC | 2 | 2016-08-12 13:24:17.233 UTC | null | null | null | null | 1,048,478 | null | 1 | 2 | oracle|oracle11g|utl-file | 83,319 | <p>first, in 11g the preferred way is to create a directory and not use utl_file. </p>
<p>secondly, please verify what exact command you used to set the directoty list :</p>
<pre><code>SELECT value
FROM V$PARAMETER
WHERE NAME = 'utl_file_dir';
/appl/mydir, /appl/mydir2, /appl/mydir3
</code></pre>
<p>was it</p>
<pre><code>alter system set utl_file_dir='/appl/mydir, /appl/mydir2, /appl/mydir3' scope = spfile;
</code></pre>
<p>or</p>
<pre><code>alter system set utl_file_dir='/appl/mydir','/appl/mydir2','/appl/mydir3' scope = spfile;
</code></pre>
<p>if its the first way, redo it again the 2nd way as the first way is wrong (it will look the same in the v$table output, but its wrong).</p>
<p>eg:</p>
<pre><code>declare
2
l_file_handle UTL_FILE.FILE_TYPE;
4
begin
l_file_handle := UTL_FILE.FOPEN('/tmp/foo/a',
'/tmp/foo/a/filename.txt',
'w');
9
UTL_FILE.FCLOSE(l_file_handle);
11
DBMS_OUTPUT.PUT_LINE('FINISHED');
13
end;
15 /
declare
*
ERROR at line 1:
ORA-29280: invalid directory path
ORA-06512: at "SYS.UTL_FILE", line 41
ORA-06512: at "SYS.UTL_FILE", line 478
ORA-06512: at line 6
SQL> show parameter utl_fil
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
utl_file_dir string /tmp/foo, /tmp/foo/a
</code></pre>
<p>humm. now lets fix that data.</p>
<pre><code>SQL> alter system set utl_file_dir='/tmp/foo','/tmp/foo/a' scope = spfile;
System altered.
SQL> shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup open
ORACLE instance started.
Total System Global Area 263049216 bytes
Fixed Size 2225584 bytes
Variable Size 176163408 bytes
Database Buffers 79691776 bytes
Redo Buffers 4968448 bytes
Database mounted.
Database opened.
declare
2
l_file_handle UTL_FILE.FILE_TYPE;
4
begin
l_file_handle := UTL_FILE.FOPEN('/tmp/foo/a',
'/tmp/foo/a/filename.txt',
'w');
9
UTL_FILE.FCLOSE(l_file_handle);
11
DBMS_OUTPUT.PUT_LINE('FINISHED');
13
end;
15 /
PL/SQL procedure successfully completed.
SQL> show parameter utl_file
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
utl_file_dir string /tmp/foo, /tmp/foo/a
SQL>
</code></pre>
<p>also verify the oracle user has r+x on /appl and rwx on /appl/mydir</p> |
19,278,776 | Find specific row data in all database tables? Without Creating A Procedure Or Table | <p>This is what I have so far to find all tables with more than 100 rows: </p>
<pre><code>SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0) AND pa.rows >100
GROUP BY sc.name,ta.name,pa.rows
ORDER BY TABLENAME
</code></pre>
<p>Is there something similar where I can go through the database to find out a specific row data for a column within a table? </p>
<p>For example:
Where c.name = GUITARS and GUTARS = 'Fender'</p>
<p>Edit:
I do not have CREATE PROCEDURE permission OR CREATE TABLE</p>
<p>Just looking for any specific data under a certain column name, doesn't matter if it returns a lot of rows. </p> | 19,279,989 | 3 | 1 | null | 2013-10-09 17:27:43.97 UTC | 1 | 2017-03-30 05:57:29.723 UTC | 2013-10-09 19:28:06.987 UTC | null | 2,657,602 | null | 2,657,602 | null | 1 | 6 | sql|sql-server|database|tsql | 40,708 | <p>Please see my answer to <a href="https://stackoverflow.com/a/12306613/880904">How do I find a value anywhere in a SQL Server Database?</a> where I provide a script to search all tables in a database.</p>
<p>A pseudo-code description of this would be be <code>select * from * where any like 'foo'</code></p>
<p>It also allows you to search specific column names using standard <code>like</code> syntax, e.g. <code>%guitar%</code> to search column names that have the word "guitar" in them.</p>
<p>It runs ad-hoc, so you do not have to create a stored procedure, but you do need access to information_schema.</p>
<p>I use this script in SQL 2000 and up almost daily in my DB development work.</p> |
17,712,359 | authenticate_or_request_with_http_token returning html instead of json | <p>I've created a rails-api application and proceeded to secure it using token authentication.</p>
<p>I've set a <code>before_filter</code> that is calling a method which uses <code>authenticate_or_request_with_http_token</code>. Everything is working fine but, when the authentication is incorrect i'm getting an html response.</p>
<p>How can I define what format the response should be?</p>
<pre><code>before_filter :restrict_access
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
check_token token
end
end
def check_token(token)
Session.exists?(access_token: token)
end
</code></pre> | 18,510,100 | 2 | 2 | null | 2013-07-18 00:04:14.857 UTC | 8 | 2020-06-04 21:22:32.42 UTC | 2016-02-13 09:23:47.343 UTC | null | 276,959 | null | 469,679 | null | 1 | 17 | ruby-on-rails|json|rails-api | 4,016 | <p>By including <code>ActionController::HttpAuthentication::Token::ControllerMethods</code> you include several methods, amongst others <code>request_http_token_authentication</code> which is simply a wrapper around <code>Token.authentication_request</code>. That <code>#authentication_request</code>-method is the culprit and sends the plain text (not HTML as your question suggests) as follows:</p>
<pre><code>def authentication_request(controller, realm)
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end
</code></pre>
<p>The trick is to override <code>request_http_token_authentication</code> in your <code>ApplicationController</code> to <em>not</em> call <code>Token.authentication_request</code> but to set the correct status and headers and then render JSON instead. Add this to your <code>ApplicationController</code>:</p>
<pre><code>protected
def request_http_token_authentication(realm = "Application")
self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
render :json => {:error => "HTTP Token: Access denied."}, :status => :unauthorized
end
</code></pre> |
3,566,462 | Google App Engine : Cursor Versus Offset | <p>Do you know which is the best approach for fetching chunks of result from a query?</p>
<h1>1.Cursor</h1>
<pre><code>q = Person.all()
last_cursor = memcache.get('person_cursor')
if last_cursor:
q.with_cursor(last_cursor)
people = q.fetch(100)
cursor = q.cursor()
memcache.set('person_cursor', cursor)
</code></pre>
<h1>2.Offset</h1>
<pre><code>q = Person.all()
offset = memcache.get('offset')
if not offset:
offset = 0
people = q.fetch(100, offset = offset)
memcache.set('offset', offset + 100)
</code></pre>
<p>Reading the <a href="http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors" rel="noreferrer">Google documentation</a>, it seems that Cursor does not add the <strong>overhead</strong> of a query offset.</p> | 3,566,878 | 1 | 1 | null | 2010-08-25 13:46:22.883 UTC | 9 | 2010-08-25 14:26:38.983 UTC | 2010-08-25 13:53:08.67 UTC | null | 130,929 | null | 130,929 | null | 1 | 20 | python|google-app-engine | 3,806 | <p>While it's hard to measure precise and reliably, I'd be astonished if the cursor didn't run rings around the offset approach at soon as a sufficiently large set of Person entities are getting returned. As <a href="http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_fetch" rel="noreferrer">the docs</a> say very clearly and explicitly,</p>
<blockquote>
<p>The datastore fetches offset + limit
results to the application. The first
offset results are not skipped by the
datastore itself.</p>
<p>The fetch() method skips the first
offset results, then returns the rest
(limit results).</p>
<p>The query has performance
characteristics that correspond
linearly with the offset amount plus
the limit.</p>
</blockquote>
<p>I'm not sure how it could be any more explicit: <strong>O(offset + limit)</strong> is the big-O performance of fetching with an offset. If overall (say over multiple scheduled tasks) you're fetching a million items, 1000 at a time, when you fetch the last 1000 (with offset 999000) the datastore does <strong>not</strong> skip the first 999000 (even though fetch does not return them), so the performance impact will be staggering.</p>
<p>No such caveat applies to using cursors: fetching resumes exactly where it left off, without having to repeatedly fetch all the (possibly many) items already fetched along that cursor in previous queries. Therefore, with performance <strong>O(limit)</strong>, elapsed time should be arbitrarily better than that you can obtain with an offset, as long as that offset gets sufficiently large.</p> |
40,801,789 | Using return value inside another function | <p>I have these two functions:</p>
<pre><code>def check_channel_number(self):
print "***************Channel Checker *********************"
print ''
user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);
channel = ("channelNr= '%d'") % (user_channel_number)
print channel
# channel_search = channel + str(user_channel_number)
datafile = file('output.txt')
found = False
for line in datafile:
if channel in line:
found = True
print 'The channel number you entered is correct and will be deleted'
return user_channel_number
print 'The channel number you entered is not on the planner'
return False
</code></pre>
<p>and</p>
<pre><code>def delete_events(self):
if user_channel_number == True:
return 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
</code></pre>
<p>When I run my script, it says that <code>user_channel_number</code> is not defined globally. How can I use <code>user_channel_number</code> inside the <code>delete_events</code> function?</p> | 40,801,904 | 3 | 1 | null | 2016-11-25 09:39:47.107 UTC | 3 | 2022-06-05 17:07:43.6 UTC | 2022-06-05 17:07:43.6 UTC | null | 523,612 | null | 4,069,939 | null | 1 | 5 | python|python-2.7 | 61,622 | <p>Functions can not share their local variables. You can return the value from the first and pass it to the second:</p>
<pre><code>def check_channel_number(self):
...
return user_channel_number
def delete_events(self):
user_channel_number = self.check_channel_number()
...
</code></pre>
<p>Or save value on the object:</p>
<pre><code>def check_channel_number(self):
...
self.user_channel_number = user_channel_number
...
def delete_events(self):
if self.user_channel_number:
....
</code></pre> |
2,034,281 | PHP form token usage and handling | <p>I'm a beginner working on a login script in PHP. This is the form token statement that I have so far:</p>
<pre><code>$_SESSION["form_token"] = md5(rand(time (), true)) ;
</code></pre>
<p>The statement is issued just after the user indicates that he/she wants to login.</p>
<p>My limited understanding is that the tokens purpose is to identify a unique user at a unique point in time and to disguise the form token information. </p>
<p>Then everything becomes fuzzy. Here are my 3 open questions:</p>
<ol>
<li><p>When is the best time to "check" the form token for security purposes? </p></li>
<li><p>How do I check it? </p></li>
<li><p>When, if ever, do I "destroy" the form token? (IOW, would the form token stay "active" until the user logs out?</p></li>
</ol> | 2,034,310 | 3 | 2 | null | 2010-01-09 17:50:27.613 UTC | 21 | 2017-09-28 19:09:34.99 UTC | 2012-08-15 16:27:12.217 UTC | null | 221,381 | null | 185,727 | null | 1 | 17 | php|forms|authentication|token | 45,420 | <p>There is no need to do what you are attempting. When you start a session in PHP with session_start() a unique SESSIONID is already generated for you. You should <em>not</em> be putting this on the form. It is handled via cookies by default. There is also no need to check the SESSIONID either, that again is handled for you. </p>
<p>You are responsible for authenticating the user and storing their authenticated identity (e.g. $_SESSION['user_id'] = $userId in the SESSION. If a user logs out you destroy their session with session_destroy.</p>
<p>You should ensure session_start() is one of the <em>first</em> things for all pages in your site.</p>
<p>Here is a basic example:</p>
<pre><code><?php
session_start(); // starts new or resumes existing session
session_regenerate_id(true); // regenerates SESSIONID to prevent hijacking
function login($username, $password)
{
$user = new User();
if ($user->login($username, $password)) {
$_SESSION['user_id'] = $user->getId();
return true;
}
return false;
}
function logout()
{
session_destroy();
}
function isLoggedIn()
{
return isset($_SESSION['user_id']);
}
function generateFormHash($salt)
{
$hash = md5(mt_rand(1,1000000) . $salt);
$_SESSION['csrf_hash'] = $hash
return $hash;
}
function isValidFormHash($hash)
{
return $_SESSION['csrf_hash'] === $hash;
}
</code></pre>
<p>Edit: I misunderstood the original question. I added the relevant methods above for generating and validating form hashes;</p>
<p>Please see the following resources:</p>
<ul>
<li><a href="http://us3.php.net/manual/en/book.session.php" rel="noreferrer">PHP Session Handling</a></li>
<li><a href="http://us3.php.net/manual/en/function.session-start.php" rel="noreferrer">session_start()</a></li>
<li><a href="http://us3.php.net/manual/en/function.session-destroy.php" rel="noreferrer">session_destroy()</a></li>
</ul> |
2,287,695 | Is parallel programming == multithread programming? | <p>Is parallel programming == multithread programming?</p> | 2,288,309 | 3 | 1 | null | 2010-02-18 10:03:25.367 UTC | 10 | 2010-02-19 10:53:24.777 UTC | 2010-02-19 10:53:24.777 UTC | null | 35,501 | null | 275,930 | null | 1 | 45 | multithreading|terminology|parallel-processing|concurrent-programming | 11,732 | <p>Multithreaded programming is parallel, but parallel programming is not necessarily multithreaded.</p>
<p>Unless the multithreading occurs on a single core, in which case it is only concurrent.</p> |
8,717,198 | foreman only shows line with βstarted with pid #β and nothing else | <p>When I run foreman I get the following:</p>
<pre><code> > foreman start
16:47:56 web.1 | started with pid 27122
</code></pre>
<p>Only if I stop it (via ctrl-c) it shows me what is missing:</p>
<pre><code>^CSIGINT received
16:49:26 system | sending SIGTERM to all processes
16:49:26 web.1 | => Booting Thin
16:49:26 web.1 | => Rails 3.0.0 application starting in development on http://0.0.0.0:5000
16:49:26 web.1 | => Call with -d to detach
16:49:26 web.1 | => Ctrl-C to shutdown server
16:49:26 web.1 | >> Thin web server (v1.3.1 codename Triple Espresso)
16:49:26 web.1 | >> Maximum connections set to 1024
16:49:26 web.1 | >> Listening on 0.0.0.0:5000, CTRL+C to stop
16:49:26 web.1 | >> Stopping ...
16:49:26 web.1 | Exiting
16:49:26 web.1 | >> Stopping ...
</code></pre>
<p>How do I fix it?</p> | 8,873,793 | 6 | 1 | null | 2012-01-03 18:56:14.297 UTC | 16 | 2019-01-21 08:19:09.14 UTC | 2019-01-21 08:19:09.14 UTC | null | 2,142,505 | null | 990,268 | null | 1 | 54 | ruby-on-rails|ruby|heroku|rubygems|foreman | 13,369 | <p>Iβve been able to resolve this issue by 2 different ways:</p>
<ol>
<li><p>From <a href="https://github.com/ddollar/foreman/wiki/Missing-Output" rel="noreferrer">https://github.com/ddollar/foreman/wiki/Missing-Output</a>:</p>
<blockquote>
<p>If you are not seeing any output from your program, there is a likely
chance that it is buffering stdout. Ruby buffers stdout by default. To
disable this behavior, add this code as early as possible in your
program:</p>
</blockquote>
<pre><code># ruby
$stdout.sync = true
</code></pre></li>
<li><p>By installing foreman via the <a href="http://toolbelt.heroku.com/" rel="noreferrer">heroku toolbelt package</a></p></li>
</ol>
<p>But I still donβt know whatβs happening nor why this 2 ways above resolved the issueβ¦</p> |
19,423,326 | Partition a Set into smaller Subsets and process as batch | <p>I have a continuous running thread in my application, which consists of a HashSet to store all the symbols inside the application. As per the design at the time it was written, inside the thread's while true condition it will iterate the HashSet continuously, and update the database for all the symbols contained inside HashSet.</p>
<p>The maximum number of symbols that might be present inside the HashSet will be around 6000. I don't want to update the DB with all the 6000 symbols at once, but divide this HashSet into different subsets of 500 each (12 sets) and execute each subset individually and have a thread sleep after each subset for 15 minutes, so that I can reduce the pressure on the database.</p>
<p>This is my code (sample code snippet)</p>
<p>How can I partition a set into smaller subsets and process (I have seen the examples for partitioning ArrayList, TreeSet, but didn't find any example related to HashSet)</p>
<pre><code>package com.ubsc.rewji.threads;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.PriorityBlockingQueue;
public class TaskerThread extends Thread {
private PriorityBlockingQueue<String> priorityBlocking = new PriorityBlockingQueue<String>();
String symbols[] = new String[] { "One", "Two", "Three", "Four" };
Set<String> allSymbolsSet = Collections
.synchronizedSet(new HashSet<String>(Arrays.asList(symbols)));
public void addsymbols(String commaDelimSymbolsList) {
if (commaDelimSymbolsList != null) {
String[] symAr = commaDelimSymbolsList.split(",");
for (int i = 0; i < symAr.length; i++) {
priorityBlocking.add(symAr[i]);
}
}
}
public void run() {
while (true) {
try {
while (priorityBlocking.peek() != null) {
String symbol = priorityBlocking.poll();
allSymbolsSet.add(symbol);
}
Iterator<String> ite = allSymbolsSet.iterator();
System.out.println("=======================");
while (ite.hasNext()) {
String symbol = ite.next();
if (symbol != null && symbol.trim().length() > 0) {
try {
updateDB(symbol);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void updateDB(String symbol) {
System.out.println("THE SYMBOL BEING UPDATED IS" + " " + symbol);
}
public static void main(String args[]) {
TaskerThread taskThread = new TaskerThread();
taskThread.start();
String commaDelimSymbolsList = "ONVO,HJI,HYU,SD,F,SDF,ASA,TRET,TRE,JHG,RWE,XCX,WQE,KLJK,XCZ";
taskThread.addsymbols(commaDelimSymbolsList);
}
}
</code></pre> | 19,423,561 | 6 | 1 | null | 2013-10-17 09:48:03.123 UTC | 1 | 2022-06-16 10:17:26.74 UTC | 2020-12-19 10:51:42.8 UTC | null | 466,862 | null | 784,597 | null | 1 | 21 | java|multithreading | 40,757 | <p>Do something like</p>
<pre><code>private static final int PARTITIONS_COUNT = 12;
List<Set<Type>> theSets = new ArrayList<Set<Type>>(PARTITIONS_COUNT);
for (int i = 0; i < PARTITIONS_COUNT; i++) {
theSets.add(new HashSet<Type>());
}
int index = 0;
for (Type object : originalSet) {
theSets.get(index++ % PARTITIONS_COUNT).add(object);
}
</code></pre>
<p>Now you have partitioned the <code>originalSet</code> into 12 other HashSets.</p> |
1,105,241 | What permissions needed to connect to SQL Server Integration Services | <p>I need to allow a consultant to connect to SSIS on a SQL Server 2008 box without making him a local administrator. If I add him to the local administrators group, he can connect to SSIS just fine, but it seems that I can't grant him enough permissions through SQL Server to give him these rights without being a local admin.</p>
<p>I've added him to every role on the server, every database role in MSDB shy of DBO, and he's still not able to connect. I don't see any SSIS-related Windows groups on the server - <strong>Is membership in the Local Administrators group really required to connect to the SSIS instance on a SQL Server?</strong> It seems like there is somewhere I should be able to grant "SSIS Admin" rights to a user (even if it's a Windows account and not a SQL account), but I can't find that place.</p>
<p><strong>UPDATE</strong>: I've found an <a href="http://msdn.microsoft.com/en-us/library/aa337083.aspx" rel="nofollow noreferrer">MSDN article</a> (See the section titled "Eliminating the 'Access if Denied' Error") that describes how to resolve problem, but even after following the steps, I'm still not able to connect. Just wanted to add it to the discussion</p> | 2,595,916 | 4 | 0 | null | 2009-07-09 17:10:15.76 UTC | null | 2015-03-04 17:54:03.253 UTC | 2010-04-27 21:21:32.603 UTC | null | 8,114 | null | 8,114 | null | 1 | 5 | sql-server-2008|ssis|permissions | 42,129 | <p>When exactly does he get the "Access is Denied Error"? When trying to connect to SSIS using SSMS (SQL Server Management Studio) and specifying "SSIS" in the connection dialog? Or after this when trying to execute a package or something?</p>
<p>I guess it is the first situation and might be able to dig something up when I am back in the office tomorrow. I would let you know of course. Until then: where would your packages be stored if he could connect to the SSIS server: on the file system or in MSDB? If on the file system in the default location (under SQL Servers' root) or somewhere else? I think if you are not storing them in MSDB there are no SQL Server permissions involved here...</p>
<p>I was always able to work around this issue using the information provided in the article you mention.</p>
<p><strong>Edit:</strong> Too bad; I cannot find anything "special" that we did but the steps mentioned in that MSDN article that you followed already.</p>
<blockquote>
<ul>
<li><p>In the <em>Launch Permission</em> dialog box,
add or delete users, and assign the
appropriate permissions to the
appropriate users and groups. The
available permissions are Local
Launch, Remote Launch, Local
Activation, and Remote Activation. The
Launch rights grant or deny permission
to start and stop the service; <strong>the
Activation rights grant or deny
permission to connect to the service</strong>.</p></li>
<li><p>In the <em>Access Permission</em> dialog box,
add or delete users, and assign the
appropriate permissions to the
appropriate users and groups.</p></li>
<li><p>Restart the Integration Services
service.</p></li>
</ul>
<p><strong>Connecting by using a Local Account</strong></p>
<p>If you are working in a <em>local Windows
account</em> on a client computer, you can
connect to the Integration Services
service on a remote computer <strong>only if a
local account that has the same name
and password and the appropriate
rights exists on the remote computer</strong>.</p>
</blockquote> |
1,014,505 | How does the ACM ICPC Online Judge prevent malicious attacks? | <p>I've spent more than a few hours humbling myself on the <a href="http://acm.uva.es/problemset/" rel="nofollow noreferrer">ACM ICPC's problem set archive</a>, and I've wondered how the online judge is able to compile and run source code from any user and prevent malicious attacks to their system. </p>
<p>Are the compiled binaries run from some kind of limited sandbox? How would one go about setting up this kind of sandbox? What OS would you use? How would you launch a user's compiled executable?</p> | 1,014,977 | 4 | 0 | null | 2009-06-18 18:49:54.273 UTC | 10 | 2015-01-21 19:40:48.52 UTC | 2015-01-21 19:40:48.52 UTC | null | 100,297 | null | 16,460 | null | 1 | 11 | security | 1,706 | <p>You could run it in a Linux chroot jail, or link it against a libc that doesn't implement any file I/O.</p> |
736,524 | How Can I Have A Conditional .htaccess Block? | <p>This is an Apache question you've probably come across before. I want to have one source package that I can deploy to my workstation, my staging server, and my production server, but for it to load different .htaccess settings based on what the URL was. </p>
<p>Note that I was using a kludge with an IfModule call, but that won't work with our new production server because it shares all the same modules as my staging server.</p>
<p>Note I need to bundle SetEnv with these rewrites. Currently if you use RewriteCond, it only ties to the following RewriteRule, but not the SetEnv underneath.</p> | 773,849 | 4 | 0 | null | 2009-04-10 02:23:18.493 UTC | 9 | 2018-10-10 12:30:15.573 UTC | 2009-04-10 03:35:13.297 UTC | Volomike | null | Volomike | null | null | 1 | 18 | apache|.htaccess|apache2 | 17,657 | <p>Instead of using SetEnv, use the environment variable setting capabilities of RewriteRule itself:</p>
<pre><code>RewriteCond %{HTTP_HOST} =foo.com
RewriteRule ^ - [E=VARNAME:foo]
RewriteCond %{HTTP_HOST} =bar.com
RewriteRule ^ - [E=VARNAME:bar]
</code></pre>
<p>Although I prefer doing this sort of thing by passing flags to the httpd process at startup and looking for them using IfDefine blocks.</p>
<pre><code><IfDefine FOO>
SetEnv VARNAME foo
</IfDefine>
<IfDefine BAR>
SetEnv VARNAME bar
</IfDefine>
</code></pre> |
614,619 | How to find out which fonts are referenced and which are embedded in a PDF document | <p>We have a little problem with fonts in PDF documents. In order to put the finger on the problem I'd like to inspect, which fonts are actually embedded in the pdf document and which are only referenced. Is there an easy (and cheap as in free) way to do that?</p> | 614,748 | 4 | 0 | null | 2009-03-05 12:44:46.273 UTC | 44 | 2016-03-09 07:05:02.223 UTC | null | null | null | Jens Schauder | 66,686 | null | 1 | 128 | pdf|fonts | 95,379 | <p>I finally got an example file that actually seems to have fonts embedded.</p>
<p>Using the normal Adobe Reader (or Foxit if you prefer). Select File->Properties on the resulting Dialog choose the Font tab. You will see a list of fonts. The ones that are embedded will state this fact in ( ) behind the font name.</p> |
14,653,784 | Add condition to this INDEX MATCH formula if it returns #N/A | <p>I have a formula in Sheet3 to look up a value from sheet1 and return it, but sometimes, if values are not in sheet1, I want it to check in sheet2. sheet1 and sheet2 have same data in column A:A, only columns have different values. </p>
<pre><code>=INDEX(Sheet1!D:D,MATCH(Sheet3!A2&"MAN_CHANGE",Sheet1!A:A,0))
</code></pre>
<p>How can I modify the formula to check in sheet2 if there's not a match in sheet1?</p> | 14,653,885 | 3 | 0 | null | 2013-02-01 19:40:57.007 UTC | 1 | 2017-12-01 05:08:45.55 UTC | 2015-09-22 23:44:17.623 UTC | null | 1,505,120 | null | 1,512,440 | null | 1 | 0 | vba|excel|excel-formula|excel-2010 | 40,470 | <p>Glad to hear from you again!) Try this please: </p>
<pre><code>=INDEX(Sheet1!D:D,IFERROR(MATCH(Sheet3!A2&"MAN_CHANGE",Sheet1!A:A,0),MATCH(Sheet3!A2&"MAN_CHANGE",Sheet2!A:A,0)))
</code></pre> |
20,253,322 | How can I hide an element when the page is scrolled? | <p>Ok, I'm a little stumped.</p>
<p>I'm trying to think the angular way coming from a jQuery background.</p>
<p>The problem:
I'd just like to hide a fixed element if the window is not scrolled. If someone scrolls down the page I would like to hide the element.</p>
<p>I've tried creating a custom directive but I couldnt get it to work as the scroll events were not firing. I'm thinking a simple controller like below, but it doesnt even run.</p>
<p>Controller:</p>
<pre><code>.controller('MyCtrl2', function($scope,appLoading, $location, $anchorScroll, $window ) {
angular.element($window).bind("scroll", function(e) {
console.log('scroll')
console.log(e.pageYOffset)
$scope.visible = false;
})
})
</code></pre>
<p>VIEW</p>
<pre><code><a ng-click="gotoTop()" class="scrollTop" ng-show="{{visible}}">TOP</a>
</code></pre>
<p>LIVE PREVIEW
<a href="http://www.thewinetradition.com.au/new/#/portfolio">http://www.thewinetradition.com.au/new/#/portfolio</a></p>
<p>Any ideas would be greatly appreciated.</p> | 20,253,831 | 1 | 0 | null | 2013-11-27 21:22:51.423 UTC | 8 | 2017-04-21 20:05:17.153 UTC | 2017-04-21 20:05:17.153 UTC | null | 1,264,804 | null | 1,914,605 | null | 1 | 32 | angularjs|scroll | 87,052 | <p>A basic directive would look like this. One key point is you'll need to call <code>scope.$apply()</code> since scroll will run outside of the normal <code>digest</code> cycle.</p>
<pre><code>app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
scope.visible = false;
scope.$apply();
});
};
});
</code></pre>
<p>I found this jsfiddle which demonstrates it nicely <a href="http://jsfiddle.net/88TzF/" rel="noreferrer">http://jsfiddle.net/88TzF/</a></p> |
20,063,068 | how to check if mysql query return no result(record not found) using php? | <p>i am passing images file names via textarea to php script to find information about each image in mysql db .The problem is i am trying to output those image file names that not found in mysql db and inform the user which image file names not found in mysql. my current code fails to output those missing records in db but it correctly outputs information about those images found in db. could any one tell me what i am doing wrong ?</p>
<pre><code>foreach ($lines as $line) {
$line = rtrim($line);
$result = mysqli_query($con,"SELECT ID,name,imgUrl,imgPURL FROM testdb WHERE imgUrl like '%$line'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
//echo $result;
if($result == 0)
{
// image not found, do stuff..
echo "Not Found Image:".$line;
}
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>"; echo "</tr>";
}
};
echo "</table>";
echo "<br>totalRows:".$totalRows;
</code></pre> | 20,063,116 | 3 | 0 | null | 2013-11-19 04:13:14.803 UTC | 3 | 2017-06-09 03:58:08.367 UTC | null | null | null | null | 1,788,736 | null | 1 | 3 | php|mysql | 65,299 | <p>You can use <code>mysqli_num_rows()</code> in mysqli</p>
<pre><code>if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='4'>Not Found Image:".$line.'</td></tr>';
}
</code></pre> |
21,885,225 | Showing custom InfoWindow for Android Maps Utility Library for Android | <p>I'm using the library <a href="http://googlemaps.github.io/android-maps-utils/" rel="nofollow noreferrer">Google Maps Utility for Android</a> which allows to create clustering int he maps and I need to show a custom <code>InfoWindow</code> but I can't find any method to do this.
In order to show the info window, I have the following class, and in the method <code>onClusterItemRendered</code> is where I have access to the info of the marker:</p>
<pre><code>class MyClusterRenderer extends DefaultClusterRenderer<MarkerItem> {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MarkerItem> clusterManager) {
super(context, map, clusterManager);
}
@Override
protected void onBeforeClusterItemRendered(MarkerItem item,
MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(String.valueOf(item.getMarkerId()));
}
@Override
protected void onClusterItemRendered(MarkerItem clusterItem,
Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
}
}
</code></pre>
<p>Is there anybody who has used the library and knows how to show a custom <code>InfoWindow</code> such as the way it was used in the Google Maps? Like:</p>
<pre><code>getMap().setInfoWindowAdapter(new InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker arg0) {
return null;
}
});
</code></pre> | 21,964,693 | 2 | 0 | null | 2014-02-19 15:36:39.233 UTC | 19 | 2017-08-08 17:27:54.99 UTC | 2017-08-08 17:27:54.99 UTC | null | 3,885,376 | null | 257,948 | null | 1 | 32 | android|google-maps|google-maps-android-api-2|markerclusterer | 12,826 | <p>Yes, this can be done. <code>ClusterManager</code> maintains two <code>MarkerManager.Collections</code>:</p>
<ul>
<li>one for cluster markers, and</li>
<li>one for individual item markers</li>
</ul>
<p>You can set a custom <code>InfoWindowAdapter</code> for each of these kinds of markers independently.</p>
<hr>
<h2>Implementation</h2>
<p>First, install your ClusterManager's MarkerManager as the map's InfoWindowAdapter:</p>
<pre><code>ClusterManager<MarkerItem> clusterMgr = new ClusterManager<MarkerItem>(context, map);
map.setInfoWindowAdapter(clusterMgr.getMarkerManager());
</code></pre>
<p>Next, install your custom <code>InfoWindowAdapter</code> as the adapter for one or both of the marker collections:</p>
<pre><code>clusterMgr.getClusterMarkerCollection().setOnInfoWindowAdapter(new MyCustomAdapterForClusters());
clusterMgr.getMarkerCollection().setOnInfoWindowAdapter(new MyCustomAdapterForItems());
</code></pre>
<p>The final piece is mapping the raw <code>Marker</code> object that you'll receive in your custom InfoWindowAdapter's callback to the <code>ClusterItem</code> object(s) that you added to the map in the first place. This can be achieved using the onClusterClick and onClusterItemClick listeners, as follows:</p>
<pre><code>map.setOnMarkerClickListener(clusterMgr);
clusterMgr.setOnClusterClickListener(new OnClusterClickListener<MarkerItem>() {
@Override
public boolean onClusterClick(Cluster<MarkerItem> cluster) {
clickedCluster = cluster; // remember for use later in the Adapter
return false;
}
});
clusterMgr.setOnClusterItemClickListener(new OnClusterItemClickListener<MarkerItem>() {
@Override
public boolean onClusterItemClick(MarkerItem item) {
clickedClusterItem = item;
return false;
}
});
</code></pre>
<hr>
<p>Now you have everything you need to assemble your custom InfoWindow content in your respective Adapters! For example:</p>
<pre><code>class MyCustomAdapterForClusters implements InfoWindowAdapter {
@Override
public View getInfoContents(Marker marker) {
if (clickedCluster != null) {
for (MarkerItem item : clickedCluster.getItems()) {
// Extract data from each item in the cluster as needed
}
}
// build your custom view
// ...
return view;
}
}
</code></pre> |
50,070,384 | SQSListener with ThreadpoolExecutor | <p>In the below example , I am setting the max and core pool size to 1. However no messages are being processed. When I enable debug log , I am able to see the messages being pulled from SQS , but I guess it is not being processed / deleted. However when I increase core and max pool size to 2 , the messages seem to be processed.</p>
<p><strong>EDIT</strong></p>
<p>I believe Spring maybe allocating a thread for receiver which reads data off the queue and hence it is unable to allocate a thread to listener which is processing the message. When I increased the corepoolsize to 2 , I saw that messages were being read off the queue. When I added another listener (for dead letter queue) , I encountered the same issue - 2 threads were not sufficient as the messages were not being processed. When I increased the corepoolsize to 3 , it started processing the messages. I assume in this case , 1 thread was allocated to read messages off the queue and 2 listeners were assigned 1 thread each.</p>
<pre><code>@Configuration
public class SqsListenerConfiguration {
@Bean
@ConfigurationProperties(prefix = "aws.configuration")
public ClientConfiguration clientConfiguration() {
return new ClientConfiguration();
}
@Bean
@Primary
public AWSCredentialsProvider awsCredentialsProvider() {
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("credential");
try {
credentialsProvider.getCredentials();
System.out.println(credentialsProvider.getCredentials().getAWSAccessKeyId());
System.out.println(credentialsProvider.getCredentials().getAWSSecretKey());
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
return credentialsProvider;
}
@Bean
@Primary
public AmazonSQSAsync amazonSQSAsync() {
return AmazonSQSAsyncClientBuilder.standard().
withCredentials(awsCredentialsProvider()).
withClientConfiguration(clientConfiguration()).
build();
}
@Bean
@ConfigurationProperties(prefix = "aws.queue")
public SimpleMessageListenerContainer simpleMessageListenerContainer(AmazonSQSAsync amazonSQSAsync) {
SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
simpleMessageListenerContainer.setMessageHandler(queueMessageHandler());
simpleMessageListenerContainer.setMaxNumberOfMessages(10);
simpleMessageListenerContainer.setTaskExecutor(threadPoolTaskExecutor());
return simpleMessageListenerContainer;
}
@Bean
public QueueMessageHandler queueMessageHandler() {
QueueMessageHandlerFactory queueMessageHandlerFactory = new QueueMessageHandlerFactory();
queueMessageHandlerFactory.setAmazonSqs(amazonSQSAsync());
QueueMessageHandler queueMessageHandler = queueMessageHandlerFactory.createQueueMessageHandler();
return queueMessageHandler;
}
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setThreadNamePrefix("oaoQueueExecutor");
executor.initialize();
return executor;
}
@Bean
public QueueMessagingTemplate messagingTemplate(@Autowired AmazonSQSAsync amazonSQSAsync) {
return new QueueMessagingTemplate(amazonSQSAsync);
}
}
</code></pre>
<p><strong>Listener Config</strong></p>
<pre><code> @SqsListener(value = "${oao.sqs.url}", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void onMessage(String serviceData, @Header("MessageId") String messageId, @Header("ApproximateFirstReceiveTimestamp") String approximateFirstReceiveTimestamp) {
System.out.println(" Data = " + serviceData + " MessageId = " + messageId);
repository.execute(serviceData);
}
</code></pre> | 50,103,237 | 1 | 1 | null | 2018-04-27 21:13:16.837 UTC | 9 | 2021-07-30 17:06:51.88 UTC | 2018-07-12 00:57:08.483 UTC | null | 174,777 | null | 1,042,646 | null | 1 | 13 | java|spring|amazon-web-services|spring-cloud|amazon-sqs | 9,716 | <p>By setting <code>corePoolSize</code> and <code>maximumPoolSize</code> the same, you create a <code>fixed-size thread pool</code>. A very good explanation of the rules are documented <a href="http://www.bigsoft.co.uk/blog/2009/11/27/rules-of-a-threadpoolexecutor-pool-size" rel="noreferrer">here</a></p>
<p>Setting <code>maxPoolSize</code> implicitly allows for tasks to get dropped.
However, the default queue capacity is <code>Integer.MAX_VALUE</code>, which, for practical purposes, is infinity.</p>
<p>Something to watch out for is that <code>ThreadPoolTaskExecutor</code> uses a <code>ThreadPoolExecutor</code> underneath, which has a somewhat unusual approach to queueing, described in <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">the docs</a>:</p>
<blockquote>
<p>If <code>corePoolSize</code> or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.</p>
</blockquote>
<p>This means that <code>maxPoolSize</code> is only relevant when the queue is full, otherwise the number of threads will never grow beyond <code>corePoolSize</code>.
As an example, if we submit tasks <strong>that never complete</strong> to the thread pool:</p>
<ul>
<li>the first <code>corePoolSize</code> submissions will start a new thread each;</li>
<li>after that, all submissions go to the queue;</li>
<li>if the queue is finite and its capacity is exhausted, each submission starts a new thread, up to <code>maxPoolSize</code>;</li>
<li>when both the pool and the queue are full, new submissions are rejected.</li>
</ul>
<p><strong>Queuing</strong> - Read the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">docs</a></p>
<p>Any <code>BlockingQueue</code> may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:</p>
<ul>
<li>If fewer than corePoolSize threads are running, the Executor always
prefers adding a new thread rather than queuing. </li>
<li>If corePoolSize or more threads are running, the Executor always
prefers queuing a request rather than adding a new thread. </li>
<li>If a request cannot be queued, a new thread is created unless
this would exceed maximumPoolSize, in which case, the task will
be rejected.</li>
</ul>
<blockquote>
<p><code>Unbounded queues</code>. Using an unbounded queue (for example a
<code>LinkedBlockingQueue</code> without a predefined capacity) will cause new
tasks to be queued in cases where all corePoolSize threads are busy.
Thus, no more than <code>corePoolSize</code> threads will ever be created. (And the
value of the <code>maximumPoolSize</code> therefore doesn't have any effect.)</p>
</blockquote>
<ol>
<li>If the number of threads is less than the <code>corePoolSize</code>, create a new
Thread to run a new task.</li>
<li>If the number of threads is equal (or greater than) the
<code>corePoolSize</code>, put the task into the queue.</li>
<li>If the queue is full, and the number of threads is less than the
<code>maxPoolSize</code>, create a new thread to run tasks in.</li>
<li>If the queue is full, and the number of threads is greater than or
equal to <code>maxPoolSize</code>, reject the task.</li>
</ol> |
19,172,565 | how append date build to versionNameSuffix on gradle | <p>I am using Android Studio and I need to append a suffix to the <code>versionNameSuffix</code> on my Android <em>build.gradle</em> file. I have three different build types and I only need to append the datetime to my "beta" release. My actual file is:</p>
<pre class="lang-groovy prettyprint-override"><code>defaultConfig {
versionCode 14
versionName "0.7.5"
minSdkVersion 9
targetSdkVersion 18
}
buildTypes {
beta {
packageNameSuffix ".beta"
versionNameSuffix "-beta"
signingConfig signingConfigs.debug
}
....
}
</code></pre>
<p>For testing and automatic deploy, I need to get a final versionName like: <code>0.7.5-beta-build20131004</code>, <code>0.7.5-beta-build1380855996</code> or something like that. Any ideas?</p> | 19,184,323 | 7 | 0 | null | 2013-10-04 03:11:11.497 UTC | 20 | 2022-05-04 08:03:41.353 UTC | 2022-02-18 10:05:51.147 UTC | null | 8,583,692 | null | 1,116,322 | null | 1 | 89 | android|android-studio|gradle|android-gradle-plugin|build.gradle | 64,066 | <pre class="lang-groovy prettyprint-override"><code>beta {
packageNameSuffix ".beta"
versionNameSuffix "-beta" + "-build" + getDate()
signingConfig signingConfigs.debug
}
def getDate() {
def date = new Date()
def formattedDate = date.format('yyyyMMddHHmmss')
return formattedDate
}
</code></pre>
<p>Condensed:</p>
<pre><code>def getDate() {
return new Date().format('yyyyMMddHHmmss')
}
</code></pre> |
19,125,266 | How to take heap snapshot of Xamarin.Android's Mono VM? | <p>Background: I am trying to track down a memory leak in a Xamarin.Android app. Using DDMS and Eclipse Memory Profiler, I am able to see which objects are alive. When trying to track what is holding them alive (GC Root), I only see "Native stack" (of course).</p>
<p>How can I take a heap snapshot of the MONO VM? So I can later use it with i.e. heapshot tool?</p>
<p>Or are there ANY OTHER TECHNIQUES I can use to find what is holding an object alive in Xamarin.Android's .NET part? Is it possible to do something from within the program?</p> | 19,126,051 | 2 | 0 | null | 2013-10-01 20:25:58.63 UTC | 9 | 2014-08-20 09:24:24.71 UTC | null | null | null | null | 38,325 | null | 1 | 6 | android|memory-leaks|xamarin|memory-profiling|heap-dump | 5,195 | <blockquote>
<p>How can I take a heap snapshot of the MONO VM? So I can later use it with i.e. heapshot tool?</p>
</blockquote>
<p>It is now possible to get heap snapshots of the Mono VM (tested with Xamarin.Android 4.8.2 beta; may apply to prior releases, your mileage may vary). It's a four step process:</p>
<ol>
<li><p>Enable heapshot logging:</p>
<pre><code>adb shell setprop debug.mono.profile log:heapshot
</code></pre></li>
<li><p>Start your app. (If your app was already running before (1), kill and restart it.)</p>
<p>Use your app.</p></li>
<li><p>Grab the profile data for your app:</p>
<pre><code>adb pull /data/data/@PACKAGE_NAME@/files/.__override__/profile.mlpd
</code></pre>
<p><code>@PACKAGE_NAME@</code> is the package name of your application, e.g. if your package is <code>FooBar.FooBar-Signed.apk</code>, then <code>@PACKAGE_NAME@</code> will be <code>FooBar.FooBar</code>.</p></li>
<li><p>Analyze the data:</p>
<pre><code>mprof-report profile.mlpd
</code></pre>
<p><code>mprof-report</code> is included with Mono.</p></li>
</ol>
<p><strong>Note</strong>: <code>profile.mlpd</code> is <em>only</em> updated when a GC occurs, so you <em>may</em> want to call <code>GC.Collect()</code> at some "well known" point to ensure that <code>profile.mlpd</code> is regularly updated .</p> |
19,052,354 | SIGHUP for reloading configuration | <p>According to <code>signal(7)</code>, <code>SIGHUP</code> is used to detect hangup on controlling terminal or death of controlling process.</p>
<p>However, I have come across a lot of OSS daemons(services) where <code>SIGHUP</code> is used to initiate a reload of configuration. Here are a few examples: <code>hostapd</code>, <code>sshd</code>, <code>snort</code> etc.</p>
<p>Is this a standard(or a generally acceptable) way to implement a reload? If not, whats recommended?</p> | 28,327,659 | 2 | 0 | null | 2013-09-27 13:43:05.97 UTC | 6 | 2016-02-16 08:59:32.64 UTC | 2014-07-16 07:25:05.56 UTC | null | 1,044,366 | null | 1,865,794 | null | 1 | 29 | linux|unix|configuration|signals|reload | 26,955 | <p>SIGHUP as a notification about terminal closing event doesn't make sense for a daemon, because deamons are detached from their terminal. So the system will never send this signal to them.
Then it is common practice for daemons to use it for another meaning, typically reloading the daemon's configuration.
This is not a rule, just kind of a convention. That's why it's not documented in the manpage.</p>
<p>See the wikipedia entry for <a href="http://en.wikipedia.org/wiki/Unix_signal#SIGHUP" rel="noreferrer">SIGHUP</a>
and from there, <a href="http://perldoc.perl.org/perlipc.html#Handling-the-SIGHUP-Signal-in-Daemons" rel="noreferrer">a longer description with implementation example</a></p> |
49,522,776 | Helm: How to Override Value with Periods in Name | <p>I am trying to script setup of Jenkins so that I can create and tear down Jenkins clusters programmatically with helm. I've hit an annoying snag where I cannot set a key with dots in the name. My helm values.yaml file looks like this:</p>
<pre><code>---
rbac:
install: true
Master:
HostName: jenkins.mycompany.com
ServiceType: ClusterIP
ImageTag: lts
InstallPlugins:
- kubernetes
- workflow-aggregator
- workflow-job
- credentials-binding
- git
- blueocean
- github
- github-oauth
ScriptApproval:
- "method groovy.json.JsonSlurperClassic parseText java.lang.String"
- "new groovy.json.JsonSlurperClassic"
- "staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods leftShift java.util.Map java.util.Map"
- "staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods split java.lang.String"
- "method java.util.Collection toArray"
- "staticMethod org.kohsuke.groovy.sandbox.impl.Checker checkedCall java.lang.Object boolean boolean java.lang.String java.lang.Object[]"
- "staticMethod org.kohsuke.groovy.sandbox.impl.Checker checkedGetProperty java.lang.Object boolean boolean java.lang.Object"
Ingress:
Annotations:
kubernetes.io/ingress.class: nginx
kubernetes.io/tls-acme: "true"
TLS:
- secretName: jenkins-mycompany-com
hosts:
- jenkins.mycompany.com
Memory: "2Gi"
# This breaks the init container
# RunAsUser: 1000
# FSGroup: 1000
Agent:
Enabled: false
ImageTag: latest
</code></pre>
<p>After installing <code>cert-manager</code>, <code>external-dns</code>, <code>nginx-ingress</code> (for now via a bash script) I install it like so:</p>
<pre><code>helm install --values helm/jenkins.yml stable/jenkins
</code></pre>
<p>I failed to read the letsencrypt docs at all, so throughout the course of testing I used my production quota. I want to be able to add an annotation to the <code>Ingress</code>: <code>certmanager.k8s.io/cluster-issuer: letsencrypt-staging</code> so that I can continue testing (and set this as the default in the future, overriding when I'm ready for production).</p>
<p>The trouble is... I can't figure out how to pass this via the <code>--set</code> flag, since there are periods in the key name. I've tried:</p>
<pre><code>helm install --values helm/jenkins.yml stable/jenkins --set Master.Ingress.Annotations.certmanager.k8s.io/cluster-issuer=letsencrypt-staging
</code></pre>
<p>and</p>
<pre><code>helm install --values helm/jenkins.yml stable/jenkins --set Master.Ingress.Annotations.certmanager\.k8s\.io/cluster-issuer=letsencrypt-staging
</code></pre>
<p>I can of course solve this by adding a value that I use as a flag, but it's less explicit. Is there any way to set it directly?</p> | 50,399,612 | 2 | 0 | null | 2018-03-27 21:34:39.257 UTC | 4 | 2021-02-03 16:27:03.06 UTC | 2018-03-27 21:44:39.963 UTC | null | 1,342,445 | null | 1,342,445 | null | 1 | 31 | kubernetes-helm | 15,585 | <p>You need to enclose the key with quotations and then escape the dots</p>
<pre><code>helm install --values helm/jenkins.yml stable/jenkins --set Master.Ingress.Annotations."certmanager\.k8s\.io/cluster-issuer"=letsencrypt-staging
</code></pre> |
40,663,198 | ng-reflect-model shows correct value but not reflecting in input | <p>Encountered a very weird issue where my application misbehaves in a very specific user case. I have a portal where users can add questions and answers and then edit them. In this case when I remove a set(q+a) and then try adding it, the model is getting updated but my view takes values from placeholders and updates itself. Here I am just splicing and pushing values in an array and rendering using ngFor. The last element is a dummy and that is used to enter values which are pushed up.</p>
<p>Attaching a screenshot if it makes any sense.</p>
<p>You can see that for the textbox, the ng-reflect-model shows correct question, but the element itself displays the placeholder text.</p>
<p><a href="https://i.stack.imgur.com/h7PY3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h7PY3.png" alt=""></a></p> | 41,504,893 | 3 | 3 | null | 2016-11-17 19:14:33.713 UTC | 8 | 2019-12-05 14:39:34.537 UTC | null | null | null | null | 2,424,990 | null | 1 | 17 | angular|angular2-template|angular2-forms | 24,486 | <p>Apparently the issue was being caused because Angular wasn't able to track the elements of my array properly. I found this out very hard way. So just adding a trackBy attribute to my ngFor, I was able to resolve this.</p>
<p>Added this to my component:</p>
<pre><code>customTrackBy(index: number, obj: any): any {
return index;
}
</code></pre>
<p>and then in the template:</p>
<pre><code><div class="margin-bottom-15"
*ngFor="let assessment of language.assessments; trackBy:customTrackBy">
</code></pre>
<p>So basically I am asking angular to track my elements in the array by index. It resolved the issue.</p>
<p>Here assessment is the model for each of the question-answer set.</p> |
52,995,962 | Kubernetes namespace default service account | <p>If not specified, pods are run under a default service account.</p>
<ul>
<li>How can I check what the default service account is authorized to do?</li>
<li>Do we need it to be mounted there with every pod?</li>
<li>If not, how can we disable this behavior on the namespace level or cluster level.</li>
<li>What other use cases the default service account should be handling?</li>
<li>Can we use it as a service account to create and manage the Kubernetes deployments in a namespace? For example we will not use real user accounts to create things in the cluster because users come and go.</li>
</ul>
<p>Environment: Kubernetes 1.12 , with RBAC</p> | 52,998,473 | 4 | 0 | null | 2018-10-25 18:34:03.9 UTC | 11 | 2021-12-02 15:03:19.693 UTC | 2020-08-24 01:32:04.277 UTC | null | 219,658 | null | 4,550,110 | null | 1 | 25 | kubernetes|rbac | 35,459 | <ol>
<li>A default service account is automatically created for each namespace.</li>
</ol>
<blockquote>
<p>kubectl get serviceaccount</p>
<p>NAME SECRETS AGE</p>
<p>default 1 1d</p>
</blockquote>
<ol start="2">
<li><p>Service accounts can be added when required. Each pod is associated with exactly one service account but multiple pods can use the same service account.</p>
</li>
<li><p>A pod can only use one service account from the same namespace.</p>
</li>
<li><p>Service account are assigned to a pod by specifying the accountβs name in the pod manifest. If you donβt assign it explicitly the pod will use the default service account.</p>
</li>
<li><p>The default permissions for a service account don't allow it to
list or modify any resources. The default service account isn't allowed to view cluster state let alone modify it in any way.</p>
</li>
<li><p>By default, the default service account in a namespace has no permissions other than those of an unauthenticated user.</p>
</li>
<li><p>Therefore pods by default canβt even view cluster state. Its up to you to grant them appropriate permissions to do that.</p>
</li>
</ol>
<blockquote>
<p>kubectl exec -it test -n foo sh / # curl
localhost:8001/api/v1/namespaces/foo/services { "kind": "Status",<br />
"apiVersion": "v1", "metadata": {</p>
<p>}, "status": "Failure", "message": "services is forbidden: User
"system:serviceaccount:foo:default" cannot list resource
"services" in API group "" in the namespace "foo"", "reason":
"Forbidden", "details": {
"kind": "services" }, "code": 403</p>
</blockquote>
<p>as can be seen above the default service account cannot list services</p>
<p>but when given proper role and role binding like below</p>
<pre><code>apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
creationTimestamp: null
name: foo-role
namespace: foo
rules:
- apiGroups:
- ""
resources:
- services
verbs:
- get
- list
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
creationTimestamp: null
name: test-foo
namespace: foo
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: foo-role
subjects:
- kind: ServiceAccount
name: default
namespace: foo
</code></pre>
<p>now i am able to list the resurce service</p>
<pre><code>kubectl exec -it test -n foo sh
/ # curl localhost:8001/api/v1/namespaces/foo/services
{
"kind": "ServiceList",
"apiVersion": "v1",
"metadata": {
"selfLink": "/api/v1/namespaces/bar/services",
"resourceVersion": "457324"
},
"items": []
</code></pre>
<ol start="8">
<li><p>Giving all your service accounts the <code>clusteradmin</code> ClusterRole is a
bad idea. It is best to give everyone only the permissions they need to do their job and not a single permission more.</p>
</li>
<li><p>Itβs a good idea to create a specific service account for each pod
and then associate it with a tailor-made role or a ClusterRole through a
RoleBinding.</p>
</li>
<li><p>If one of your pods only needs to read pods while the other also needs to modify them then create two different service accounts and make those pods use them by specifying the <code>serviceaccountName</code> property in the
pod spec.</p>
</li>
</ol>
<p>You can refer the below link for an in-depth explanation.</p>
<p><a href="https://developer.ibm.com/recipes/tutorials/service-accounts-and-auditing-in-kubernetes/" rel="noreferrer">Service account example with roles</a></p>
<p>You can check <code>kubectl explain serviceaccount.automountServiceAccountToken</code> and edit the service account</p>
<p>kubectl edit serviceaccount default -o yaml</p>
<pre><code>apiVersion: v1
automountServiceAccountToken: false
kind: ServiceAccount
metadata:
creationTimestamp: 2018-10-14T08:26:37Z
name: default
namespace: default
resourceVersion: "459688"
selfLink: /api/v1/namespaces/default/serviceaccounts/default
uid: de71e624-cf8a-11e8-abce-0642c77524e8
secrets:
- name: default-token-q66j4
</code></pre>
<p>Once this change is done whichever pod you spawn doesn't have a serviceaccount token as can be seen below.</p>
<pre><code>kubectl exec tp -it bash
root@tp:/# cd /var/run/secrets/kubernetes.io/serviceaccount
bash: cd: /var/run/secrets/kubernetes.io/serviceaccount: No such file or directory
</code></pre> |
22,184,012 | How to put an existing DataTable into a DataSet? | <p>That's just it. I have an existing DataTable, and I would like to make it a part of a existing DataSet. Any ideas on how to go about it? I tried a couple of things, but none of them work...</p> | 22,184,110 | 2 | 0 | null | 2014-03-04 21:58:36.97 UTC | null | 2014-03-04 22:10:00.48 UTC | null | null | null | null | 3,380,611 | null | 1 | 3 | vb.net | 40,429 | <p>The Dataset contains a collection of Tables, and, as with every collection, you could use the method Add to add your table to the dataset.<br>
However there is one thing to be aware of. If your table is already part of another dataset (probably because you used the DataAdapter.Fill(DataSet) method), then you should remove the table from the previous dataset tables collection before adding it to the new one.</p>
<pre><code>Dim dsNew = New DataSet() ' The dataset where you want to add your table
Dim dt As DataTable = GetTable() ' Get the table from your storage
Dim dsOld = dt.DataSet ' Retrieve the DataSet where the table has been originally added
if dsOld IsNot Nothing Then
dsOld.Tables.Remove(dt.TableName) ' Remove the table from its dataset tables collection
End If
dsNew.Tables.Add(dt) ' Add to the destination dataset.
</code></pre> |
23,679,367 | What does the PF function do in Primefaces? | <p>On many places one can find usage of a function <code>PF</code> with Primefaces. For example in this <a href="https://stackoverflow.com/questions/17922306/primefaces-dialog-does-not-show">answer</a></p>
<p>From what I have seen so far it seems to be a magic "make it work a little better" function. But I don't believe in this kind of stuff so:</p>
<p>What does this function do?</p>
<p>And where can I find documentation about it?</p> | 23,681,573 | 3 | 1 | null | 2014-05-15 13:14:34.17 UTC | 3 | 2017-11-23 19:03:03.537 UTC | 2017-05-23 10:30:45.363 UTC | null | -1 | null | 66,686 | null | 1 | 35 | jsf-2|primefaces | 48,559 | <p><code>PF</code> is a Javascript function. </p>
<p>In Primefaces 4.0 the Javascript scope of widgets changed. Prior to version 4.0 you could open a dialog widget with <code>widgetVar.show();</code>. </p>
<p>In Primefaces 4.0 and above the widgets are stored in a Javascript widget array. When you call PF('widgetVar') it is looking for the widget in the array and returning it.</p>
<pre><code>PF=function(d){
var c=b.widgets[d];
if(!c){
if(a.console&&console.log){
console.log("Widget for var '"+d+"' not available!")
}
b.error("Widget for var '"+d+"' not available!")
}
return c
};
</code></pre>
<p>I could not find much on this either this is what I was able to decipher using Chrome's developer tools. </p> |
37,168,888 | iOS 9 : Warning "All interface orientations must be supported unless the app requires full screen" for universal app | <p>I'm working on an universal app with <em>all orientations</em> on iPad and <em>only portrait</em> on iPhone. The app works well with split-screen multitasking on iOS 9 compatible iPad, but I have this warning:</p>
<pre><code>All interface orientations must be supported unless the app requires full screen
</code></pre>
<p>And my app does not require full screen. It's only limited to portrait on iPhone... Shouldn't it be ok? Is there a way to declare <em>Requires Full Screen</em> only on iPhone?</p>
<p>Thanks in advance</p>
<p>By the way I'm using Xcode 7.3.1</p> | 43,623,382 | 5 | 2 | null | 2016-05-11 16:55:08.603 UTC | 13 | 2018-07-09 11:05:46.983 UTC | null | null | null | null | 842,327 | null | 1 | 56 | ios|iphone|xcode|ipad|multitasking | 24,197 | <p>The solution to this is to use "Device Specific Keys":
<a href="https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html#//apple_ref/doc/uid/TP40009254-SW9" rel="noreferrer">https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html#//apple_ref/doc/uid/TP40009254-SW9</a></p>
<p>Your plist values would therefore look something like:</p>
<pre><code><key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIRequiresFullScreen~ipad</key>
<false/>
</code></pre>
<p>When I remove the iPad specific version of the <code>UIRequiresFullScreen</code> key, I lose the full split-screen functionality - only "slide over" is available because that doesn't affect my app's use of the full device screen.</p>
<p>The "Device Orientation" checkboxes are for the default plist values. The only way they wouldn't affect the app on the iPad is if there's a more specific value in the plist, therefore a value specifically for iPad.</p>
<blockquote>
<p>When the system searches for a key in your appβs Info.plist file, it chooses the key that is most specific to the current device and platform.</p>
</blockquote> |
30,294,571 | multiprocessing.Queue and Queue.Queue are different? | <p>If I use <code>Queue.Queue</code>, then my <code>read()</code> function doesn't work, why? But if I use <code>multiprocessing.Queue</code>, it works well:</p>
<pre><code>from multiprocessing import Pool, Process, Queue
import os, time
# from Queue import Queue
def write(q):
for v in ['A', 'B', 'C']:
print 'Put %s to queue ' % v
q.put_nowait(v)
time.sleep(0.2)
def read(q):
while 1:
if not q.empty():
v = q.get(True)
print "Get %s from queue" % v
time.sleep(0.2)
else:
break
if __name__ == '__main__':
q = Queue()
pw = Process(target=write, args=(q, ))
pr = Process(target=read, args=(q, ))
pw.start()
pw.join()
pr.start()
pr.join()
print "all done..."
</code></pre> | 30,294,648 | 1 | 1 | null | 2015-05-18 03:15:56.97 UTC | 10 | 2017-08-03 01:29:24.253 UTC | 2017-08-03 01:29:24.253 UTC | null | 355,230 | null | 4,737,876 | null | 1 | 18 | python|multiprocessing | 8,327 | <p><code>Queue.Queue</code> is just an in-memory queue that knows how to deal with multiple threads using it at the same time. It only works if both the producer and the consumer are in the same process.</p>
<p>Once you have them in separate system processes, which is what the <code>multiprocessing</code> library is about, things are a little more complicated, because the processes no longer share the same memory. You need some kind of inter-process communication method to allow the two processes to talk to each other. It can be a shared memory, a pipe or a socket, or possibly something else. This is what <code>multiprocessing.Queue</code> does. It uses pipes to provide a way for two processes to communicate. It just happens to implement the same API as <code>Queue.Queue</code>, because most Python programmers are already familiar with it.</p>
<p>Also note that the way you are using the queue, you have a race condition in your program. Think about what happens if the <code>write</code> process writes to the queue right after you call <code>q.empty()</code> in the <code>read</code> process. Normally you would add some special item to the queue (e.g. <code>None</code>) which would mean that the consumer can stop.</p> |
20,763,629 | Test whether a directory exists inside a makefile | <p>In his <a href="https://stackoverflow.com/a/59839/671013">answer</a> @Grundlefleck explains how to check whether a directory exists or not. I tried some to use this inside a <code>makefile</code> as follow:</p>
<pre><code>foo.bak: foo.bar
echo "foo"
if [ -d "~/Dropbox" ]; then
echo "Dir exists"
fi
</code></pre>
<p>Running <code>make foo.bak</code> (given that <code>foo.bar</code> exists) yields the following error:</p>
<pre><code>echo "foo"
foo
if [ -d "~/Dropbox" ]; then
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [foo.bak] Error 2
</code></pre>
<p>The workaround I made was to have a standalone bash script where the test is implemented and I called the script from the <code>makefile</code>. This, however, sounds very cumbersome. Is there a nicer way to check whether a directory exists from within a <code>makefile</code>?</p> | 20,763,829 | 7 | 1 | null | 2013-12-24 16:02:10.933 UTC | 19 | 2021-08-10 17:56:18.093 UTC | 2017-05-23 11:33:17.283 UTC | null | -1 | null | 671,013 | null | 1 | 84 | bash|makefile | 107,377 | <p>Make commands, if a shell command, must be in one line, or be on multiple lines using a backslash for line extension. So, this approach will work:</p>
<pre><code>foo.bak: foo.bar
echo "foo"
if [ -d "~/Dropbox" ]; then echo "Dir exists"; fi
</code></pre>
<p>Or</p>
<pre><code>foo.bak: foo.bar
echo "foo"
if [ -d "~/Dropbox" ]; then \
echo "Dir exists"; \
fi
</code></pre> |
13,893,634 | String split and count the number of occurrences and also | <p>I have a string </p>
<pre><code>var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
</code></pre>
<p>How to get the count of the number of occurrences of each entry, The occurrence I get, is from a JSON like Java = 8 and etc...</p> | 51,579,290 | 6 | 1 | null | 2012-12-15 15:47:32.247 UTC | 1 | 2018-07-29 10:15:52.74 UTC | null | null | null | null | 309,721 | null | 1 | 6 | javascript|jquery|string|split | 50,174 | <p>Now a days you can do </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> const str = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
var result = str.split("$$").reduce(function(acc, curr) {
curr && (acc[curr] = (acc[curr] + 1) || 1);
return acc
}, {});
console.log(result);</code></pre>
</div>
</div>
</p> |
48,623,533 | How to load navigation properties on an IdentityUser with UserManager | <p>I've extended <code>IdentityUser</code> to include a navigation property for the user's address, however when getting the user with <code>UserManager.FindByEmailAsync</code>, the navigation property isn't populated. Does ASP.NET Identity Core have some way to populate navigation properties like Entity Framework's <code>Include()</code>, or do I have to do it manually?</p>
<p>I've set up the navigation property like this:</p>
<pre><code>public class MyUser : IdentityUser
{
public int? AddressId { get; set; }
[ForeignKey(nameof(AddressId))]
public virtual Address Address { get; set; }
}
public class Address
{
[Key]
public int Id { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string Country { get; set; }
}
</code></pre> | 48,623,646 | 5 | 5 | null | 2018-02-05 13:19:44.88 UTC | 9 | 2022-05-23 11:30:29.243 UTC | 2018-02-05 13:23:06.253 UTC | null | 2,141,621 | null | 1,096,201 | null | 1 | 40 | c#|asp.net-core|entity-framework-core|asp.net-core-identity | 11,695 | <p>Unfortunately, you have to either do it manually or create your own <code>IUserStore<IdentityUser></code> where you load related data in the <code>FindByEmailAsync</code> method:</p>
<pre><code>public class MyStore : IUserStore<IdentityUser>, // the rest of the interfaces
{
// ... implement the dozens of methods
public async Task<IdentityUser> FindByEmailAsync(string normalizedEmail, CancellationToken token)
{
return await context.Users
.Include(x => x.Address)
.SingleAsync(x => x.Email == normalizedEmail);
}
}
</code></pre>
<p>Of course, implementing the entire store just for this isn't the best option. </p>
<p>You can also query the store directly, though:</p>
<pre><code>UserManager<IdentityUser> userManager; // DI injected
var user = await userManager.Users
.Include(x => x.Address)
.SingleAsync(x => x.NormalizedEmail == email);
</code></pre> |
39,362,730 | How to capture packets for single docker container | <p>There have many container running on the host. And I want to capture packets for the one container of these. Is there any way to do this?</p> | 49,277,873 | 4 | 4 | null | 2016-09-07 06:37:15.677 UTC | 11 | 2022-08-17 19:41:20.27 UTC | null | null | null | null | 1,233,410 | null | 1 | 38 | networking|docker | 37,812 | <p>You can bind to the network namespace of one container to another:</p>
<pre><code>docker run -it --rm --net container:<container_name> \
nicolaka/netshoot tcpdump ...
</code></pre>
<p>To see more about the netshoot image used above, see: <a href="https://github.com/nicolaka/netshoot" rel="noreferrer">https://github.com/nicolaka/netshoot</a></p> |
6,578,205 | Swing JLabel text change on the running application | <p>I have a Swing window which contains a button a text box and a <code>JLabel</code> named as flag. According to the input after I click the button, the label should change from flag to some value. </p>
<p>How to achieve this in the same window? </p> | 6,578,266 | 2 | 0 | null | 2011-07-05 05:19:41.793 UTC | 6 | 2011-07-05 05:44:02.573 UTC | 2011-07-05 05:44:02.573 UTC | null | 418,556 | null | 651,362 | null | 1 | 5 | java|swing|jlabel | 121,882 | <pre><code>import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
</code></pre> |
6,483,711 | Union in entity framework | <p>I have two tables: Vehicles and Workers. </p>
<pre><code>Vehicle(Id, Number)
Workers(Id, Name, ContractorVehicleNumber)
</code></pre>
<p>I would like to write lambda query to return all the vehicles and the contractor vehicles. Something like in sql:</p>
<pre><code>SELECT Id, Number
FROM Vehicle
UNION
SELECT NULL, ContractorVehicleNumber
FROM Workers
</code></pre>
<p>This is what I made:</p>
<pre><code>public IQueryable<Vehicle> Get(bool includeContractorVehicles)
{
IQueryable<Vehicle> query = GetQuery();
if (includeContractorVehicles == true)
{
WorkerRepository rep = new WorkerRepository();
IQueryable<Vehicle> contractorsVehicles = rep.GetWirkers().
Select(x => new Vehicle()
{
VehicleNumber = x.ContractorVehicleNumber
});
query = query.Union(contractorsVehicles);
}
return query;
}
</code></pre>
<p>But I get an exception:</p>
<blockquote>
<p>The entity or complex type 'XXXXXXXX' cannot be constructed in a LINQ to Entities query.</p>
</blockquote> | 6,484,165 | 2 | 0 | null | 2011-06-26 11:49:01.403 UTC | 4 | 2018-04-09 01:42:42.223 UTC | 2015-01-21 00:47:26.467 UTC | null | 41,956 | null | 289,246 | null | 1 | 18 | c#|.net|entity-framework|linq-to-entities | 59,239 | <p>You cannot construct mapped entity type in projection. Your former example will work only if you create a new special type used for projection:</p>
<pre><code>public class VehicleResult
{
public string Number { get; set; }
... // If you don't need more then one column you can use simple type instead of custom class
}
</code></pre>
<p>And your method will look like:</p>
<pre><code>public IQueryable<VehicleResult> Get(bool includeContractorVehicles)
{
IQueryable<VehicleResult> query = GetQuery().Select(v => new VehicleResult { ... });
if (includeContractorVehicles == true)
{
WorkerRepository rep = new WorkerRepository();
IQueryable<VehicleResult> contractorsVehicles = rep.GetWorkers().
Select(x => new VehicleResult()
{
Number = x.ContractorVehicleNumber
});
query = query.Union(contractorsVehicles);
}
return query;
}
</code></pre> |
6,599,071 | Array Like Objects in Javascript | <p>I'm wondering how jQuery constructs its array-like object. The key thing I'm trying to work out is how it manages to get the console to interpret it as an array and display it as such. I know it has something to do with the length property, but after playing a bit I can't quite figure it out. </p>
<p>I know this has no technical advantage over a normal array like object as in the example below. But I think it's an important semantic element when users are testing and debugging.</p>
<p>A normal Array like Object.</p>
<pre><code>function foo(){
// Array like objects have a length property and it's properties use integer
// based sequential key names, e.g. 0,1,2,3,4,5,6 just like an array.
this.length = 1;
this[0] = 'hello'
}
// Just to make sure add the length property to the prototype to match the Array
// prototype
foo.prototype.length = 0;
// Give the Array like object an Array method to test that it works
foo.prototype.push = Array.prototype.push
// Create an Array like object
var bar = new foo;
//test it
bar.push('world');
console.log(bar);
// outputs
{ 0: 'hello',
1: 'world',
length: 2,
__proto__: foo
}
</code></pre>
<p>Where as jQuery would output</p>
<pre><code>var jQArray = $('div')
console.log(jQArray);
// outputs
[<div></div>,<div></div>,<div></div>,<div></div>]
</code></pre>
<p>If you run </p>
<pre><code>console.dir(jQArray)
// Outputs
{ 0: HTMLDivElement,
1: HTMLDivElement,
2: HTMLDivElement,
3: HTMLDivElement,
4: HTMLDivElement,
context: HTMLDocument,
length: 5,
__proto__: Object[0]
}
</code></pre>
<p>The proto of the jQuery object is especially interesting since its the Object and not jQuery.fn.init as would be expected, also the [0] indicates something as this is what you get when you. </p>
<pre><code>console.dir([])
// outputs Array[0] as the object name or Array[x] x being the internal length of the
// Array
</code></pre>
<p>I have no idea how jQuery has set it's proto to be Object[0] but my guess is that answer lies somewhere in there. Anyone got any ideas?</p> | 6,599,447 | 2 | 2 | null | 2011-07-06 15:33:58.93 UTC | 22 | 2015-06-04 01:05:05.81 UTC | 2015-06-04 01:05:05.81 UTC | null | 707,111 | null | 710,556 | null | 1 | 32 | javascript|jquery|arrays|javascript-objects | 5,928 | <p>The object has to have <code>length</code> and <code>splice</code></p>
<pre><code>> var x = {length:2, '0':'foo', '1':'bar', splice:function(){}}
> console.log(x);
['foo', 'bar']
</code></pre>
<hr>
<p>and FYI, the <code>Object[0]</code> as the prototype is for exactly the same reason. The browser is seeing the prototype itself as an array because:</p>
<pre><code>$.prototype.length == 0;
$.prototype.splice == [].splice;
</code></pre> |
7,509,978 | How can I find out which button was clicked? | <p>I've got my buttons working right, and I'm a listener to each button like this:</p>
<pre><code>for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
</code></pre>
<p>Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that? </p>
<pre><code>ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
</code></pre>
<p>I need some way to find the button in the array.</p> | 7,510,013 | 4 | 1 | null | 2011-09-22 05:35:43.457 UTC | 6 | 2020-05-29 11:10:31.89 UTC | 2011-09-22 15:38:59.013 UTC | null | 261,156 | null | 230,453 | null | 1 | 14 | java|swing|button|actionlistener | 60,496 | <p>try this</p>
<pre class="lang-java prettyprint-override"><code>ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
</code></pre> |
1,439,102 | Improving soccer simulation algorithm | <p>In another question, you helped me to build a simulation algorithm for soccer. <a href="https://stackoverflow.com/questions/1427043/soccer-simulation-for-a-game">I got some very good answers there.</a> Thanks again!</p>
<p>Now I've coded this algorithm. I would like to improve it and find little mistakes which could be in it. I don't want to discuss how to solve it - as we did in the last question. Now I only want to improve it. Can you help me again please?</p>
<ol>
<li>Are there any mistakes?</li>
<li>Is the structure of the nested if-clauses ok? Could it be improved?</li>
<li>Are the tactics integrated correctly according to my description?</li>
</ol>
<p><strong>Tactical settings which should have an influence on the randomness:</strong></p>
<ul>
<li>$tactics[x][0] adjustment (1=defensive, 2=neutral, 3=offensive): the higher the value is the weaker is the defense and the stronger is the offense</li>
<li>$tactics<a href="https://stackoverflow.com/questions/1427043/soccer-simulation-for-a-game">x</a> speed of play (1=slow, 2=medium, 3=fast): the higher the value is the better are the opportunities but the higher is the risk of getting a quick counter attack</li>
<li>$tactics<a href="https://github.com/delight-im/Ballmanager" rel="nofollow noreferrer">x</a> distance of passes (1=short, 2=medium, 3=long): the higher the value is the less but better opportunities you get and the more often you are offside</li>
<li>$tactics<a href="https://github.com/delight-im/Ballmanager/blob/master/Website/aa_spieltag_simulation.php" rel="nofollow noreferrer">x</a> creation of changes (1=safe, 2=medium, 3=risky): the higher the value is the better are your opportunities but the higher is the risk of getting a quick counter attack</li>
<li>$tactics[x][4] pressure in defense (1=low, 2=medium, 3=high): the higher the value is the more quick counter attacks you will have</li>
<li>$tactics[x][5] aggressivity (1=low, 2=medium, 3=high): the higher the value is the more attacks you will stop by fouls</li>
</ul>
<p><strong>Note:</strong>
Tactic 0 and tactic 4 are partly integrated in the rest of the engine, not needed in this function.</p>
<p><strong>The current algorithm:</strong></p>
<pre><code><?php
function tactics_weight($wert) {
$neuerWert = $wert*0.1+0.8;
return $neuerWert;
}
function strengths_weight($wert) {
$neuerWert = log10($wert+1)+0.35;
return $neuerWert;
}
function Chance_Percent($chance, $universe = 100) {
$chance = abs(intval($chance));
$universe = abs(intval($universe));
if (mt_rand(1, $universe) <= $chance) {
return true;
}
return false;
}
function simulate_attack($teamname_att, $teamname_def, $strength_att, $strength_def) {
global $minute, $goals, $_POST, $matchReport, $fouls, $yellowCards, $redCards, $offsides, $shots, $tactics;
// input values: attacker's name, defender's name, attacker's strength array, defender's strength array
// players' strength values vary from 0.1 to 9.9
$matchReport .= '<p>'.$minute.'\': '.comment_action($teamname_att, 'attack');
$offense_strength = $strength_att['forwards']/$strength_def['defenders'];
$defense_strength = $strength_def['defenders']/$strength_att['forwards'];
if (Chance_Percent(50*$offense_strength*tactics_weight($tactics[$teamname_att][1])/tactics_weight($tactics[$teamname_att][2]))) {
// attacking team passes 1st third of opponent's field side
$matchReport .= ' '.comment_action($teamname_def, 'advance');
if (Chance_Percent(25*tactics_weight($tactics[$teamname_def][5]))) {
// the defending team fouls the attacking team
$fouls[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'foul');
if (Chance_Percent(43)) {
// yellow card for the defending team
$yellowCards[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'yellow');
}
elseif (Chance_Percent(3)) {
// red card for the defending team
$redCards[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'red');
}
// indirect free kick
$matchReport .= ' '.comment_action($teamname_att, 'iFreeKick');
if (Chance_Percent(25*strengths_weight($strength_att['forwards']))) {
// shot at the goal
$shots[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'iFreeKick_shot');
if (Chance_Percent(25/strengths_weight($strength_def['goalkeeper']))) {
// attacking team scores
$goals[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'shot_score');
}
else {
// defending goalkeeper saves
$matchReport .= ' '.comment_action($teamname_def, 'iFreeKick_shot_save');
}
}
else {
// defending team cleares the ball
$matchReport .= ' '.comment_action($teamname_def, 'iFreeKick_clear');
}
}
elseif (Chance_Percent(17)*tactics_weight($tactics[$teamname_att][2])) {
// attacking team is caught offside
$offsides[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_def, 'offside');
}
else {
// attack isn't interrupted
// attack passes the 2nd third of the opponent's field side - good chance
$matchReport .= ' '.comment_action($teamname_def, 'advance_further');
if (Chance_Percent(25*tactics_weight($tactics[$teamname_def][5]))) {
// the defending team fouls the attacking team
$fouls[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'foul');
if (Chance_Percent(43)) {
// yellow card for the defending team
$yellowCards[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'yellow');
}
elseif (Chance_Percent(3)) {
// red card for the defending team
$redCards[$teamname_def]++;
$matchReport .= ' '.comment_action($teamname_def, 'red');
}
if (Chance_Percent(19)) {
// penalty for the attacking team
$shots[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'penalty');
if (Chance_Percent(77)) {
// attacking team scores
$goals[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'shot_score');
}
elseif (Chance_Percent(50)) {
// shot misses the goal
$matchReport .= ' '.comment_action($teamname_att, 'penalty_miss');
}
else {
// defending goalkeeper saves
$matchReport .= ' '.comment_action($teamname_def, 'penalty_save');
}
}
else {
// direct free kick
$matchReport .= ' '.comment_action($teamname_att, 'dFreeKick');
if (Chance_Percent(33*strengths_weight($strength_att['forwards']))) {
// shot at the goal
$shots[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'dFreeKick_shot');
if (Chance_Percent(33/strengths_weight($strength_def['goalkeeper']))) {
// attacking team scores
$goals[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'shot_score');
}
else {
// defending goalkeeper saves
$matchReport .= ' '.comment_action($teamname_def, 'dFreeKick_shot_save');
}
}
else {
// defending team cleares the ball
$matchReport .= ' '.comment_action($teamname_def, 'dFreeKick_clear');
}
}
}
elseif (Chance_Percent(62*strengths_weight($strength_att['forwards'])*tactics_weight($tactics[$teamname_att][2])*tactics_weight($tactics[$teamname_att][3]))) {
// shot at the goal
$shots[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'shot');
if (Chance_Percent(30/strengths_weight($strength_def['goalkeeper']))) {
// the attacking team scores
$goals[$teamname_att]++;
$matchReport .= ' '.comment_action($teamname_att, 'shot_score');
}
else {
if (Chance_Percent(50)) {
// the defending defenders block the shot
$matchReport .= ' '.comment_action($teamname_def, 'shot_block');
}
else {
// the defending goalkeeper saves
$matchReport .= ' '.comment_action($teamname_def, 'shot_save');
}
}
}
else {
// attack is stopped
$matchReport .= ' '.comment_action($teamname_def, 'stopped');
if (Chance_Percent(15*$defense_strength*tactics_weight($tactics[$teamname_att][1])*tactics_weight($tactics[$teamname_att][3])*tactics_weight($tactics[$teamname_def][4]))) {
// quick counter attack - playing on the break
$strength_att['defenders'] = $strength_att['defenders']*0.8; // weaken the current attacking team's defense
$matchReport .= ' '.comment_action($teamname_def, 'quickCounterAttack');
$matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line
return simulate_attack($teamname_def, $teamname_att, $strength_def, $strength_att); // new attack - this one is finished
}
}
}
}
// attacking team doesn't pass 1st third of opponent's field side
elseif (Chance_Percent(15*$defense_strength*tactics_weight($tactics[$teamname_att][1])*tactics_weight($tactics[$teamname_att][3])*tactics_weight($tactics[$teamname_def][4]))) {
// attack is stopped
// quick counter attack - playing on the break
$matchReport .= ' '.comment_action($teamname_def, 'stopped');
$strength_att['defenders'] = $strength_att['defenders']*0.8; // weaken the current attacking team's defense
$matchReport .= ' '.comment_action($teamname_def, 'quickCounterAttack');
$matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line
return simulate_attack($teamname_def, $teamname_att, $strength_def, $strength_att); // new attack - this one is finished
}
else {
// ball goes into touch - out of the field
$matchReport .= ' '.comment_action($teamname_def, 'throwIn');
if (Chance_Percent(33)) {
// if a new chance is created
if (Chance_Percent(50)) {
// throw-in for the attacking team
$matchReport .= ' '.comment_action($teamname_def, 'throwIn_att');
$matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line
return simulate_attack($teamname_att, $teamname_def, $strength_att, $strength_def); // new attack - this one is finished
}
else {
// throw-in for the defending team
$matchReport .= ' '.comment_action($teamname_def, 'throwIn_def');
$matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line
return simulate_attack($teamname_def, $teamname_att, $strength_def, $strength_att); // new attack - this one is finished
}
}
}
$matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line
return TRUE; // finish the attack
}
</code></pre>
<p><strong>Update (2014):</strong> A few years later, I have now released the full code base of the game as <a href="https://github.com/delight-im/Ballmanager" rel="nofollow noreferrer">open-source on GitHub</a>. You'll find the specific implementation of this simulation <a href="https://github.com/delight-im/Ballmanager/blob/master/Website/aa_spieltag_simulation.php" rel="nofollow noreferrer">in this file</a>, if anyone is interested.</p> | 1,468,628 | 4 | 5 | null | 2009-09-17 14:04:12.09 UTC | 12 | 2014-07-10 03:17:10.79 UTC | 2017-05-23 11:45:28.967 UTC | null | -1 | null | 89,818 | null | 1 | 7 | php|simulation | 6,337 | <p>In general, it looks like this is a fairly complicated problem, and I'm not sure how efficient you'll get it.</p>
<p>That said, I have seen some things which would decidedly help you.</p>
<p>First I would type the variables in the parameters. This may not necessarily make your code faster, but it would make it easier to read and debug. Next, I would remove the $teamname_att, $teamname_def parameters and simply have those as values in the associative $strength_att, $strength_def arrays. Since this data is always paired up anyway, this will reduce the risk of accidentally using one team's name as a reference to the other team.</p>
<p>This will make it so you will not have to continually look up values in arrays:</p>
<pre><code>// replace all $tactics[$teamname_att] with $attackers
$attackers = $tactics[$teamname_att];
$defenders = $tactics[$teamname_def];
// Now do the same with arrays like $_POST[ "team1" ];
</code></pre>
<p>You have three helper functions which all have the pattern:</p>
<pre><code>function foo( $arg ){
$bar = $arg * $value;
return $bar;
}
</code></pre>
<p>Since this means that you have to create an extra variable (something which can be costly) each time you run the function, use these instead:</p>
<pre><code>function tactics_weight($wert) {
return $wert*0.1+0.8;
}
function strengths_weight($wert) {
return log10($wert+1)+0.35;
}
/*
Perhaps I missed it, but I never saw Chance_Percent( $num1, $num2 )
consider using this function instead: (one line instead of four, it also
functions more intuitively, Chance_Percent is your chance out of 100
(or per cent)
function Chance_Percent( $chance ) {
return (mt_rand(1, 100) <= $chance);
}
*/
function Chance_Percent($chance, $universe = 100) {
$chance = abs(intval($chance)); // Will you always have a number as $chance?
// consider using only abs( $chance ) here.
$universe = abs(intval($universe));
return (mt_rand(1, $universe) <= $chance);
}
</code></pre>
<p>I couldn't help but notice this pattern coming up consistently:</p>
<pre><code>$matchReport .= ' ' . comment_action($teamname_att, 'attack');
</code></pre>
<p>My general experience is that if you move the concatenation of $matchReport into comment_action, then it will be just <em>slightly</em> faster (Generally less than a dozen milliseconds, but since you're calling that function a half-dozen times inside of a recursive function, this could shave a couple tenths of a second per running).</p>
<p>I think that this would flow much better (both from a reader's perspective, and from </p>
<p>Finally, there are several times where you will use the same call to the same function with the same parameter. Make that call up front:</p>
<pre><code>$goalieStrength = strengths_weight($strength_def['goalkeeper']);
</code></pre>
<p>Hope this helps.</p> |
1,399,273 | Test if Convert.ChangeType will work between two types | <p>This is a follow-up to <a href="https://stackoverflow.com/questions/1398796/casting-with-reflection">this question</a> about converting values with reflection. Converting an object of a certain type to another type can be done like this:</p>
<pre><code>object convertedValue = Convert.ChangeType(value, targetType);
</code></pre>
<p>Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed? </p>
<p>E.g. can I write an extension method like this:</p>
<pre><code>public static class TypeExtensions
{
public static bool CanChangeType(this Type fromType, Type toType)
{
// what to put here?
}
}
</code></pre>
<p>EDIT: This is what I have right now. Ugly, but I don't see another way yet...</p>
<pre><code>bool CanChangeType(Type sourceType, Type targetType)
{
try
{
var instanceOfSourceType = Activator.CreateInstance(sourceType);
Convert.ChangeType(instanceOfSourceType, targetType);
return true; // OK, it can be converted
}
catch (Exception ex)
{
return false;
}
</code></pre> | 4,102,028 | 4 | 4 | null | 2009-09-09 12:04:18.757 UTC | 3 | 2019-04-01 15:40:49.64 UTC | 2017-05-23 12:34:29.413 UTC | null | -1 | null | 20,047 | null | 1 | 31 | c#|reflection | 23,544 | <p>I was just encountering this same issue, and I used Reflector to look at the source for ChangeType. ChangeType throws exceptions in 3 cases:</p>
<ol>
<li>conversionType is null</li>
<li>value is null</li>
<li>value does not implement IConvertible</li>
</ol>
<p>After those 3 are checked, it is guaranteed that it can be converted. So you can save a lot of performance and remove the try{}/catch{} block by simply checking those 3 things yourself:</p>
<pre><code>public static bool CanChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
return false;
}
if (value == null)
{
return false;
}
IConvertible convertible = value as IConvertible;
if (convertible == null)
{
return false;
}
return true;
}
</code></pre> |
1,727,682 | WCF Disable Deserialization Order Sensitivity | <p>I have a recurring problem when passing Serialized objects between non-.NET Clients, and .NET WCF Services. </p>
<p>When WCF Deserializes objects, it is strictly dependant upon the order of properties. </p>
<p>That is, if I define my class as: </p>
<pre><code>public class Foo
{
public int ID { get; set; }
public int Bar { get; set; }
}
</code></pre>
<p>Then WCF Will serialize the object as as: </p>
<pre><code><Foo>
<Bar>123</Bar>
<ID>456</ID>
</Foo>
</code></pre>
<p>Note: The properties are serialized in alphabetical order. </p>
<p>If you attempt to Deserialize an object which has the positions of <code>Bar</code> and <code>ID</code> swapped, WCF will treat the incorrectly positioned elements as null. </p>
<p>Whilst I know I can use the <code>DataMember</code> attribute, and force a specific ordering, I want to reduce the number of times I have to debug issues where fields are 'mysteriously' null. </p>
<p>So, my question is: Can you tell the WCF Deserializer to ignore the order of fields, when deserializing objects. </p> | 1,727,745 | 4 | 0 | null | 2009-11-13 07:24:35.587 UTC | 4 | 2020-07-02 08:51:42 UTC | null | null | null | user111013 | null | null | 1 | 31 | .net|wcf|serialization | 16,928 | <p>There's an old thread on this here:</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/a891928b-d27a-4ef2-83b3-ee407c6b9187" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/a891928b-d27a-4ef2-83b3-ee407c6b9187</a></p>
<p>Looks like the only option is to swap the serializer, but then it becomes opt in which is even more annoying. </p>
<p><strong>Edit:</strong> you could write your own serializer to re-order the elements and then pass it on to <code>DataContractSerializer</code>. </p> |
7,165,700 | Google Maps API for Android, getting SHA1 cert instead of MD5 | <p>When I try to get the MD5 fingerprint using <code>keytool</code>, I get a SHA1 fingerprint instead and the Google Maps doesn't recognize it. How do I get the MD5 fingerprint?</p> | 7,221,014 | 5 | 7 | null | 2011-08-23 18:19:29.93 UTC | 9 | 2021-04-11 08:45:59.827 UTC | 2021-04-11 08:45:59.827 UTC | null | 3,964,927 | null | 556,167 | null | 1 | 54 | android|google-maps|md5|sha1|fingerprint | 47,718 | <p>Use JDK version 1.6 instead of 1.7 because 1.7 generates the fingerprint with SHA1 by default.
or you can use (-v) option of the keytool to give you all supported algorithms output and you will find the MD5 in it. for examble : keytool -v -list -keystore [your keystore path] and then enter the password which is [android] by default (you can get the keystore path from Eclipse window>Prefs>Android>build).</p>
<p>Sincerely,
DigitalFox</p> |
13,813,046 | How is MVC supposed to work in CodeIgniter | <p>As a mostly self-taught programmer I'm late to the game when it comes to design patterns and such. I'm writing a labor management webapp using CodeIgniter.</p>
<p>I did a bit of MVC ASP.NET/C# and Java at school, and the convention was that your model mainly consisted of classes that represented actual objects, but also abstracted all the database connection and such...which is pretty standard MVC stuff from what I've gathered.</p>
<p>I imagine I'm right in saying that CI abstracts the database connection completely out of sight (unless you go looking), which is par for the course, and the models you can create can abstract the 'generic' CRUD methods a bit more to create some methods that are more useful for the specific model.</p>
<p>The thing I have a problem with, because it's different to what I'm used to with MVC, is that whenever you say...return a row from a database, the convention is to just put it in an associative array or standard object with the properties representing the data from the row.</p>
<p>In ASP you'd have actual classes that you could construct to store this information. For example you'd have a <code>House</code> class and the data would be stored as properties (e.g. <code>bedrooms</code>, <code>bathrooms</code>, <code>address</code>) and the methods would represent useful things you could do with the data (e.g. <code>printInfo()</code> may <code>print("$address has $bedrooms bedrooms and $bathrooms bathrooms!')</code>).</p>
<p>I'm getting the impression β just from code I've seen around the Internet β that this isn't the standard way of doing things. Are you supposed to just use arrays or generic objects, and say...do <code>$this->house_model->print_info($houseobject)</code> instead of <code>$houseobject->print_info();</code>?</p>
<p>Thanks.</p> | 13,821,880 | 3 | 0 | null | 2012-12-11 03:09:42.523 UTC | 13 | 2012-12-12 13:35:03.53 UTC | null | null | null | null | 729,785 | null | 1 | 10 | php|codeigniter|model-view-controller|web | 8,353 | <p>Despite its claims to the contrary, Codeigniter does not use MVC at all (In fact, very few web frameworks do!) it actually uses a PAC (Presentation-abstraction-control) architecture. Essentially, in PAC the presentation layer is fed data by a presenter (which CodeIgniter calls a controller) and in MVC the View gets its own data from the model. The confusion exists because of this mislabeling of MVC. </p>
<p>As such, CodeIgniter (and most of the other popular web frameworks) don't encourage a proper model but just use very rudimentary data access its place. This causes a large set of problems because of "fat controllers". None of the code which relates to the domain becomes reusable.</p>
<p>Further reading:</p>
<ul>
<li><p><a href="http://www.garfieldtech.com/blog/mvc-vs-pac" rel="noreferrer" title="MVC vs. PAC">MVC vs. PAC</a></p></li>
<li><p><a href="http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstood-and-unappreciated/" rel="noreferrer" title="The M in MVC: Why Models are Misunderstood and Unappreciated">The M in MVC: Why Models are Misunderstood and Unappreciated</a></p></li>
<li><p><a href="http://r.je/views-are-not-templates.html" rel="noreferrer" title="Model-View-Confusion: The View gets its own data from the Model">Model-View-Confusion part 1: The View gets its own data from the Model</a></p></li>
<li><a href="http://codebetter.com/iancooper/2008/12/03/the-fat-controller/" rel="noreferrer" title="The Fat Controller">The Fat Controller</a></li>
</ul>
<p>This is a widespread point of confusion in the PHP Community (The MVC vs. PAC article identifies the problem as stemming from the PHP community. that was written in 2006 and nothing has changed, if anything it's got worse because there are more frameworks and tutorials teaching an erroneous definition of MVC.) and why people looking at "MVC" PHP code who have come from a background outside web development understandably become confused. Most "MVC" implementations in PHP are not MVC. You are correct in thinking models should be properly structured, it's CodeIgniter that's wrong to label itself as MVC. </p> |
13,990,681 | PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View | <p>I am getting an <code>unexpected end of file</code> error on my CodeIgniter View.</p>
<p>I have pasted the PHP code at <a href="http://codepad.org/S12oXE4t" rel="nofollow noreferrer">http://codepad.org/S12oXE4t</a>.</p>
<p>This code passed various online PHP syntax tests, but I don't know why still it shows me the below error while I was trying to run in WAMP Server.</p>
<pre><code>Parse error: syntax error, unexpected end of file in
E:\wampserver\www\CodeIgniter\application\views\layouts\default.php on line 676
</code></pre>
<p>For reference, <code>line 676</code> is the last line in the code. What did I do wrong?</p> | 13,991,002 | 3 | 7 | null | 2012-12-21 12:59:12.88 UTC | 5 | 2018-02-28 00:54:31.31 UTC | 2018-02-28 00:16:41.08 UTC | null | 63,550 | null | 1,117,987 | null | 1 | 11 | php|codeigniter | 120,400 | <p>Check your <a href="http://fr.php.net/manual/en/ini.core.php#ini.short-open-tag" rel="noreferrer">short_open_tag</a> setting (use <code><?php phpinfo() ?></code> to see its current setting).</p> |
13,894,345 | How to position and align a matplotlib figure legend? | <p>I have a figure with two subplots as 2 rows and 1 column. I can add a nice looking figure legend with</p>
<pre><code>fig.legend((l1, l2), ['2011', '2012'], loc="lower center",
ncol=2, fancybox=True, shadow=True, prop={'size':'small'})
</code></pre>
<p>However, this legend is positioned at the center of the <strong>figure</strong> and not below the center of the <strong>axes</strong> as I would like to have it. Now, I can obtain my axes coordinates with </p>
<pre><code>axbox = ax[1].get_position()
</code></pre>
<p>and in theory I should be able to position the legend by specifying the <em>loc</em> keyword with a tuple:</p>
<pre><code>fig.legend(..., loc=(axbox.x0+0.5*axbox.width, axbox.y0-0.08), ...)
</code></pre>
<p>This works, <strong>except</strong> that the legend is left aligned so that <em>loc</em> specifies the left edge/corner of the legend box and not the center. I searched for keywords such as <em>align</em>, <em>horizontalalignment</em>, etc., but couldn't find any. I also tried to obtain the "legend position", but legend doesn't have a *get_position()* method. I read about *bbox_to_anchor* but cannot make sense of it when applied to a figure legend. This seems to be made for axes legends.</p>
<p>Or: should I use a shifted axes legend instead? But then, why are there figure legends in the first place? And somehow it must be possible to "center align" a figure legend, because <em>loc="lower center"</em> does it too.</p>
<p>Thanks for any help,</p>
<p>Martin</p> | 13,962,752 | 2 | 0 | null | 2012-12-15 17:11:37.887 UTC | 9 | 2020-04-04 10:12:28.037 UTC | null | null | null | null | 1,901,376 | null | 1 | 28 | python|matplotlib|legend | 63,567 | <p>In this case, you can either use axes for figure <code>legend</code> methods. In either case, <code>bbox_to_anchor</code> is the key. As you've already noticed <code>bbox_to_anchor</code> specifies a tuple of coordinates (or a box) to place the legend at. When you're using <code>bbox_to_anchor</code> think of the <code>location</code> kwarg as controlling the horizontal and vertical alignment. </p>
<p>The difference is just whether the tuple of coordinates is interpreted as axes or figure coordinates.</p>
<p>As an example of using a figure legend:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
x = np.linspace(0, np.pi, 100)
line1, = ax1.plot(x, np.cos(3*x), color='red')
line2, = ax2.plot(x, np.sin(4*x), color='green')
# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0.5
# in figure coordinates.
# "center" is basically saying center horizontal alignment and
# center vertical alignment in this case
fig.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5],
loc='center', ncol=2)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/fwCsW.png" alt="enter image description here"></p>
<p>As an example of using the axes method, try something like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
x = np.linspace(0, np.pi, 100)
line1, = ax1.plot(x, np.cos(3*x), color='red')
line2, = ax2.plot(x, np.sin(4*x), color='green')
# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0
# in axes coordinates.
# "upper center" is basically saying center horizontal alignment and
# top vertical alignment in this case
ax1.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0],
loc='upper center', ncol=2, borderaxespad=0.25)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/hekWn.png" alt="enter image description here"></p> |
14,245,227 | Python - reset stdout to normal, after previously redirecting it to a file | <p>At the beginning of my python program I have the following line:</p>
<pre><code>sys.stdout = open('stdout_file', 'w')
</code></pre>
<p>Halfway through my program I would like to set stdout back to the normal stdout. How do I do this?</p> | 14,245,252 | 4 | 1 | null | 2013-01-09 19:47:04.283 UTC | 9 | 2020-05-29 19:11:06.813 UTC | null | null | null | null | 1,701,170 | null | 1 | 28 | python|stdout | 18,915 | <p>The original <code>stdout</code> can be accessed as <code>sys.__stdout__</code>. This <a href="http://docs.python.org/2/library/sys.html#sys.__stdin__">is documented</a>.</p> |
14,343,893 | How do I reset my database state after each unit test without making the whole test a transaction? | <p>I'm using Spring 3.1.1.RELEASE, Hibernate 4.1.0.Final, JPA 2, JUnit 4.8.1, and HSQL 2.2.7. I want to run some JUnit tests on my service methods, and after each test, I would like any data written to the in-memory database to be rolled back. However, I do NOT want the entire test to be treated as a transaction. For example in this test</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class ContractServiceTest
{
β¦
@Autowired
private ContractService m_contractService;
@Test
public void testUpdateContract()
{
// Add the contract
m_contractService.save(m_contract);
Assert.assertNotNull(m_contract.getId());
// Update the activation date by 6 months.
final Calendar activationDate = Calendar.getInstance();
activationDate.setTime(activationDate.getTime());
activationDate.add(Calendar.MONTH, 6);
m_contract.setActivationDate(activationDate.getTime());
m_contractService.save(m_contract);
final List<Contract> foundContracts = m_contractService.findContractByOppId(m_contract.getOpportunityId());
Assert.assertEquals(foundContracts.get(0), m_contract);
} // testUpdateContract
</code></pre>
<p>there are three calls to the service, ("m_contractService.save", "m_contractService.save", and "m_contractService.findContractByOppId") and each is treated as a transaction, which I want. But I don't know how to reset my in-memory database to its original state after each unit test.</p>
<p>Let me know if I need to provide additional information. </p> | 14,349,589 | 7 | 3 | null | 2013-01-15 18:00:51.29 UTC | 3 | 2021-08-03 09:47:03.673 UTC | null | null | null | null | 1,235,929 | null | 1 | 39 | spring|junit|transactions|hsqldb | 51,226 | <p>Since you are using Hibernate, you could use the property <code>hibernate.hbm2ddl.auto</code> to create the database on startup every time. You would also need to force the spring context to be reloaded after each test. You can do this with the <code>@DirtiesContext</code> annotation.</p>
<p>This might add a bit extra overhead to your tests, so the other solution is to just manually delete the data from each table.</p> |
43,352,501 | CSS grid: content to use free space but scroll when bigger | <p>I've been working with <a href="https://www.w3.org/TR/css3-grid-layout/" rel="noreferrer">CSS Grid Layouts</a> for the first time and they're awesome. Right now, however, I'm having trouble keeping one of my grid cells under control.</p>
<p>What I want is to have an element that takes up the existing free space and <em>no more</em>, scrolling when the content gets too big. My understanding is that a grid size of <code>1fr</code> takes up a uniform amount of the available space after everything else is calculated. I've tried various sizes such as <code>minmax(auto, 1fr)</code> but to no avail - <code>1fr</code> seems to expand to fit the content which is not what I want. Setting a maximum size size like <code>100px</code> is also no good because I want the size to be determined by other elements in the grid.</p>
<p>Here's the example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 1fr 1fr;
}
.container>div {
border: 1px solid blue;
border-radius: 5px;
}
.left {
grid-column: 1;
grid-row: 1/4;
}
.header {
grid-column: 2;
grid-row: 1;
}
.problem-child {
grid-column: 2;
grid-row: 2;
overflow-y: scroll;
}
.footer {
grid-column: 2;
grid-row: 3;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="left">left<br>I don't want this one to scroll<br>this should<br>determine<br>the height of the whole grid container</div>
<div class="header">column header</div>
<div class="problem-child">problem child:<br>I<br>want<br>this<br>to<br>scroll<br>rather<br>than<br>making<br>everything<br>tall</div>
<div class="footer">column footer</div>
</div></code></pre>
</div>
</div>
</p>
<p>What grid declaration (if any) can I use to let the "problem child" scroll on overflow rather than expanding?</p> | 43,352,777 | 4 | 1 | null | 2017-04-11 17:23:27.06 UTC | 10 | 2019-05-07 12:05:06.243 UTC | 2017-04-11 17:37:33.053 UTC | null | 1,701,416 | null | 1,701,416 | null | 1 | 26 | css|styling|grid-layout|css-grid | 30,170 | <p>You can use <code>max-height:100%;</code> and also <code>min-height</code> to leave enough heights to show a proper scrollbar.<strong><em>(firefox will do, chrome will not at this time)</em></strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: grid;
grid-template-rows: auto minmax(1fr, 25vh) auto;
grid-template-columns: 1fr 1fr;
}
.container>div {
border: 1px solid blue;
border-radius: 5px;
}
.left {
grid-column: 1;
grid-row: 1/4;
}
.header {
grid-column: 2;
grid-row: 1;
}
.problem-child {
grid-column: 2;
grid-row: 2;
min-height:4em;
max-height:100%;
overflow-y: auto;
}
.footer {
grid-column: 2;
grid-row: 3;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="left">left<br>I don't want this one to scroll<br>this should<br>determine<br>the height of the whole grid container</div>
<div class="header">column header</div>
<div class="problem-child">problem child:<br>I<br>want<br>this<br>to<br>scroll<br>rather<br>than<br>making<br>everything<br>tall</div>
<div class="footer">column footer</div>
</div></code></pre>
</div>
</div>
</p>
<hr>
<p>As a work around, you can also use an extra wrapper in <code>absolute</code> position to take it off the flow and size it to the row's height: <em>(both cases require a min-height to show properly the scrollbar when needed)</em></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 1fr 1fr;
}
.container>div {
border: 1px solid blue;
border-radius: 5px;
}
.left {
grid-column: 1;
grid-row: 1/4;
}
.header {
grid-column: 2;
grid-row: 1;
}
.problem-child {
grid-column: 2;
grid-row: 2;
position:relative;
min-height:4em;
}
.problem-child >div {
position:absolute;
top:0;
left:0;
right:0;
max-height:100%;
overflow:auto ;
}
.footer {
grid-column: 2;
grid-row: 3;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="left">left<br>I don't want this one to scroll<br>this should<br>determine<br>the height of the whole grid container</div>
<div class="header">column header</div>
<div class="problem-child">
<div>problem child:<br>I<br>want<br>this<br>to<br>scroll<br>rather<br>than<br>making<br>everything<br>tall</div>
</div>
<div class="footer">column footer</div>
</div></code></pre>
</div>
</div>
</p> |
9,404,683 | How to get the length of row/column of multidimensional array in C#? | <p>How do I get the length of a row or column of a multidimensional array in C#?</p>
<p>for example:</p>
<pre><code>int[,] matrix = new int[2,3];
matrix.rowLength = 2;
matrix.colLength = 3;
</code></pre> | 9,404,722 | 5 | 1 | null | 2012-02-22 23:08:15.487 UTC | 13 | 2022-09-03 19:15:23.327 UTC | 2019-08-13 19:45:09.88 UTC | null | 2,543,778 | null | 1,036,286 | null | 1 | 86 | c#|arrays|multidimensional-array | 112,169 | <pre><code>matrix.GetLength(0) -> Gets the first dimension size
matrix.GetLength(1) -> Gets the second dimension size
</code></pre> |
62,707,558 | ImportError: cannot import name 'adam' from 'keras.optimizers' | <p>I am trying to import Keras but I get the following error:</p>
<pre><code>ImportError: cannot import name 'adam' from 'keras.optimizers' (/usr/local/lib/python3.8/dist-packages/keras/optimizers/__init__.py)
</code></pre>
<p>The import is invoked here:</p>
<pre><code>from tensorflow import keras
from keras.layers import Conv2D, Input, MaxPool2D,Flatten, Dense, Permute, GlobalAveragePooling2D
from keras.models import Model
from keras.optimizers import adam
import numpy as np
import pickle
import keras
import cv2
import sys
import dlib
import os.path
from keras.models import Sequential
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import Dense
from keras.optimizers import Adam
import pickle
import numpy as np
import cv2
import os
from keras.layers import Dropout
</code></pre>
<p>I am sure Keras is installed along with Tensorflow:</p>
<pre><code>python3 -c 'import keras; print(keras.__version__)' // 2.4.3
</code></pre> | 68,418,955 | 9 | 1 | null | 2020-07-03 02:19:46.993 UTC | 10 | 2022-09-16 21:28:31.19 UTC | null | null | null | null | 11,356,638 | null | 1 | 62 | keras | 174,080 | <p>There are two types of modules -</p>
<ol>
<li>keras</li>
<li>tensorflow.keras</li>
</ol>
<p>Here we need to use tensorflow.keras</p>
<p>You need to import Adam (With Capital A) from tensorflow - Keras ( Not only Keras).</p>
<pre><code>from tensorflow.keras.optimizers import Adam
from tensorflow.keras.optimizers import Adam # - Works
from tensorflow.keras.optimizers import adam # - Does not work
from keras.optimizers import Adam # - Does not work
from keras.optimizers import adam # - Does not work
</code></pre> |
49,513,356 | Error running 'app': Unknown error in Android studio 3.1 | <p>I have updated my android studio to new stable <strong>version 3.1</strong>.
After build project not able to run.</p>
<p>Let me know if anyone have face same issue or find any solution.</p>
<p><a href="https://i.stack.imgur.com/QDqd5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QDqd5.png" alt="My event log show this error"></a></p> | 49,521,030 | 6 | 10 | null | 2018-03-27 12:51:18.103 UTC | 6 | 2020-07-18 20:02:58.643 UTC | 2018-03-30 14:09:37.163 UTC | null | 1,000,551 | null | 2,553,048 | null | 1 | 32 | android|android-studio|android-studio-3.1 | 11,379 | <p>Just go to "<strong>Run/edit configurations...</strong>/" and scroll down to bottom of the window and here you see an option "<strong>Before launch...</strong>"
First, remove whatever already inside the little window and then click on (<strong>+</strong>) icon and select <strong>"Gradle-aware Make</strong>" and then type "<strong>assembleDebug</strong>" and select the first option or that you need. This will solve your problem.</p> |
66,670,334 | Mono.Linker.MarkException: Error processing method: 'System.Void AndroidX.RecyclerView.Widget.RecyclerView/LayoutManager | <p>I am trying to debug my Xamarin project. Framework and all packages are up to date. In iOS it works, but in Android NOT. How can I solve this problem:</p>
<pre><code>Mono.Linker.MarkException: Error processing method: 'System.Void AndroidX.RecyclerView.Widget.RecyclerView/LayoutManager::n_OnInitializeAccessibilityNodeInfo_Landroidx_recyclerview_widget_RecyclerView_Recycler_Landroidx_recyclerview_widget_RecyclerView_State_Landroidx_core_view_accessibility_AccessibilityNodeInfoCompat_(System.IntPtr,System.IntPtr,System.IntPtr,System.IntPtr,System.IntPtr)' in assembly: 'Xamarin.AndroidX.RecyclerView.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve AndroidX.Core.View.Accessibiity.AccessibilityNodeInfoCompat
at Mono.Linker.Steps.MarkStep.HandleUnresolvedType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
at MonoDroid.Tuner.MonoDroidMarkStep.MarkType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
at Mono.Linker.Steps.MarkStep.Process()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at MonoDroid.Tuner.MonoDroidMarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
at Mono.Linker.Pipeline.Process(LinkContext context)
at MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
at Xamarin.Android.Tasks.LinkAssemblies.RunTask()
at Xamarin.Android.Tasks.AndroidTask.Execute()
</code></pre> | 66,689,618 | 9 | 1 | null | 2021-03-17 09:31:57.687 UTC | 1 | 2022-08-29 01:54:55.1 UTC | null | null | null | null | 13,790,813 | null | 1 | 35 | android|xamarin|android-recyclerview|xamarin.android|mono | 9,632 | <p>I encountered this same problem after updating Visual Studio to 16.9.2 and updating the Android SDK.</p>
<p>The simple solution was to update the '<strong>Xamarin.AndroidX.RecyclerView</strong>' Nuget package in the package manager. I Updated to the latest version (v1.1.0.8).</p> |
44,487,492 | Laravel 5.4 blade foreach loop | <p>I am building a venue manangement system, and on the landing page, i m trying to show all the available slots to the visitors. The ones that have already been booked are shown as not available. I have created two variables, one that carries the info from the time table and the other from the booking table and tyring to use blade to compare and show.
This is how I am trying to implement it in blade:</p>
<pre><code>@foreach($times as $time)
@foreach($bookings as $booking)
<tr>
@if($time->availble_times == $booking->booking_time)
<td>{{$time->availble_times}}: not available</td>
@else
<tr><td>{{$time->availble_times}}</td>
@endif
</tr>
@endforeach
@endforeach
</code></pre>
<p>But what this does instead is show all the times for as many records in the bookings table. Like if there are two rows in the bookings table, it shows the times twice, and so on. Just in case, here is my controller function:</p>
<pre><code> public function times(){
$times = Times::all();
$bookings = Bookings::all();
return view('/test2')->with('times', $times)->with('bookings', $bookings);
}
</code></pre>
<p>I recently started doing Laravel and cannot figure out this issue. My question is, how can i fix the n-times display issue and show the user which times are booked and which are available?</p> | 44,488,450 | 1 | 3 | null | 2017-06-11 18:48:40.66 UTC | 1 | 2017-06-11 20:27:49.79 UTC | 2017-06-11 19:05:25.877 UTC | null | 7,437,058 | null | 5,354,413 | null | 1 | 10 | php|laravel-5|laravel-5.4|laravel-blade | 65,152 | <p>I don't know how your data looks, but by looking at your code columns <code>availble_times</code> and <code>booking_time</code> are date fields. If Times model is dictionary for hours (like 1. 8.00, 2. 8:45, 3. 9:00) , and booking hour has to be in Times records, then you just need to invert the loops to display each time for each booking</p>
<pre><code>@foreach($bookings as $booking)
@foreach($times as $time)
<tr>
<td>{{ getImaginedChairNumber() }}</td>
<td>{{ $time->availble_times }}</td>
@if($time->availble_times == $booking->booking_time)
{{-- There is already booking for that dictionary time --}}
<td>not available</td>
@else
<td>available</td>
@endif
</tr>
@endforeach
@endforeach
</code></pre>
<p>Should produce similar table:</p>
<pre><code>βββββββββ¦βββββββ¦ββββββββββββββββ
β Chair β Time β Booking β
β ββββββββ¬βββββββ¬ββββββββββββββββ£
β A1 β 8:00 β not available β
β A1 β 8:45 β available β
β A1 β 9:00 β not available β
β A2 β 8:00 β not available β
β A2 β 8:45 β not available β
β A2 β 9:00 β not available β
β A3 β 8:00 β available β
β A3 β 8:45 β available β
β A3 β 9:00 β not available β
βββββββββ©βββββββ©ββββββββββββββββ
</code></pre>
<p>Is this the correct form of the output table you expect?
(I used this tool to draw ascii table <a href="https://senseful.github.io/web-tools/text-table/" rel="noreferrer">https://senseful.github.io/web-tools/text-table/</a>)</p> |
52,235,847 | How do I push items into an array in the data object in Vuejs? Vue seems not to be watching the .push() method | <p>I am attempting to add objects into an array I declared in Vue instance data object. I can set the values in the state's purchase object, but when I push data into the orders queue array, the empty array is not populated. The function is being triggered, but the array does not update.</p>
<p>Here is my form:</p>
<pre><code><form
v-on:submit.prevent="queuePurchase"
class="form-inline row"
id="order-creation-form"
method="POST"
>
@csrf
<autocomplete-field
sizing="col-xs-12 col-sm-3 col-md-3"
name="customer"
label="Customer"
:data="{{ json_encode($customers) }}"
v-on:setcustomer="setCustomer($event)"
></autocomplete-field>
<div class="col-xs-12 col-sm-3 col-md3 form-group d-flex flex-column align-items-start">
<label for="phone">Product</label>
<select
v-model="purchase.product"
class="form-control w-100"
name="product"
aria-describedby="productHelpBlock"
required
>
@foreach ($products as $product)
<option :value="{{ json_encode($product) }}">
{{ $product->name }}
</option>
@endforeach
</select>
<small id="productHelpBlock" class="form-text text-muted">
Select a product
</small>
</div>
<div class="col-xs-12 col-sm-3 col-md-3 form-group d-flex flex-column align-items-start">
<label for="phone">Quantity</label>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
class="form-control w-100"
aria-describedby="productHelpBlock"
required
>
<small id="productHelpBlock" class="form-text text-muted">
Product quantity
</small>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success icon-button d-flex">
<i class="material-icons">add</i>
<span>&nbsp;&nbsp; Q U E U E</span>
</button>
</div>
</form>
</code></pre>
<p>And here is my javascript:</p>
<pre><code>require("./bootstrap");
window.Vue = require("vue");
Vue.component("queue-table", require('./components/QueueTable.vue'));
Vue.component("autocomplete-field", require('./components/AutocompleteField.vue'));
const purchaseApp = new Vue({
el: "#purchase-app",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
}
},
methods: {
setCustomer: function(customerObj) {
this.purchase.customer = customerObj;
},
queuePurchase: function() {
this.queue.push( this.purchase );
}
}
});
</code></pre>
<p>Could someone please explain what & why it is happening?</p> | 52,239,532 | 1 | 5 | null | 2018-09-08 13:33:44.997 UTC | 4 | 2018-09-08 21:52:54.487 UTC | 2018-09-08 21:52:54.487 UTC | null | 3,367,343 | user4998157 | null | null | 1 | 13 | javascript|laravel-5|vue.js|vuejs2|vue-reactivity | 78,765 | <p>The <code>push()</code> method ought to add <code>purchase</code> objects to the <code>queue</code> array, but as @FK82 pointed out in his comment, <code>push()</code> is adding multiple references to the same <code>purchase</code> object. This means that if you change the object by increasing the <code>quantity</code>, every <code>purchase</code>'s <code>quantity</code> property will be updated.</p>
<p>You can give that a try here:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const exampleComponent = Vue.component("example-component", {
name: "exampleComponent",
template: "#example-component",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
};
},
methods: {
queuePurchase() {
this.queue.push( this.purchase );
}
}
});
const page = new Vue({
name: "page",
el: ".page",
components: {
"example-component": exampleComponent
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
<div>
<p>The Queue has {{ this.queue.length }} items.</p>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
placeholder="Quantity"
>
<button @click="queuePurchase">
Add to Queue
</button>
<pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
</div>
</template>
<div class="page">
<example-component></example-component>
</div></code></pre>
</div>
</div>
</p>
<p>Instead of <code>push()</code>ing a reference to the same <code>purchase</code> object, try creating a shallow copy with <code>Object.assign({}, this.purchase)</code> or by using the spread operator. Here's an example that uses the spread operator and then <code>push()</code>es the copy onto the <code>queue</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const exampleComponent = Vue.component("example-component", {
name: "exampleComponent",
template: "#example-component",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
};
},
methods: {
queuePurchase() {
this.queue.push({...this.purchase});
}
}
});
const page = new Vue({
name: "page",
el: ".page",
components: {
"example-component": exampleComponent
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
<div>
<p>The Queue has {{ this.queue.length }} items.</p>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
placeholder="Quantity"
>
<button @click="queuePurchase">
Add to Queue
</button>
<pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
</div>
</template>
<div class="page">
<example-component></example-component>
</div></code></pre>
</div>
</div>
</p> |
1,312,825 | Web Service vs. Shared Library | <p>This question has been asked a few times on SO from what I found:</p>
<p><a href="https://stackoverflow.com/questions/204653/when-should-a-web-service-not-be-used">When should a web service not be used?</a>
<a href="https://stackoverflow.com/questions/299260/web-service-or-dll">Web Service or DLL?</a></p>
<p>The answers helped but they were both a little pointed to a particular scenario. I wanted to get a more general thought on this.</p>
<p>When should a Web Service be considered over a Shared Library (DLL) and vice versa?</p> | 1,312,836 | 5 | 2 | null | 2009-08-21 15:57:37.667 UTC | 9 | 2019-05-16 22:20:02.127 UTC | 2017-05-23 12:01:22.063 UTC | null | -1 | null | 149,053 | null | 1 | 16 | web-services | 9,647 | <p>My thought on this:</p>
<p>A Web Service was designed for machine interop and to reach an audience
easily by using HTTP as the means of transport. </p>
<p>A strong point is that by publishing the service you are also opening the use of the
service to an audience that is potentially vast (over the web or at least throughout the
entire company) and/or largely outside of your control / influence / communication channel
and you don't mind or this is desired. The usage of the service is much easier as clients
simply have to have an internet connection and consume the service. Unlike a library which
may not be so easily done (but can be done). The usage of the service is largely open. You are making it available to whomever feels they could use it and however they feel to use it.</p>
<p>However, a web service is in general slower and is dependent on an internet connection.<br>
It's in general harder to test than a code library.<br>
It may be harder to maintain. Much of that depends on your maintainance and coding practices.</p>
<p>I would consider a web service if several of the above features are desired or at least one of them
is considered paramount and the downsides were acceptable or a necessary evil. </p>
<p>What about a Shared Library?</p>
<p>What if you are far more in "control" of your environment or want to be? You know who will be using the code
(interface isn't a problem to maintain), you don't have to worry about interop. You are in a situation where
you can easily achieve sharing without a lot of work / hoops to jump through.</p>
<p>Examples in my mind of when to use:</p>
<p>You have many applications in your control all hosted on the same server or two that will use the library. </p>
<p>Not so good example, you have many applications but all hosted on a dozen or so servers. Web Service may be a better choice.</p>
<p>You are not sure who or how your code could be used but know it is of good value to many. Web Service.</p>
<p>You are writing something only used by a limited set of applications, perhaps some helper functions. Library. </p>
<p>You are writing something highly specialized and is not suited for consumption by many. Such as an API for your Line of Business
Application that no one else will ever use. Library.</p>
<p>If all things being equal, it would be easier to start with a shared library and turn it into a web service but not so much vice versa.</p>
<p>There are many more but these are some of my thoughts on it...</p> |
1,242,766 | Uses of 'for' in Java | <p>I am fairly new to Java and in another Stack Overflow question about <a href="https://stackoverflow.com/questions/1241946/how-is-a-for-loop-structured-in-java">for loops</a> an answer said that there was two uses of for in Java:</p>
<pre><code>for (int i = 0; i < N; i++) {
}
for (String a : anyIterable) {
}
</code></pre>
<p>I know the first use of for and have used it a lot, but I have never seen the second one. What is it used to do and when would I use it? </p> | 1,242,771 | 5 | 0 | null | 2009-08-07 03:38:12.627 UTC | 8 | 2017-07-01 08:14:09.173 UTC | 2017-05-23 11:46:25.623 UTC | null | -1 | null | 99,135 | null | 1 | 26 | java|loops|for-loop | 81,255 | <p>The first of the two you specify is a classic C <code>for</code> loop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example:</p>
<pre><code>for (int i=0; i < N : i++)
</code></pre>
<p>There are many more instances in code where the <code>for</code> was use to iterate over collections: </p>
<pre><code>for (Iterator iter = myList.iterator(); iter.hasNext();)
</code></pre>
<p>To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the <a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf" rel="noreferrer">Generics</a> introduced in Java 1.5, the second of your two examples - the enhanced for loop, or the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="noreferrer"><code>for-each loop</code></a> - was introduced. </p>
<p>The second is used with arrays and Generic collections. <a href="http://java.sun.com/developer/JDCTechTips/2005/tt0505.html#2" rel="noreferrer">See this documentation</a>. It allows you to iterate over a generic collection, where you know the type of the <code>Collection</code>, without having to cast the result of the <code>Iterator.next()</code> to a known type.</p>
<p>Compare:</p>
<pre><code>for(Iterator iter = myList.iterator; iter.hasNext() ; ) {
String myStr = (String) iter.next();
//...do something with myStr
}
</code></pre>
<p>with </p>
<pre><code>for (String myStr : myList) {
//...do something with myStr
}
</code></pre>
<p>This 'new style' for loop can be used with arrays as well:</p>
<pre><code>String[] strArray= ...
for (String myStr : strArray) {
//...do something with myStr
}
</code></pre> |
567,879 | How can I process command line arguments in Python? | <p>What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?</p>
<p>I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:</p>
<pre><code>if 'debug' in argv[1:]:
print 'Will be running in debug mode.'
</code></pre>
<p>How to find out if 009 or 575 was passed?</p>
<p>All those are expected calls:</p>
<pre><code>python script.py
python script.py 011
python script.py 256 debug
python script.py 391 xls
python script.py 999 debug pdf
</code></pre>
<p>At this point I don't care about calls like that:</p>
<pre><code>python script.py 001 002 245 568
python script.py some unexpected argument
python script.py 0001
python script.py 02
</code></pre>
<p>...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.</p> | 567,923 | 5 | 1 | null | 2009-02-20 00:41:02.203 UTC | 11 | 2010-04-24 17:26:05.173 UTC | 2010-04-24 17:26:05.173 UTC | Barry Wark | 56,285 | null | 63,503 | null | 1 | 30 | python|command-line|command-line-arguments | 55,851 | <p>As others answered, optparse is the best option, but if you just want quick code try something like this:</p>
<pre><code>import sys, re
first_re = re.compile(r'^\d{3}$')
if len(sys.argv) > 1:
if first_re.match(sys.argv[1]):
print "Primary argument is : ", sys.argv[1]
else:
raise ValueError("First argument should be ...")
args = sys.argv[2:]
else:
args = ()
# ... anywhere in code ...
if 'debug' in args:
print 'debug flag'
if 'xls' in args:
print 'xls flag'
</code></pre>
<p><strong>EDIT</strong>: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.</p>
<p>The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.</p>
<p>So here's an example using optparse:</p>
<pre><code>import sys, re, optparse
first_re = re.compile(r'^\d{3}$')
parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()
if len(args) == 1:
if first_re.match(args[0]):
print "Primary argument is : ", args[0]
else:
raise ValueError("First argument should be ...")
elif len(args) > 1:
raise ValueError("Too many command line arguments")
if options.debug:
print 'debug flag'
if options.xls:
print 'xls flag'
</code></pre>
<p>The differences here with optparse and your spec is that now you can have command lines like:</p>
<pre><code>python script.py --debug --xls 001
</code></pre>
<p>and you can easily add new options by calling parser.add_option()</p> |
594,019 | How do I access query string parameters in asp.net mvc? | <p>I want to have different sorting and filtering applied on my view
I figured that I'll be passing sorting and filtering <em>params</em> through query string:</p>
<pre><code>@Html.ActionLink("Name", "Index", new { SortBy= "Name"})
</code></pre>
<p>This simple construction allows me to sort. View comes back with this in query string:</p>
<pre><code>?SortBy=Name
</code></pre>
<p>Now I want to add filtering and i want my query string to end up with </p>
<pre><code>?SortBy=Name&Filter=Something
</code></pre>
<p>How can I add another parameter to list of already existing ones in <code>ActionLink</code>? for Example:</p>
<pre><code>user requests /Index/
</code></pre>
<p>view has </p>
<pre><code> @Html.ActionLink("Name", "Index", new { SortBy= "Name"})
</code></pre>
<p>and </p>
<pre><code> @Html.ActionLink("Name", "Index", new { FilterBy= "Name"})
</code></pre>
<p><strong>Links</strong>: The first one looks like <code>/Index/?SortBy=Name</code> and The second is <code>/Index/?FilterBy=Name</code></p>
<p>I want when user pressed sorting link after he applied some filtering - filtering is not lost, so i need a way to combine my params.
My guess is there should be a way to not parse query string, but get collection of parameters from some MVC object.</p> | 594,501 | 5 | 2 | null | 2009-02-27 08:53:09.093 UTC | 17 | 2016-12-09 20:29:38.657 UTC | 2016-12-09 20:29:38.657 UTC | Alexander Taran | 35,954 | Alexander Taran | 35,954 | null | 1 | 39 | asp.net-mvc|query-string | 67,463 | <p>so far the best way I figured out is to create a copy of <code>ViewContext.RouteData.Values</code>
and inject QueryString values into it.
and then modify it before every <code>ActionLink</code> usage.
still trying to figure out how to use <code>.Union()</code> instead of modifying a dictionary all the time.</p>
<pre><code><% RouteValueDictionary tRVD = new RouteValueDictionary(ViewContext.RouteData.Values); %>
<% foreach (string key in Request.QueryString.Keys )
{
tRVD[key]=Request.QueryString[key].ToString();
} %>
<%tRVD["SortBy"] = "Name"; %>
<%= Html.ActionLink("Name", "Index", tRVD)%>
</code></pre> |
13,241,738 | Browser is showing PHP code instead of processing it | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-i-can-see-it-on-source-code-of-page">PHP code is not being executed (i can see it on source code of page)</a><br>
<a href="https://stackoverflow.com/questions/6932913/web-browser-not-processing-php-code-as-php-code">web browser not processing PHP code as PHP code</a> </p>
</blockquote>
<p>I have installed XAMPP on my computer which is Windows 8 pro. I use to work with Windows 7
every time I run the <em><code>index.php</code></em> file on Windows 8 it shows the code on the browser IE10.</p>
<p>Here is what I have done:</p>
<ol>
<li>I have named the file correctly: <em><code>index.php</code></em></li>
<li>I have installed the server and saved the files inside <em><code>c:/xampp/htdocs/PHP/</code></em></li>
<li>I have used <code><?php ?></code> to open and close all PHP tags
and everything else seems working fine, like, PHPMyAdmin, and the php.ini file </li>
</ol>
<p>I don't know whats wrong and it is driving me crazy ...</p>
<p>Farris</p> | 13,241,849 | 1 | 7 | null | 2012-11-05 22:57:02.927 UTC | 0 | 2012-11-05 23:06:58.153 UTC | 2017-05-23 12:25:36.507 UTC | null | -1 | null | 1,131,888 | null | 1 | 5 | php|xampp | 50,511 | <p>The problem is you're not parsing the file via the web server, but accessing it directly.</p>
<p>you need to use the url:</p>
<pre><code>http://localhost/index.php
</code></pre>
<p>or maybe (based on your path above) its </p>
<pre><code>http://localhost/PHP/index.php
</code></pre>
<p>in the browser</p> |
44,124,537 | Set cache to files in Firebase Storage | <p>I have a <a href="https://discipulado-7b14b.firebaseapp.com/" rel="noreferrer">PWA</a> running on Firebase. My image files are hosted on the Firebase Storage. I've noticed my browser doesn't save cache for files loaded from the storage system. The browser requests the files for every page refresh. It causes unnecessary delay and traffic.</p>
<p><a href="https://i.stack.imgur.com/bDKBX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bDKBX.jpg" alt="Network stats"></a></p>
<p>My JS script loads the files from the Firebase Storage's download link, example: <a href="https://firebasestorage.googleapis.com/v0/b/discipulado-7b14b.appspot.com/o/book3.png?alt=media&token=65b2cde7-c8a4-45da-a743-401759663c17" rel="noreferrer">https://firebasestorage.googleapis.com/v0/b/discipulado-7b14b.appspot.com/o/book3.png?alt=media&token=65b2cde7-c8a4-45da-a743-401759663c17</a>.</p>
<p>Can I cache those requests?</p>
<p><strong>UPDATE</strong></p>
<p>According to these <a href="https://stackoverflow.com/a/38121038/2684718">answer</a> I shouldn't use Firebase Storage to host files from my site. Just to manage downloads and uploads from users. Is this correct?</p> | 44,124,704 | 6 | 2 | null | 2017-05-23 01:49:17.043 UTC | 2 | 2021-05-01 14:11:01.837 UTC | 2017-05-23 02:03:32.467 UTC | null | 2,684,718 | null | 2,684,718 | null | 1 | 31 | javascript|json|caching|firebase|firebase-storage | 17,795 | <p><code>cacheControl</code> for Storage : <a href="https://firebase.google.com/docs/reference/js/firebase.storage.SettableMetadata#cacheControl" rel="noreferrer">https://firebase.google.com/docs/reference/js/firebase.storage.SettableMetadata#cacheControl</a></p>
<hr>
<p>You'll have better serving with Hosting, and deployment with the firebase CLI is extremely simple. I think by default the Cache-Control on images in Hosting is 2 hours, and you can increase it globally with the .json.</p>
<p><a href="https://firebase.google.com/docs/hosting/full-config#headers" rel="noreferrer">https://firebase.google.com/docs/hosting/full-config#headers</a></p>
<p>Hosting can scale your site and move it to different edge nodes closer to where the demand is. Storage is limited to buckets, but you can specify a bucket for Europe, one for China, on for North America, etc..</p>
<p>Storage is better for user file uploads and Hosting was for static content (although they are rolling out dynamic Hosting with cloud functions I think)</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.