qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
6,813,490 | I used multiple model from in rails, it fails to work properly in a sinario
```
<%= form_for [@listing] do |f| %>
<%= f.fields_for :photos do |ph| %>
<%= ph.file_field :data %>
<% end %>
<% end %>
```
while validation,i didn't upload a image(image is optional one) and submit the form. if the first model has any error then the form shows error message, at the time the form fails to show the input field of second form(<%= ph.file\_field :data %>) | 2011/07/25 | [
"https://Stackoverflow.com/questions/6813490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859428/"
] | Because you pass an array of unknown size which is equivalent to a pointer in this context. `sizeof` is calculated at **compile** time, not runtime. | Arrays as function arguments *do* decay to pointer, though. Since this happens before sizeof() is called, you can't prevent it.
Just think about it: how can sizeof() know the size of an array if any size array can be passed and no extra info is available? You get sizeof(pointer), and that seems to be the same size as an int, in your setup. |
212,429 | Scenario:
I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects.
I've used reflection to create the appropriate type at run time before I make the call to the web service like so:
```
public static object[] CreateProperties(Type type, IProperty[] properties)
{
//Empty so return null
if (properties==null || properties.Length == 0)
return null;
//Check the type is allowed
CheckPropertyTypes("CreateProperties(Type,IProperty[])",type);
//Convert the array of intermediary IProperty objects into
// the passed service type e.g. Service1.Property
object[] result = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
IProperty fromProp = properties[i];
object toProp = ReflectionUtility.CreateInstance(type, null);
ServiceUtils.CopyProperties(fromProp, toProp);
result[i] = toProp;
}
return result;
}
```
Here's my calling code, from one of my service implementations:
```
Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties);
_service.SetProperties(folderItem.Path, props);
```
So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface.
The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails:
>
> System.InvalidCastException: Unable to
> cast object of type 'System.Object[]'
> to type
> 'MyProject.Property[]
>
>
>
Any ideas?
I was under the impression that any cast from Object will work as long as the contained object is convertable? | 2008/10/17 | [
"https://Stackoverflow.com/questions/212429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] | As others have said, the array has to be of the right type to start with. The other answers have shown how to convert a genuine object[] after the fact, but you can create the right kind of array to start with using [Array.CreateInstance](http://msdn.microsoft.com/en-us/library/system.array.createinstance.aspx):
```
object[] result = (object[]) Array.CreateInstance(type, properties.Length);
```
Assuming `type` is a reference type, this should work - the array will be of the correct type, but you'll use it as an `object[]` just to populate it. | That's correct, but that doesn't mean that you can cast containers of type Object to containers of other types. An Object[] is not the same thing as an Object (though you, strangely, could cast Object[] to Object). |
483,259 | I'm searching for an adjective that is between rare and common - e.g. something that is everyday, or ordinary, or not remarkable.
Can anyone help suggest some words I might try?
Thank you, | 2019/01/29 | [
"https://english.stackexchange.com/questions/483259",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/10835/"
] | First of all, **common** *is* something everyday or ordinary.
However, if you want a word that's between *rare* and *common* on a frequency scale, I suggest [**occasional**](https://www.merriam-webster.com/dictionary/occasional):
>
> [Merriam-Webster]
>
>
> **3** : encountered, occurring, appearing, or taken at irregular or infrequent intervals
>
> // *occasional* visitors
>
> // an *occasional* vacation
>
> // found *occasional* errors
>
> // *occasional* episodes of chest pain
>
>
>
In addition to the synonyms *irregular* and *infrequent* shown in the definition, there is also *intermittent*. | How about "uncommon"? Typically the word used in gaming circles. |
8,871,682 | I have a string say `123dance456` which I need to split into two strings containing the first sub-string before the sub-string `dance` (i.e. `123`) and after the sub-string `dance` (i.e. `456`). I need to find them and hold them in separate string variables, say `String firstSubString = 123;` and String `secondSubString = 456;`.
Is there any given String method that does just that? | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411449/"
] | Easiest is to use the `split` method as the other answers suggest. You can also use a [`Matcher`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html) and a [`Pattern`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) for a more general approach:
```
String str = "123dance456";
String splitter = "dance";
Pattern p = Pattern.compile("(.*?)" + splitter + "(.*)");
Matcher m = p.matcher(str);
if (m.matches()) {
firstSubString = m.group(1); // may be empty
secondSubString = m.group(2); // may be empty
} else {
// splitter not found in str
}
``` | Using the Scanner is a nice alternative:
```
Scanner scanner = new Scanner( "123dance456" ).useDelimiter( "dance" );
if ( scanner.hasNext() )
System.out.println( scanner.next() );
if ( scanner.hasNext() )
System.out.println( scanner.next() );
```
It is quite convenient to process the tokens as a stream and simply ask via `hasNext()` if new tokens are available. Also you get nice conversions from the `Scanner`, even localised, like:
```
Scanner scanner = new Scanner( "123dance456" ).useDelimiter( "dance" );
System.out.println( scanner.nextDouble() * scanner.nextDouble() );
``` |
594,886 | My local computer uses Windows 7 Pro and belongs to realm LR, managed by AD servers. I login to my computer while attached to that realm's network. I can view the TGT with MIT Kerberos for Windows ver. 4.0.1.
I want to access resources on a foreign realm, FR. There is no Kerberos trust between LR and FR, but they allow TCP traffic between one another. I request a TGT for FR with its KDC (Red Hat IdM / FreeIPA) and successfully enter my password when challenged. Again, I can view the TGT with MIT Kerberos for Windows ver. 4.0.1. I can now access resources in FR over SSH without being asked for a password, despite originating from LR.
The problem is when I get the TGT for FR, the TGT for my LR principal disappears. Only the FR TGT is visible in MIT Kerberos. If I lock my computer and then unlock with my password, now the FR TGT is gone, replaced by a new LR TGT.
**It seems MIT Kerberos for Windows can only store one TGT at a time.** Each TGT completely works for its realm for all intents and purposes. How can I configure MIT Kerberos to let me have two TGTs at once, one for each realm? Is it possible to "compartmentalize" with multiple client instances, each pointing to a different KRB5\_CONFIG and local keytab? If I cannot, is there an alternative Windows implementation of client-side Kerberos 5 that will, even when there are no inter-realm trusts?
P.S. - I don't want a trust. Can't get a trust.
**UPDATE:** I left out some of these details earlier because I thought it might confuse the issue. But based on Brad's answer, it might be warranted. I expect *most* local software would use the built-in Windows implementation of Kerberos and always use the LR keytab.
However, power users like me use heimdal under Cygwin to SSH into FR. I expect anything going through Cygwin DLLs to use heimdal and never see the LR TGT (which it doesn't, at least not by default). I explicitly kinit and move on.
The tricky part comes in for non-power users I have to support who don't use Cygwin but do use PuTTY. PuTTY does let you specify both the library path and DLL for which GSSAPI implementation to use. For instance, I'm configuring SSH sessions to use MIT Kerberos DLLs instead of built-in Windows DLLs. I was hopeful there was a DLL out there that either never tried to find the LR TGT (like heimdal) or allowed multiple TGTs from multiple realms. It doesn't have to have a GUI window like MIT Kerberos, but it helps. | 2014/05/13 | [
"https://serverfault.com/questions/594886",
"https://serverfault.com",
"https://serverfault.com/users/117064/"
] | OK, I've come up with a working solution that needs some more polish, so might not work in all environments.
This works with:
1. [MIT Kerberos](http://web.mit.edu/kerberos/dist/) for Windows 4.0.1 with Windows support tools (KSETUP.EXE, KTPASS.EXE)
2. [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/) 0.63
3. Windows 7 SP1
I was looking in the MIT Kerberos source and came across the [README for Windows](https://github.com/krb5/krb5/tree/master/src/windows). Of particular interest was the different values for **Credentials Cache**. It espouses a default value of **API:**, but I surprisingly found my registry using **MSLSA:** instead.
I played around with different values of **ccname** under `HKEY_CURRENT_USER\Software\MIT\Kerberos5`. I tried **MEMORY:** at first, which lead to some interesting behavior. When opening a PuTTY session, my MIT Kerberos Ticket Manager window would restore and come to the foreground, asking me to enter credentials. Wow! That never happened before, but alas, PuTTY would reject it. The value that did the trick for me was `FILE:C:\Some\Full\File\Path`. I'm not exactly sure how to secure access to the specified file, so I'll leave that as an exercise for the reader. I got the same window-to-the-foreground behavior, only PuTTY liked it this time. The Ticket Manager window also finally both displayed the LR and FR tickets. The tickets were proven to be forwardable and would survive multiple Windows Lock/Unlocks. **NOTE:** be sure to completely Exit and restart the Ticket Manager inbetween registry edits. I haven't tried out a **ccname** of **API:** yet.
I don't know if this makes a difference or not, but I also played around with **KSETUP** before this started working. At first, a parameterless KSETUP would just show me information about the LR. I added some info about the FR on my local workstation.
```
ksetup /AddKdc FOREIGN.REALM KDC.FOREIGN.REALM
ksetup /AddRealmFlags FOREIGN.REALM TcpSupported Delegate NcSupported
``` | Following on to Toddius' answer, I have a co-worker in a similar situation (Windows 7 Enterprise 64-bit, joined to an AD domain, also running MIT Kerberos for Windows 4.0.1): His copy of the Kerberos Ticket Manager would only allow him to have one principal/one TGT. Whenever he would use the "Get Ticket" button to get a TGT for a different principal, the previous principal would disappear.
I reviewed the [README](https://github.com/krb5/krb5/tree/master/src/windows), and most of the registry keys were set as expected, **except** for the *ccname* key at path `HKEY_CURRENT_USER\Software\MIT\Kerberos5`. That key was set to the value `MSLSA:`. Our fix was to change that to `API:`. More specifically, the steps were:
1. Quit the Kerberos Ticket Manager, along with all other applications (since you'll be restarting).
2. At Registry path `HKEY_CURRENT_USER\Software\MIT\Kerberos5`, change the *ccname* key to `API:` (A-P-I, then colon).
3. Exit regedit, and restart.
4. After logging back in, run Kerberos Ticket Manager, and use the Get Ticket button to get your non-AD principal's TGT.
With the steps above, everything worked, and me coworker is now able to see multiple principals/TGTs at once.
By the way, MIT Kerberos for Windows brings in its own set of command-line programs (like klist), and those programs support multiple credential caches. On my 64-bit system, when I run `"C:\Program Files\MIT\Kerberos\bin\klist.exe" -A"` after getting multiple TGTs, I see my Active Directory principal in the MSLSA cache, and then I have one API cache for each additional principal.
P.S. This is my first entry on this site, so I wasn't able to add it as a comment to Toddius' answer. Apologies! |
616,532 | How can I compile java code from an arbitrary string (in memory) in Java 5 and Java 6, load it and run a specific method on it (predefined)?
Before you flame this, I looked over existing implementations:
* Most rely on Java 6 Compiler API.
* Those that don't, rely on tricks.
* Yes, I checked out commons-jci. Either I'm too dense to understand how it works, or it just doesn't.
* I could not find how to feed the compiler my current class path (which is quite huge).
* On the implementation that worked (in Java 6), I could not find how to correctly load inner classes (or inner anonymous classes).
* I'd quite like it if the entire thing was in-memory, as the thing runs on multiple environments.
I'm sure this has been solved before, but I can't find anything that looks even half-production quality on google (except jci, which, as I've said before, I haven't managed to use).
Edit:
* I looked over JavaAssist - I need inner classes, Java 5.0 language level support and compiling with the entire classpath. Also, I'd like to create new classes on the fly. I
might be mistaken, but I couldn't find how to do this with JavaAssit.
* I'm willing to use a file-system based solution (calling javac) but I don't know how to divine the classpath, nor how to later load the files (which are not in my classpath) with a special classloader that can be recycled for multiple invocations. While I do know how to research it, I'd prefer a ready solution.
Edit2:
For now, I'm content with BeanShell "evaluate". Apparently it does everything I need it to (get a string, evaluate it in the context of the 'current' classpath. It does miss some of Java 5 features, but it can use enums (not define) and compiled 'generic' (erased) classes, so it should be enough for what I want.
~~I don't want to mark the answer as accepted yet since I do hope for a better solution to come up.~~
Edit3: Accepted the beanshell suggestion - it really works wonderfully. | 2009/03/05 | [
"https://Stackoverflow.com/questions/616532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931/"
] | You might want to check out Janino as well.
From their website:
Janino is a compiler that reads a JavaTM expression, block, class body, source file or a set of source files, and generates JavaTM bytecode that is loaded and executed directly. Janino is not intended to be a development tool, but an embedded compiler for run-time compilation purposes, e.g. expression evaluators or "server pages" engines like JSP.
<http://www.janino.net/>
Im currently using it in a pretty large mission critical project and it works just fine | Run inside a web container like Tomcat and first generate a JSP page, and then invoke it.
This also allow you to get rid of the old class definitions by simply overwriting the JSP page instead of having your classloader slowly run full.
Is the "in-memory" requirement due to speed or due to not changing the code base? |
52,848 | Suppose you were standing on the rotating Earth (not necessarily Equator or the poles) and suddenly your body lost the ability to avoid effortlessly passing through solid rock.
Because the earth's rotation at the surface is considerably below escape velocity, you would slip below the earth's surface. If the earth's gravity were a consequence of a central point mass, you'd have an elliptical orbit (mostly) within the earth.
With a planet of constant density, the gravity you feel underground is equivalent to standing on the surface of an identically dense planet with a radius equal to your current distance from the centre. So effectively, as you fall the gravity you experience lessens.
1. What would be the shape of the trajectory?
2. How close would you get to the centre?
3. How long would it take before your orbit brought you back to the surface (assuming no losses and a stationary planet)?
4. What complications would arise from the planet being in orbit around a star?
5. Bonus points for finding two well-known places on the Earth that you could travel between in one "orbit" using this method. | 2013/02/02 | [
"https://physics.stackexchange.com/questions/52848",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20505/"
] | The force you experience is of the form $\vec{F} = - Gmr\vec{u\_r}$, and we also know that in the surface, $r=R$, it is $\vec{F}=- gm\vec{u\_r}$, so
$$\vec{F} = -gm\frac{r}{R}\vec{u\_r}$$
This is a conservative force that can be derived from a potential
$$U = \frac{1}{2}gm\frac{r^2}{R}$$
Because this is a central force, angular momentum is conserved, so $r^2 \dot{\theta} = L$, and if $\Omega$ is the rotational velocity of earth,
$$r^2 \dot{\theta} = R^2 \Omega$$
And of course we have conservation of energy,
$$\frac{1}{2}m(\dot{r}^2+r^2\dot{\theta}^2)+\frac{1}{2}gm\frac{r^2}{R} = E$$
but we also know the initial conditions, $r=R$, $\dot{\theta}=\Omega$, $\dot{r}=0$, so
$$E = \frac{1}{2}m(R^2\Omega^2)+\frac{1}{2}gmR$$
and conservation of energy can be rewritten as
$$\dot{r}^2+r^2\dot{\theta}^2+g\frac{r^2}{R} = R^2\Omega^2+gR$$
and including conservation of angular momentum as
$$\dot{r}^2+ \frac{R^4 \Omega^2}{r^2}+g\frac{r^2}{R} = R^2\Omega^2+gR$$
If you set $\dot{r} = 0$ and solve for $r$, there are two solutions, marking the annular region in which motion will happen. One is the obvious $r=R$, the other comes out to
$$r = \Omega R \sqrt{\frac{R}{g}}$$
which with the Earth parameters at the equator, comes out to $r=3740\ \mathrm{km}$.
You can rearrange the equation of energy as
$$\frac{dr}{\sqrt{R^2\Omega^2+gR - \frac{R^4 \Omega^2}{r^2}-g\frac{r^2}{R}}} = dt$$
which you could integrate to get a probably implicit relation between $r$ and $t$, which you could use in the conservation of angular momentum to get $\theta$ as a function of $r$ and/or $t$.
I have done that numerically, and again, for the point on the Equator, it would take about 21 minutes to reach the point closest to the Earth's center, and 21 more to get back up at the surface.
One neat result I don't fully understand where it comes from is that, at the minimum point, the angle $\theta$ has changed by $\pi / 2$, independently of what the rotation speed is, so that you always emerge at a point opposite where you went down. Since the Earth is rotating, you wouldn't actually come out at the antipodal point, but some $1175\ \mathrm{km}$ from it.
Away from the equator you would have a reduced $\Omega$, and the movement will happen in a plane perpendicular to the meridian going through that point. | This is a pretty fun topic of classical mechanics.
You should check this article out: [here](http://www.wired.com/wiredscience/2012/11/how-long-would-it-take-to-fall-through-the-earth/)
It has a really detailed analysis of how to calculate the time it takes to fall through the earth. |
69,310,681 | I followed an AWS tutorial for setting up Lambda + API Gateway using SAM Template.
But the event defined under lambda template creates a Proxy integration.
I followed this tutorial because I wanted to set up similar for one of my projects.
I need Non-proxy integration for that specific use case. Because I have to return xml format to the client and this can be only done by modifying the Integration Response.
But in proxy APIs integration response cannot be modified.
I searched a lot but couldn't find an answer.
For now the template.yaml looks like this
```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
callforward
Sample SAM Template for callforward
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.8
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
``` | 2021/09/24 | [
"https://Stackoverflow.com/questions/69310681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16958390/"
] | I think i solved by myself
```
paid = joins(:invoices).where(invoices: {status: true}).pluck(:id)
unpaid = joins(:invoices).where(invoices: {status: false}).pluck(:id)
#return paid
where(id: paid - unpaid)
#return unpaid
where(id: unpaid - paid)
#return partial paid
where(id: paid & unpaid)
``` | Since `paid` is a boolean field here, it holds either true or false value.
If you have another field(probably `payment_status`) in `Invoice` table that should identify the record as "Fully Paid", "Partially Paid", "Not Paid". Then the query would be:
```
Purchase.joins(:invoice).where(invoices: {paid: true, payment_status: "Fully Paid"}) # `paid: true` could be omitted
```
As a best practice you can define a scope:
```
class Purchase < ApplicationRecord
has_many :invoices
scope :paid_invoices, -> { joins(:invoice).where(invoices: {payment_status: "Fully Paid"}) }
end
``` |
8,140,990 | I'm trying to change the css of the following label using JQuery but I can't figure it out. This is actually the html from my checkboxlist (asp.net) and this is what I have so far. Can anybody please help? Thank you.
The JQuery below finds the entire table and makes all labels red, not just the one that I checked.
```
$("#CheckBoxList1").click(function() {
$(this).find('label').removeClass('red');
if ($('span').hasClass('checked'))
$(this).find('label').addClass('red');
});
<table id="CheckBoxList1" border="0">
<tbody>
<tr>
<td>
<div class="checker" id="uniform-CheckBoxList1_0">
<span>
<input id="CheckBoxList1_0" type="checkbox" name="CheckBoxList1$0" style="opacity: 0; "/>
</span>
</div>
<label for="CheckBoxList1_0">Mark Park</label>
</td>
<td>
<div class="checker" id="uniform-CheckBoxList1_1">
<span>
<input id="CheckBoxList1_1" type="checkbox" name="CheckBoxList1$1" style="opacity: 0; "/>
</span>
</div>
<label for="CheckBoxList1_1">Amy Lee</label>
</td>
<td/>
</tr>
</tbody>
</table>
``` | 2011/11/15 | [
"https://Stackoverflow.com/questions/8140990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967092/"
] | ```
$("#CheckBoxList1").click(function() {
$(this).find('label').removeClass('red');
$('span.checked').parent().next('label').addClass('red');
});
``` | Can you add an class/id to the labels and checkboxes and access it that way:
```
$(".check").click(function() {
var id = $(this).attr("id").split("_");
//access array of id
$(".label_"+id[1]).addClass("red");
}
```
then add the id/ classes onto your html:
```
<input id="CheckBoxList1_0" id="check_1" type="checkbox" class="check" name="CheckBoxList1$0" style="opacity: 0; "/>
<label for="CheckBoxList1_0" id="label_1">Mark Park</label>
``` |
62,202,674 | I am working on a program that displays a object from my Stock class in a jlist. I have it working where I can write this information to a file but when I try to read from that same file my program just freezes. I am wondering if I have my code set up wrong to read from the file as this is my first time trying that. All I am looking to do is set the variables for my Stock object from the saved variables in the file. Thanks
```
public void getData(){
StringTokenizer row;
Stock aStock = new Stock();
try{
BufferedReader inbuffer = new BufferedReader(new FileReader(fileName));
String inputString;
inputString = inbuffer.readLine();
while(inputString != null){
row = new StringTokenizer(inputString, DELIMTER);
aStock.setStockName(row.nextToken());
aStock.setStockQuantity(Integer.parseInt(row.nextToken()));
aStock.setPurchasePrice(Double.parseDouble(row.nextToken()));
aStock.setCurrentPrice(Double.parseDouble(row.nextToken()));
}
inbuffer.close();
}
catch(IOException ioe){
JOptionPane.showMessageDialog(null, ioe.getMessage(), "File Read Error", JOptionPane.ERROR);
}
}
``` | 2020/06/04 | [
"https://Stackoverflow.com/questions/62202674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13682433/"
] | You need an `if` block instead of a `while` block because you want to set values to only one `Stock` object.
Replace
```
while(inputString != null)
```
with
```
if(inputString != null)
```
Also, change the return type from `void` to `Stock` and return `aStock` so that you can use the returned value.
```
public Stock getData() {
StringTokenizer row;
Stock aStock = new Stock();
try {
BufferedReader inbuffer = new BufferedReader(new FileReader(fileName));
String inputString;
inputString = inbuffer.readLine();
if (inputString != null) {
row = new StringTokenizer(inputString, DELIMTER);
aStock.setStockName(row.nextToken());
aStock.setStockQuantity(Integer.parseInt(row.nextToken()));
aStock.setPurchasePrice(Double.parseDouble(row.nextToken()));
aStock.setCurrentPrice(Double.parseDouble(row.nextToken()));
}
inbuffer.close();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage(), "File Read Error", JOptionPane.ERROR);
}
return aStock;
}
``` | Your loop is not set up correctly, and thus will never exit. Notice that after you read the first line, you are never reading another new line, so the loop never ends.
Secondly, if you are writing to the file at the same time as you are reading from it, inputString will never be null - the call to inbuffer.readLine will wait for more data before returning. You might do better using a threaded callback reader like DataFetcher (<https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/DataFetcher.java>)
```
inputString = inbuffer.readLine();
while(inputString != null){
row = new StringTokenizer(inputString, DELIMTER);
aStock.setStockName(row.nextToken());
aStock.setStockQuantity(Integer.parseInt(row.nextToken()));
aStock.setPurchasePrice(Double.parseDouble(row.nextToken()));
aStock.setCurrentPrice(Double.parseDouble(row.nextToken()));
inputString = inbuffer.readLine();
}
``` |
74,410,527 | I'm trying to make simple function to adding elements to my array but it doesnt work well. can you help me?
```
void insert(int &n, string name[]){
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>name[i];
}
}
int main(){
int n;
string name[n];
insert(n,name);
}
``` | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483219/"
] | C++ arrays [] do not grow on run time, use std::vector instead.
Also, since you are reading an integer from cin, you should insert in the vector the same type, not a string.
```
std::vector<int> v; // creates a vector
v.push_back( 10 ); // include a number in a vector
```
<https://godbolt.org/z/v4xG6WEo1> | You are declaring the size of your array "name[]" to be "n" but you are asking the value of "n" after you have allocated the memory for array already. Either ask for size before creating array or just use vector to have it resize during runtime.
If you want to use arrays then do this:
```
void insert(string name[]){
for (int i = 0; i < name.size(); i++)
{
cin>>name[i];
}
}
int main(){
int n;
cin >> n;
string name[n];
insert(name);
}
```
If you want your array size to change whenever you want basically use vectors:
```
void insert(int &n, vector<string> name){
string tmp;
for (int i = 0; i < n; i++)
{
cin>>tmp;
name.push_back(tmp);
}
}
int main(){
int n = ???;
vector<string> name;
insert(n,name);
}
```
you will still have to give the value of "n" in vector example as well because you need the value of "n" to run the loop in "insert" function. |
52,166,826 | I am building mock restful API to learn better. I am using MongoDB and node.js, and for testing I use postman.
I have a router that sends update request `router.patch`. In my DB, I have `name` (string), `price` (number) and `imageProduct` (string - I hold the path of the image).
I can update my `name` and `price` objects using **raw-format** on the postman, but I cannot update it with **form-data**. As I understand, in **raw-form**, I update the data using the array format. Is there a way to do it in **form-data**? The purpose of using **form-data**, I want to upload a new image because I can update the path of `productImage`, but I cannot upload a new image public folder. How can I handle it?
*Example of updating data in raw form*
```
[ {"propName": "name"}, {"value": "test"}]
```
*router.patch*
```
router.patch('/:productId', checkAuth, (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.updateMany({_id: id}, {$set: updateOps})
.exec()
.then(result => {
res.status(200).json({
message: 'Product Updated',
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
err: err
});
});
});
``` | 2018/09/04 | [
"https://Stackoverflow.com/questions/52166826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7943285/"
] | I know this answer might be too late to help you but it might help someone in 2020 and beyond.
First, comment out this block:
```
//const updateOps = {};
//for (const ops of req.body) {
//updateOps[ops.propName] = ops.value;
//}
```
and change this line:
```
Product.updateMany({_id: id}, {$set: updateOps})
```
to this:
```
Product.updateMany({_id: id}, {$set: req.body})
```
Everything else is fine. I was having similar issues, but this link helped me:
[[What is the difference between ( for... in ) and ( for... of ) statements in JavaScript?](https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-statements-in-jav][1]) | To handle multi-part form data, the `bodyParser.urlencoded()` or `app.use(bodyParser.json());`body parser will not work.
See the suggested modules [here](https://www.npmjs.com/package/body-parser#readme) for parsing multipart bodies.
You would be required to use `multer` in that case
```
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
// for parsing application/json
app.use(bodyParser.json());
// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true }));
//form-urlencoded
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
``` |
320,716 | I'm trying to find a reliable way of finding which process on my machine is changing a configuration file (`/etc/hosts` to be specific).
I know I can use `lsof /etc/hosts` to find out what processes currently have the file open, but this doesn't help because the process is obviously opening the file, writing to it, and then closing it again.
I also looked at `lsof`'s repeat option (-r), but it seems to only go as fast as once a second, which probably won't ever capture the write in progress.
I know of a couple tools for monitoring changes to the filesystem, but in this case I want to know which process is responsible, which means catching it in the act. | 2011/10/12 | [
"https://serverfault.com/questions/320716",
"https://serverfault.com",
"https://serverfault.com/users/138387/"
] | You can use auditing to find this. If not already available, install and enable auditing for your distro.
set an audit watch on /etc/hosts
```
/sbin/auditctl -w /etc/hosts -p war -k hosts-file
-w watch /etc/hosts
-p warx watch for write, attribute change, execute or read events
-k hosts-file is a search key.
```
Wait till the hosts file changes and then use ausearch to seer what is logged
```
/sbin/ausearch -f /etc/hosts | more
```
You'll get masses of output e.g.
---
```
> time->Wed Oct 12 09:34:07 2011 type=PATH
> msg=audit(1318408447.180:870): item=0 name="/etc/hosts" inode=2211062
> dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00
> obj=system_u:object_r:etc_t:s0 type=CWD msg=audit(1318408447.180:870):
> cwd="/home/iain" type=SYSCALL msg=audit(1318408447.180:870):
> arch=c000003e syscall=2 success=yes exit=0 a0=7fff73641c4f a1=941
> a2=1b6 a3=3e7075310c items=1 **ppid=7259** **pid=7294** au id=1001 uid=0 gid=0
> euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=123
> comm="touch" **exe="/bin/touch"** subj=user_u:system_r:unconfined_t:s0
> key="hosts-file"
```
---
In this case I used the touch command to change the files timstamp it's pid was 7294 and it's ppid was 7259 (my shell). | probably better to use something like incron then
<http://inotify.aiken.cz/?section=incron&page=about&lang=en>
you can then get it to trigger a script to so some sort of diags |
6,382 | Who knows two hundred ten?
--------------------------
*Please cite/link your sources, if possible. At some point at least twenty-four hours from now, I will:*
* *Upvote all interesting answers.*
* *Accept the best answer.*
* *Go on to the next number.* | 2011/03/18 | [
"https://judaism.stackexchange.com/questions/6382",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/2/"
] | 210 are the years of *shi'bud Mitzrayim*. (*[Rash"i](http://he.wikisource.org/wiki/%D7%9E%22%D7%92_%D7%91%D7%A8%D7%90%D7%A9%D7%99%D7%AA_%D7%98%D7%95_%D7%99%D7%92#.D7.A8.D7.A9.22.D7.99_.28.D7.9B.D7.9C_.D7.94.D7.A4.D7.A8.D7.A7.29.28.D7.9B.D7.9C_.D7.94.D7.A4.D7.A1.D7.95.D7.A7.29)* on *B'reshis* 15:13) | 210 is the total number of days in all the *Adar Rishon* months in a nineteen-year cycle. |
44,292,527 | I have two activities, Activity A and Activity B. Activity A has a button that leads to Activity B, and when the back button pressed, it returns to Activity A as it should.
However, if I go to Activity B and minimize the app, open the app, and then press the back button, it closes the app. How can I preserve the navigation done by the user? | 2017/05/31 | [
"https://Stackoverflow.com/questions/44292527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765618/"
] | Use `window.self` instead of `self`. | Add `var self = this;` or use `this.addEventListener(...)` |
29,909,648 | So I've attached a debugger, and tried different inputs and I can't seem to figure out why this won't get past the loop. When ran I enter "l" or "L", then entry gets set to that, then input is set to the capitalized version and then it repeats.
```
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while (input != 'L' || input!='M' || input != 'P' || input != 'Q');
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29909648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4840151/"
] | your have used logical or condition it needs just one true statement to run, even though you enter 'L' , at this point your one statement is false but other statements became true that why it keeps on repeating. | ```
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while ((input != 'L') && (input!='M') && (input != 'P') && (input != 'Q'));
```
try this |
49,381,139 | This is a tricky one - I have a java interface that I want to implement in scala:
```
public interface Foo {
public void bar(scala.Array arr);
}
```
Is it even possible to implement in scala? when I try:
```
class FooImpl extends Foo {
override def bar(arr: Array[_]): Unit = ???
}
```
I get:
```
Error:(13, 7) class FooImpl needs to be abstract, since method bar
in trait Foo of type (x$1: Array)Unit is not defined
(Note that Array does not match Array[_]. To implement a raw type, use
Array[_])
class FooImpl extends Foo {
``` | 2018/03/20 | [
"https://Stackoverflow.com/questions/49381139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5417333/"
] | The error message is giving you the answer for any generic type other than `Array` (after replacing the name, of course):
>
> To implement a raw type, use `Array[_]`
>
>
>
"Raw type" is what Java calls a generic type used without a type parameter and e.g. <https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html> explains why you should not use them except to interface with now horribly obsolete pre-Java-5 code. So if it is at all an option, you should fix the Java interface in the first place.
Now, why does this not work for `Array`? It's a special type, which is really built into compiler. Its instances are real JVM arrays, which don't have a common type in Java. So when it's used in Scala code, the compiled bytecode doesn't use `scala.Array` at all. I guess that it only exists as a JVM type (unlike e.g. `scala.Any` or `scala.Null`) to put the static methods there, but all instance methods are defined as `throw new Error()`. It seems the error message didn't take this unique case into account.
So, the answer is: no, it can't be implemented in Scala, as far as I am aware. But it can't be non-trivially implemented in Java either. And even for trivial implementations, you'd run into the same issues when trying to write code *using* it. | To make the code work you either have to
* Make the `FooImpl` declaration as `abstract` class
* Implement the `bar` method
because "Java interfaces don’t implement behaviour".
For your reference see [this](https://alvinalexander.com/scala/how-to-extend-java-interfaces-like-scala-traits) page. |
1,282,622 | Show that a rectangular prism (box) of given volume has minimum surface area if the box is a cube.
Could you give me some hints what we are supposed to do??
$$$$
**EDIT**:
Having found that for $z=\frac{V}{xy}$ the function $A\_{\star}(x, y)=A(x, y, \frac{V}{xy})$ has its minimum at $(\sqrt[3]{V}, \sqrt[3]{V})$, how do we conclude that the box is a cube??
We have that $x=y$. Shouldn't we have $x=y=z$ to have a cube?? | 2015/05/14 | [
"https://math.stackexchange.com/questions/1282622",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/80708/"
] | **Hint:** Let a box be $x$-by-$y$-by-$z$. Here we assume $x>0$, $y>0$, $z>0$. Then the surface area of the box is
$$A=2(xy+xz+yz)$$
and the volume $V=xyz$ is fixed. We need to find the minimum of $A(x,y,z)$ given additional condition $V=xyz$. But $z=\frac{V}{xy}$ and, hence, $A$ can be considered as a function in two variables $x$ and $y$:
$$A\_\star(x,y)=2\left(xy+\frac{(x+y)V}{xy}\right).$$
You need to find the minimum of $A\_\star(x,y)$.
So let
$$
\left\{
\begin{array}{l}
\frac{\partial A\_\star}{\partial x} = 0,\\
\frac{\partial A\_\star}{\partial y} =0;
\end{array}
\right.
$$
and so on ... The minimum will be at $x=y=\sqrt[3]{V}$.
**Update:**
$$
\left\{
\begin{array}{l}
\frac{\partial A\_\star}{\partial x} = \frac{\partial}{\partial x}
\left( 2xy +\frac{2V}{x}+\frac{2V}{y}\right)=2y-\frac{2V}{x^2}=
\frac{2x^2y-2V}{x^2}=0,\\
\frac{\partial A\_\star}{\partial y} = \frac{\partial}{\partial y}
\left( 2xy +\frac{2V}{x}+\frac{2V}{y}\right)=2x-\frac{2V}{y^2}=
\frac{2xy^2-2V}{y^2}=0.
\end{array}
\right.
$$
Since $x > 0$ and $y > 0$ we obtain
$$
\left\{
\begin{array}{l}
x^2y-V=0,\\
xy^2-V=0;
\end{array}
\right.
\qquad\text{or}\qquad
\left\{
\begin{array}{l}
x=\sqrt[3]{V},\\
y=\sqrt[3]{V};
\end{array}
\right.
$$
Now we'll proof that $(x\_0,y\_0)=(\sqrt[3]{V},\sqrt[3]{V})$ is the minimum of $A\_\star(x,y)$. Consider
$$
\begin{bmatrix}
\frac{\partial^2 A\_\star}{\partial x^2} & \frac{\partial^2 A\_\star}{\partial x \partial y} \\
\frac{\partial^2 A\_\star}{\partial x \partial y} & \frac{\partial^2 A\_\star}{\partial y^2}
\end{bmatrix}\_{(x\_0,y\_0)}
=
\begin{bmatrix}
\frac{4V}{x^3} & 2 \\
2 & \frac{4V}{y^3}
\end{bmatrix}\_{(x\_0,y\_0)}
=
\begin{bmatrix}
4 & 2 \\
2 & 4
\end{bmatrix}
$$
We have the minimum if the matrix above is positively defined. Or, in other words, using Sylvester's criterion we should obtain
$$
\left\{
\begin{array}{l}
\left.\frac{\partial A\_\star^2}{\partial x^2}\right|\_{(x\_0,y\_0)} >0,\\
\left.\frac{\partial A\_\star^2}{\partial x^2}\right|\_{(x\_0,y\_0)}
\left.\frac{\partial A\_\star^2}{\partial y^2}\right|\_{(x\_0,y\_0)}-
\left( \left.\frac{\partial A\_\star^2}
{\partial x \partial y}\right|\_{(x\_0,y\_0)} \right)^2 >0.
\end{array}
\right.
$$
Obviously, it is the case. So, $(x\_0,y\_0)=(\sqrt[3]{V},\sqrt[3]{V})$ is the minimum. Finally, $z\_0=\frac{V}{x\_0y\_0}=\sqrt[3]{V}$. Hence, $x\_0=y\_0=z\_0=\sqrt[3]{V}$ gives the minimum of the area. Consequently, the box should be a cube. | Volume $V=xyz$ given. Area $A(x,y,z)=2(xy+yz+zx)$, to minimise, when $x,y,z>0$ and $xyz=V$.
**Fact.** If $a,b,c>0$, then $a+b+c\ge 3\sqrt[3]{abc}$, and equality holds if and only if $a=b=c$.
*Proof.* We set $X=\sqrt[3]{a}$, $Y=\sqrt[3]{b}$ and $Z=\sqrt[3]{c}$. Then the identity
$$
X^3+Y^3+Z^3-3XYZ=\frac{1}{2}(X+Y+Z)\big((X-Y)^2+(Y-Z)^2+(Z-X)^2\big),\tag{1}
$$
holds. This means that
$$
a+b+c-3\sqrt[3]{abc}=X^3+Y^3+Z^3-3XYZ\ge 0,
$$
as the right-hand-side of $(1)$ is non-negative, and the equality only if $X-Y=Y-Z=Z-X=0$ or $X=Y=Z=0$ or $a=b=c=0$. $\quad\Box$
Hence,
$$
\frac{A}{2}=xy+yz+zx\ge 3\sqrt[3]{xy\cdot yz\cdot zx}=3\sqrt[3]{x^2y^2z^2}=3V^{2/3}.
$$
and equality holds iff $xy=zx=yz$ or equivalently iff $x=y=z$.
Indeed, $A$ is minimised when $x=y=z$, and $A\_{\mathrm{min}}=6V^{2/3}$. |
9,211,405 | I would like to know the recommended way to move our code from a SVN repository to a GIT repository, so that we transition our developers team & start using GIT.
Can we do the transition and keep all the commits done in the SVN repository ?
Also, our team is happy with SVN currently, but, they don't know that branching in GIT is much easier than SVN, where can I find a practical example that proves power of GIT in branching ? | 2012/02/09 | [
"https://Stackoverflow.com/questions/9211405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396681/"
] | Eric Raymond (esr) has created [reposurgeon](http://catb.org/~esr/reposurgeon/), “a command interpreter for performing tricky editing operations on version-control histories.” The tool includes scripts for various purposes, including cleaning up the results of VCS conversions. Check it out from <https://gitlab.com/esr/reposurgeon>.
As of version 2.0 it includes support for reading SVN dumpfiles for complete and idiomatic translation to Git, Mercurial, *etc.*; see <http://esr.ibiblio.org/?p=4071> for details. Reposurgeon has been used to convert several large projects to Git, including Emacs whose repository, ESR says, “is large, complex in branch structure, and old enough to have begun life as a CVS repo. That last part matters because some of the ugliest translation problems lurking in the back history of Subversion projects are strange Subversion operation sequences (including combinations of branch copy operations) generated by cvs2svn.”
(The git-svn tool included with Git will handle many Subversion repositories, including branches. It’s pretty commonly used, especially by teams that are in the process of doing a conversion, since it allows Git to behave as a Subversion client. But see ESR’s [*Don’t do svn-to-git repository conversions with git-svn!*](http://esr.ibiblio.org/?p=6778), where he discusses the drawbacks to git-svn as a conversion tool.)
Regarding your second question, it isn’t branching where the power of Git is so helpful (though Git is at least as powerful as Subversion in this regard); it’s when it comes to *merging* those branches that Git shines. Read through the [Git Community Book](http://book.git-scm.com/index.html), especially the section in chapter 3 titled “[Basic Branching and Merging](http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging)” and the section in chapter 7 titled “[Advanced Merging](http://git-scm.com/book/en/Git-Tools-Advanced-Merging)”. | Update Apr 2014
There is a tool called [Svn2Git](https://github.com/nirvdrum/svn2git) that does a pretty good job of making this process a bit easier. The documentation on the Github project is pretty good. (**Ruby required**)
It's worth noting that while git-svn defaults to pulling from just the path you specify, not branches, tags and trunk. Svn2git is the opposite. It will default to looking for a trunk, branches and tags under the path and you should use `--nobranches` or `--notags` to tell it not to search for those (though this may nullify the advantages of svn2git).
---
Once you move to Git, I suggest you move everyone and stay using Git. It's more complicated but the transition will be worth it. Github.com supports accessing the repo using an Subversion client (but you may loose the power of Git branching) and that might be a good stop-gap.
Can I keep my Subversion repo?
------------------------------
When you use the below method to move, all the current commits will remain in the Subversion repo. You may be able to do a one-way sync from the Subversion repo to the Git repo, but going the other way gets very complicated very fast. I would not recommend trying to sync either way and just move everyone one-time.
What's powerful about Git?
--------------------------
Git branching is powerful but it's not all there is to Git. Having a complete history locally means you can do everything you can do with Subversion, but without having to contact the server. Reviewing and searching the history, undoing changes, committing locally, branching locally become immensely faster. Git also compresses it's data, so a Subversion checkout (that includes only the latest revision) ends up being about the same size as a Git checkout (that includes the full history). Also, because data is compressed when transferred, pushing and pulling are much faster as well. Don't just push Git branches, put everything about Git.
How to move a repo using the `git svn` method.
----------------------------------------------
First, clone the Subversion repo. This might take a while.
```
git svn clone http://www.example.com/svn-repo/projectA/trunk/
```
Where `http://www.example.com/svn-repo/` is the URL to the Subversion repo and `projectA/trunk/` is the path you want to copy into Git.
If you have a standard layout such as `projectA/trunk`, `projectA/branches/` and `projectA/tags/` than you can add `--stdlayout` and clone from a directory up like this
```
git svn clone --stdlayout http://www.example.com/svn-repo/projectA/ projectA.git-svn
```
And, if you have a trunk, branches and tags folder named differently then above, you an give `git svn clone` custom names for each.
```
git svn clone --trunk my-trunk --branches my-branches --tags my-tags http://www.example.com/svn-repo/projectA/ projectA.git-svn
```
Once that completes all you have to do is push to the remote git repo with `--mirror`.
```
cd projectA.git-svn
git push --mirror git@github.com:Account/projectA.git
```
At this point you should make your Subversion repo read-only to keep people from trying to commit to an out dated location. |
4,912,755 | I have an integer array of length 900 that contains only binary data [0,1].
I want to short the length of the array without losing binary data formate(original array values).
Is it possible to short the length of array of 900 into 10 or 20 length in C#??? | 2011/02/06 | [
"https://Stackoverflow.com/questions/4912755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605171/"
] | You could actually apply some compression on bits and then store it. if its only 1s and 0s, Run-length encoding may help reduce size drastically in not-worst scenarios.
[Run length encoding - Wiki article](http://en.wikipedia.org/wiki/Run-length_encoding) | In fact, you have a binary integer with 900 digits. There are lots of ways you can hold that "number" depending on the what do you want with it and how fast.
Ask yourself:
* do I need fast set function ( `arr[n] = something` )
* do I need fast retrieval function ( val = arr[n] )
* do I need iteration of some kind, for example find next n for which arr[n] is 1
and so on.
Then, ask again or modify you original question.
Otherwise, `BitArray`
EDIT:
Since we found something (a little) I would suggest rolling your own class for that.
Class would have a container such as byte[] and methods to set and unset a item on some position.
Checking common 1s from two arrays would be as simple as &&-ing an array on byte to byte basis. |
38,393,747 | I'm working on an addon which opens a new tab on click on a button with a special html. Right now, the html file is on a dedicated webspace but is there a workaround for that that means, can I put the html file in the data structure of the addon itself and access it from there? Problem is, I deliver the url of the active site when the button is clicked to the url by concatenating it and I'm using AngularJS within that html which seems to be a problem.
My code:
index.js:
```
var { ActionButton } = require("sdk/ui/button/action");
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;
var button = ActionButton({
id: "my-button",
label: "Start LLIBrowser",
icon: {
"16": "./img/logo-16.png"
},
onClick: showPlugIn
});
function showPlugIn(state){
let currUrl = tabs.activeTab.url;
//var file = "file:///home/janine/OneDrive/Uni/OvGU/4. Semester/SoftwareProjekt/LLIBrowserGalleryAndInfo/data/overlay.html"; just for testing
var file = "http://www-e.uni-magdeburg.de/jpolster/LLIBrowser/overlay.html";
var completePath = file.concat("?url=").concat(currUrl);
tabs.open(completePath)
}
```
any ideas?
Cheers! | 2016/07/15 | [
"https://Stackoverflow.com/questions/38393747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5551126/"
] | In theory, I don't see any problems.
Place your HTML-file in your data folder, and access it through:
```
var file = data.url("overlay.html");
```
Edit: M.Onyshchuk is correct in saying that this will trigger an
>
> The address isn't valid
>
>
>
error. I didn't think of the ":". In order to fix this simply remove the protocol information from the URL.
```
currUrl = currUrl.replace(/^https?\:\/\//i, "");
```
To still use AngularJS within your addon, the easiest way would be to simply ship the current version with your addon. Download the latest version, place it into your data folder, and simply access it in your HTML-file the way you normally would.
While I'm not familiar with AngularJS, I can't think of any reason why this shouldn't work.
Good luck with your project!
Sintho | It is not enough to change the file loading URI:
```
var file = data.url("overlay.html");
```
You will see error in this case as
>
> The address isn't valid
>
>
>
But you can modify your code and send current tab url not as a query part of URI, but as a fragment part:
```
let currUrl = tabs.activeTab.url;
currUrl = currUrl.replace(":", "%");
var file = data.url("overlay.html");
var completePath = file.concat("#").concat(currUrl);
```
Unfortunately **encodeURIComponent** does not work:
```
let currUrl = encodeURIComponent(tabs.activeTab.url); // The address isn't valid
```
You will need parse fragment URI (after #) in overlay.html |
7,811,468 | When trying to write read an int from standard in I'm getting a compile error.
```
System.out.println("Hello Calculator : \n");
int a=System.in.read();
```
The program throws an exception:
```
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)
```
How do I fix this error?
My Code :
```
try {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
}
``` | 2011/10/18 | [
"https://Stackoverflow.com/questions/7811468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/868995/"
] | in.read() can throw a checked exception of type IOException.
You can read about Exception Handling in Java [Here.](http://download.oracle.com/javase/tutorial/essential/exceptions/index.html)
You can either change your program to throw an IOException, or you can put the read in a try catch block.
```
try{
int a=System.in.read();
catch(IOException ioe){
ioe.printStackTrace();
}
```
or
```
public static void main(String[] args) throws IOException {
System.out.println("Hello Calculator : \n");
int a=System.in.read();
}
``` | The program doesn't have a bug.
The method `read()` requires you to catch an `Exception` in case something goes wrong.
Enclose the method inside a `try/catch`statement:
```
try {
int a = System.in.read();
...
}
catch (Exception e) {
e.printStackTrace();
}
```
In any case **I strongly suggest you to use documentation and/or Java tutorials**, in which these things are clearly stated. Programming with out using them is just pointless. You will save yourself a lot of headaches, and probably also our time. |
17,960,817 | I need to check if a number is even.
Here's what I've tried.
```
newY="281"
eCheck=$(( $newY % 2 ))
echo $newY
echo $eCheck
while [ $eCheck -eq 0 ]; do
newY=$((newY-1))
eCheck=$(( $newY % 2 ))
echo $newY
done
```
...
returns `eCheck = 1`
how can it be? 281/2 = 140.5
i've also tried using `bc`, but it went into an infinite loop `eCheck=$(echo "scale=1;$newY%2" | bc)` | 2013/07/31 | [
"https://Stackoverflow.com/questions/17960817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228383/"
] | Nici is right, "%" is the modulo, and gives you the remainder of the division.
Your script can be simplified as follows :
```
if [[ $((var % 2)) -eq 0 ]];
then echo "$var is even";
else echo "$var is odd";
fi
``` | Since this question is tagged as Bash, the right way to check if a number is even in Bash is:
```
if ((num%2 == 0)); then
echo "The number is even"
fi
```
or, more even shorter:
```
if ((num % 2)); then
echo "The number is even"
fi
```
We don't need to use `[[ ... ]]` in this case.
---
See also:
* [Difference between Bash operators double vs single brackets and ((](https://unix.stackexchange.com/q/306111/201820) (on Unix & Linux Stack Exchange)
* [How do I check whether a variable has an even numeric value?](https://stackoverflow.com/a/15660039/6862601) |
17,595,091 | How can I create new `File` (from `java.io`) in memory, not on the hard disk?
I am using the Java language. I don't want to save the file on the hard drive.
I'm faced with a bad API (`java.util.jar.JarFile`). It's expecting `File file` of `String filename`. I have no file (only `byte[]` content) and can create temporary file, but it's not beautiful solution. I need to validate the digest of a signed jar.
```
byte[] content = getContent();
File tempFile = File.createTempFile("tmp", ".tmp");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(archiveContent);
JarFile jarFile = new JarFile(tempFile);
Manifest manifest = jarFile.getManifest();
```
Any examples of how to achieve getting manifest without creating a temporary file would be appreciated. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17595091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It is not possible to create a `java.io.File` that holds its content in (Java heap) memory \*.
Instead, normally you would use a stream. To write to a stream, in memory, use:
```
OutputStream out = new ByteArrayOutputStream();
out.write(...);
```
But unfortunately, a stream can't be used as input for `java.util.jar.JarFile`, which as you mention can only use a `File` or a `String` containing the path to a valid JAR *file*. I believe using a temporary file like you currently do is the only option, unless you want to use a different API.
If you are okay using a different API, there is conveniently a class in the same package, named `JarInputStream` you can use. Simply wrap your `archiveContent` array in a `ByteArrayInputStream`, to read the contents of the JAR and extract the manifest:
```
try (JarInputStream stream = new JarInputStream(new ByteArrayInputStream(archiveContent))) {
Manifest manifest = stream.getManifest();
}
```
---
\*) It's obviously possible to create a full file-system that resides in memory, like a RAM-disk, but that would still be "on disk" (and not in Java heap memory) as far as the Java process is concerned. | I think temporary file can be another solution for that.
```
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(byteArray);
```
There is a an answer about that [here](https://stackoverflow.com/questions/19006461/create-a-temporary-java-io-file-from-byte). |
10,316 | What is the difference between 硕士英语A班 and 工程硕士英语?
I just want to know their exact meaning as Google Translate gives me the same result for both but these words seems to have different meaning.
What I am supposing is that 硕士英语A班 is masters English class and 工程硕士英语 is *not* a class but a whole department or whatever. So I just need to know clear meanings of these two words | 2014/11/12 | [
"https://chinese.stackexchange.com/questions/10316",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3713/"
] | `硕士` means the college degree in modern Chinese, nothing else, unlike the English word Master.
`工程硕士` is Master of Engineering.
`硕士英语` is the English course for a student who is pursuing a master's degree.
`班` is an assembly in which people study and take exams together, usually consisting of 30 or more people.
So to conclude:
`工程硕士英语` is the English course in a college aimed at Chinese M.Eng students who usually have no more than 5000 English words in command. After the course you'll gain an additional 1000 vocabularies as well as a few reading, writing, and translating skills. It's a class focused on basic English skill, not necessarily related to engineering.
`硕士英语A班` is an assembly of M.Eng students taking an English course, this group is labelled as A. There might be B, C, D, etc., but A usually doesn't mean it's better or prioritized; These are just labels. | 工程硕士英语 - English for Master Engineering
硕士英语A班 - English class A for Master (Engineering).
Note that 硕士英语A班 could also be Master (level) English Class A, in a sense of Beginner - Intermediate - Master. `Master` here is referring to the level not a degree |
26,739,622 | I'm trying to import both android support libraries. I'm trying to implent GoogleMaps AP2 into my Android Application. Therefore I need both libraries. I'm using AndroidStudio and Gradle.
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'com.android.support:appcompat-v7:21.0.+'
// compile 'com.google.android.gms:play-services:6.1.+'
compile "com.android.support:support-v13:18.0.+"
compile "com.loopj.android:android-async-http:1.4.5"
repositories {
mavenCentral()
}
compile "com.github.chrisbanes.actionbarpulltorefresh:library:+"
compile 'joda-time:joda-time:2.5'
}
```
The error is:
```
Module version com.android.support:support-v13:18.0.0 depends on libraries but is not a library itself
``` | 2014/11/04 | [
"https://Stackoverflow.com/questions/26739622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908475/"
] | You have to use the latest version of support-v13:21.0.+
You have this error because both appcompat and support-v13 depends on support-v4 and their is a version conflict.
Not the best error by the way. | Remove line: `compile 'com.android.support:appcompat-v7:21.0.+'` |
47,716,468 | I am trying to fix a button to the right edge of a div.
**HTML:**
```
<div id="header">
<button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>
```
**CSS:**
```
#header {
margin-left: 240px;
background-color: #0070e0;
padding: 20px;
position: relative;
}
#header > button {
position: absolute;
top: 10px;
right: 10px;
color: #ffffff;
}
```
**After applying `position: absolute`:**
[](https://i.stack.imgur.com/dsj6e.png)
You can see in the image above that original `padding: 20px` on the parent div is ignored.
**While removing `position: absolute`:**
[](https://i.stack.imgur.com/CRpKm.png)
Brings the original padding back but as you can see the `button` is then not to the right. Applying `float: right` has the same effect.
**Can somebody help me fix this issues and more importantly explain whats causing this so I can better learn.** Apologies if this is a very basic question. | 2017/12/08 | [
"https://Stackoverflow.com/questions/47716468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190986/"
] | It is not ignored, absolute position will not take the padding of parent div. Just set the height of div and center the absolute element. The 20px padding is probabbly the entire height of parent div, if the child element is absolute. To clarify better: Your header is taking the height of 40px (20px padding top, 20px padding bottom), and your absolute button is not going to change the height, however if you don't set the position to absolute, the parent div will take the height of button + 40px of padding.
```css
#header {
margin-left: 240px;
background-color: #0070e0;
padding: 20px;
position: relative;
}
#header > button {
position: absolute;
top: 10px;
right: 10px;
color: #ffffff;
}
```
```html
<div id="header">
<button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus"></button>
</div>
``` | Padding is not removed when you use `absolute`, but the `height` and `width` of your `absolute` element is not a part of your `parent` element anymore so therefore is loses `height`. Now if you want to change `height` of parent element you can either increase `padding` or give it `height` property.
```css
#header {
margin-left: 240px;
background-color: #0070e0;
padding: 40px;
position: relative;
}
#header > button {
position: absolute;
top: 30px;
right: 10px;
color: #ffffff;
}
```
```html
<div id="header">
<button type="button" uk-toggle="target: #offcanvas-flip" uk-icon="icon: plus">x</button>
</div>
``` |
59,030,141 | The following is the date column and it's vardump :
```
<td>{{$words['return_dt'] }}</td>
```
```
2019-11-25 10:08:55
```
How can I add three hours to this so that the output would be :
```
2019-11-25 01:08:55
``` | 2019/11/25 | [
"https://Stackoverflow.com/questions/59030141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6053564/"
] | you can do this via
```
{{ date("Y-m-d H:i:s", strtotime($words["return_dt"]." +3 hours")) }}
```
and output will become
>
> 2019-11-25 13:08:55
>
>
>
If you need `2019-11-25 01:08:55` then you have to minus 9 Hours. | If you use twig you can try this:
```
{{ $words['return_dt']|date_modify("+3 hours")|date("Y-m-d H:i:s") }}
``` |
154,586 | I read this in late '90s and thought the premise was fascinatingly haunting: A very ancient alien race created either a single or many "berzerker" (?) machines during a war with another race. The machines were programmed so that, IIRC, they would continue to go around smashing any planet found to have sentient life.
The war has been long over with both races destroyed but the machines remain on their mission of unstoppable destruction and are the scourge of the galaxy. The story is told from the view of one man who is attempting to stop one of these machines from reaching its next unintended destination, Earth. I don't recall whether he succeeded. The story ended with him in some kind of orbit in an asteroid belt or debris field and going mad, partially or completely, at the enormity of the scene through his viewport. I'm pretty sure the orbit was around a black hole.
I've tried a number of times over the years to find the title of the book. The "berzerker" machine(s) may be just a name that occurred to me and not what they were called in the novel. | 2017/03/13 | [
"https://scifi.stackexchange.com/questions/154586",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28213/"
] | Others ([dmckee](https://scifi.stackexchange.com/questions/154586/identify-science-fiction-novel-about-ancient-machines-destroying-all-sentient-pl#comment402088_154586) and [can-ned food](https://scifi.stackexchange.com/questions/154586/identify-science-fiction-novel-about-ancient-machines-destroying-all-sentient-pl/154590#154590)) have already pointed out that the story you're looking for is from [Fred Saberhagen](https://en.wikipedia.org/wiki/Fred_Saberhagen)'s [*Berserker*](https://en.wikipedia.org/wiki/Berserker_(Saberhagen)) series. There are many stories in this series. I believe you're asking about the ones where Johann Karlsen purposely gets himself and a pursuing berserker trapped in an orbit around a black hole. Karlsen is featured in the four stories described below.
**1.** ["Stone Place"](https://www.isfdb.org/cgi-bin/title.cgi?54078): novelette, first published in [*If*, March 1965](https://www.isfdb.org/cgi-bin/pl.cgi?58786+c), available at the [Internet Archive](https://archive.org/details/1965-03_IF). ISFDB synopsis:
>
> The various human societies inside and outside the Solar System form an uneasy alliance to launch a massed attack on the mechanized Berserker fleet which is dedicated to destroying all life.
>
>
>
This story introduces the character Johann Karlsen, leader of the fleet of the human alliance in a great battle against the berserkers:
>
> Throughout the long war, the berserker computers had gathered and collated all available data on the men who became leaders of Life. Now against this data they matched, point for point, every detail that could be learned about Johann Karlsen.
>
>
> The behavior of these leading units often resisted analysis, as if some quality of the life-disease in them was forever beyond the reach of machines. These individuals used logic, but sometimes it seemed they were not bound by logic. The most dangerous life-units of all sometimes acted in ways that seemed to contradict the known supremacy of the laws of physics and chance, as if they could be minds possessed of true free will, instead of its illusion.
>
>
>
>
**2.** ["Masque of the Red Shift"](https://www.isfdb.org/cgi-bin/title.cgi?54115): novelette, first published in [*If*, November 1965](https://www.isfdb.org/cgi-bin/pl.cgi?58819+c), available at the [Internet Archive](https://archive.org/details/1965-11_IF). ISFDB synopsis:
>
> A robotic representative of a giant artificially intelligent war machine programmed to destroy all life infiltrates the decadent court of the human rulers.
>
>
>
The black hole, or "hypermass" as it's called, is introduced at the beginning of this story:
>
> Nogara had not come here to look at galaxies, however; he had come to look at something new, at a phenomenon never before seen by men at such close range.
>
>
>
>
It ends with Karlsen and the pursuing berserker flying into the hypermass:
>
> The launch was now going certainly into the hypermass, gripped by a gravity that could make any engines useless. And the berserker-ship was going headlong after the launch, caring for nothing but to make sure of Karlsen.
>
>
>
>
**3.** ["In the Temple of Mars"](https://www.isfdb.org/cgi-bin/title.cgi?54139): novelette, first published in [*If*, April 1966](https://www.isfdb.org/cgi-bin/pl.cgi?58699+c), available at the [Internet Archive](https://archive.org/details/1966-03_IF). ISFDB synopsis:
>
> A gladiator becomes a pawn in the schemes of a death cult which worships Berserker machines.
>
>
>
Karlsen is offstage in this story, but a plan for rescuing him is discussed:
>
> "Yes, I think there is a chance." Hemphill's face had become iron again. "You saw what efforts the berserkers made to kill him. They feared him, in their iron guts, as they feared no one else. Though I never quite understood why . . . so, if we can save him, we must do so without delay. Do you agree?"
>
>
>
>
**4.** ["The Face of the Deep"](https://www.isfdb.org/cgi-bin/title.cgi?54165): short story, originally published in [*If*, September 1966](https://www.isfdb.org/cgi-bin/pl.cgi?58846+c), available at the [Internet Archive](https://archive.org/stream/1966-09_IF#page/n47/mode/2up). ISFDB synopsis:
>
> A hero in the war against machines which intend to exterminate all life is rescued from orbit around a black hole.
>
>
>
This story opens with Karlsen, in orbit around the hypermass, admiring the view outside his craft:
>
> After five minutes had gone by with no apparent change in his situation, Karlsen realized that he might be going to live for a while yet. And as soon as this happened, as soon as his mind dared open its eyes again, so to speak, he began to see the depths of space around him and what they held.
>
>
>
>
I think you must have read more than one of these stories; you certainly must have read "The Face of the Deep", because that's the only one that depicts Karlsen in orbit around the black hole, admiring the scenery; but I think you must have read one or more of the earlier stories as well. All four of them appeared in the collection [*Berserkers: The Beginning*](https://www.isfdb.org/cgi-bin/pl.cgi?4062) which was published in 1998, agreeing with your "late 90s." Alternatively, you could have read them in in the earlier collection [*Berserker*](https://www.isfdb.org/cgi-bin/titlecovers.cgi?25732), perhaps in one of the [Ace Books editions](https://www.isfdb.org/cgi-bin/pl.cgi?355186). | If it wasn't a book, it could've been this:
>
> An alien probe approaches the station with a series of questions that have to be answered correctly within 24 hours, or Babylon 5 will be destroyed.
>
> The probe does not in fact explode but is part of a Berserker style campaign, designed to wipe out races that are technologically superior to the creators of the probe.[1](https://en.wikipedia.org/wiki/A_Day_in_the_Strife)
>
>
>
(It probably wasn't, but I thought it deserved an honorable mention as my first introduction to a similar concept.) |
29,480,421 | A friend of mine had to draw a mandelbrot with opengl in c. I decided to do it in Swift.
The first method I tried was by creating an array with ARGB data and convert this into a CGImage and view that one in an UIImageView. However this was not fast enough.
Now I am wondering, what is the fastest way to draw individual pixels onto the screen. I looked into Metal but that seemed to be mostly about triangles and 3d stuff. Then I came to scenekit shaders (.fsh) and thought maybe that was a good solution. However I want also be able to zoom into the mandelbrot fractal and I couldnt find a way to input variables in my mandelbrot (my reference: <https://www.weheartswift.com/fractals-xcode-6/>)
Can you guys tell me/give an example (Swift please) on the fastest way of drawing individual pixels, or at least a way to draw raw pixels to the screen without having to use something intermediate like composing a CGImage? | 2015/04/06 | [
"https://Stackoverflow.com/questions/29480421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3696798/"
] | Rather than using vertex and fragment shaders, take a look at using a kernel function (or compute shader). This would be a single shader that does the maths and sets the color value at each pixel of a texture. You can then render the texture to screen using CAMetalLayer.
Take a look at this blog post where I write to a texture using the coordinates of particles passed into a kernel function: <http://flexmonkey.blogspot.co.uk/2015/03/swift-metal-four-million-particles-on.html> | If you want to compute the fractal on the GPU, then this is much more an OpenGL (or Metal) question than a Swift question. You need to take smaller steps:
1. Get a solid-color triangle on the screen with OpenGL.
2. Fill the screen with two solid-color triangles.
3. Fill the triangles with a simple gradient using a fragment shader.
4. Fill the triangles with a simple texture.
5. Perform two-stage drawing: draw into an off-screen buffer (with triangles and a shader), then use that buffer as your texture to draw on-screen.
6. Draw your fractal into the off-screen buffer using a shader.
Note that step 6 may be hard, and you might need help with it, but there's no point in even starting it until you can do steps 1-5 successfully. You should be able to find lots of tutorials to help you get through steps 1-5, though you may have to translate them to Swift from C, C++, or Objective-C.
The page you linked skips steps 1-5 entirely, because the Xcode scene viewer takes care of them for you. If you want to write a standalone app, you need to learn how to do those steps. |
50,673,678 | I have written a python class whose constructor takes two lists as arguments.
```
class nn:
def __init__(layer_dimensions=[],activations=[]):
self.parameters = {}
self.cache = []
self.activations= []
initialize_parameters(layer_dimensions)
initialize_activations(activations)
net = nn(list([2,15,2]),list(['relu','sigmoid']))
```
On trying to pass two lists as arguments in the constructor I get the following error:
```
TypeError: __init__() takes from 0 to 2 positional arguments but 3 were given
```
The error states that 3 arguments have been passed but its quite obvious that I've passed only 2. | 2018/06/04 | [
"https://Stackoverflow.com/questions/50673678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8253860/"
] | Really appreciate your question, it is very typical to manage if you don't know the way.
Here is a solution.
Magic method is [requestDisallowInterceptTouchEvent](https://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)), this method can allow or deny touch events.
```
public static void smartScroll(final ScrollView scrollView, final RecyclerView recyclerView) {
recyclerView.setOnTouchListener(new View.OnTouchListener() {
private boolean isListOnTop = false, isListOnBottom = false;
private float delta = 0, oldY = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
scrollView.requestDisallowInterceptTouchEvent(true);
recyclerView.requestDisallowInterceptTouchEvent(false);
oldY = event.getY();
break;
case MotionEvent.ACTION_UP:
delta = 0;
break;
case MotionEvent.ACTION_MOVE:
delta = event.getY() - oldY;
oldY = event.getY();
isListOnTop = false;
isListOnBottom = false;
View first = recyclerView.getChildAt(0);
View last = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (first != null && layoutManager.findFirstVisibleItemPosition() == 0 && first.getTop() == 0 && delta > 0.0f) {
isListOnTop = true;
}
if (last != null && layoutManager.findLastVisibleItemPosition() == recyclerView.getChildCount() - 1 && last.getBottom() <= recyclerView.getHeight() && delta < 0.0f) {
isListOnBottom = true;
}
if ((isListOnTop && delta > 0.0f) || (isListOnBottom && delta < 0.0f)) {
scrollView.requestDisallowInterceptTouchEvent(false);
recyclerView.requestDisallowInterceptTouchEvent(true);
}
break;
default:
break;
}
return false;
}
});
}
```
This solution is for ScrollView and RecyclerView but you can use this for any kind of Views like ViewPager, ScrollView, ListView by using `requestDisallowInterceptTouchEvent`. | Can you please try following example or way may be this will help you.
```
myRecyclerViewHorizental.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false) {
@Override
public boolean canScrollHorizontally() {
//return false if you don't want to scroll horizontal
return true;
}
@Override
public boolean canScrollVertically() {
//return false if you don't want to scroll vertical
return false;
}
});
``` |
2,004,870 | I have a comma separated string, out of which I need to create a new string which contains a random order of the items in the original string, while making sure there are no recurrences.
For example:
Running 1,2,3,1,3 will give 2,3,1 and another time 3,1,2, and so on.
I have a code which picks a random item in the original string, and then iterates over the new string to see if it does not exist already. If it does not exist - the item is inserted.
However, I have a feeling this can be improved (in C# I would have used a hashtable, instead of iterating every time on the new array). One improvement can be removing the item we inserted from the original array, in order to prevent cases where the random number will give us the same result, for example.
I'd be happy if you could suggest improvements to the code below.
```
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}
```
Thanks! | 2010/01/05 | [
"https://Stackoverflow.com/questions/2004870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124110/"
] | You can still use a 'hash' in javascript to remove duplicates. Only in JS they're called objects:
```
function removeDuplicates(arr) {
var hash = {};
for (var i=0,l=arr.length;i<l;i++) {
hash[arr[i]] = 1;
}
// now extract hash keys... ahem...
// I mean object members:
arr = [];
for (var n in hash) {
arr.push(n);
}
return arr;
}
```
Oh, and the select random from an array thing. If it's ok to destroy the original array (which in your case it is) then use splice:
```
function randInt (n) {return Math.floor(Math.random()*n)}
function shuffle (arr) {
var out = [];
while (arr.length) {
out.push(
arr.splice(
randInt(arr.length),1 ));
}
return out;
}
// So:
newArray = shuffle(
removeDuplicates(
string.split(',') ));
``` | With your solution, you are not guaranteed not to pick same number several times, thus leaving some others of them never being picked. If the number of elements is not big (up to 100), deleting items from the source array will give the best result.
**Edit**
```
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1 - j));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
var tmp = originalArray[originalArray.length - 1 - j];
originalArray[originalArray.Length - 1 - j] = originalArray[iPlaceInOriginalArray];
originalArray[iPlaceInOriginalArray] = tmp;
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}
``` |
48,148,163 | I have an existing pdf file with multiple pages to which I would like to put a border to all pages.
So I create a class that inherits from PdfPageEventHelper and I override the OnEndPage and assign the instance of that class to the PageEvent of PdfWriter instance:
```
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace My.Apps.WPF.Classes
{
public class PdfEventHelper : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
{
// Add border to page
PdfContentByte content = writer.DirectContent;
iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(document.PageSize);
rectangle.Left += document.LeftMargin;
rectangle.Right -= document.RightMargin;
rectangle.Top -= document.TopMargin;
rectangle.Bottom += document.BottomMargin;
content.SetColorStroke(BaseColor.BLACK);
content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
content.Stroke();
}
}
}
```
Then in main program I have a method that returns a new PDF with a border in all its pages (source pdf document 'pdfFilePath' is in landscape, so I keep orientation in new one):
```
private string PutBorderToPdfPages(string pdfFilePath)
{
string newPdf = @"C:\Output.pdf";
using (var reader = new PdfReader(pdfFilePath))
{
using (var fileStream = new FileStream(newPdf, FileMode.Create, FileAccess.Write))
{
iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
PdfEventHelper pdfEvent = new PdfEventHelper();
PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
writer.PageEvent = pdfEvent;
document.Open();
document.Close(); // here it crashes, see below in post exception thrown
writer.Close();
}
}
return newPdf;
}
```
In run-time, in line:
```
document.Close();
```
I get an IO.Exception that says:
>
> The document has no pages.
>
>
>
In this case, Pdf document has only 1 page.
What am I doing wrong? I do not want to write anything to the existing pdf file, I only want to create a new PDF file exactly the same as source but with a border in all its pages.
**UPDATE**:
**ATTEMPT #1**:
I have done below, but I get all page in black (I do not know how to do the rectangle not filled):
```
private string PutBorderToPdfPages(string pdfFilePath)
{
string newPdf = @"C:\Output.pdf";
using (var reader = new PdfReader(pdfFilePath))
{
using (var fileStream = new FileStream(newPdf, FileMode.Create, FileAccess.Write))
{
using (var pdfStamper = new PdfStamper(reader, fileStream))
{
int PageCount = reader.NumberOfPages;
for (int p = 1; p <= PageCount; p++)
{
// Add border to page
PdfContentByte cb = pdfStamper.GetOverContent(p);
iTextSharp.text.Rectangle rectangle = pdfReader.GetPageSizeWithRotation(p);
rectangle.BackgroundColor = iTextSharp.text.BaseColor.BLACK;
cb.Rectangle(rectangle);
}
}
}
}
return newPdf;
}
```
**ATTEMPT #2**:
In this attempt, I get an ObjectDisposedException:
>
> Cannot access to a closed file.
>
>
>
when exiting the using of pdfStamper:
```
private string PutBorderToPdfPages(string pdfFilePath)
{
string newPdf = @"C:\Output.pdf";
using (var reader = new PdfReader(pdfFilePath))
{
using (var fileStream = new FileStream(newPdf, FileMode.Create, FileAccess.Write))
{
iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
using (var pdfStamper = new PdfStamper(reader, fileStream))
{
for (int p = 0; p < pdfStamper.Reader.NumberOfPages; p++)
{
// Add border to page
PdfContentByte content = writer.DirectContent;
iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(document.PageSize);
rectangle.Left += document.LeftMargin;
rectangle.Right -= document.RightMargin;
rectangle.Top -= document.TopMargin;
rectangle.Bottom += document.BottomMargin;
content.SetColorStroke(iTextSharp.text.BaseColor.BLACK);
content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
content.Stroke();
}
document.Close();
writer.Close();
}
}
}
return newPdf;
}
``` | 2018/01/08 | [
"https://Stackoverflow.com/questions/48148163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624552/"
] | You do
```
document.Open();
document.Close(); // here it crashes, see below in post exception thrown
```
I.e. you start a new document, add nothing to it, and then close it. Thus, it would be empty which iText responds to with `The document has no pages.`
Thus, the exception is completely correct.
---
The correct way to *"put a border to all pages"* of *"an existing pdf file"* is to
* open the document in a `PdfReader`,
* create a `PdfStamper` operating on that `PdfReader`,
* iterate over the pages of it and add borders,
* and close the `PdfStamper`.
E.g. like this for a source file `source` and a target file `dest`:
```
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
{
Rectangle cropBox = reader.GetCropBox(pageNumber);
Rectangle rectangle = new Rectangle(cropBox);
rectangle.Left += 20;
rectangle.Right -= 20;
rectangle.Top -= 20;
rectangle.Bottom += 20;
PdfContentByte content = stamper.GetOverContent(pageNumber);
content.SetColorStroke(iTextSharp.text.BaseColor.BLACK);
content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
content.Stroke();
}
}
``` | The **The document has no pages** error is thrown because you create a document that has no pages. It's as simple as that.
Look at your code:
```
Document document = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
document.Close();
```
You aren't adding any content between `document.Open();` and `document.Close();`
Change it to:
```
Document document = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
document.Add(new Paragraph("Some content"));
document.Close();
```
The error will disappear. If you don't want to add any content to the document, then... what's the point in creating the document?
**Extra remark:** I see that you create a document with a page size that is taken from another document: `reader.GetPageSizeWithRotation(1)`. What's your purpose? If you want to copy a page from another document, you are doing it wrong! You should use `PdfStamper` instead; that is, if you insist on working with an old version of iText.
**The real solution:** upgrade to iText 7, and you won't have this problem. |
4,863,650 | In C, I sometimes used structures such as
```
enum {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;
```
Is there any Java equivalent? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4863650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282635/"
] | You don't need that binary logic with enums in java any more. You just need `enum` itself and `EnumSet`.
For example:
```
enum Color {
Red, Green, Blue, Orange, White, Black
}
...
EnumSet<Color> mainColors = EnumSet.of(Color.Red, Color.Green, Color.Blue);
Color color = getSomeColor();
if (mainColors.contains(color)) {
//mainColors is like Red | Green | Blue,
//and contains() is like color & mainColors
System.out.println("Your color is either red or blue or green");
}
``` | Don't really know what that C code does, but here's the closest you'll get to it in Java:
```
enum UIView {
UIViewAutoresizingNone ( 0),
UIViewAutoresizingFlexibleLeftMargin ( 1 << 0),
UIViewAutoresizingFlexibleWidth ( 1 << 1),
UIViewAutoresizingFlexibleRightMargin ( 1 << 2),
UIViewAutoresizingFlexibleTopMargin ( 1 << 3),
UIViewAutoresizingFlexibleHeight ( 1 << 4),
UIViewAutoresizingFlexibleBottomMargin ( 1 << 5);
private final int value;
private UIView(int value){
this.value = value;}
public int getValue(){
return value;
}
};
``` |
47,000,335 | I have a variable `var image = SKSpriteNode(imageNamed: "image")` and it is an outline. I want to fill the image with colour but do not know the code necessary. Would someone be able to provide a solution? | 2017/10/29 | [
"https://Stackoverflow.com/questions/47000335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6784553/"
] | Simply
```
[.?!]*(?=[.?!]$)
```
should do it for you. Like
```
Regex re = new Regex("[.?!]*(?=[.?!]$)");
Console.WriteLine(re.Replace("This is a string....!", ""));
```
This replaces all punctuations but the last with nothing.
`[.?!]*` matches any number of consecutive punctuation characters, and the `(?=[.?!]$)` is a positive lookahead making sure it leaves one at the end of the string.
[See it here at ideone](https://ideone.com/4wXFLR). | Your solution works almost fine ([demo](https://ideone.com/VamiZW)), the only issue is when the same sequence could be matched starting at different spots. For example, `..!?!?` from your last line is not part of the substitution list, so `..!?` and `!?` get replaced by two separate matches, producing `??` in the output.
It looks like your strategy is pretty straightforward: in a chain of multiple punctuation characters the last character wins. You can use regular expressions to do the replacement:
```
[!?.]*([!?.])
```
and replace it with `$1`, i.e. the capturing group that has the last character:
```
string s;
while ((s = Console.ReadLine()) != null) {
s = Regex.Replace(s, "[!?.]*([!?.])", "$1");
Console.WriteLine(s);
}
```
[Demo](https://ideone.com/Lge6gJ) |
14,671 | I've got a dataset of demographic details of store customers and which store they (most frequently) visit. **I would like to categorize the stores based on their customers.**
To clarify: The issue here is to create clusters of shops, on the basis of the characteristics of the customers who have attended them. In other words, the aim is to create clusters of shops having a similar clientele.
I have around 7,000 customer records, distributed (unevenly) across about 50 stores. Most of the customer data is categorical, but there are a couple of continuous variables. How should I go about categorizing the different stores? | 2011/08/23 | [
"https://stats.stackexchange.com/questions/14671",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/179/"
] | I would greatly consider looking into Latent Dirichlet Allocation. It's not a clustering algorithm, but rather a topic model -- individual stores would be modeled as mixes of underlying themes. Different types of customers would have varying likelihoods based on particular themes. It is a fully generative, Bayesian model, so you get some very detailed information about the themes in each store, and the customer properties associated with themes.
There is a free C version of it that you can use; otherwise, a Gibbs Sampling package like BUGS can fit the model using a fairly straightforward of the Bayesian network underlying the model. | I'm doing something similar and my process is described. Using PCA could be helpful. This will give you the most significant variables from the demographics that are present. Using K-means, pam, clara etc, cluster the stores using the significant variables.
Hope This Helps |
69,065,985 | I have two JSON objects with the same structure/value and I want to concat them together using Javascript.
My first array looks like this:
```js
[{
"name": "Spain",
"year": [
"2010"
]
},
{
"name": "Brazil",
"year": [
"1994",
"1970",
"1962",
"2002",
"1958"
]
},
{
"name": "Germany",
"year": [
"2014",
"1990",
"1974",
"1954"
]
},
{
"name": "Italy",
"year": [
"2006",
"1982",
"1938",
"1934"
]
},
{
"name": "France",
"year": [
"2018",
"1998"
]
},
{
"name": "Argentina",
"year": [
"1986",
"1978"
]
},
{
"name": "Uruguay",
"year": [
"1930",
"1950"
]
},
{
"name": "England",
"year": [
"1966"
]
}
]
```
My second array:
```js
[{
"name": "Spain",
"anzahl": 1
},
{
"name": "Brazil",
"anzahl": 5
},
{
"name": "Germany",
"anzahl": 4
},
{
"name": "Italy",
"anzahl": 4
},
{
"name": "France",
"anzahl": 2
},
{
"name": "Argentina",
"anzahl": 2
},
{
"name": "Uruguay",
"anzahl": 2
},
{
"name": "England",
"anzahl": 1
}
]
```
I am looking for a solution to merge all the same keys and add the values of the merged keys together to get something looking like this:
```js
[{
"name": "Spain",
"year": [
"2010"
]
"anzahl": 1
},
{
"name": "Brazil",
"year": [
"1994",
"1970",
"1962",
"2002",
"1958"
]
"anzahl": 5
},
.....
]
```
Any help would be awesome, thanks :) | 2021/09/05 | [
"https://Stackoverflow.com/questions/69065985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15005346/"
] | Map through the first array and use [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) to assign the properties from the item with the same `name` property in the second array (with [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)) to the current item:
```js
const arr1=[{name:"Spain",year:["2010"]},{name:"Brazil",year:["1994","1970","1962","2002","1958"]},{name:"Germany",year:["2014","1990","1974","1954"]},{name:"Italy",year:["2006","1982","1938","1934"]},{name:"France",year:["2018","1998"]},{name:"Argentina",year:["1986","1978"]},{name:"Uruguay",year:["1930","1950"]},{name:"England",year:["1966"]}],arr2=[{name:"Spain",anzahl:1},{name:"Brazil",anzahl:5},{name:"Germany",anzahl:4},{name:"Italy",anzahl:4},{name:"France",anzahl:2},{name:"Argentina",anzahl:2},{name:"Uruguay",anzahl:2},{name:"England",anzahl:1}]
const result = arr1.map(e => Object.assign(e, arr2.find(f => f.name == e.name)))
console.log(result)
``` | A naive solution to work with any number of dynamic keys:
[Solution Link](https://jsfiddle.net/2n5xf47d/)
```
const json1 = [{
name: "test1",
city: [
]
}, {
name: "test2",
city: [
]
}];
const json2 = [{
age: "19",
address:"cb usa"
}, {
age: "20"
}];
let t = Object.assign({}, json1);
for(let i=0;i< json1.length;i++) {
let l = Object.keys(json2[i]);
for(let j=0;j< l.length;j++) {
t[i][l[j]] =json2[i][l[j]] ;
}
}
console.log(t);
``` |
15,464,146 | My goal is get a JSON like
```json
{
"meta": {
"error_type": "error type",
"code": 400,
"error_message": "error msg"
}
}
```
In case something went wrong.
I tried to put the try catch block both in the rest controller's action and in the model but I get the whole exception stack (I mean with the layout + view)
What's the right way ? | 2013/03/17 | [
"https://Stackoverflow.com/questions/15464146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356380/"
] | **Yet another way**
Do you have access to MS-Access 2000+?
If so add the Access Objects library reference and you will be able to use Eval function:
```
result = Eval("'y' IN ('x1', 'x2', '...' 'xn')")
```
It evaluates string expressions. Some of the SQL operators like the `IN` can be used.
See [documentation](http://msdn.microsoft.com/en-us/library/office/aa159060%28v=office.10%29.aspx) | Quite easy idea to check if the value exist is to use `Match` function:
```
Dim myTBL As Variant
myTBL = Array(20, 30, 40, 50, 60)
'if value '30' exists in array than the position (which is >0) will be returned
Debug.Print WorksheetFunction.Match(30, myTBL, 0)
```
The only problem is that if the value doesn't exist the Match function returns an error. Therefore you should use error handling technique.
That could look like for non existing value '70':
```
'if doesn't exists error would be returned
On Error Resume Next
Debug.Print WorksheetFunction.Match(70, myTBL, 0)
If Err.Number <> 0 Then
Debug.Print "not exists"
Err.Clear
End If
```
Unfortunately, that will work only in Excel. |
16,635,182 | I have this CSS rule for rounded corner:
```
th, td { padding: 8px;
background: #E8ECE0;
text-align: center;
border: 1px solid #444;
border-bottom-width: 0px;
}
thead { background-color: #446bb3 ; color :#fff; padding:4px; line-height:30px }
tbody tr:nth-child(even) {background: #F6F6EC;}
tbody tr:nth-child(odd) {background: #FFF}
tr:first-child td, tr:first-child th {
border-top-left-radius: 12px; border-top-right-radius: 12px;
}
tr:last-child td {
border-bottom: 1px solid #444;
border-bottom-left-radius: 12px; border-bottom-right-radius: 12px;
}
table { border-spacing: 0; border: 0; margin:0px; width:100%; padding:5px}
td.pd {border-bottom-left-radius: 12px; border-bottom-right-radius: 12px;}
td.pu {border-top-left-radius: 12px; border-top-right-radius: 12px;}
```
My html table is:
```
<table >
<tbody>
<tr >
<td >Hello</td><td >Hello</td>
</tr>
<tr >
<td >Hello</td><td >Hello</td>
</tr>
<tr >
<td >Hello</td><td >Hello</td>
</tr>
<tr >
<td >Hello</td><td >Hello</td>
</tr>
</tbody>
</table>
```
which gives me this

How do I fix this problem, as the td elements within the table and in the middle of the table have rounded corners too? I only need the first row and last row to have rounded corners. | 2013/05/19 | [
"https://Stackoverflow.com/questions/16635182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362461/"
] | This answer doesn't answer your question directly, but a variant.
If you dont want the middle columns to have rounded corners, this is a possible solution:
Illustration:

Properties for the table row (tr): update the table data (td) for the left most column:
```
tbody tr td:first-child
{
border-radius: 0.6em 0 0 0.6em;
}
```
Properties for the table row (tr): update the table data (td) for the second column:
```
tbody td:nth-child(2)
{
border-radius: 0 0.6em 0.6em 0;
}
```
Here is an example: [JS Fiddle demo](http://jsfiddle.net/rtc11/S88YL/)
If you have more than one column (td or th) you simply add something like this:
```
tbody td:nth-child(2) /* This is now the middle element out of three */
{
border-radius: 0 0 0 0;
}
tbody td:nth-child(3) /* This is now the right most column */
{
boder-radius: 0 0.6em 0.6em 0;
}
``` | You can give id to the td elements and using the id's of td elements set the border radius to 0px. |
31,418,569 | Whenever I try to install any of Google's cocoapods I get one of two errors.
Either:
```
$ pod install
Analyzing dependencies
[!] The version of CocoaPods used to generate the lockfile (0.38.0.beta.2) is higher than the version of the current executable (0.37.2). Incompatibility issues may arise.
CocoaPods 0.38.0.beta.2 is available.
To update use: `gem install cocoapods --pre`
[!] This is a test version we'd love you to try.
For more information see http://blog.cocoapods.org
and the CHANGELOG for this version http://git.io/BaH8pQ.
Downloading dependencies
Installing Google (1.0.7)
[!] Error installing Google
...
inflating: /var/folders/<myDirectory>/Samples/signin/SignInExampleSwift/ViewController.swift
warning [/var/folders/<myDirectory>/file.zip]: 375 extra bytes at beginning or within zipfile
(attempting to process anyway)
```
Or:
```
$ pod install
[in /Users/<user>/Desktop/FakeProject]
Analyzing dependencies
CocoaPods 0.38.0.beta.2 is available.
To update use: `gem install cocoapods --pre`
[!] This is a test version we'd love you to try.
For more information see http://blog.cocoapods.org
and the CHANGELOG for this version http://git.io/BaH8pQ.
Downloading dependencies
Installing AppInvites (1.0.1)
[!] Error installing AppInvites
[!] /usr/bin/tar xfz /var/folders/<myDirectory>/file.tgz -C /var/folders/<myDirectory>
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.
```
I've been trying this with both new and existing objective-c projects and have tried uninstalling and re-installing cocoapods. Not really sure what the issue seems to be and Google doesn't have any troubleshooting for their cocoapods. | 2015/07/14 | [
"https://Stackoverflow.com/questions/31418569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5117157/"
] | Try updating your gem
```
sudo gem update -n /usr/local/bin cocoapods
pod install
``` | **After 6 hours i found this**
go to <http://cocoapods.org/> and download tar file |
15,096,486 | I am trying to track `pageviews` with `Google Analytics` but I keep getting an error on the import. I have listed in the code below where the errors are.
I also have put the jar file in the java build path and added the two lines in the `Android Manifest`.
My question is how to get the below code to compile correctly.
```
import com.google.android.apps.analytics.GoogleAnalyticsTracker; //Error: "The import com.google.android.apps cannot be resolved"
public class MainMenu extends Activity {
GoogleAnalyticsTracker tracker; //Error: "The import com.google.android.apps cannot be resolved to a type"
final Context context = this;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainmenumain);
tracker = GoogleAnalytics.getInstance();
tracker.startSession("UA-38788135-1", this);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
tracker.trackPageView("/Categories"); //Error: "The import com.google.android.apps cannot be resolved to a type"
Intent intent = new Intent(MainMenu.this, Categories.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
tracker.trackPageView("/Highscores"); //Error: "The import com.google.android.apps cannot be resolved to a type"
Intent intent = new Intent(MainMenu.this, Highscores.class);
startActivity(intent);
}
});
btn3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
tracker.trackPageView("/About"); //Error: "The import com.google.android.apps cannot be resolved to a type"
Intent intent = new Intent(MainMenu.this, About.class);
startActivity(intent);
}
});
btn4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
tracker.trackPageView("/ComingSoon"); //Error: "The import com.google.android.apps cannot be resolved to a type"
Intent intent = new Intent(MainMenu.this, ComingSoon.class);
startActivity(intent);
}
});
}
```
 | 2013/02/26 | [
"https://Stackoverflow.com/questions/15096486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1866707/"
] | You are trying to track Button clicks in google analytics but don't use trackPageView inside onClick() to track button events
```
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
tracker.trackPageView("/Categories"); //Error: "The import com.google.android.apps cannot be resolved to a type"
Intent intent = new Intent(MainMenu.this, Categories.class);
startActivity(intent);
}
});
```
Use this code for Button events tracking inside onClick() instead of above onClick() code
```
GaTracker.trackEvent("Your Buttons Category", "Your event name", "", 0L);
GAServiceManager.getInstance().dispatch();
```
Declare
```
private Tracker GaTracker;
private GoogleAnalytics GaInstance;
```
Inside onCreate() method use
```
GaInstance = GoogleAnalytics.getInstance(this);
GaTracker = GaInstance.getTracker("YOUR UA-Here");
GaTracker.sendView("/YourActivity"); // Include this line if you want to track page view
``` | GoogleAnalyticsTracker is used in libGoogleAnalyticsV1.jar but you are using libGoogleAnalyticsV2.jar which is the latest version. To track a page view in libGoogleAnalyticsV2 use the following code
Declare
```
private Tracker GaTracker;
private GoogleAnalytics GaInstance;
```
Inside onCreate() method
```
GaInstance = GoogleAnalytics.getInstance(this);
GaTracker = GaInstance.getTracker("YOUR UA-Here");
GaTracker.sendView("/YourActivity");
``` |
19,996,124 | How can implement in current class every abstracts methods quickly from her extended classes in Android Studio?
For example, in Eclipse, putting mouse over warning and pressing on implement abstract methods message do it automatically. | 2013/11/15 | [
"https://Stackoverflow.com/questions/19996124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/851951/"
] | `android studio` Right click than Select `Generate..` or `Alt` + `Enter` and get list of methods you can add into your `Activity`
For more to Implementing Methods of an Interface IntelliJ IDEA check <https://www.jetbrains.com/idea/help/implementing-methods-of-an-interface.html> | Which Android-Studio version are you using? I'm using Android-Studio 0.3.6 and this is working pretty similar to eclipse just hover the error , click the red light and Android-Studio offers you to generate the missing methods. |
110,364 | Can somebody please explain the difference between "ask of me" and "ask me"? Why do we use "of" between ask and me? | 2013/04/04 | [
"https://english.stackexchange.com/questions/110364",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/12348/"
] | "Ask of someone" would tend to imply asking for something from someone, perhaps a favor. Whereas, "ask someone" simply means to ask someone something, like a question. | I think they are both like a question, just with different usage between "ask something of someone" and "ask someone something". |
847,946 | If I want to define domain controller then i would say DC is where active directory installed or
Acitve Directory simply means: Secure centralized authentication and management
and domain controller = ADDS + DNS.
But I get confused when i read [here](https://serverfault.com/questions/573681/should-i-expose-my-active-directory-to-the-public-internet-for-remote-users#573751) that
>
> I also think it is VERY EASY to say DOMAIN CONTROLLER == ACTIVE
> DIRECTORY, which isn't quite the case.
>
>
>
I want to know is it correct or wrong? If wrong then what is the difference? | 2017/05/03 | [
"https://serverfault.com/questions/847946",
"https://serverfault.com",
"https://serverfault.com/users/413527/"
] | Active Directory is what is called a directory service, it stores objects like users and computers. So you can consider it as as database that store users and computers configuration in AD domain.
A domain controller is the server running Active Directory; Domain controllers are typically referred as DC. Domain controller is a server based on MS windows Server 200X which is responsible for allowing host access to domain resources.
A Domain controller authenticates the users and the computers to join the domain. You can have many Domain controllers in your AD for many reasons, like redundancy and load balance as users can use anyone of them as they are replicating AD database. | Active directory is just like a database that stores information as object of users and computers. But Domain Controller (DC) is a server that runs Active Directory and use data stored on AD for authentication and authorization of users. Domain controller manages security policies of Window NT or Windows Server. |
19,406,149 | I have a UITableView and I have set my cell background color to RGB 244, 240, 246. I've done this by setting the background color on the table, table cell, and the content view in the table cell.
However, the accessory (in this case the checkmark) has a black background instead.

When I enable editing on the table, the delete circle on the left side also has a black background.

I cannot seem to change this background color.
I've tried doing so with the following code:
```
cell.editingAccessoryView = [[UIView alloc] init];
cell.editingAccessoryView.backgroundColor = [UIColor colorWithRed:244/255 green:240/255 blue:246/255 alpha:1.0];
```
but it has no effect.
I've tried looking for a setting within the storyboard but nothing seems to make any difference.
I did notice that if I change the table cell and content view background color to "default" the whole cell background becomes black (even though the table background color is still my custom color).
I've gone through the iOS7 Transition guide and I didn't see anything related to the UIAccessoryView. I've also searched through stackoverflow but I wasn't able to find anything matching the issue I'm having.
How can I fix this? | 2013/10/16 | [
"https://Stackoverflow.com/questions/19406149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293818/"
] | The problem was caused by the colour object. The correct line is:
```
cell.editingAccessoryView.backgroundColor = [UIColor colorWithRed:244/255.0f green:240/255.0f blue:246/255.0f alpha:1.0];
```
My best guess is that without the .0f it was treating the numbers as ints and truncating all the values to 0 (which would give me black). | For table view cell, there is a property called `backgroundView`. You only need to change the backgroundcolor for the backgroundView. Thats it.
```
cell.backgroundView.backgroundColor = [UIColor yourcolor];
``` |
33,689,875 | I know that
```
class A { }
class B extends A { }
class C extends B { }
```
is completely legal and I can
```
C obj = new C();
obj.anyMethodfromA();
```
is possible.
Now question is this What if I don't want to access **class A** methods in **class C** only **class B** methods should be inherited.
Is this possible?
```
C anotherObj = new C();
anotherObj.anyMethodfromA(); //can be illegal?
anotherObj.anyMethodfromB(); //should be legal.
``` | 2015/11/13 | [
"https://Stackoverflow.com/questions/33689875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Restricting access for certain subclasses is not possible. You could use interfaces instead to add certain a functionality to a specific class in addition to inheritance. | You can use some sleight of hand using `interface` to hide the `methodFromA` but you cannot actually remove it.
```
class A {
public void methodFromA() {
System.out.println("methodFromA");
}
}
class B extends A {
public void methodFromB() {
System.out.println("methodFromB");
}
}
class C extends B {
}
interface D {
public void methodFromB();
}
class E extends B implements D {
}
public void test() {
// Your stuff.
C obj = new C();
obj.methodFromA();
// Make a D
D d = new E();
d.methodFromB();
// Not allowed.
d.methodFromA();
// Can get around it.
E e = (E) d;
e.methodFromA();
}
``` |
40,257,207 | I'm having this simple `<input>` radio user choice.
```
<sample>
<ul>
<li each={ techs }>
<input
type='radio'
name='dev_choice'
value={ name }
onclick={ check_choice }>
{ name }
</input>
</li>
</ul>
<button onclick={ check_selection }>Check</button>
<script>
this.message = 'Hello, Riot!'
this.techs = [
{ name: 'HTML', rank: '10' },
{ name: 'JavaScript', rank: '20' },
{ name: 'CSS', rank: '30' }
]
check_choice(e) {
// This is working fine
console.log(e.item.rank)
}
check_selection(e) {
// How do I get the rank of my selected item ??
// None of the below is working
console.log(this.dev_choice)
var choice = $("input[name='dev_choice']:checked")
console.log(choice)
}
</script>
</sample>
```
RiotJs seems to bind the object used to create the loop to the html objects. However, I don't see any way to access this object from another function.
Any clue would be welcome !
More generally speaking, how to access `this.techs` from `$('sample')` ?
Full running example on <http://plnkr.co/edit/2ZuIF4iZQ1WS2CuOOiQb> | 2016/10/26 | [
"https://Stackoverflow.com/questions/40257207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/554374/"
] | I'm using closures for this kind of problem
```
<sample>
<h2>{ message }</h2>
<ul>
<li each={ techs }>
<input
type='radio'
name='dev_choice'
value={ name }
checked={currentRank === rank}
onclick={ check_choice(rank) }>
{ name }
</input>
</li>
</ul>
<button onclick={ check_selection }>Check</button>
<script>
this.message = 'Hello, Riot!'
this.techs = [
{ name: 'HTML', rank: '10' },
{ name: 'JavaScript', rank: '20' },
{ name: 'CSS', rank: '30' }
]
// Use this line if you want no radio checked
// this.currentRank = void 0
// Use this line if you want a default value
this.currentRank = '30'
check_choice(rank) {
return () => {
this.currentRank = rank
}
}
check_selection() {
alert(this.currentRank)
}
</script>
</sample>
```
Please, check my fork <http://plnkr.co/edit/TUvaWnL8glRWCoBi549g?p=preview> | I am 100% sure what you want but I interpret that you want to get the full object of the tech (with name and rank) for the selected object. If so here is what I will do ( [Plnkr](http://plnkr.co/edit/2ZuIF4iZQ1WS2CuOOiQb?p=preview) )
Basically I add a var to get the selected item for later access.
```
var selectedTech = null
check_choice(e) {
selectedTech = e.item
}
check_selection(e) {
alert(JSON.stringify(selectedTech))
}
```
Everything else is the same.
Hope this helps. |
15,689,440 | Is it possible to display an icon or image in a row of a dataview when using the XPages UP1 mobile control?
A facet for an icon is available in the control but it does not seem to render an image/icon on the browser page. | 2013/03/28 | [
"https://Stackoverflow.com/questions/15689440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1195975/"
] | The iconColumn does render on mobile controls using Domino 9.0 | Icons can be displayed in **DataView** on mobile.
On **DataView** control there is a property **iconColumn -> icons**.
It can be done like so:
```
<xe:this.iconColumn>
<xe:viewIconColumn>
<xe:this.icons>
<xe:iconEntry alt="Discussion" styleClass="mblListItemIcon">
<xp:this.url>.....
```
For a complete example, please look at the code in **TeamRoom** template in **dynamicMobileView.xsp** Custom Control. |
114,803 | A race of pseudo-humans army must plan a system of rations for a long campaign on a faraway land in which they cannot rely on foraging. The campaign’s expected to last somewhere between a few months to a couple of years.
Here are the details of the army:
1. It numbers around 50.000 men, all will leave the country, leaving its defense in the hands of a separate defense force.
2. It’s divided into brigades of 5.000, regiments of 1.600, and battalions of 500. There are many types of smaller divisions but they’re dismissible in this question.
3. 2/3 of it is infantry and 1/3 is cavalry (half of it light, the other half heavy).
4. Horses used by the heavy cavalry are very strong and can carry a lot of weight (aside from armour), but the light-breed cannot afford to carry anymore weight without compromising its speed.
5. The soldiers’ health is very important to the army for a number of reasons, and must be kept in pristine condition, so they must provide soldiers with the bare minimum healthy intake of vitamins, carbohydrates, etc...
6. It’s well trained and disciplined.
Details on the race:
1. Their daily water intake is about two to three times bigger than a human’s.
2. Aside from water, all other food consumption is similar to a human’s.
Country details:
1. It’s a producer of limes, lemons, oranges, nuts, corn, potatoes, wheat, pig/cow/chicken/sheep/deer meat, and milk.
2. Its manpower doesn’t allow it to make available more than 1 auxiliary for every 5 soldiers
3. Despite having only 16th century technology, they have discovered the bottling and pasteurization/boiling method of food preservation.
So here comes the questions:
1. How much food (in kg and calories), and what types of food, would the average soldier consume daily?
2. How could this food be transported without compromising speed, maneuverability, and effectiveness? | 2018/06/11 | [
"https://worldbuilding.stackexchange.com/questions/114803",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/38809/"
] | With 16th century logistics, staying in the field for extended periods of time probably requires extensive foraging / raiding. There is an old adage about an army traveling on it's stomach....
Consider this: if it takes 1 lb of food (ignore calories for now) to feed 1 soldier for one day, then feeding 50 soldiers for 20 days is 1000 lbs of food and water. (This is probably a bit light, but it depends on how much water you need to carry, and water is heavy)
In 20 days, soldiers can probably travel 10 miles a day (possibly more, but lets assume no roads but not terribly rough terrain). How are you going to get the 200 lbs of food the 200 miles you have gone? Horses and wagons, probably. But you now have to feed two horses and the teamster for 20 days. Their food has weight, too. Perhaps they eat a collective 5 lbs of food a day (teamster 1, horses 2 each), so they need to carry an additional 100 lbs of food. Just being in the field for 20 days (not very long), and you have to carry 10% more food just to feed the people carrying food!
This isn't taking into account other things like medicine, special equipment, replacement weapons / ammunition, tools, tents, etc. And the further you go, the more you need to carry with you. The more you carry, the more your teamsters and horses eat. And that's just the start of it...
A 16th century army would have cooks, medics, smiths (blacksmiths, gunsmiths, armorsmiths), navigators, engineers (bridges, forts, siege warfare), teamsters, cart wrights, animal handlers, special troops (archers / gunners, pikemen, cavalry, rangers / scouts), artillery, etc. That doesn't even start to consider non-official army personnel, like prostitutes, soldiers family members, and the king's favorite court jester.
Recruiting and supporting and army is a very costly affair. Modern logistics planners have a number they call the 'teeth to tail' ratio. It measures the number of people in an army that actually go out and fight, versus the number of support personnel. It will be pretty low, perhaps 1:10 for ancient armies, to 1:100 or more for advanced modern armies. (Technology takes a lot of support)
I bet you can find estimates of 'teeth to tail' for all sorts of fighting forces through the centuries if you google that phrase.
For your example, if we use my estimates, the troops alone consume 50000 lb a day, and the cavalry horses another 33000 lb of food and water. Your teamsters are going to have their hands full (and their bellies empty) keeping your army in the field for a year. | Please refer to a book called **Supplying war** by *Martin van Creveld*. There's special part dedicated to water systems in supplying armies.
Two things:
* For water armies always relied on local sources. In the 16 century it was not only for humans but all animals that went along. And they did bring a lot of them, horses for army, horses for carriages, oxes for carriages and eating. Carrying water for them would greatly pump up carts you need to take with you. So an ox that pull water barrels also drink that water so after few days maybe weeks he would drink all that he pulled. So his effectiveness is zero.
* Food, [This video](https://www.youtube.com/watch?v=qUt1ZHs3wQ8) talks about 18th century rations but also that this rationing stayed the same for 150 years. We can safely assume calories intake didn't changed much as soldiers had to do similar tasks and works in 16th century.
Now, for the $math$
I will take Grunwald Battle Polish Side. We know that in 30 of June army crossed river in Czerwinsk that was 140 km from Grunwald where they fought on 15th July.
The supplies that Polish army had to amass was projected to last for 5 weeks. From start till the planned attack on Malbork.
The crossing army consisted of 18 thousand of cavalry, 4 thousand of infantry, around 30 cannon and 8 thousand supply carts.
Now you have 8 thousand carts. Even if you split that number by two (so two cart linked together) you end up with 4 thousand carters and 8 thousand draft animals.
**26 thousand men**
**26 thousand animals**
Totally ignoring fact that one knight could have up to 10 people serving him.
So, ignoring the fact that we know that army did hunt and gather while they were moving **AND** assuming that animals eat grass that grow along the way.
We end up with 8 thousand carts for 26 thousand people for 5 weeks.
That means 4 carts was enough for 15 people.
Now we arrive at speed, maneuverability and effectiveness. Look at the start of math sections. 14 days to traverse 140 kilometres. **10km a day** and it was a speed where whole army was traveling at once so supplies won't lag behind and enemy won't have the opportunity to attack and destroy it. |
158,845 | *Edit: I was walking down an intolerably long sidewalk one day, and every time a mounted another hill, I saw more of it seeming to stretch out before me. It got me to thinking: is there a word for "going on and on for miles and miles?"*
I'm looking for a single adjective that is aptly descriptive of a road that stretches for miles and never seems to end. I tried various words already; for example, it can't be *ramifying* because that word means *branching out in different directions.* Neither is it *redounding,* which has the idea of repetition. *Long* or *lengthy* would be too plain, while at the same time not saying enough.
So what I'm asking for is a single adjective (or present participle) that applies to a road or path and describes it as *stretching out ahead for miles with no end in sight* in a single word. Does this word even exist? If it does, what is it?
Example: *It was a long road, stretching and* \_\_\_*ing as it went, and it seemed like it would never end.* | 2014/03/20 | [
"https://english.stackexchange.com/questions/158845",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/66066/"
] | You're making this much harder than it really is.
The word you are looking for is "endless", used like this:
"He traveled what seemed an endless road.
It was indeed a long and tiresome road, stretching out before him as though it would never reach its destination" | The first word that came to mind is *spanning*, which according to [TFD's citation of AHD](http://www.thefreedictionary.com/span) means
>
> To extend across in space or time
>
>
>
Because it is a transitive verb, it needs an object, as in:
>
> It was a long road, stretching and spanning the countryside as it went, and it seemed like it would never end.
>
>
>
*Span* seems to imply boundedness, as in "a bridge that spans the gorge" (from TFD). But in both cases, the "spanner" is limited by what it spans: The bridge spans as long as there is a gorge to span, and the road as long as there is countryside. Emphasizing the size of the countryside, I think, helps.
Because of *span*'s transitivity, the sentence above may be read as "the long road is stretching the countryside." If undesired, I remedied this by adding a preposition
>
> It was a long road, stretching across and spanning the (infinite) countryside as it went, and it seemed like it would never end.
>
>
> |
54,100,469 | I have a custom pipe for transform temperature value. I want call this pipe on started component (done) and when value of lang change (not working). Can you help me?
My pipe:
```
@Pipe({
name: 'temperatureConverter'
})
export class TemperatureConverterPipe implements PipeTransform {
value: number;
constructor(private _translateService: TranslateService, private language: LanguageProvider) {
this.language.getLanguage().subscribe((value) => {
this.transform(this.value, value.lang);
})
}
transform(value: number, unit : string = this.language.selectedLanguage) {
this.value = value;
if(value && !isNaN(value)){
if(unit === 'fr'){
let tempareature = (value - 32) / 1.8 ;
return tempareature.toFixed(2) + " °C";
}
if(unit === 'en'){
let tempareature = (value * 32) + 1.8 ;
return tempareature.toFixed(2) + " F";
}
}
return;
}
}
``` | 2019/01/08 | [
"https://Stackoverflow.com/questions/54100469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720463/"
] | UPDATE:
The solution is to put the the "pure" flag to false. This solves the issue.
```
@Pipe({
name: 'TemperatureConverter',
pure: false
})
```
--- Previous answer ---
I have the same issue. What I have found out is that having the language as an parameter works. Not what I was hoping for but this could work for someone. This will update the field when the language is changed.
In the constructor of the component using the pipe subscribe as the language changes. The other way (your way) needs you to reload the component:
```
lang: string;
constructor(private languageService: LanguageService) {
this.languageService.language$.subscribe(l => this.lang = l);
}
```
In the component use the pipe like so:
```
<span>3 | TemperatureConverter : lang</span
``` | you first need to register your pipes into your module declarations. After that you can call it inside your html page simply by
```
{{ myTempDegree | temperatureConverter : 'fr' }}
``` |
55,036 | I have list of data and its plot and I don't know how to fit the plot with fourier series of either sine or cosine.
Full Data:
```
{{0., -0.176091}, {0.034, -0.163291}, {0.067, -0.156391}, {0.1,
-0.152791}, {0.134, -0.149391}, {0.167, -0.144791}, {0.2, -0.141291},
{0.234, -0.135991}, {0.267, -0.126191}, {0.301, -0.123591}, {0.334,
-0.113091}, {0.367, -0.108991}, {0.401, -0.0985909}, {0.434,
-0.0929909}, {0.467, -0.0891909}, {0.501, -0.0831909}, {0.534,
-0.0748909}, {0.567, -0.0667909}, {0.601, -0.0666909}, {0.634,
-0.0679909}, {0.668, -0.0678909}, {0.701, -0.0731909}, {0.734,
-0.0735909}, {0.768, -0.0720909}, {0.801, -0.0690909}, {0.834,
-0.0689909}, {0.868, -0.0634909}, {0.901, -0.0585909}, {0.934,
-0.0551909}, {0.968, -0.0534909}, {1.001, -0.0486909}, {1.035,
-0.0470909}, {1.068, -0.0449909}, {1.101, -0.0424909}, {1.135,
-0.0426909}, {1.168, -0.0407909}, {1.201, -0.0404909}, {1.235,
-0.0379909}, {1.268, -0.0379909}, {1.301, -0.0387909}, {1.335,
-0.0422909}, {1.368, -0.0441909}, {1.402, -0.0480909}, {1.435,
-0.0532909}, {1.468, -0.0636909}, {1.502, -0.0672909}, {1.535,
-0.0740909}, {1.569, -0.0825909}, {1.602, -0.0927909}, {1.635,
-0.102191}, {1.669, -0.108991}, {1.702, -0.120491}, {1.736,
-0.134691}, {1.769, -0.139191}, {1.802, -0.152791}, {1.836,
-0.168791}, {1.869, -0.182891}, {1.902, -0.191091}, {1.936,
-0.198991}, {1.969, -0.219991}, {2.002, -0.236191}, {2.035,
-0.243891}, {2.069, -0.255391}, {2.102, -0.268591}, {2.136,
-0.281391}, {2.169, -0.292691}, {2.202, -0.296891}, {2.236,
-0.313391}, {2.269, -0.323991}, {2.302, -0.334691}, {2.337,
-0.342691}, {2.369, -0.352291}, {2.402, -0.359091}, {2.436,
-0.367891}, {2.469, -0.372091}, {2.502, -0.375991}, {2.536,
-0.377191}, {2.569, -0.376691}, {2.603, -0.377891}, {2.636,
-0.377191}, {2.669, -0.369691}, {2.703, -0.361491}, {2.736,
-0.349791}, {2.769, -0.341491}, {2.803, -0.338591}, {2.837,
-0.333591}, {2.869, -0.321591}, {2.903, -0.311191}, {2.936,
-0.303291}, {2.97, -0.289291}, {3.003, -0.284691}, {3.036,
-0.279691}, {3.07, -0.259491}, {3.103, -0.247591}, {3.136,
-0.244791}, {3.17, -0.236991}, {3.203, -0.231191}, {3.236,
-0.215191}, {3.27, -0.201091}, {3.303, -0.194591}, {3.337,
-0.187891}, {3.37, -0.182991}, {3.403, -0.173591}, {3.437,
-0.160891}, {3.47, -0.157091}, {3.503, -0.150791}, {3.537,-0.142991}, {3.57, -0.137591}, {3.604, -0.131591}, {3.637,
-0.116991}, {3.67, -0.108091}, {3.704, -0.101591}, {3.737,
-0.101591}, {3.77, -0.101591}, {3.804, -0.100291}, {3.837,
-0.104591}, {3.87, -0.112991}, {3.904, -0.122591}, {3.937,
-0.137291}, {3.971, -0.146891}, {4.004, -0.157091}, {4.037,
-0.173491}, {4.071, -0.190691}, {4.104, -0.202191}, {4.137,
-0.219491}, {4.171, -0.231491}, {4.204, -0.238291}, {4.238,
-0.247191}, {4.271, -0.264391}, {4.305, -0.281991}, {4.338,
-0.285991}, {4.371, -0.288691}, {4.404, -0.302691}, {4.438,
-0.310891}, {4.471, -0.319791}, {4.504, -0.325891}, {4.538,
-0.330891}, {4.571, -0.333291}, {4.605, -0.338791}, {4.638,
-0.351091}, {4.671, -0.359491}, {4.705, -0.363591}, {4.738,
-0.370191}, {4.771, -0.378591}, {4.805, -0.385291}, {4.838,
-0.393591}, {4.871, -0.403191}, {4.905, -0.410791}, {4.938,
-0.420591}, {4.972, -0.425491}, {5.005, -0.429491}, {5.038,
-0.428791}, {5.072, -0.423291}, {5.105, -0.411891}, {5.138,
-0.402391}, {5.172, -0.392591}, {5.205, -0.381591}, {5.239,
-0.371091}, {5.272, -0.353891}, {5.305, -0.341791}, {5.339,
-0.335791}, {5.372, -0.325091}, {5.405, -0.309291}, {5.439,
-0.301791}, {5.472, -0.296091}, {5.505, -0.289291}, {5.539,
-0.284391}, {5.572, -0.275991}, {5.606, -0.266891}, {5.639,
-0.259291}, {5.672, -0.251191}, {5.706, -0.242291}, {5.739,
-0.233391}, {5.773, -0.221291}, {5.806, -0.207391}, {5.839,
-0.196291}, {5.873, -0.192791}, {5.906, -0.185991}, {5.939,
-0.176191}, {5.973, -0.165291}, {6.006, -0.152591}, {6.039,
-0.148691}, {6.073, -0.136091}, {6.106, -0.127591}, {6.14,
-0.119391}, {6.173, -0.113891}, {6.206, -0.106791}, {6.24,
-0.0938909}, {6.273, -0.0782909}, {6.306, -0.0742909}, {6.34,
-0.0710909}, {6.373, -0.0606909}, {6.406, -0.0489909}, {6.44,
-0.0412909}, {6.473, -0.0289909}, {6.506, -0.0232909}, {6.54,
-0.0150909}, {6.573, -0.00669086}, {6.607, 0.00140914}, {6.64,
0.00980914}, {6.673, 0.0133091}, {6.707, 0.0205091}, {6.74,
0.0226091}, {6.773, 0.0255091}, {6.807, 0.0254091}, {6.84,
0.0259091}, {6.874, 0.0250091}, {6.907, 0.0299091}, {6.94,
0.0401091}, {6.974, 0.0428091}, {7.007, 0.0410091}, {7.04,
0.0410091}, {7.074, 0.0406091}, {7.107, 0.0370091}, {7.141,
0.0326091}, {7.174, 0.0246091}, {7.207, 0.0196091}, {7.241,
0.0131091}, {7.274,
0.00230914}, {7.307, -0.00419086}, {7.341, -0.0222909}, {7.374,
-0.0349909}, {7.408, -0.0534909}, {7.441, -0.0693909}, {7.474,
-0.0898909}, {7.508, -0.103991}, {7.541, -0.121191}, {7.574,
-0.133891}, {7.608, -0.142891}, {7.641, -0.156591}, {7.674,
-0.173991}, {7.708, -0.188791}, {7.741, -0.197691}, {7.775,
-0.205891}, {7.808, -0.222291}, {7.841, -0.228991}, {7.875,
-0.234191}, {7.908, -0.240591}, {7.941, -0.245191}, {7.975,
-0.254191}, {8.008, -0.265391}, {8.041, -0.271791}, {8.075,
-0.277791}, {8.108, -0.283791}, {8.142, -0.284791}, {8.175,
-0.286991}, {8.208, -0.299891}, {8.242, -0.307491}, {8.275,
-0.309591}, {8.308, -0.314391}, {8.342, -0.321791}, {8.375,
-0.324191}, {8.409, -0.324691}, {8.442, -0.324191}, {8.475,
-0.317291}, {8.509, -0.308491}, {8.542, -0.296091}, {8.575,
-0.287691}, {8.609, -0.283691}, {8.642, -0.275491}, {8.675,
-0.271491}, {8.709, -0.268991}, {8.742, -0.256991}, {8.776,
-0.246491}, {8.809, -0.244191}, {8.842, -0.240491}, {8.876,
-0.233391}, {8.909, -0.226791}, {8.942, -0.211891}, {8.976,
-0.198891}, {9.009, -0.195791}, {9.042, -0.191491}, {9.076,
-0.185791}, {9.109, -0.177791}, {9.143, -0.169491}, {9.176,
-0.163891}, {9.209, -0.149591}, {9.243, -0.144191}, {9.276,
-0.139191}, {9.309, -0.127391}, {9.343, -0.113491}, {9.376,
-0.108791}, {9.41, -0.0967909}, {9.443, -0.0905909}, {9.476,
-0.0789909}, {9.51, -0.0755909}, {9.543, -0.0740909}, {9.576,
-0.0666909}, {9.61, -0.0640909}, {9.643, -0.0581909}, {9.676,
-0.0575909}, {9.71, -0.0627909}, {9.743, -0.0715909}, {9.776,
-0.0876909}, {9.81, -0.0975909}, {9.843, -0.107691}, {9.877,
-0.130391}, {9.91, -0.140491}, {9.943, -0.152091}, {9.977,
-0.159191}, {10.01, -0.160591}, {10.044, -0.185091}, {10.077,
-0.215291}, {10.11, -0.243091}, {10.144, -0.264791}, {10.177,
-0.272491}, {10.21, -0.272791}, {10.244, -0.262091}, {10.277,
-0.247391}, {10.31, -0.243391}, {10.344, -0.239291}, {10.377,
-0.234891}, {10.411, -0.233991}, {10.444, -0.233691}, {10.477,
-0.203691}, {10.511, -0.157191}, {10.544, -0.148491}, {10.577,
-0.148491}, {10.611, -0.148691}, {10.644, -0.143591}, {10.678,
-0.133091}, {10.711, -0.123391}, {10.744, -0.116991}, {10.778,
-0.111891}, {10.811, -0.101491}, {10.845, -0.0897909}, {10.878,
-0.0858909}, {10.911, -0.0777909}, {10.945, -0.0730909}, {10.978,
-0.0731909}, {11.011, -0.0639909}, {11.045, -0.0559909}, {11.078,
-0.0469909}, {11.111, -0.0414909}, {11.145, -0.0336909}, {11.178,
-0.0258909}, {11.211, -0.0174909}, {11.245, -0.00539086}, {11.278,
-0.00059086}, {11.312, 0.00330914}, {11.345, 0.00680914}, {11.378,
0.0155091}, {11.412, 0.0215091}, {11.445, 0.0219091}, {11.478,
0.0266091}, {11.512, 0.0286091}, {11.545, 0.0297091}, {11.58,
0.0274091}, {11.612, 0.0239091}, {11.645, 0.0172091}, {11.679,
0.0113091}, {11.712, 0.0100091}, {11.746, 0.00680914}, {11.779,
0.00770914}, {11.812, 0.00470914}, {11.846, 0.00280914}, {11.879,
0.00370914}, {11.912, 0.00490914}, {11.946, 0.00140914}, {11.979,
0.00130914}, {12.013, 0.00450914}, {12.046, 0.00850914}, {12.079,
0.00830914}, {12.113, 0.00660914}, {12.146, 0.00930914}, {12.18,
0.0105091}, {12.213, 0.00980914}, {12.246, 0.00700914}, {12.279,
0.00520914}, {12.313, -0.0000908604}, {12.346, 0.00330914}, {12.38,
0.00560914}, {12.413, 0.00620914}, {12.446, 0.0191091}, {12.48,
0.0241091}, {12.513, 0.0242091}, {12.546, 0.0250091}, {12.58,
0.0318091}, {12.613, 0.0332091}, {12.646, 0.0370091}, {12.68,
0.0361091}, {12.713, 0.0374091}, {12.747, 0.0370091}, {12.78,
0.0379091}, {12.813, 0.0399091}, {12.847, 0.0394091}, {12.88,
0.0386091}, {12.914, 0.0379091}, {12.947, 0.0386091}, {12.98,
0.0413091}, {13.013, 0.0431091}, {13.047, 0.0459091}, {13.08,
0.0466091}, {13.114, 0.0436091}, {13.147, 0.0419091}, {13.181,
0.0427091}, {13.214, 0.0436091}, {13.247, 0.0394091}, {13.28,
0.0378091}, {13.314, 0.0341091}, {13.347, 0.0224091}, {13.38,
0.0180091}, {13.414, 0.00960914}, {13.448,
0.00410914}, {13.481, -0.00819086}, {13.514, -0.0264909}, {13.547,
-0.0456909}, {13.581, -0.0626909}, {13.614, -0.0694909}, {13.648,
-0.0821909}, {13.681, -0.0941909}, {13.714, -0.113991}, {13.748,
-0.132791}, {13.781, -0.143691}, {13.814, -0.150791}, {13.848,
-0.162191}, {13.881, -0.178391}, {13.915, -0.189691}, {13.948,
-0.195791}, {13.981, -0.203191}, {14.015, -0.223491}, {14.048,
-0.230991}, {14.081, -0.238491}, {14.115, -0.246791}, {14.148,
-0.263591}, {14.182, -0.278591}, {14.215, -0.291291}, {14.248,
-0.296291}, {14.281, -0.300191}, {14.315, -0.298991}, {14.348,
-0.300991}, {14.381, -0.295691}, {14.415, -0.290191}, {14.448,
-0.280791}, {14.482, -0.275191}, {14.515, -0.263791}, {14.548,
-0.251391}, {14.582, -0.239491}, {14.615, -0.231591}, {14.648,
-0.222991}, {14.682, -0.208491}, {14.715, -0.195791}, {14.748,
-0.188491}, {14.782, -0.182491}, {14.816, -0.177191}, {14.849,
-0.165491}, {14.882, -0.155491}, {14.916, -0.146391}, {14.949,
-0.136891}, {14.982, -0.135591}, {15.015, -0.131191}, {15.049,
-0.122891}, {15.082, -0.117491}, {15.116, -0.116591}, {15.149,
-0.117291}, {15.182, -0.121291}, {15.216, -0.123791}, {15.249,
-0.131291}, {15.282, -0.137891}, {15.316, -0.149291}, {15.35,
-0.162091}, {15.383, -0.177391}, {15.416, -0.189691}, {15.449,
-0.201891}, {15.483, -0.214291}, {15.516, -0.225291}, {15.549,
-0.227691}, {15.583, -0.225691}, {15.616, -0.223491}, {15.65,
-0.230191}, {15.683, -0.246191}, {15.717, -0.275491}, {15.75,
-0.296991}, {15.783, -0.311691}, {15.817, -0.289291}, {15.85,
-0.272091}, {15.883, -0.270291}, {15.916, -0.281991}, {15.95,
-0.261391}, {15.983, -0.233891}, {16.017, -0.231791}, {16.05,
-0.234491}, {16.083, -0.220791}, {16.117, -0.185091}, {16.15,
-0.172991}, {16.183, -0.177391}, {16.217, -0.178591}, {16.25,
-0.169891}, {16.284, -0.157691}, {16.317, -0.150291}, {16.35,
-0.143791}, {16.384, -0.141791}, {16.417, -0.140791}, {16.451,
-0.138491}, {16.484, -0.130191}, {16.517, -0.118191}, {16.551,
-0.110491}, {16.584, -0.103891}, {16.618, -0.0959909}, {16.651,
-0.0904909}, {16.684, -0.0904909}, {16.718, -0.0836909}, {16.751,
-0.0777909}, {16.784, -0.0724909}, {16.817, -0.0674909}, {16.851,
-0.0596909}, {16.884, -0.0515909}, {16.918, -0.0463909}, {16.951,
-0.0331909}, {16.984, -0.0270909}, {17.018, -0.0224909}, {17.051,
-0.0218909}, {17.084, -0.0183909}, {17.118, -0.0119909}, {17.151,
-0.00359086}, {17.185, 0.00700914}, {17.218, 0.00790914}, {17.251,
0.0137091}, {17.285, 0.0175091}, {17.318, 0.0217091}, {17.351,
0.0281091}, {17.385, 0.0313091}, {17.418, 0.0370091}, {17.451,
0.0384091}, {17.485, 0.0384091}, {17.518, 0.0418091}, {17.552,
0.0398091}, {17.585, 0.0384091}, {17.618, 0.0480091}, {17.652,
0.0538091}, {17.685, 0.0548091}, {17.718, 0.0468091}, {17.752,
0.0407091}, {17.785, 0.0371091}, {17.818, 0.0346091}, {17.852,
0.0235091}, {17.885, 0.0168091}, {17.919, 0.0129091}, {17.952,
0.00860914}, {17.986,
0.00490914}, {18.019, -0.00749086}, {18.052, -0.0237909}, {18.087,
-0.0261909}, {18.119, -0.0401909}, {18.152, -0.0499909}, {18.186,
-0.0605909}, {18.219, -0.0764909}, {18.253, -0.0861909}, {18.286,
-0.0924909}, {18.319, -0.101291}, {18.352, -0.117191}, {18.386,
-0.126591}, {18.419, -0.139091}, {18.452, -0.146891}, {18.486,
-0.161391}, {18.519, -0.174391}, {18.553, -0.182491}, {18.587,
-0.193191}, {18.619, -0.195291}, {18.653, -0.204091}, {18.686,
-0.216891}, {18.72, -0.227591}, {18.753, -0.237291}, {18.786,
-0.241291}, {18.819, -0.245991}, {18.853, -0.254991}, {18.886,
-0.270091}, {18.92, -0.278391}, {18.953, -0.279591}, {18.986,
-0.284991}, {19.02, -0.292191}, {19.053, -0.294091}, {19.086,
-0.291091}, {19.12, -0.287191}, {19.153, -0.281091}, {19.186,
-0.277591}, {19.22, -0.270791}, {19.254, -0.261891}, {19.287,
-0.249191}, {19.32, -0.242891}, {19.353, -0.241091}, {19.387,
-0.235791}, {19.42, -0.229191}, {19.453, -0.222491}, {19.487,
-0.217291}, {19.52, -0.209791}, {19.554, -0.203391}, {19.588,
-0.197691}, {19.62, -0.187791}, {19.654, -0.178791}, {19.687,
-0.172691}, {19.72, -0.159691}, {19.754, -0.148191}, {19.787,
-0.138191}, {19.821, -0.127691}, {19.854, -0.117891}, {19.887,
-0.105391}, {19.921, -0.0924909}, {19.954, -0.0861909}, {19.988,
-0.0772909}, {20.021, -0.0648909}, {20.054, -0.0556909}, {20.087,
-0.0488909}, {20.121, -0.0394909}, {20.154, -0.0287909}, {20.188,
-0.0213909}, {20.221, -0.0153909}, {20.254, -0.0106909}, {20.288,
-0.00649086}, {20.322, 0.0114091}, {20.354, 0.0145091}, {20.388,
0.0144091}, {20.421, 0.0176091}, {20.455, 0.0183091}, {20.488,
0.0201091}, {20.521, 0.0279091}, {20.555, 0.0352091}, {20.588,
0.0421091}, {20.621, 0.0456091}, {20.655, 0.0477091}, {20.688,
0.0557091}, {20.722, 0.0580091}, {20.755, 0.0602091}, {20.788,
0.0637091}, {20.822, 0.0637091}, {20.855, 0.0691091}, {20.888,
0.0686091}, {20.922, 0.0674091}, {20.955, 0.0656091}, {20.989,
0.0704091}, {21.022, 0.0710091}, {21.056, 0.0712091}, {21.088,
0.0693091}, {21.122, 0.0697091}, {21.155, 0.0712091}, {21.188,
0.0705091}, {21.222, 0.0705091}, {21.255, 0.0696091}, {21.289,
0.0705091}, {21.322, 0.0691091}, {21.355, 0.0724091}, {21.389,
0.0724091}, {21.422, 0.0711091}, {21.455, 0.0707091}, {21.489,
0.0705091}, {21.522, 0.0694091}, {21.556, 0.0657091}, {21.589,
0.0632091}, {21.622, 0.0539091}, {21.656, 0.0461091}, {21.689,
0.0448091}, {21.722, 0.0351091}, {21.756, 0.0250091}, {21.789,
0.0183091}, {21.823, 0.00920914}, {21.856,
0.00010914}, {21.89, -0.0142909}, {21.923, -0.0217909}, {21.956,
-0.0273909}, {21.989, -0.0379909}, {22.023, -0.0471909}, {22.056,
-0.0487909}, {22.089, -0.0635909}, {22.123, -0.0775909}, {22.157,
-0.0885909}, {22.189, -0.0981909}, {22.223, -0.106291}, {22.256,
-0.121391}, {22.29, -0.135991}, {22.323, -0.145691}, {22.357,
-0.155891}, {22.39, -0.168691}, {22.424, -0.187791}, {22.456,
-0.201491}, {22.49, -0.213791}, {22.523, -0.230891}, {22.557,
-0.235091}, {22.59, -0.241291}, {22.623, -0.250991}, {22.657,
-0.265291}, {22.69, -0.279791}, {22.723, -0.284491}, {22.757,
-0.296391}, {22.79, -0.317691}, {22.824, -0.321991}, {22.857,
-0.329291}, {22.89, -0.332491}, {22.924, -0.332391}, {22.957,
-0.330691}, {22.99, -0.328191}, {23.024, -0.314891}, {23.057,
-0.301791}, {23.091, -0.296791}, {23.124, -0.288291}, {23.157,
-0.280491}, {23.191, -0.270791}, {23.224, -0.259591}, {23.257,
-0.251391}, {23.291, -0.239891}, {23.324, -0.237791}, {23.358,
-0.233791}, {23.391, -0.222491}, {23.424, -0.211591}, {23.458,
-0.210391}, {23.491, -0.203691}, {23.524, -0.198591}, {23.558,
-0.195691}, {23.591, -0.191591}, {23.624, -0.186991}, {23.658,
-0.185691}, {23.691, -0.180891}, {23.725, -0.171091}, {23.758,
-0.167991}, {23.791, -0.166091}, {23.824, -0.162691}, {23.858,
-0.149191}, {23.891, -0.145791}, {23.925, -0.134991}, {23.958,
-0.122291}, {23.991, -0.115091}, {24.025, -0.106691}, {24.058,
-0.102491}, {24.092, -0.0934909}, {24.125, -0.0914909}, {24.158,
-0.0871909}, {24.192, -0.0756909}, {24.225, -0.0709909}, {24.258,
-0.0594909}, {24.292, -0.0575909}, {24.325, -0.0567909}, {24.359,
-0.0535909}, {24.392, -0.0495909}, {24.425, -0.0410909}, {24.459,
-0.0401909}, {24.492, -0.0363909}, {24.525, -0.0332909}, {24.559,
-0.0315909}, {24.592, -0.0267909}, {24.626, -0.0248909}, {24.659,
-0.0169909}, {24.692, -0.0114909}, {24.725, -0.00659086}, {24.759,
-0.00119086}, {24.792, 0.00590914}, {24.826, 0.0110091}, {24.859,
0.0117091}, {24.893, 0.0118091}, {24.926, 0.0142091}, {24.959,
0.0103091}, {24.993,
0.00530914}, {25.026, -0.00219086}, {25.059, -0.00399086}, {25.092,
0.00250914}, {25.126, 0.0104091}, {25.16, 0.00570914}, {25.193,
0.00620914}, {25.226, 0.00510914}, {25.259, 0.00370914}, {25.293,
0.00580914}, {25.326, 0.00760914}, {25.36, 0.0110091}, {25.393,
0.0129091}, {25.426, 0.0126091}, {25.459, 0.0139091}, {25.493,
0.0148091}, {25.526, 0.0178091}, {25.56, 0.0205091}, {25.593,
0.0200091}, {25.626, 0.0205091}, {25.66, 0.0209091}, {25.693,
0.0179091}, {25.727, 0.0129091}, {25.76, 0.00490914}, {25.793,
0.00280914}, {25.827, -0.00349086}, {25.86, -0.0106909}, {25.893,
-0.0205909}, {25.927, -0.0304909}, {25.96, -0.0372909}, {25.993,
-0.0457909}, {26.027, -0.0514909}, {26.06, -0.0641909}, {26.094,
-0.0774909}, {26.127, -0.0875909}, {26.16, -0.0986909}, {26.194,
-0.111591}, {26.227, -0.125291}, {26.26, -0.136691}, {26.294,-0.146391}, {26.327, -0.160691}, {26.361, -0.177291}, {26.394,
-0.193791}, {26.427, -0.207691}, {26.461, -0.221691}, {26.494,
-0.231391}, {26.527, -0.243591}, {26.561, -0.261691}, {26.595,
-0.280291}, {26.627, -0.287191}, {26.661, -0.300991}, {26.694,
-0.317491}, {26.728, -0.325491}, {26.761, -0.330891}, {26.794,
-0.342691}, {26.828, -0.349091}, {26.861, -0.358891}, {26.894,
-0.373891}, {26.928, -0.379791}, {26.961, -0.382891}, {26.994,
-0.385391}, {27.028, -0.386191}, {27.061, -0.381991}, {27.095,
-0.377691}, {27.128, -0.368991}, {27.161, -0.358691}, {27.195,
-0.345991}, {27.228, -0.341191}, {27.261, -0.337791}, {27.295,
-0.328791}, {27.328, -0.323091}, {27.362, -0.310791}, {27.395,
-0.301091}, {27.428, -0.290891}, {27.462, -0.282591}, {27.495,
-0.275791}, {27.529, -0.258291}, {27.562, -0.252991}, {27.595,
-0.244791}, {27.629, -0.238991}, {27.662, -0.234291}, {27.695,
-0.228291}, {27.729, -0.219491}, {27.762, -0.216991}, {27.795,
-0.211691}, {27.829, -0.205591}, {27.862, -0.202391}, {27.895,
-0.202991}, {27.929, -0.203891}, {27.962, -0.204391}, {27.996,
-0.203891}, {28.029, -0.198791}, {28.062, -0.193691}, {28.096,
-0.191491}, {28.129, -0.191991}, {28.162, -0.194391}, {28.196,
-0.201891}, {28.229, -0.219591}, {28.262, -0.240891}, {28.296,
-0.265491}, {28.329, -0.270991}, {28.363, -0.245291}, {28.396,
-0.234191}, {28.429, -0.230191}, {28.463, -0.230591}, {28.496,
-0.210591}, {28.529, -0.189991}, {28.563, -0.188491}, {28.596,
-0.181291}, {28.63, -0.156991}, {28.663, -0.146191}, {28.696,
-0.146091}, {28.73, -0.148191}, {28.763, -0.144691}, {28.796,
-0.137391}, {28.83, -0.130191}, {28.863, -0.122891}, {28.896,
-0.111391}, {28.93, -0.107091}, {28.963, -0.0970909}, {28.997,
-0.0891909}, {29.03, -0.0774909}, {29.063, -0.0731909}, {29.097,
-0.0659909}, {29.13, -0.0527909}, {29.164, -0.0428909}, {29.197,
-0.0354909}, {29.23, -0.0246909}, {29.263, -0.0196909}, {29.297,
-0.0161909}, {29.33, -0.0139909}, {29.364, -0.0113909}, {29.397,
-0.00589086}, {29.43, -0.00259086}, {29.464, -0.00219086}, {29.497,
-0.00219086}, {29.53, -0.00199086}, {29.564, -0.00269086}, {29.597,
-0.00989086}, {29.63, -0.0256909}, {29.664, -0.0306909}, {29.697,
-0.0460909}, {29.73, -0.0574909}, {29.764, -0.0722909}, {29.797,
-0.0874909}, {29.831, -0.102591}, {29.864, -0.117291}, {29.898,
-0.134191}, {29.931, -0.148991}, {29.964, -0.165391}, {29.998,
-0.187091}, {30.031, -0.197291}, {30.064, -0.206891}, {30.098,
-0.219791}, {30.131, -0.230491}, {30.164, -0.233891}, {30.198,
-0.239491}, {30.231, -0.249491}, {30.265, -0.260891}, {30.298,
-0.279191}, {30.331, -0.284591}, {30.365, -0.292591}, {30.398,
-0.297491}, {30.431, -0.307391}, {30.465, -0.317591}, {30.498,
-0.321491}, {30.531, -0.322391}, {30.565, -0.316891}, {30.598,
-0.318591}, {30.632, -0.322391}, {30.665, -0.328791}, {30.698,
-0.332291}, {30.732, -0.334091}, {30.765, -0.334091}, {30.798,
-0.334091}, {30.832, -0.337691}, {30.865, -0.338491}, {30.899,
-0.338491}, {30.932, -0.337591}, {30.965, -0.341491}, {30.999,
-0.343491}, {31.032, -0.346791}, {31.065, -0.353091}, {31.099,
-0.354991}, {31.132, -0.353991}, {31.166, -0.355691}, {31.199,
-0.351291}, {31.232, -0.340791}, {31.266, -0.334091}, {31.299,
-0.330791}, {31.332, -0.326091}, {31.366, -0.309391}, {31.399,
-0.295391}, {31.432, -0.285991}, {31.466, -0.275391}, {31.499,
-0.265091}, {31.533, -0.256591}, {31.566, -0.242991}, {31.599,
-0.230091}, {31.633, -0.219391}, {31.666, -0.203691}, {31.699,
-0.189291}, {31.733, -0.183891}, {31.767, -0.169391}, {31.799,
-0.167091}, {31.833, -0.157091}, {31.866, -0.150791}, {31.9,
-0.137991}, {31.933, -0.123091}, {31.966, -0.114891}, {32.,
-0.108691}, {32.033, -0.0979909}, {32.066, -0.0907909}, {32.1,
-0.0796909}, {32.133, -0.0709909}, {32.166, -0.0611909}, {32.2,
-0.0513909}, {32.233, -0.0411909}, {32.267, -0.0323909}, {32.3,
-0.0251909}, {32.333, -0.0188909}, {32.367, -0.0125909}, {32.4,
-0.00609086}, {32.433, 0.00120914}, {32.467, 0.0100091}, {32.5,
0.0127091}, {32.533, 0.0126091}, {32.567, 0.0154091}, {32.601,
0.0235091}, {32.633, 0.0270091}, {32.667, 0.0255091}, {32.7,
0.0262091}, {32.734, 0.0262091}, {32.767, 0.0262091}, {32.8,
0.0257091}, {32.834, 0.0237091}, {32.867, 0.0241091}, {32.901,
0.0252091}, {32.934, 0.0262091}, {32.967, 0.0286091}, {33.001,
0.0328091}, {33.034, 0.0380091}, {33.067, 0.0442091}, {33.101,
0.0433091}, {33.134, 0.0389091}, {33.168, 0.0373091}, {33.201,
0.0316091}, {33.234, 0.0274091}, {33.268, 0.0295091}, {33.301,
0.0342091}, {33.334, 0.0312091}, {33.368, 0.0305091}, {33.401,
0.0299091}, {33.434, 0.0295091}, {33.468, 0.0346091}, {33.501,
0.0386091}, {33.535, 0.0375091}, {33.568, 0.0380091}, {33.601,
0.0443091}, {33.635, 0.0462091}, {33.668, 0.0469091}, {33.701,
0.0482091}, {33.735, 0.0500091}, {33.768, 0.0536091}, {33.801,
0.0540091}, {33.835, 0.0520091}, {33.868, 0.0532091}, {33.901,
0.0489091}, {33.935, 0.0472091}, {33.968, 0.0521091}, {34.002,
0.0484091}, {34.035, 0.0465091}, {34.068, 0.0456091}, {34.102,
0.0414091}, {34.135, 0.0386091}, {34.169, 0.0347091}, {34.202,
0.0271091}, {34.235, 0.0255091}, {34.269, 0.0161091}, {34.302,
0.0125091}, {34.338,
0.00480914}, {34.369, -0.00539086}, {34.402, -0.0129909}, {34.435,
-0.0208909}, {34.469, -0.0297909}, {34.502, -0.0326909}, {34.536,
-0.0474909}, {34.569, -0.0595909}, {34.602, -0.0718909}, {34.636,
-0.0764909}, {34.669, -0.0861909}, {34.703, -0.0960909}, {34.736,
-0.107591}, {34.769, -0.117691}}
```
This is the graph of whole data.
 | 2014/07/16 | [
"https://mathematica.stackexchange.com/questions/55036",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/16094/"
] | I've done this from first principles:
some random data:
```
data = Table[{x + RandomReal[{-.05, .05}] + 4,
Sin[x] + Sin[x/3] + RandomReal[{-.3, .3}]}, {x, 0, 12 Pi , .1}];
```
treat the discrete data as a function and and use trapezoidal integration:
```
trule = Mean /@
Partition[
Differences@
{data[[1, 1]], Sequence @@ data[[;; , 1]], data[[-1, 1]]}, 2, 1];
len = Subtract @@ data[[{-1, 1}]][[;; , 1]]
```
the fourier sine coefficients:
```
ck = 2 / len Table[
trule.(#[[2]] Sin[k (#[[1]] - data[[1, 1]]) Pi/len ] & /@ data ) ,
{k, 1, 20} ];
Show[{ListPlot[data], Plot[ Total@
MapIndexed[# Sin[First@#2 Pi (t - data[[1, 1]]) / len ] & , ck ] ,
{t, data[[1, 1]], data[[-1, 1]]}]}]
```

Now I expect someone will show a built-in way to get this...
Using the example data, with 30 terms:
 | I took george2079's statement "Now I expect someone will show a built-in way to get this..." as a challenge, so I did the same thing using `FindFit`. Also, writing it this way seems more clear to me what the actual function being fitted is (but obviously relying on the internal `FindFit` function)
```
len = (Max[#] - Min[#]) &@data[[All, 1]];
func = Sum[Subscript[a, n] Sin[( \[Pi] n)/len t], {n, 1, 40}];
params = Table[Subscript[a, n], {n, 1, 40}];
soln = FindFit[data, func, params, t];
function = Compile[{{t, _Real}},
Evaluate[func /. soln]];
Show[ListPlot[data],Plot[function[t], {t, 0, len}, PlotStyle -> {{Thick, Red}}]]
```
 |
16,284,264 | I have 3 lists, one for hours, one for minutes, and one for seconds. What I have done is create a function that will take 3 lists as input and calculate the total amount of time.
My issue is that the function is so redundant and my question to you, is simpy: what is a better way to do this.
Here is my function:
```
def final_time(hours,minutes,seconds):
draft_hours = sum(hours)
draft_minutes = sum(minutes)
draft_seconds = sum(seconds)
adding_seconds = str(draft_seconds/60.0)
second_converting = adding_seconds.split(".")
seconds_to_minutes = int(second_converting[0])
seconds_to_seconds = draft_seconds - (seconds_to_minutes * 60)
total_seconds = str(seconds_to_seconds)
more_minutes = draft_minutes + seconds_to_minutes
adding_minutes = str(more_minutes/60.0)
minute_converting = adding_minutes.split(".")
minutes_to_hours = int(minute_converting[0])
minutes_to_minutes = more_minutes - (minutes_to_hours * 60)
total_minutes = str(minutes_to_minutes)
total_hours = str(draft_hours + minutes_to_hours)
return total_hours + " hours, " + total_minutes + " minutes, and " + total_seconds + " seconds."
```
here is an example:
```
my_hours = [5, 17, 4, 8]
my_minutes = [40, 51, 5, 24]
my_seconds = [55, 31, 20, 33]
print final_time(my_hours,my_minutes,my_seconds)
```
above returns:
```
36 hours, 2 minutes, and 19 seconds.
```
so it does work, but as you can see, the function is just not a pythonic nor efficient function...**what would a better method be?** | 2013/04/29 | [
"https://Stackoverflow.com/questions/16284264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2127988/"
] | I would probably convert it all to seconds first:
```
seconds = sum(3600*h + 60*m + s for (h,m,s) in zip(hours,minutes,seconds)
```
Now break it back down:
```
n_hours,minutes = divmod(seconds,3600)
n_minutes,n_seconds = divmod(minutes,60)
``` | I would use time objects from Datetime <http://docs.python.org/2/library/datetime.html#time-objects>
That would be something like :
```
def final_time(hours,minutes,seconds):
times=[datetime.time(hours[i],minutes[i],seconds[i]) for i in range(0,length(hours))]
return sum(times)
``` |
35,006,628 | I have an array of strings:
```
strings = ['fo','foo','fooo']
```
What code should I write in order to find a string that has only `oo` in it?
I tried following code
```
strings.select!{|string| string.include? 'oo'}
#=> ['foo','fooo']
```
However, `'fooo'` is not what I wanted in a resulting array, in this case only an array with `['foo']` should be returned. | 2016/01/26 | [
"https://Stackoverflow.com/questions/35006628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4635750/"
] | To determine whether a string contains one or more strings of the form "xooy", where "x" and "y" are any characters other than "o", but contains no strings "xoy" and or "ooo" (and by extension, no "oooo", etc.), you could do the following:
```
def double_os_only?(str)
str.scan(/o+/).map(&:size).minmax == [2,2]
end
strings = ['fo','foo','fooo', 'oofo', 'oofoo', 'oofooo', 'photo', 'potatoo', "dang"]
strings.map { |s| puts "#{ s } => #{ double_os_only?(s) }" }
fo => false
foo => true
fooo => false
oofo => false
oofoo => true
oofooo => false
photo => false
potatoo => false
dang => false
```
Note that, if `str.scan(/o+/) #=> []`, `[].map(&:size) #=> []` and `[].minmax #=> [nil,nil]`.
Another way is to modify a regex given by @Avinash:
```
R = /
^ # match beginning of the line
(?: # begin a non-capture group
[^o]* # match zero or more characters other than 'o'
oo # match 'oo'
[^o]* # match zero or more characters other than 'o'
(?!o) # do not match 'o' in a negative lookahead
)+ # end the non-capture group and perform >= 1 times
$ # match end of line
/x # extended/free-spacing regex definition
def double_os_only?(str)
!!(str =~ R)
end
```
`!` converts a truthy value to `false` and a falsy value to `true`. `!!` therefore converts a truthy value to `true` and a falsy value to `false`. | Use negative lookarounds..
```
> strings.select{ |i| i[/(?<!o)oo(?!o)/] }
=> ["foo"]
```
`(?<!o)` asserts that the match won't be preceded by `o`, `(?!o)` asserts that the match won't be followed by `o`
To match the string which contain exactly 2 o's
```
strings.select{ |i| i[/^[^o]*oo[^o]*$/] }
``` |
7,798,237 | What is the best way of performing the following in C++. Whilst my current method works I'm not sure it's the best way to go:
1) I have a master class that has some function in it
2) I have a thread that takes some instructions on a socket and then runs one of the functions in the master class
3) There are a number of threads that access various functions in the master class
I create the master class and then create instances of the thread classes from the master. The constructor for the thread class gets passed the "this" pointer for the master. I can then run functions from the master class inside the threads - i.e. I get a command to do something which runs a function in the master class from the thread. I have mutex's etc to prevent race problems.
Am I going about this the wrong way - It kinda seems like the thread classes should inherit the master class or another approach would be to not have separate thread classes but just have them as functions of the master class but that gets ugly. | 2011/10/17 | [
"https://Stackoverflow.com/questions/7798237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/702845/"
] | This is the solution, I just had to get the proper value from the first unitName I wanted...
```
public class XElementComparer : IEqualityComparer<XElement>
{
public bool Equals(XElement x, XElement y)
{
string unitNameX = x.Element("unitName ").Value;
string unitNameY = y.Element("unitName ").Value;
return unitNameX == unitName Y;
}
public int GetHashCode(XElement x)
{
string val = x.Element("unitName ").Value;
return val.GetHashCode();
}
}
``` | You can also write something which will work for most of xml.
```
public class XElementComparer : IEqualityComparer<XElement>
{
public bool Equals(XElement x, XElement y)
{
return (x.FirstAttribute.Value.Equals(y.FirstAttribute.Value)
&& x.LastAttribute.Value.Equals(y.LastAttribute.Value));
}
public int GetHashCode(XElement x)
{
return x.Value.GetHashCode();
}
}
``` |
41,478,698 | In my website, text is dynamically appended to the page.
My need if the `td` has attribute has `colspan=2`, apply `text-align:center`.
```
tblCustomers tr td
{
padding-left:25px;
}
//how do I do this
tblCustomer tr td:hasattribute(colspan=2)
{
text-align:center;
}
```
**Note:-**
* No suggestion for adding class or id. Its not feasible in my scenario.
* No JavaScript or jQuery for this. | 2017/01/05 | [
"https://Stackoverflow.com/questions/41478698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326367/"
] | Here is a solution
```
tblCustomer tr td[colspan="2"]
{
text-align:center;
}
``` | Just added `width: 100%` to your table so you see visualize the effect properly.
```css
.tblCustomer
{
width: 100%;
}
.tblCustomer tr td[colspan="2"]
{
text-align:center;
}
```
```html
<table class="tblCustomer">
<tr>
<td colspan="2">Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>
``` |
23,364,419 | Consider a base class `class Base` which has a function `virtual void foo(void)`. This function is implemented in `Base`; i.e. is not pure virtual.
Is there a pattern I can use which when inheriting from this class, i.e. `class Child : public Base`, compels me to override `foo`? | 2014/04/29 | [
"https://Stackoverflow.com/questions/23364419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415258/"
] | Yes, actually there is:
```
#include <iostream>
class Base
{
public:
virtual void someFun() {std::cout << "Base::fun" << std::endl;}
virtual ~Base() {}
};
class AlmostBase : public Base
{
public:
virtual void someFun() = 0;
};
class Derived : public AlmostBase
{
public:
virtual void someFun() {std::cout << "Derived::fun" << std::endl;}
};
int main()
{
Derived *d = new Derived();
d->someFun();
delete d;
}
```
If you uncomment the `someFun` from `Derived` the compiler will complain ...
You introduce an intermediary class `AlmostBase` which has the function as pure virtual. This way you can have `Base` objects too, and the only drawback now is that all your classes will need to inherit from the intermediary base. | you can make the base method throw an exception when called, then the class must override it to avoid the parent execution.
this is used in the MFC FrameWork for example
```
// Derived class is responsible for implementing these handlers
// for owner/self draw controls (except for the optional DeleteItem)
void CComboBox::DrawItem(LPDRAWITEMSTRUCT)
{ ASSERT(FALSE); }
void CComboBox::MeasureItem(LPMEASUREITEMSTRUCT)
{ ASSERT(FALSE); }
int CComboBox::CompareItem(LPCOMPAREITEMSTRUCT)
{ ASSERT(FALSE); return 0; }
```
those methods must be inherited if the control is owner drawn it is responsible for the measuer, draw,... if you missed it while you are testing the function you will get an assert or exception with useful information thrown. |
42,189,357 | I am creating a chat box using bootstrap css version 3 like this:
```
<div class="col-md-12 col-sm-12 col-xs-12" id="chatBox">
<div class="row" id="chatHeader">
<div class="col-md-10 col-sm-10 col-xs-10">Chat bot</div>
<div class="col-md-2 col-sm-2 col-xs-2">x</div>
</div>
<div class="row" id="chatContent">
<div class="col-md-12 col-sm-12 col-xs-12">
<!--CONTENT HERE-->
</div>
</div>
<div class="row" id="chatFooter" style="margin-bottom: 0px;">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="input-group">
<textarea rows="1" class="form-control" rows="3" style="resize:none; white-space: nowrap; border-radius: 0px;"></textarea>
<span id="send_chat" class="input-group-addon btn btn-primary" style="background: #357ebd">Send</span>
</div>
</div>
<!--<div class="col-md-4 col-sm-4 col-xs-4">Send</div>-->
</div>
</div>
```
style:
```
#chatBox{
position: fixed;
bottom:0;
right:0;
height: 300px;
width: 300px;
z-index: 1001;
box-shadow: 3px 5px 20px #888888;
}
#chatHeader{
padding: 10px;
background: green;
color: white;
}
#chatContent{
height: 250px;
background: white;
}
#chatFooter{
background: white;
}
```
The last row where the footer div is hidden behind the browser (I mean I had to using `bottom: 25px;` to make it appear properly)
Why is it like that? Here is the plunker:
<https://plnkr.co/edit/v0X8lSL84oNd5KNZT0TV?p=preview>
Update:
Not setting the height of `chatBox` fixed the issue. But other problem is I am unable to dynamically set the height of div. Please check this plunker: <https://plnkr.co/edit/v0X8lSL84oNd5KNZT0TV?p=preview> | 2017/02/12 | [
"https://Stackoverflow.com/questions/42189357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1800583/"
] | Do not set the height of the `#chatBox` (you overflowing it currently), but if you need it to be exactly `300px` as you set, play with `#chatContent` and make it flexible height for example. | One of the main reasons is that you have a `padding` set to your header. The padding is pushing everything under it down. I guess the best option is to set the `bottom` to `25px`. This will do no damage as far I can see. |
5,109,537 | I had a site <http://www.test.com>
Now i make the folder 'test' secure
So the site is avialable in <https://www.test.com>
My requirement is ,when some one type <http://www.test.com> ,
then it should go to <https://www.test.com>.
Is there any way using .Htaccess or any other method? | 2011/02/24 | [
"https://Stackoverflow.com/questions/5109537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310850/"
] | In Apache2 configuration, you could use the redirect command :
```
<VirtualHost *:80>
ServerName www.test.com
Redirect / https://www.test.com/
</VirtualHost>
<VirtualHost *:443>
ServerName www.test.com
...
</VirtualHost>
``` | ```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Your Page Title</title>
<meta http-equiv="REFRESH" content="0;url=http://www.the-domain-you-want-to-redirect-to.com"></HEAD>
<BODY>
Optional page text here.
</BODY>
</HTML>
```
That should do it. |
120,894 | So I decided I wanted to make this script part of a separate swap-able weapon so I made a child and put the script there. Before the script worked fine but now it won't work. The script works as follows: if the left mouse button is pressed send a ray cast out forward, if it hits something matching the condition (a tag check, and distance check) parent it to the player, and if the right click button is pressed than un-parent it.
The code:
```
public class PhysGun : MonoBehaviour
{
public GameObject Player;
private bool isPlayerHolding;
private GameObject RayCastHitObject;
// Update is called once per frame
void Update()
{
Vector3 fwd = transform.forward;
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && hit.collider.gameObject.CompareTag("Pickable"))
{
Debug.Log("Press detected");
isPlayerHolding = true;
hit.transform.SetParent(Player.transform);
Debug.Log("We hit: " + hit.transform.name);
hit.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
MoveScrollWheel();
}
if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hit, 10f))
{
hit.transform.parent = null;
isPlayerHolding = false;
hit.rigidbody.constraints = RigidbodyConstraints.None;
}
if (isPlayerHolding != false)
{
MoveScrollWheel();
}
}
void MoveScrollWheel ()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward
{
Debug.Log("Mouse wheel up");
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards
{
Debug.Log("Mouse wheel down");
}
}
}
```
What is wrong with my setup?
To clarify a few things...
* It's not working - By this mean it does not parent the object to the player like it should.
* Steps I've taken to resolve the issue (some are already above)...
* Remove tag check requirement - this causes a weird issue no matter where I am it always parents the terrain to the player and causes the player fall through it.
* Manually attach the player GameObject to the script.
* Detach the child (and make it a sibling) and put in front to see if it works that way (it doesn't).
* The raycast is **hits something** without the tag check (in this case the terrain as described above) but that is totally the wrong thing.
* No error messages appear in the console or anywhere.
* As per request [here](https://youtu.be/DtUJ4UqlWMM) is a demonstration of the issue. | 2016/05/03 | [
"https://gamedev.stackexchange.com/questions/120894",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/69408/"
] | A Couple things to check:
1) Transform.forward may not be the direction you actually want to shoot the ray. For example if this is a first-person game, the direction the PhysGun is facing (transform.forward) may be totally different than where the *camera* is looking, and in that case you would probably want to shoot the ray from the camera.
2) Have you tried using [RaycastAll](http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html) to get more than just one hit? Perhaps you are raycasting in the correct direction, but the first result is undesirable. | Well I finally figured out the issue with some help from here and Reddit. Basically I was trying to send the raycast from the model's (the child) forward and that was the wrong forward.
So I changed the third (2nd) line of code in the update statement to `Ray ray = new Ray(Player.transform.position, Player.transform.forward);`. This basically makes it so that the ray will originate from the players forward facing position rather than whatever the model's (child) forward is.
Long story short I used the Player's forward position and it worked brilliantly. |
20,607,260 | How do I show one random icon on page load with js? Below is the HTML code I have:
```
<span>
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
```
I need to show only one of the three icons. | 2013/12/16 | [
"https://Stackoverflow.com/questions/20607260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2210364/"
] | My HTML would be
```
<span id = "mySpan"></span>
```
You can do this using javascript
```
var myRand = Math.floor(Math.random() * 3) + 1;
var randString = '';
if(myRand == 1)
randString = 'one';
else if(myRand == 2)
randString = 'two';
else if(myRand == 3)
randString = 'three';
var ele = document.createElement("div");
ele.setAttribute("id","icon-"+randString );
document.getElementById("mySpan").appendChild(ele);
```
Well , this assumes that your ids have the icon and not the classes | you can use java script here. So if there are only three icons one , two and three.
use random function to generate a number between one two and three
```
var x= Math.floor((Math.random()*3)+1);
if (x==1)
{
//fetch the div id = "icon-one" and display
}
else if (x==2)
{
//fetch the div id = "icon-two" and display
}
else
{
//fetch the div id = "icon-three" and display
}
```
Although this will work way better if you can rename your id's two icon1,icon2 and so on
it will just be this then :
```
var x= Math.floor((Math.random()*3)+1);
var icon = "icon";
var id = icon.concat(x);
``` |
51,091 | I own a url shortening service. I want to deliver only legitimate statistics to my clients. There are possible scenarios that a particular user writes a script to automatically open the shortened URL, thus making the statistics look bad. What are the approaches one can follow to detect if a click is legitimate or not? The very basic approach that I can think of is to monitor the IP address of the user and block if the number of requests exceed a threshold. | 2014/02/07 | [
"https://security.stackexchange.com/questions/51091",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/39635/"
] | There's a number of potential methods you can use to differentiate bots from humans but none of them are likely 100%
Obviously as you say rate limiting catches the really stupid bots who don't know to click at human speed. You could say one click per IP but that will artificially deflate your stats in the case of humans behind a proxy (becoming more common as IPv4 addresses run out)
IP blocking isn't too useful in the days of cloud computing, it's pretty easy for an attacker to get a different IP or range of IPs to work from if they're dedicated enough.
As @fas says you can try user agent, but again that'll only catch bots who don't know how to set a user-agent which isn't really too difficult to do.
You could introduce some "computer hard" task into the clicking process but that would make your site pretty user unfriendly (e.g. CAPTCHA's). Again not 100% but harder to overcome trivially.
Ultimately I'd suggest it depends on how motivated/well funded your attackers are. If they are reasonably motivated and have some cash they can just hire real people to click the link (e.g. via amazon mechanical turk), at which point you're likely going to find it tricky to differentiate legitimate traffic from non-legitimate traffic.
Assuming your attackers are more casual about it, I'd say combine User Agent and source IP address. User Agents can actually be relatively identifying (more info on the [panopticlick site](https://panopticlick.eff.org/) ). So if you limit each user agent to one click per source IP address you may get a decent approximation, against an relatively unsophisticated attacker. | Try checking for valid user agents and referers. User Agents can always be spoofed but that's your best bet. Even if a bot is clicking through though, I'd consider that traffic. |
28,110 | ### The issue
My father has lately made a few sexist (and other -ist) "jokes", in the form of what I came to learn are called "disparagement jokes".
This has made me, and my wife, a bit uncomfortable.
Given the way he has raised me, I am convinced he can be taught to be better.
### What I tried
The first case was a very horrible US right-wing dog whistle of a "joke" against "snowflakes" shared via Whatsapp. I reacted sternly, saying that knowing the politics behind it (we're not from the US, and he's very much not exposed to the US cultural debate), I really could not see the fun in it. He started complaining that I should be more flexible, understand that his intentions are not evil, and that "nowadays you can't joke about anything without offending someone". I replied that lots of jokes can be made without offending someone, and being convinced of the contrary is not a good look. The conversation died.
A few days later he made a joke at the dinner table saying that I was lucky that my wife in those days what without voice as I "could have a bit of peace". I gave him the stink-eye on the spot.
I then resumed the conversation pointing out that it's not a nice thing to say. His response was unchanged, with the addition that I should remember that it was a joke based on a stereotype, so not directed towards my wife in particular.
### Side Issues
His age definitely does not help. He's now a 60+ years old grandfather. His mind and attitudes are pretty difficult to change and he's demonstrating more and more an unwillingness to learn new things, starting with technology.
He's also former military and the son/grandson of someone who fought WWII for the wrong side and never recanted their beliefs. He only recently started being fed up with voting center-right-wing (only after the company he worked for was basically sold for scraps by a right-wing government).
In addition, my parents - but here is mostly my mother, I feel - think that in a marriage, the woman pulls the husband away from his family, and thus they might think that these issues I have with those "jokes" have been forced upon me by my US wife, rather than being something I really think, so they might be more prone to dismiss them.
I also have lived out of my parents' home for the last 20 years, so they have not seen me change gradually, they only have seen the big changes (such as refusing to go to church since ~15 years ago).
### My Aim
I would like to have him understand why certain jokes are hurtful, without burning bridges with him.
I think I need to teach him about the problems of disparaging jokes in general and have him understand the way they hurt people, but I can't find a good way.
How can I explain my point to my father in an effective way without burning bridges?
### Risks
I risk alienating my father if I continue telling him that certain jokes are not ok/hurtful without having him understand why. Knowing him, he'd rather stop talking to me rather than being told that he's making mistakes. As a middle ground he would simply stop making jokes of all kinds around me, but I know he would resent me in that case, and resolution would be more complicated. | 2023/01/10 | [
"https://interpersonal.stackexchange.com/questions/28110",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/23093/"
] | Your father has made it indirectly apparent that he does not care about the impact of his behaviour on you or your wife.
The next step may be to confront him directly and tell him very clearly the effect his behaviour is having on you.
He will then have the opportunity to modify his behaviour. The silly adage "you can't teach an old dog new tricks" is nonsense and nothing more than an excuse for stubborn people to willfully refuse to change. After all, you're just asking him to act like a decent and respectful person, not [prove whether the Riemann Hypothesis is true or false](https://sciencetrends.com/this-is-the-hardest-math-problem-in-the-world/).
If he changes his behaviour, great. Remember, change isn't always linear, and sometimes involves 2 steps forward and 1 step backward. But change does involve a gradual progression, over time, in a general direction.
If he continues to demonstrate he doesn't care about the impact he is having on you and your wife, you have your unfortunate answer: your father is, regrettably, a self-centered person who places his desire to be offensive above the feelings of his son and his daughter-in-law. At that point you'll have to decide how much time, if any, you want to spend around him. | If it were practicable to change someone's mind by stratagem, then we'd have done away with politics both domestic and international. I don't think you should be trying to change your father's mind, at least not directly. Instead, focus on his behaviour (which might lead him to change his mind "himself", too).
In either case, I don't think that this issue yet rises to the level of *ethics*. Rather I believe that it needs to be dealt with as an issue of *etiquette*. Your father is making jokes, and we could have a very long and quite difficult discussion about the merits of comedic license in various cases (a discussion that I feel sure would result in changing no one's mind). As is such, I would expect that assaults aimed to change your father's position will be fruitless. His beliefs are a fortress in which he will feel quite safe.
His behaviour, on the other hand, is much more vulnerable to redress. Persons almost never agree completely on any items of political or personal belief, and they cannot be forced to change their thoughts, one way or the other; but in polite society the responsibility to treat others with kindness and respect can and should regulate their conduct.
If I were you, I would politely, but firmly, inform your father that these sorts of jokes are not funny to you, or your wife. That you would ask him not to make them in your presence, as they sour your mood and ruin what should be a pleasant meeting of parent and child. If he wishes to know, you are happy to explain just why you find them objectionable, and even why you think them wrong (although this should in my opinion be done as an *explanation* only, and not as *accusation* or *evangelization*). But the main point is that you want to enjoy your time with your father, and the behaviour that he takes makes that impossible for you.
If he still refuses to stop, then he is wronging you, intentionally, for the benefit only of what he himself calls "just a joke". It's rude, and it's wrong of him. But you'll have to respond to it, show your displeasure, and possibly give him less of your time and interest until he decides to treat you properly. Or else you'll have to give in. But that's up to you.
Additionally, I would not be likely to countenance jokes which insult my significant other in any capacity. In such circumstances the first step would be a firm and uncompromising rebuttal of the premise; "there is nothing about my wife's voice which brings me anything but peace, and the sooner it comes back the better". And if the hint is not taken, and such jokes continue, a more direct stipulation that insults of that kind against your wife are not acceptable, and you won't let them pass. |
27,459,548 | I have 3 true conditions:
**EDITED:**
```
#sell-status-no {
background-color: #fe220b;
margin: 0 auto;
width: 240px;
border: 1px solid #000000;
}
#sell-status-yes {
background-color: #25b116;
margin: 0 auto;
width: 240px;
border: 1px solid #000000;
}
if (($profit >= 10.00 && $markup_percentage >= 30.00) || ($profit
< 10.00 && $markup_percentage >= 30.00) ||
($profit >= 10.00 && $markup_percentage < 30.00)){
$status = "YES";
$div_id = 'sell-status-yes';
}
else $status = "no"; {
$div_id = 'sell-status-no';
}
<div id="<?php echo $div_id; ?>">
<h2>Sell Status: <?php echo $status; ?> <h2>
</div>
```
Basically if any of the conditions are true, I output a div with a green background with the words YES. If false, the box is red and the word NO is used.
However, whenever I encounter a situation where the $profit < 10 && $markup\_percentage is > 30, I end up with the false condition (red box and a NO)??
I am not sure why this is the case so any help or a better solution to tackle this problem would be appreciated.
Cheers | 2014/12/13 | [
"https://Stackoverflow.com/questions/27459548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3914746/"
] | Add following to `YourClass.m` file:
```
@interface YourClass() {
int variableName;
}
```
@end
in `viewDidLoad` initialize variableName to `0`.
```
- (IBAction)btn:(id)sender
{
if (variableName == arrayImg.count)
{
variableName = 0;
}
[img setImage:[arrayImg objectAtIndex:classVariable]];
variableName++
}
``` | In your `viewDidLoad`, add one more line:
```
[buttonName setTag:0];
```
Here change in btn event:
```
- (IBAction)btn:(UIButton *)sender {
[img setImage: [arrayImg objectAtIndex: [sender tag]]];
[sender setTag: [sender tag]+1];
if ([sender tag] > [arrayImg count]) {
[sender setTag: 0];
}
}
```
This will help you in memory management as well, because here no other extra flag variable required to hold your integer value, whereas your `UIButton` object only will hold.
Hope this will help you to achieve your requirement. |
560,777 | We all know the famous Euler's Formula.
It says that if a polyhedron has F(Faces), V(vertices) and E(edges) then F + V – E = 2.
My question is “is there any restriction on these variables?”
By restriction, I mean something like aF + bV + cE > 0 (for some a, b and c) must be satisfied before the formula can be applied.
For example, if there is no such restriction, can I ask the following question:-
Given that E= 6 and V = 7, (i) find F; (ii) draw that figure and (iii) name that figure. | 2013/11/10 | [
"https://math.stackexchange.com/questions/560777",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/42351/"
] | (ii)/(iii): Putting the other parts of your question aside, this is something that is an issue. For instance, a [decagonal prism](http://en.wikipedia.org/wiki/Decagonal_prism) and a [dodecahedron](http://en.wikipedia.org/wiki/Dodecahedron) both have 12 faces, 20 vertices, and 30 edges, so these counts alone don't always determine which polyhedron you have.
Finding F (or V or E) *if* there are any simple (no holes) polyhedra with the given counts for the other two numbers is what the formula is for. So *if* there were a polyhedron with 6 edges and 7 vertices, it must have only 1 face, but that wouldn't make for much of a polyhedron.
There are some basic inequalities to cut down what's possible, though. Since every edge has two halves, and every vertex is attached to at least three "half-edges", we have $2E\ge3V$ (your E=6 V=7 example doesn't obey this). Similarly, since every edge bounds exactly two faces, and every face has at least three edges, we have $2E\ge3F$.
**Edit:** These inequalities, with Euler's formula, basically reduce to $(V+4)/2\le F\le2V-4$ and [this table of polyhedron counts](http://www.numericana.com/data/polycount.htm) suggests that all numbers satisfying that are possible (they certainly are up to 32 vertices/faces). | Observe the following two constructions, where I assume $V$ is even.
Behold the glory of MS Paint.


In the first construction, $V/2$ vertices are on top, $V/2$ on the bottom, and there are just $\dfrac{3V}{2}$ edges, the minimal possible (as Mark S. points out). In the second construction, I have added $\dfrac{V}{2}$ red and orange edges, and $V-6$ green edges, for a total of $3V-6$ edges, the maximal possible. For any amount of edges in between, just choose any subset of the new edges in the second construction of the appropriate size.
The case where $V$ is odd I have not considered, but can probably be handled similarly. |
39,480,832 | I'm trying to leverage any automatic handling of validation and displaying errors for a form using multiple entities.
The user can dynamically create multiple new entities via the form UI. The data is marshalled through `newEntities()`:
```
$this->MyModel->newEntities($data);
```
The first part of the problem I have is that in order to check if validation failed on any of the entities, I have to do it manually by checking every entity:
```
$errors = false;
foreach ($entities as $entity) {
if ($entity->errors()) {
$errors = true;
break;
}
}
if (!$errors) {
// Save...
```
Does Cake provide anything out of the box which allows you to check if `newEntities()` failed validation on any of its entities? If not, then never mind...
The main problem is how I get the errors from the individual entities to then show inline in my form next to the relevant inputs.
```
<?= $this->Form->create(); ?>
```
What can I pass to `create()` to link it to the entities? At the moment there doesn't seem to be any way for it to know what happens once the form is submitted, and therefore doesn't show errors.
My form inputs are created using the standard array notation, where `$i` comes from the loop building the form inputs from all the entities.
```
$this->Form->hidden("MyModel.$i.field");
``` | 2016/09/14 | [
"https://Stackoverflow.com/questions/39480832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/851885/"
] | simply pass the array of entities to your form
```
$this->Form->create($entities);
```
also you don't have to specify the model name in the input name. Simply
```
$this->Form->hidden("$i.field");
```
and not
```
$this->Form->hidden("MyModel.$i.field");
``` | Use newEntity and add those to an array. Loop over that array accessing errors().
```
$array = [];
$array[] = $TableRegistry->newEntity([
'hi' => 'hey'
]);
foreach($array as $r){
var_dump($r->errors());
}
```
Hopefully that works with your use-case. I've never used newEntities, but you may be able to iterate over that as well? |
25,780 | I am fed up with the text editor [TextMate](https://web.archive.org/web/20221208003521/https://macromates.com/). It's great, but it's old and keeps crashing on me. No development in (what, 3+?) years, etc.
So I'm looking for a viable alternative, mainly for [PHP](https://en.wikipedia.org/wiki/Php) development. However, I don't want a bloated and slow editor that runs on Java (so [NetBeans](https://netbeans.apache.org/), [Komodo](https://github.com/Komodo/KomodoEdit), [Eclipse](https://www.eclipse.org/), etc are out), nor something that includes the kitchen sink (goodbye Coda, I already own [Espresso](https://espressoapp.com/) but am extremely disappointed that after latest version doesn't include variable autocompletion). [BBEdit](https://www.barebones.com/products/bbedit/) is a little too bare bones for me.
In summary, as the title says, a TextMate replacement that is modern, stable and still in development. Does such an editor exist? | 2011/09/23 | [
"https://apple.stackexchange.com/questions/25780",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/9454/"
] | Have a look at Sublime Text. It basically is what I would expect TextMate2 to be.
<http://www.sublimetext.com/> | [MacVIM](https://github.com/b4winckler/macvim) + the [Janus Plugins](https://github.com/carlhuda/janus)
-------------------------------------------------------------------------------------------------------
Fear not the VIM. MacVIM gives you visual VIM that's OS X friendly. All the usual suspects work (Cmd+S, Cmd+W, etc.). And the Janus plugins give you nice addons like a side drawer for projects, etags/ctags without even having to know what that is, TAB key completion and more.
It's really very good. It lowers the VIM learning curve by a massive amount.
The MacVIM is getting good amounts of active development. It had full-screen Lion support within days of Lion being out the door. I can't tell you how nice full screen Lion MacVIM coding is. You really have to experience the joy and wonder of it for yourself. It's very distraction free, let me say that.
It's free to try so you're not out any money if you decide it really isn't for you.
---
[Komodo](http://www.activestate.com/komodo-ide) or ([Komodo Edit](http://www.activestate.com/komodo-edit))
----------------------------------------------------------------------------------------------------------
I used, and loved, Komodo v4 for years in my last job. I liked it's big, old IDE-ness at the time and that it looked and (nearly) behaved the same on Linux and Windows -- the two platforms I had to switch between during the course of a development day. I used it mainly for Perl and Tcl development. But it bundles in a ton of support for PHP.
It is not a Java application. Most definitely v4 is a native binary on OS X. I just fired up my old v4 copy to verify this.
It runs fast, but not as fast as something like TextMate or MacVIM because it is, after all, trying to be a big old IDE. And big old IDEs try to do lots of project-level analysis and integrations and scanning and what not to give you that big old IDE experience. That being said, it wasn't that slow.
Komodo Edit is free. I used the paid version.
I gave up the whole IDE thing when I switched to OS X full time for development. [My tool chain still looks pretty much like this answer I posted to a similar question over here](https://apple.stackexchange.com/questions/10533/looking-for-the-ultimate-ide-for-mac/10558#10558). I use MacVIM more and more now that TextMate though. |
3,189,245 | What is the integral of:
$$I=\int \sin(ax) \cos(ax) dx$$
My approach is down below. I have attempted the problem and posted it as an answer. I did the problem using trigonometric substitution.
$$u=ax$$
$$\frac{du}a=dx$$
$$\frac{1}a\int\sin u \cos u \ du$$
$$g=\sin u$$
$$dg = \cos u \ du$$
$$\frac{1}a\int g\ dg$$
$$I=\frac{1}a\frac{\sin^2ax}{2}+C$$ | 2019/04/15 | [
"https://math.stackexchange.com/questions/3189245",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/372659/"
] | If we have that
$$f(x)=\frac1{1+e^{\frac{x-b}{c}}}=k$$
for some $k\in\mathbb{C}$ then we can rearrange this to get
$$1+e^{\frac{x-b}{c}}=\frac1k$$
$$e^{\frac{x-b}{c}}=\frac1k-1$$
$$\frac{x-b}{c}=\ln{\left(\frac1k-1\right)}$$
$$x-b=c\ln{\left(\frac1k-1\right)}$$
$$x=b+c\ln{\left(\frac1k-1\right)}$$
Which is undefined for $k=0$ but otherwise allows a unique value of $x$ to be found. | It sounds like you are seeking an analytic solution to the equation
$$
\frac{1}{1+\exp((x-b)/c)} = 0,
$$
but the LHS is always positive for any $x$ since exponent is always positive, so both numerator and denominator are always positive.
However, as $x \to \infty$ if $c>0$ you will get the desired effect. |
5,830,833 | Is it possible to select a form element using it's name attribute?
For example if I had something like this:
```
<input type="text" name="my_element" />
```
How would I go about setting a javascript variable to the value of this input?
```
var name_val = $(input[name='my_element']).val();
```
? | 2011/04/29 | [
"https://Stackoverflow.com/questions/5830833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278533/"
] | Your almost there
```
var name_val = $('input[name=my_element]').val();
``` | The following should work:
```
var name_val = $('input[name="my_element"]').val();
``` |
5,214 | What does *salad days* mean? I've heard the term used to describe past better days, but what does that have to do with salad?
Also, when was the phrase coined? | 2010/11/18 | [
"https://english.stackexchange.com/questions/5214",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/1914/"
] | It refers to the time of youth when one was naive and inexperienced, and therefore happy and optimistic - in other words, when one was "green," as in "unripe" or "not yet mature." It's a bit of a convoluted pun.
Like so many English idioms, the term was coined by Shakespeare in the 17th century (Antony and Cleopatra.) | Just agreeing with @PyroTyger, with [the actual quote](http://www.enotes.com/antony-and-cleopatra-text/act-scene-5#saladdays):
>
> Charmian: By your most gracious
> pardon, I sing but after you.
>
>
> Cleopatra: My **salad days**, When I was
> green in judgment, cold in blood, To
> say as I said then!
>
>
> |
50,393,027 | I'm pulling information from 3 different tables in MSSQL 2008 and I'd like to get the SUM of `CC_qty` as well as each `Location` condensed into one field per `id`. If this can be done in the query itself that would be fantastic - `listagg` and `GROUP_CONCAT` are not cutting it. Otherwise I've been working with array\_reduce, array\_merge, array\_diff to no avail.
Here is my query and the original array:
```
SELECT a.id, a.qty, b.locationID, b.CC_qty, c.Location FROM (
SELECT left(id, 10) as id, MAX(qty) as qty
FROM db1
WHERE id like 'abc-abc%'
GROUP BY left(id, 10)
) as a
JOIN (
SELECT locationID, left(SKU, 10) as SKU, CC_qty FROM db2
WHERE CC_qty > 25
) as b on a.abc-abc = b.SKU
JOIN (
SELECT locationID, Location FROM db3
) as c on b.locationID = c.locationID
Array
(
[0] => Array
(
[id] => abc-abc-12
[qty] => 0
[locationID] => 276
[CC_qty] => 250
[Location] => NOP11
)
[1] => Array
(
[id] => abc-abc-12
[qty] => 0
[locationID] => 310
[CC_qty] => 1385
[Location] => NOP01
)
[2] => Array
(
[id] => abc-abc-23
[qty] => 0
[locationID] => 84
[CC_qty] => 116
[Location] => NOP06
)
[3] => Array
(
[id] => abc-abc-23
[qty] => 0
[locationID] => 254
[CC_qty] => 432
[Location] => NOP08
)
[4] => Array
(
[id] => abc-abc-23
[qty] => 0
[locationID] => 228
[CC_qty] => 101
[Location] => NOP04
)
[5] => Array
(
[id] => abc-abc-34
[qty] => 0
[locationID] => 254
[CC_qty] => 436
[Location] => NOP08
)
[6] => Array
(
[id] => abc-abc-34
[qty] => 0
[locationID] => 254
[CC_qty] => 62
[Location] => NOP08
)
[7] => Array
(
[id] => abc-abc-45
[qty] => 0
[locationID] => 75
[CC_qty] => 89
[Location] => NOP05
)
[8] => Array
(
[id] => abc-abc-45
[qty] => 0
[locationID] => 202
[CC_qty] => 372
[Location] => NOP07
)
)
```
This is my desired output, for simplicity of knowing what information I absolutely require I've removed `qty` and `locationID` but those don't have to be removed:
```
Array
(
[0] => Array
(
[id] => abc-abc-12
[CC_qty] => 1635
[Location] => NOP11, NOP01
)
[1] => Array
(
[id] => abc-abc-23
[CC_qty] => 649
[Location] => NOP06, NOP08, NOP04
)
[2] => Array
(
[id] => abc-abc-34
[CC_qty] => 495
[Location] => NOP08
[3] => Array
(
[id] => abc-abc-45
[CC_qty] => 461
[Location] => NOP05, NOP07
)
)
```
Thanks for looking! | 2018/05/17 | [
"https://Stackoverflow.com/questions/50393027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5116212/"
] | Being that I left an answer for MySQL, it wasn't going to work for this. I don't know MSSQL well enough to use it, so here's a way to do it with PHP so I don't leave you completely without an answer.
```
$arr = array
(
array
(
'id' => 'abc-abc-12',
'qty' => 0,
'locationID' => 276,
'CC_qty' => 250,
'Location' => 'NOP11'
),
array
(
'id' => 'abc-abc-12',
'qty' => 0,
'locationID' => 310,
'CC_qty' => 1385,
'Location' => 'NOP01'
),
array
(
'id' => 'abc-abc-23',
'qty' => 0,
'locationID' => 84,
'CC_qty' => 116,
'Location' => 'NOP06'
)
);
$combinedArr = array();
foreach ($arr as $a)
{
$found = false;
foreach ($combinedArr as $i => $b)
{
if ($b['id'] == $a['id'])
{
$found = true;
$locs = explode(',', $a['Location']);
$combinedArr[$i]['CC_qty'] += $a['CC_qty'];
if (!in_array($b['Location'], $locs))
{
$locs[] = $b['Location'];
$combinedArr[$i]['Location'] = implode(', ', $locs);
}
}
}
if (!$found)
$combinedArr[] = $a;
}
print_r($combinedArr);
/*
Array
(
[0] => Array
(
[id] => abc-abc-12
[qty] => 0
[locationID] => 276
[CC_qty] => 1635
[Location] => NOP01, NOP11
)
[1] => Array
(
[id] => abc-abc-23
[qty] => 0
[locationID] => 84
[CC_qty] => 116
[Location] => NOP06
)
)
*/
``` | I don't have any experience with MSSQL, but I feel rather confident that it provides the necessary functionality to merge, sum, and concatenate. Anyhow, I am compelled to post an answer because I find the answer from Thomas to be unrefined.
Essentially, you should use the `id` values as temporary keys to determine if you are processing the first occurrence of the group or a subsequent occurrence. On the first encounter, just save the whole row to the output array. For all future rows belonging to the same group, just sum and concatenate the desired values.
To remove the temporary keys in the result array, just call `array_values($result)`.
Code: ([Demo](https://3v4l.org/FqtjX))
```
$array = [
['id' => 'abc-abc-12', 'qty' => 0, 'locationID' => 276, 'CC_qty' => 250, 'Location' => 'NOP11'],
['id' => 'abc-abc-12', 'qty' => 0, 'locationID' => 310, 'CC_qty' => 1385, 'Location' => 'NOP01'],
['id' => 'abc-abc-23', 'qty' => 0, 'locationID' => 84, 'CC_qty' => 116, 'Location' => 'NOP06'],
['id' => 'abc-abc-23', 'qty' => 0, 'locationID' => 254, 'CC_qty' => 432, 'Location' => 'NOP08'],
['id' => 'abc-abc-23', 'qty' => 0, 'locationID' => 228, 'CC_qty' => 101, 'Location' => 'NOP04'],
['id' => 'abc-abc-34', 'qty' => 0, 'locationID' => 254, 'CC_qty' => 436, 'Location' => 'NOP08'],
['id' => 'abc-abc-34', 'qty' => 0, 'locationID' => 254, 'CC_qty' => 62, 'Location' => 'NOP08'],
['id' => 'abc-abc-45', 'qty' => 0, 'locationID' => 75, 'CC_qty' => 89, 'Location' => 'NOP05'],
['id' => 'abc-abc-45', 'qty' => 0, 'locationID' => 202, 'CC_qty' => 372, 'Location' => 'NOP07'],
];
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['id']])) {
$result[$row['id']] = $row;
} else {
$result[$row['id']]['qty'] += $row['qty']; // SUM
$result[$row['id']]['locationID'] .= ", " . $row['locationID']; // CONCAT
$result[$row['id']]['CC_qty'] += $row['CC_qty']; // SUM
$result[$row['id']]['Location'] .= ", " . $row['Location']; // CONCAT
}
}
var_export(array_values($result));
```
Output:
```
array (
0 =>
array (
'id' => 'abc-abc-12',
'qty' => 0,
'locationID' => '276, 310',
'CC_qty' => 1635,
'Location' => 'NOP11, NOP01',
),
1 =>
array (
'id' => 'abc-abc-23',
'qty' => 0,
'locationID' => '84, 254, 228',
'CC_qty' => 649,
'Location' => 'NOP06, NOP08, NOP04',
),
2 =>
array (
'id' => 'abc-abc-34',
'qty' => 0,
'locationID' => '254, 254',
'CC_qty' => 498,
'Location' => 'NOP08, NOP08',
),
3 =>
array (
'id' => 'abc-abc-45',
'qty' => 0,
'locationID' => '75, 202',
'CC_qty' => 461,
'Location' => 'NOP05, NOP07',
),
)
``` |
32,678,080 | How can I call a javascript function (`repeatedFunction()`) repeatedly but make it so that, let's say an `alert("This function is being executed for the first time")`, is only activated the first time that `repeatedFunction()` is, but the `//other code` is always activated? And also, how can I make the `alert()` allowed to be activated for one more time, like if the `repeatedFunction()` was being executed for the first time again? | 2015/09/20 | [
"https://Stackoverflow.com/questions/32678080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308892/"
] | JavaScript [closure approach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) will fit in this task. It has no global variables, and keeps your task in a single function.
```js
var closureFunc = function(){
var numberOfCalls = 0;
return function(){
if(numberOfCalls===0)
{
console.log('first run');
}
numberOfCalls++;
console.log(numberOfCalls);
};
};
var a = closureFunc(); //0
a(); //1
a(); //2
var a = closureFunc(); //drop numberOfCalls to 0
a(); //1
```
<http://jsfiddle.net/hmkuchhn/> | ```
var firstTime = true;
var myFunction = function() {
if(firstTime) {
alert("This function is being executed for the first time");
firstTime=false;
}else{
//whatever you want to do...
}
}; //firstTime will be true for the first time, after then it will be false
var milliseconds = 1000;
setInterval(myFunction, milliseconds);
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second.
``` |
60,542,960 | I have been researching this problem for 2 hours online (including combing though other SO questions) and I can't seem to find an answer, so this is a last resort. For completeness I have added the entire function as it is only just over 100 lines.
Quick Summary : I have a button that the user clicks to start a function named ***measure*** that has an if/else statement. When the condition is true, there are two onclick() functions that are started. (functions *a* and *b*).
When the condition is false (the button is clicked again), the *else* portion is triggered correctly (I verified this)... and I also want the onclick functions to stop. However, they go on forever. I had tried using stopPropogation() but that seems to do nothing and the functions still go on. I have noted in comments where this is.
What am I doing wrong? Skip to the *else* statement to quickly see my problem. (Very bottom).
```
function measure()
{
if (ims_measure==0) // if variable is 0 (or "off"), set it to 1 (on) and add layers along with onclick() events
{
ims_measure=1;
document.getElementById("cpanel_measure").src = "images/cpanel_measure.png";
map.setLayoutProperty('measure-points', 'visibility', 'visible');
map.setLayoutProperty('measure-lines', 'visibility', 'visible');
measuring_tool_menu = "Measuring Tool (mi.)<br>";
var distanceContainer = document.getElementById('distance');
// GeoJSON object to hold our measurement features
var geojson_measure = {
'type': 'FeatureCollection',
'features': []
};
// Used to draw a line between points
var linestring = {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': []
}
};
map.addSource('geojson_measure', {
'type': 'geojson',
'data': geojson_measure
});
// Add styles to the map
map.addLayer({
id: 'measure-points',
type: 'circle',
source: 'geojson_measure',
paint: {
'circle-radius': 2,
'circle-color': '#ffcc33'
},
filter: ['in', '$type', 'Point']
});
map.addLayer({
id: 'measure-lines',
type: 'line',
source: 'geojson_measure',
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': '#ffcc33',
'line-width': 2.5
},
filter: ['in', '$type', 'LineString']
});
// First onclick function below (a)
map.on('click', function(a) {
var features = map.queryRenderedFeatures(a.point, {
layers: ['measure-points']
});
// Remove the linestring from the group
// So we can redraw it based on the points collection
if (geojson_measure.features.length > 1)
geojson_measure.features.pop();
// Clear the Distance container to populate it with a new value
distanceContainer.innerHTML = '';
// If a feature was clicked, remove it from the map
if (features.length) {
var id = features[0].properties.id;
geojson_measure.features = geojson_measure.features.filter(function(point) {
return point.properties.id !== id;
});
} else {
var point = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [a.lngLat.lng, a.lngLat.lat]
},
'properties': {
'id': String(new Date().getTime())
}
};
geojson_measure.features.push(point);
}
if (geojson_measure.features.length > 1) {
linestring.geometry.coordinates = geojson_measure.features.map(function(
point
) {
return point.geometry.coordinates;
});
geojson_measure.features.push(linestring);
// Populate the distanceContainer with total distance
var value = document.createElement('pre');
value.textContent =
'Total distance: ' +
turf.length(linestring, {units: 'miles'}).toLocaleString() +'mi';
distanceContainer.appendChild(value);
}
map.getSource('geojson_measure').setData(geojson_measure);
});
// Second onclick function below (b)
map.on('mousemove', function(b) {
var features = map.queryRenderedFeatures(b.point, {
layers: ['measure-points']
});
// UI indicator for clicking/hovering a point on the map - Can't use because inable to change back?!
// map.getCanvas().style.cursor = features.length
// ? 'pointer'
// : 'crosshair';
});
}
else {
ims_measure=0;
document.getElementById("cpanel_measure").src = "images/cpanel_measure_dark.png";
map.setLayoutProperty('measure-points', 'visibility', 'none');
map.setLayoutProperty('measure-lines', 'visibility', 'none');
map.removeLayer("measure-lines");
map.removeLayer("measure-points");
map.getSource('geojson_measure').setData("");
map.removeSource("geojson_measure");
document.getElementById("distance").innerHTML = " ";
measuring_tool_menu = "null";
// here is where I wish to stop the onclick functions.
// I have tried a.stopPropogation(), b.stopPropogation() as well as numerous other methods. None will seemingly do anything
// as the onclick methods still fires as if I put no code here at all.
return;
}
}
``` | 2020/03/05 | [
"https://Stackoverflow.com/questions/60542960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9946112/"
] | To hide the browser while executing tests using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491)'s [python](/questions/tagged/python "show questions tagged 'python'") you can use the [minimize\_window()](https://www.selenium.dev/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html#selenium.webdriver.remote.webdriver.WebDriver.minimize_window) method which eventually minimizes/pushes the *Chrome Browsing Context* effectively to the background using the following solution:
```
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://www.google.co.in')
driver.minimize_window()
```
---
Alternative
-----------
As an alternative you can use the **`headless`** attribute to configure [ChromeDriver](https://stackoverflow.com/questions/48079120/what-is-the-difference-between-chromedriver-and-webdriver-in-selenium/48080871#48080871) to initiate [google-chrome](/questions/tagged/google-chrome "show questions tagged 'google-chrome'") browser in *Headless* mode using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) and you can find a couple of relevant discussions in:
* [How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?](https://stackoverflow.com/questions/46920243/how-to-configure-chromedriver-to-initiate-chrome-browser-in-headless-mode-throug/49582462#49582462) | If you're using Firefox, try this:
```py
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
driver_exe = 'path/to/firefoxdriver'
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(driver_exe, options=options)
```
similar to what @Meshi answered in case of Chrome |
6,092 | I've asked this myself sometimes already. A lot of knowledgeable developers are using Stackoverflow to give advice and help solving other peoples problems - for free. Giving back your own knowledge and helping students, newcomers or just less experienced developers can be a really good thing. It's a great feeling to know that you've helped someone. I wonder if people would also be up for voluntary (donations at maximum) mentoring other people - face to face via video chat (assuming the person mentored is actually intending to learn and not just trying get help on a project for free from an expert).
I know there are sites like codementor, but they are all based on a fixed hourly rate - you can basically only hire a mentor/expert. | 2019/12/07 | [
"https://cseducators.stackexchange.com/questions/6092",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8691/"
] | I is hard to give a sufficiently nuanced answer to this question. There are many factors. I will try to give my own perspective.
First, I give away a lot for free in this forum and in others, both within the SE framework and to the [SIGCSE](https://sigcse.org/sigcse/) and [APCS](https://en.wikipedia.org/wiki/AP_Computer_Science) communities. So, my basic instinct is to be generous with my skills and experience.
Second, not everyone is as economically advantaged as everyone else. Some people would like an education but various factors, both economic and political, make that very difficult. In the US, the tax system used for support of schools is incredibly unfair to many people. If you live in a rich area, you have good schools. If you live in a poor area your schools will find a very difficult time providing you the education you deserve.
Third, an educated populace is a good thing. The education available to an individual shouldn't depend on where they live (locally or otherwise), or their particular economic circumstances. To insist that everyone must pay their own way for an education leads to a sub-optimally educated general population, which is a poor path to progress for a nation or the world.
However, fourth, if something is given to you, you may not appreciate it sufficiently, or work to optimize the potential of the gift. I've retired from academia (several years ago), but still teach Tai Chi. It has always been the practice of Tai Chi masters that students must pay something to obtain instruction. Even if it is just a few eggs or a kilo of grain. And the purpose of payment isn't for the support of the masters, but so that the students will be more likely to apply themselves and take advantage of the instruction. It is, in many ways, a mutual gift system.
There is a common flaw in free online courses, that students tend to drop out at too-high rates. If they commit nothing, they probably don't feel obligated to commit to the work required to learn. People paying for higher education, often work hard because they are already "investing" a lot of money and want a good return and will therefore "invest" a lot of effort.
So, if you want to know whether I would, personally, teach for nothing, you'd have to tell me who the students are and what it is that they are willing to "invest" of themselves. If you can find a way to somehow assure that they will do the work necessary so that my efforts aren't just wasted, then I'm willing to listen. But, yes, I'm willing to contribute, provided that I think I can make a difference, somehow. But that is easier in small face-to-face groups than in broadcasting to the web.
Finally, providing the conditions for true learning online are very difficult. If you read other things I've written here and on academia.se you will understand that I have definite ideas about learning and what it takes (primarily reinforcement and feedback) and both of those are hard to arrange *faithfully* on the web. | A key difference with stackoverflow vs. private mentoring is that one doesn't need to be invested in any particular person's understanding. If the OP doesn't get it, marks my answer down, upvotes or checkmarks an answer I consider incorrect, no problem for me. Maybe some other random person(s) will find my answer useful. Or useless. About which I may never find out.
With individual mentoring, there is a more personal feedback loop: one must try to actually figure out what's wrong with the students brain that keeps them from understanding (or my own brain that makes my explanation incomprehensible). Those may or may not be possible. But if one succeeds, especially after some effort, the result can create a positive emotional experience. |
66,651,478 | I have an array with nested objects having parent-child relationship like so:
```
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4, children: []},
{id: 6, title: 'hello', parent: 4, children: []}
]},
{id: 7, title: 'hello', parent: 3, children: []}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2, children: []}
]}
]
```
I need to convert it into a plain array retaining the parent child relationship like so and in the order of parent and all its children returned first before proceeding on to the next parent.
```
[
{id: 1, title: 'hello', parent: 0},
{id: 3, title: 'hello', parent: 1},
{id: 4, title: 'hello', parent: 3},
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4},
{id: 7, title: 'hello', parent: 3},
{id: 2, title: 'hello', parent: 0},
{id: 8, title: 'hello', parent: 2}
]
```
I was able to convert the other way round with a recursive function.
But I need to do the opposite in an efficient way. There is multilevel nesting as shown in the sample nested array.
EDIT: Updated the nested array to have an empty children array for leaf nodes.
And also, an answer in ES5 would help. | 2021/03/16 | [
"https://Stackoverflow.com/questions/66651478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744195/"
] | In ES5 you can also use some *functional programming* approach, and flatten an array with `[].concat.apply`:
```js
function flatten(arr) {
return [].concat.apply([], arr.map(function (obj) {
return [].concat.apply([
{ id: obj.id, title: obj.title, parent: obj.parent }
], flatten(obj.children));
}));
}
let arr = [{id: 1, title: 'hello', parent: 0, children: [{id: 3, title: 'hello', parent: 1, children: [{id: 4, title: 'hello', parent: 3, children: [{id: 5, title: 'hello', parent: 4, children: []},{id: 6, title: 'hello', parent: 4, children: []}]},{id: 7, title: 'hello', parent: 3, children: []}]}]},{id: 2, title: 'hello', parent: 0, children: [{id: 8, title: 'hello', parent: 2, children: []}]}];
console.log(flatten(arr));
```
In ES6 the same algorithm reduces to the following:
```js
const flatten = arr => arr.flatMap(({children, ...o}) => [o, ...flatten(children)]);
let arr = [{id: 1, title: 'hello', parent: 0, children: [{id: 3, title: 'hello', parent: 1, children: [{id: 4, title: 'hello', parent: 3, children: [{id: 5, title: 'hello', parent: 4, children: []},{id: 6, title: 'hello', parent: 4, children: []}]},{id: 7, title: 'hello', parent: 3, children: []}]}]},{id: 2, title: 'hello', parent: 0, children: [{id: 8, title: 'hello', parent: 2, children: []}]}];
console.log(flatten(arr));
``` | if data is large can consider use tail optimization and async/await
```js
const arr = [
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
];
const convertArr = (arr) => {
return arr.reduce((init, cur) => {
const plain = init.concat(cur);
const children = cur.children;
return plain.concat(children && children.length ? convertArr(children) : [])
}, [])
}
const generateArr = (arr) => {
return convertArr(arr).map(v => ({
id: v.id,
parent: v.parent,
title: v.title
}))
}
console.log('result:', generateArr(arr))
``` |
1,243,113 | I often want to clear the session store in Rails, in particular, the default cookie-based session store. Some sites seem to suggest that
```
rake tmp:sessions:clear
```
accomplishes this task, but it appears that it does not. What is the proper way to clear the cookie-based session store? | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85509/"
] | The problem is that cookies are client side. Running a rake task on your server won't delete cookies on all the machines that have visited the web page, obviously.
Perhaps you can use `session.clear` in your controllers somehow? You're right about changing the cookie key, though. Doing so would invalidate any session belonging to the old key. You would have to rescue from `ActionController::StaleSession` (or something like that), but it'd work. | If you are running this on a production server I recommend:
```
rake secret
```
Which is simply generating a random secure token. The rake task is basically doing this, which you could do in a console.
```
SecureRandom.hex(64)
```
Never check the production key into version control / GIT but use an environment variable instead. So in your `config/secrets.yml` file use something like:
```
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
``` |
4,767,010 | I am trying to give my div and textarea some padding. When I do this, it increases the size of the element, instead of shrinking the content area inside of it. Is there any way to achieve what I am trying to do? | 2011/01/22 | [
"https://Stackoverflow.com/questions/4767010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576389/"
] | You could add `box-sizing:border-box` to the container element, to be able to specify a width and height that don't vary when you add padding and/or border to the element.
See [here (MDN)](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) for specifications.
**Update (copied comment to answer)**
Right now, the value `border-box` is supported in all major browsers, according to [MDN Specs](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#Browser_compatibility)
Some browsers of course requires proper prefix i.e. `-webkit` and `-moz` as you can clearly see [here](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#Examples) | It depends on the browser and it's implementation of the [box model](http://www.w3.org/TR/CSS21/box.html). What you are experiencing is the correct behavior.
IE traditionally got it wrong: <http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug> |
6,380,191 | ```
double ***x;
```
what does it mean to declare declare a variable with three asterisks? Is this a pointer to a pointer to a pointer to a double? | 2011/06/17 | [
"https://Stackoverflow.com/questions/6380191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/574733/"
] | It is a pointer to a pointer to a pointer to a double. | Indeed it is a pointer to a pointer to a pointer to a double.
Either a big multi-dimensional array, or just many levels of pointer indirection. |
40,246 | I'm currently writing a story in the universe of the role playing game "Mahamot".
Basically, in this world, what's left of human kind lives on huge spaceships swarming with little plants called "micelis" (it seems to be a French game, so I don't have any translation for this word which doesn't even exist in French). The description of those micelis is unclear but they are mostly a mix of mosses and lichens and their size ranges from one micron to ten centimetres. There are several thousands species of micelis and they are the base materials for everything humans need (clothes, food, weapons...).
Now here is the rub : in this game, swords, axes, knives and so on are said to be made of a something that closely resembles metal. So how can people turn mosses and lichens into such weapons ?
Two problems :
* A plant doesn't seem to be hard enough to forge a weapon. So micelis have to be transformed in a way that reinforces their structure. That being said, micelis aren't precisely described so if you can imagine how can some species naturally came to become stiff and hard, that'd be great !
* Since micelis are ten centimetres long at best, you have to use several of them to forge a weapon. But how can you mix them together into one object that won't break each time you hit something ?
Feel free to invent micelis species and features that would allow them to be turned into weapons more easily. As long as those features are plausible for a plant and respect the few indications I gave about micelis, it's OK with me.
Remember that everything you use to turn micelis into weapons is also made of micelis. In particular, I only have access to chemicals that can be created by plants.
Last thing you should know : there is absolutely NO magic in this world. | 2016/04/18 | [
"https://worldbuilding.stackexchange.com/questions/40246",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/19976/"
] | There are two ideas I have about this.
First is purification. Maybe the hulls of the spaceships are made from metal alloy that is simply impossible to work with or separate using technology available to humans. But the micelis could separate the various components of the alloy, thus producing raw materials that then can be used for standard metallurgy.
Second idea is mold forming. The micelis simply eat whatever metals is nearby and grow into available space, filling it with eaten metal. So simply create a mold in form of sword and put micelis inside it and just wait. Depending on it's growth speed, it might fill the sword mold in a few months or years. | So you have a colonial micelis that is grown in a mold of the weapon that you need, it naturally forms firm cellular links between the individual micelis so that they're effectively a single larger organism. They don't live long in this formation but they can be feed a metal salt solution that they convert into a solid-ish form that mirrors their shape. Basically you end up with a weapon made from metal structured to resemble coral, it's solid enough, slightly lighter than a forging would be and a bit rough in the raw but it would work just fine, in fact it would be slightly more shock resistant than solid steel. |
38,536,737 | Each line in my table has an Edit button.
I trying to fetch the row number by clicking on the Edit button. I succeed to do that in JavaScript but in PHP I don't know how.
So I thought to pass the variable from JS to PHP and from some reason I get an error
>
> Undefined index: selectedRow
>
>
>
when I use this: `$_GET['selectedRow']`;
The final goal is to make specific row editor.
So if you have an different idea to make it done I'd like to hear.
Relevant piece of my code:
```
echo '<table width = "100%" id = "contactsTable"><tr>'.
'<th style=" width:3em; ">עריכה</th>'.
'<th style=" width:7em; ">אזור</th>'.
'<th style=" width:7em; ">תפקיד</th>'.
'<th style=" width:15em; ">הערה</th>'.
'<th style=" width:15em; ">אימייל</th>'.
'<th style=" width:10em; ">טלפון</th>'.
'<th style=" width:15em; ">כתובת</th>'.
'<th style=" width:10em; ">שם מלא</th>';
while($row = mysql_fetch_array($query)){
echo '<tr><td onclick="selectedRow(this)">'.
'<a href="?editRow=true">'.
'<input type="image" src="../image/edit-icon.png" alt="עריכה" width="30" height="30">'.
'</a></td>'.
'<td>'.$row['area'].'</td>'.
'<td>'.$row['role'].'</td>'.
'<td>'.$row['note'].'</td>'.
'<td>'.$row['email'].'</td>'.
'<td>'.$row['phoneNumber'].'</td>'.
'<td>'.$row['address'].'</td>'.
'<td>'.$row['fullName'].'</td>'.
'</tr>';
}
echo '</table>';
echo '<script>';
echo 'function selectedRow(obj) {'.
'var num = obj.parentNode.rowIndex - 1;'.
'alert ("selectedRow: "+num);'.
'window.location.href = "?selectedRow="+ num;'.
'}';
echo '</script>';
}
if(isset($_GET['editRow'])){
echo 'selectedRow :'. $_GET['selectedRow'];
}
```
I tried also to use AJAX instead of `'window.location.href = "?selectedRow="+ num;'.`:
```
'$.ajax({'.
'type: "POST",'.
'url: "index.php",'.
'data: "selectedRow=" + num'.
'});'.
``` | 2016/07/22 | [
"https://Stackoverflow.com/questions/38536737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3178398/"
] | Change your anchor tag href value in while loop with following text :
```
<a href="?editRow=true"> <---> <a href="javascript:;">
```
And now replace your window.location.href in script
```
'window.location.href = "?selectedRow="+ num;'. <---> 'window.location.href = "?editRow=true&selectedRow="+ num;'.
```
It will work file in your condition. | I continued to do tests, Someone test my code in his computer and told me that my code works, I continued my tests and eventually found the way it works.
I removed this line : `'<a href="?editRow=true">'.` from the table.
I add the **editRow=true** to the JS function with **selectedRow** like this: `'window.location.href = "?editRow=true&selectedRow="+ num;'.`
And now its working, Anyway it should work both ways so I don't know what was the problem. |
64,878,896 | i am currently building a shopping website . i finished the homepage and i have to make routing for other pages
i have 3 main files: App.js, Menuitem.js (which is to execute props), and Homepage.js (which also is used to apply executing props from sections array which includes titles and background images and sections paths)
this is the App js
```
import React from "react";
import Homepage from './Homepage'
import "./styles.css";
import './Homepage.css'
import {Route, Switch} from "react-router-dom";
const Hatspage=function() {
return(
<div>
<h1>
Hats page
</h1>
</div>
)
}
function App() {
return (
<div>
<Switch>
<Route exact path='/'component={Homepage}/>
<Route path='/hats'component={Hatspage}/>
</Switch>
</div>
);
}
export default App
```
Menuitem.js
```
import React from 'react'
import {WithRouter} from 'react'
const Menuitem= function(props){
return(
<div className='card' style={{ backgroundImage: `url(${props.imageUrl})` }} >
<div className='text-frame'>
<h1 className='title'>{props.title}</h1>
<p className='subtitle'>shop now</p>
</div>
</div>
)
}
export default Menuitem
```
Homepage.js
```
import React from "react";
import sections from './directory-components';
import Menuitem from "./menu-item-components";
const arrayOne=[sections.slice(0,3)]
const arrayTwo=[sections.slice(3,)]
function extract(item){
return(
<Menuitem
title={item.title} imageUrl={item.imageUrl}/>
)
}
function Homepage(){
return(
<div className='directory-menu'>
<div className='content'>
{sections.slice(0,3).map(extract) }
</div>
<div className='second'>
{sections.slice(3,).map(extract) }
</div>
</div>
)
}
export default Homepage
```
so i need for example when i click on hats picture i switch to hats page . how to do that
image attached
Thanks in advance
[reactjs routing](https://i.stack.imgur.com/GyMBV.jpg) | 2020/11/17 | [
"https://Stackoverflow.com/questions/64878896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14638199/"
] | with cut:
```
cut -d\/ -f1,2,3 file
``` | This might work for you (GNU sed):
```
sed -E 's/^(([^/]*[/]){3}).*/\1/' file
```
Delete everything after the third group of non-forward-slashes/slash. |
2,254,222 | What are the points that should be kept in mind while writing code that should be portable on both 32 bit and 64 bit machines?
Thinking more on this, I feel if you can add your experience interms of issues faced, that would help.
Adding further on this, I once faced a problem due to a missing prototype for a function which was returning returning a pointer. When I ported the same to a 64 bit machine, the code was crashing and I had no clue about the reason for quite some time, later realised that all missing prototypes are assumed to return int causing the problem.
Any such examples can help.
EDIT: Adding to community wiki. | 2010/02/12 | [
"https://Stackoverflow.com/questions/2254222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236222/"
] | Gotchas:
1. Casting pointers to integer types is dangerous
2. Data structure sizes can change
3. Watch out for sign extension
4. Different ABI?
Some tips & tricks I've found helpful:
1. Get yourself a native-size integer type (from a header or `typedef` your own) and use it when you have variables that don't care about size.
2. Use explicit variable types wherever possible (u\_int64\_t, int\_32\_t, etc.) | Write automated tests and run them regularly on both platforms. |
15,862,741 | does anybody know a way or a tool how inheritance can be used in CSS independent of the structure of the elements?
Example:
```
.bg_red {
background: red;
}
.bold {
font-weight: bold;
}
.bg_red_and_bold {
//this class should inherit all the properties of the above two classes
}
```
I hope it is clear what I mean...
Thanks | 2013/04/07 | [
"https://Stackoverflow.com/questions/15862741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1313884/"
] | CSS does not support this.
Consider using [LESS](http://lesscss.org), which compiles to CSS and supports mixins:
```
.bg_red_and_bold {
.bg_red();
.bold();
}
``` | Probably not what you want but there is aggregation:
```
<div class="bg_red bold"...
```
The div will "inherit" characteristics of both styles. |
3,405,511 | for example if it is given to make all the choices between 1 to 5 and the answer goes like this..
```
1,2,3,4,5,
1-2,1-3,1-4,1-5,2-3,2-4,2-5,3-4,3-5,4-5,
1-2-3,1-2-4,1-2-5,1-3-4,
.....,
1-2-3-4-5.
```
can anyone suggest a fast algorithm? | 2010/08/04 | [
"https://Stackoverflow.com/questions/3405511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172543/"
] | The fastest is by using [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming), which will trade compile time and code size for execution time. But this will only be practical for lowish numbers of combinations, and you have to know them ahead of time. But, you said "fast" :)
```
#include <iostream>
using namespace std;
typedef unsigned int my_uint;
template <my_uint M>
struct ComboPart {
ComboPart<M-1> rest;
void print() {
rest.print();
for(my_uint i = 0; i < sizeof(my_uint) * 8; i++)
if(M & (1<<i)) cout << (i + 1) << " ";
cout << endl;
}
};
template <>
struct ComboPart<0> {
void print() {};
};
template <my_uint N>
struct TwoPow {
enum {value = 2 * TwoPow<N-1>::value};
};
template <>
struct TwoPow<0> {
enum {value = 1};
};
template <my_uint N>
struct Combos {
ComboPart<TwoPow<N>::value - 1> part;
void print() {
part.print();
}
};
int main(int argc, char *argv[]) {
Combos<5> c5 = Combos<5>();
c5.print();
return 0;
}
```
This one constructs all the combinations at compile time. | >
> can anyone suggest a fast algorithm?
>
>
>
Algorithms can be expressed in many languages, here is the power set in Haskell:
```
power [] = [[]]
power (x:xs) = rest ++ map (x:) rest
where rest = power xs
``` |
24,990 | I have a list called *Tenders*. I need to make sure that when Tender status field is set to "open" no one can delete it. Ideally would be if I won't see options in ecb and ribbon. It is not connected to users permissions but with state of list item. Should I use jQuery or is there an easier way? | 2011/12/09 | [
"https://sharepoint.stackexchange.com/questions/24990",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/4064/"
] | You could create an Event Receiver for the OnDeleting event that prevents the item from being deleted. Basically have the event receiver check for the value of the field and cancel deletion if the right requirements are not met. | Could you check this post for some help? - <http://pholpar.wordpress.com/2011/10/16/disabling-item-deletion-at-the-sharepoint-user-interface/> |
307,600 | During the installation, there is a choice to let you choose which desktop and whether or not install the `standard system utilities`. See [here](http://csmojo.com/posts/what-debian-standard-system-utilities-include.html) for the screen shot and the packages included.
[](https://i.stack.imgur.com/tJQ3w.png)
Personally I don't like to install many packages I don't need, so I ask here what is the consequences of not installing these utilities. **Please in plain language what functionality I will lose or inconvenience I will get.** | 2016/09/03 | [
"https://unix.stackexchange.com/questions/307600",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/115506/"
] | >
> What's the consequences that I don't install the standard system utilities of debian?
>
>
>
**Edit**
Without installing the `standard system utilities` , you will get a **working** operating system but you will need most of the `utilities` later.
I have tested debian in a Virtualbox offline install without a GUI and without `standard system utilities`. The output of `apt list --installed > installed.txt` is [here](http://pastebin.com/Fj8WGLP5).
From the installed OS i have configured `apt` because it is not fully working only the security update is enabled:
```
deb http://security.debian.org/ jessie/updates main
deb-src http://security.debian.org/ jessie/updates main
```
then i have installed a GUI , here are the two steps that I execute:
1) To configure my `sources.list` i have comment out the following lines:
```
deb http://ftp.fr.debian.org/debian/ jessie/updates main
deb http://ftp.fr.debian.org/debian/ jessie/updates main
```
Then adding:
```
deb http://ftp.fr.debian.org/debian/ jessie main
deb-src http://ftp.fr.debian.org/debian/ jessie main
```
2) Runing `tasksel` to install the Gui: i mounted the debian.iso to save the bandwidth , connecting to the internet then installing my desktop .
Updating the package and everything work fine.
**NB the `standard system utilities` isn't available"** after runing `tasksel` on the installed system.
>
> [What does the "standard system" task include?](https://wiki.debian.org/tasksel)
>
>
>
This task is available only during the installation, it contains the following packages:
```
# tasksel --task-packages standard
~pstandard
~prequired
~pimportant
```
It corresponds to the following command:
```
aptitude search ~pstandard ~prequired ~pimportant -F%p
```
The following [priority levels](https://www.debian.org/doc/debian-policy/ch-archive.html#s-priorities) are recognized by the Debian package management tools.
**required**
>
> Packages which are necessary for the proper functioning of the system (usually, this means that dpkg functionality depends on these packages). Removing a required package may cause your system to become totally broken and you may not even be able to use dpkg to put things back, so only do so if you know what you are doing. Systems with only the required packages are probably unusable, but they do have enough functionality to allow the sysadmin to boot and install more software.
>
>
>
**important**
>
> Important programs, including those which one would expect to find on any Unix-like system. If the expectation is that an experienced Unix person who found it missing would say "What on earth is going on, where is foo?", it must be an important package.[6] Other packages without which the system will not run well or be usable must also have priority important. This does not include Emacs, the X Window System, TeX or any other large applications. The important packages are just a bare minimum of commonly-expected and necessary tools.
>
>
>
**standard**
>
> These packages provide a reasonably small but not too limited character-mode system. This is what will be installed by default if the user doesn't select anything else. It doesn't include many large applications.
>
>
> | According to [csmojo article](http://csmojo.com/posts/what-debian-standard-system-utilities-include.html) *standard system utilities* consists of following packages on **Debian 8** (jessie):
>
> apt-listchanges, lsof, mlocate, w3m, at, libswitch-perl, xz-utils, telnet, dc, bsd-mailx, file, exim4-config, m4, bc, dnsutils, exim4, python2.7, openssh-client, aptitude, bash-completion, python, host, install-info, bzip2, reportbug, krb5-locales, bind9-host, time, info, liblockfile-bin, whois, aptitude-common, patch, ncurses-term, mutt, mime-support, exim4-daemon-light, ftp, nfs-common, python-reportbug, rpcbind, texinfo, python-minimal, procmail, libclass-isa-perl, python-apt, python-support, exim4-base, debian-faq, doc-debian
>
>
> |
62,057,338 | **In angular simple app, I have to show common header to all pages after login, but common header is not visible to user details page**
**I want to make common header visible to user details page also, which is not going to happen.**
```
-myapp
-src
-layout
-common
-header
header.component.css
header.component.html
header.component.spec.ts
header.component.ts
-dashboard
dashboard-routing.module.ts
dashboard.component.css
dashboard.component.html
dashboard.component.spec.ts
dashboard.module.ts
dashboard.component.ts
- userdetails
userdetails-routing.module.ts
userdetails.component.css
userdetails.component.html
userdetails.component.spec.ts
userdetails.module.ts
userdetails.component.ts
layout-routing.module.ts
layout.component.css
layout.component.html
layout.component.spec.ts
layout.module.ts
layout.component.ts
-login
-services
app-routing.module.ts
app.component.css
app.component.html
app.component.spec.ts
app.module.ts
app.component.ts
```
**layout & dashboard components module & routing files are lazy files**
**app.modules.ts:**
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { LayoutModule } from './layout/layout.module';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
**layout.modules.ts:**
```
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LayoutRoutingModule } from './layout-routing.module';
import { LayoutComponent } from './layout.component';
import { DashboardModule } from './dashboard/dashboard.module';
import { HeaderComponent } from './common/header/header.component';
@NgModule({
declarations: [
LayoutComponent,
HeaderComponent
],
imports: [
CommonModule,
LayoutRoutingModule,
DashboardModule
],
exports: [HeaderComponent]
})
export class LayoutModule { }
```
**dashbard.modules.ts:**
```
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { DashboardComponent } from './dashboard.component'
import { UserdetailsModule } from './userdetails/userdetails.module';
@NgModule({
declarations: [DashboardComponent],
imports: [
CommonModule,
DashboardRoutingModule,
UserdetailsModule
],
exports: [DashboardComponent]
})
export class DashboardModule { }
```
**app.component.html:**
```
<router-outlet></router-outlet>
```
**layout.component.html:**
```
<app-header></app-header>
<router-outlet></router-outlet>
```
**dashboard.component.html:**
```
<router-outlet></router-outlet>
..
..
```
**app-routing.module.ts:**
```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './layout/dashboard/dashboard.component';
const routes: Routes = [
{ path: "", component: LoginComponent },
{ path: 'layout', loadChildren: './layout/layout.module#LayoutModule'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
**layout-routing.module.ts:**
```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LayoutComponent } from './layout.component';
const routes: Routes = [
{
path: '', component: LayoutComponent,
children: [
{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LayoutRoutingModule { }
```
**dashboard-routing.module.ts:**
```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { UserdetailsComponent } from './userdetails/userdetails.component';
const routes: Routes = [
{
path: '', component: DashboardComponent,
children: [
{path: "user-details/:id", loadChildren: './userdetails/userdetails.module#UserdetailsModule'}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule { }
```
**Please suggest me changes to show that common header on user-details page also**.. | 2020/05/28 | [
"https://Stackoverflow.com/questions/62057338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553758/"
] | I have made a simple example code like this, you could take it a try and change what you want:
```js
import React, { Component } from "react";
import {TextInput } from "react-native";
class App extends Component {
constructor(props) {
super(props);
this.state = { text: '' };
}
onChangeTextHandler(text){
var len = text.length;
if ((len===5 || len===10)&& len>=this.state.text.length){
text = text +"-"
}
if(text.length!==16){
this.setState({text:text})
}
}
render() {
return (
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1,marginTop:20}}
onChangeText={(text) => this.onChangeTextHandler(text)}
value={this.state.text}
placeholder="ABCDE-1234-5678"
/>
);
}
}
export default App;
```
[Test Link](https://codesandbox.io/s/polished-thunder-fxm9d?file=/src/App.js) | for **point 1** you can use `onFocus` prop of TextInput like this
```
<TextInput
value={this.state.searchTerm}
style={/* your style*/}
onFocus={()=>{
if(this.state.searchTerm==""){
this.setState({searchTerm:"ABCDE-"})
}
}}
/>
```
for **Point 2** use `keyboardType` and `onChangeText` prop of TextInput like this
```
<TextInput
value={this.state.searchTerm}
style={/* your style*/}
keyboardType={"numeric"}
onChangeText={(text)=>{
/*since there 6 characters placed on focus so n character login will be*/
if(this.state.searchTerm.length>6){
if(value.length%5==0){
let temp = this.state.searchTerm+"-"+text[text.length-1]
onChangeText(temp)
} else {
onChangeText(text)
}
}else{
onChangeText(text)
}
}}
onFocus={()=> {
if(this.state.searchTerm==""){
this.setState({searchTerm:"ABCDE-"})
}
}}
/>
```
Hopefully, you will get an idea from this code how to implement guided user input |
68,006,623 | I have the following PHP Script, and a HTML form that will send POST values to the php page. My problem is, when I select the "override schedule message" and submit the form, it displays the correct message, However when I go directly to the url.php, it displays the same message every time, regardless of what was submitted on the form.
The indented behavior is when the form is submitted and the "override schedule message" is selected, the url.php will display "*Override is on, and would display rss feed*"
If "display message for schedule" is selected, then "*overide is not on, and would display time based message
Array ( [0] => )*" should display.
**Php Code:**
```
<?php
if ($_POST['override'] == 'value2' ) {
$myArray=array("");
array_push($myArray,"override");
}
else{
$myArray=array("");
}
?>
<?php
if (in_array("override", $myArray)) {
echo "Override is on, and would display rss feed";
echo "<br>";
print_r($myArray);
}
else{
echo "overide is not on, and would display time based message";
echo "<br>";
print_r($myArray);
}
?>
```
**HTML Form**
```
<form style="margin: auto; width: 95%; padding:10px;" action="https://example.com/url.php" method="post" >
<div class="radio">
<input type="radio" name="override" value="value1">
<label class="radio-label">Display message for schedule</label>
</div>
<div class="radio">
<input type="radio" name="override" value="value2">
<label class="radio-label">Override schedule message</label>
</div>
<input class="ppw_submit_btn" type="submit" value="Submit">
</form>
``` | 2021/06/16 | [
"https://Stackoverflow.com/questions/68006623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16245175/"
] | Another alternate way to achieve this is to just relay on the GridPane constraint features.
You can add Column/Row constraints and set the fillHeight/fillWidth to `true` and hgrow/vgrow policies to `ALWAYS`. Also set the desired nodes maxWidth/maxHeight to `Infinity` to auto stretch.
[](https://i.stack.imgur.com/yhTeE.gif)
```
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane xmlns:fx="http://javafx.com/fxml" alignment="center">
<Label fx:id="label" text="Number Format Error !" maxWidth="Infinity" alignment="CENTER" GridPane.columnSpan="3"/>
<TextField fx:id="a" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<TextField fx:id="b" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<TextField fx:id="c" GridPane.columnIndex="2" GridPane.rowIndex="1"/>
<Button fx:id="solveButton" text="Solve" maxWidth="Infinity" maxHeight="Infinity" GridPane.columnSpan="3" GridPane.rowIndex="2" />
<Button fx:id="clearButton" text="Clear" maxWidth="Infinity" maxHeight="Infinity" GridPane.columnSpan="3" GridPane.rowIndex="3" />
<columnConstraints>
<ColumnConstraints fillWidth="true" hgrow="ALWAYS"/>
<ColumnConstraints fillWidth="true" hgrow="ALWAYS"/>
<ColumnConstraints fillWidth="true" hgrow="ALWAYS"/>
</columnConstraints>
<rowConstraints>
<RowConstraints vgrow="ALWAYS"/>
<RowConstraints vgrow="NEVER"/>
<RowConstraints fillHeight="true" vgrow="ALWAYS"/>
<RowConstraints fillHeight="true" vgrow="ALWAYS"/>
</rowConstraints>
</GridPane>
``` | >
> How do I make children actually fit the GridPane [...]?
>
>
>
You can wrap a child node in an `AnchorPane` and set the anchors to zero.
>
> [...] and why those textfields are not of the same size?
>
>
>
I don't know but you can use `ColumnConstraints` and set each column width to 33.33 %.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane alignment="center" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.mycompany.mavenproject1.PrimaryController">
<columnConstraints>
<ColumnConstraints percentWidth="33.33"/>
<ColumnConstraints percentWidth="33.33"/>
<ColumnConstraints percentWidth="33.33"/>
</columnConstraints>
<AnchorPane GridPane.columnSpan="3" GridPane.hgrow="always" GridPane.vgrow="always">
<children>
<Label fx:id="label" alignment="CENTER" style="-fx-background-color: tomato;" text="Number format error!"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0"/>
</children>
</AnchorPane>
<TextField fx:id="a" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<TextField fx:id="b" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<TextField fx:id="c" GridPane.columnIndex="2" GridPane.rowIndex="1"/>
<AnchorPane GridPane.columnSpan="3" GridPane.rowIndex="2">
<Button fx:id="solveButton" onAction="#solve" text="_Solve" AnchorPane.bottomAnchor="0.0"
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"/>
</AnchorPane>
<AnchorPane GridPane.columnSpan="3" GridPane.rowIndex="3">
<Button fx:id="clearButton" onAction="#clear" text="_Clear" AnchorPane.bottomAnchor="0.0"
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"/>
</AnchorPane>
</GridPane>
``` |
52,251,389 | I need to retrieve values from the database for the column names specified. The below code I've tried,
```
import pyodbc
def get_db_data():
cursor = getConnection.cursor()
cursor.execute("select * from student")
return cursor
cur = get_db_data()
for row in cur.fetchall():
print(row["student_name"])
```
I'm facing below error
```
TypeError: row indices must be integers, not str
```
How to achieve this? | 2018/09/10 | [
"https://Stackoverflow.com/questions/52251389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7386335/"
] | If you want to access a column by name, you should specify it as an attribute of the row rather than an index:
```
for row in cur.fetchall():
print(row.student_name)
``` | As per the pyodbc documentation "Row objects are similar to tuples, but they also allow access to columns by name". You can try row[0] or row.student\_name (Assuming column index for student\_name is 0)
```
import pyodbc
def get_db_data():
cursor = getConnection.cursor()
cursor.execute("select * from student")
return cursor
cur = get_db_data()
for row in cur.fetchall():
print(row[0])
``` |
19,444,933 | I want to export my java project (using eclipse) into executable jar,
but I want hibernate.cfg.xml, config.properties, and log4j.properties editable for future,
so how to make hibernate access that file from outside project folder or any other way to make that file editable for future,
I have try this code for acces hibernate.cfg.xml from outside project folder
```
SessionFactory sessionFactory = new Configuration().configure("mon/hibernate.cfg.xml").buildSessionFactory();
```
but i got this error
```
mon/hibernate.cfg.xml not found
Exception in thread "main" java.lang.ExceptionInInitializerError
```
and still have no idea about config.properties and log4j.properties,
any help will be pleasure :) | 2013/10/18 | [
"https://Stackoverflow.com/questions/19444933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1941064/"
] | there is my solution to your problem:
**config.properties**
You define your configuration file trough parameter `-DconfigurationFile` set to your JVM. Then try to find `confiFile` in your `classpath` (inside jar) if is not found then filesystem will be searched. Well, as last the properties will be override with JVM parameters.
```
Properties prop = new Properties();
String configFile = System.getProperty("configurationFile",defaultConfigurationFile);
try {
InputStream classPathIo = getClass().getClassLoader().getResourceAsStream(configFile);
if(classPathIo != null) {
prop.load(classPathIo);
} else {
prop.load(new FileReader(configFile));
} catch (FileNotFoundException e) {
log.warn("The config file {} cannot be found. It can be setup by -DconfigurationFile parameter.",configFile);
} catch (IOException e) {
log.warn("The config file {} is not readable.",configFile);
} finally {
log.info("Configuration loaded! {} values found from configFile {}.",prop.entrySet().size(),configFile);
prop.putAll(System.getProperties());
}
```
**log4j.properties**
The solution is using of the following JVM parameter:
```
-Dlog4j.configuration={path to file}
```
If the file is NOT in the classpath (in WEB-INF/classes in case of Tomcat) but somewhere on you disk, use file:, like
```
-Dlog4j.configuration=file:/somewhere/on/disk/log4j.properties
```
**hibernate.cfg.xml**
I have no idea how to do this. Anyway, it hard to configure persistance after release because the configuration is hard bind to implementation. I think it is OK to keep it inside classpath. | You can instruct hibernate to load config file from file system,
There are lots of overloaded `configure()` methods are available, see the link for the documentaion
and below is the way you can do:
```
File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml");
Configuration configuration = new Configuration().configure(conf.getAbsoluteFile());
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
```
[http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/cfg/Configuration.html#configure(java.io.File)](http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/cfg/Configuration.html#configure%28java.io.File%29)
and for log4j, you can give -D argument with log4j config file
like `-Dlog4j.configuration={path to .properties or .xml }`
similar question for log4j externalization : [How to initialize log4j properly?](https://stackoverflow.com/questions/1140358/how-to-initialize-log4j-properly)
It will be worth reading that as well. |
16,410,085 | is there difference between char\* pt and char \*pt in c++?
type\* pt or type \*pt?
as titled, Thanks in advance. | 2013/05/07 | [
"https://Stackoverflow.com/questions/16410085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288446/"
] | No but be careful of something like `char* a, b;` only a is a pointer in this statement. | They have no functional difference. |
109,789 | *Moderator note:* A [follow-on question about how to avoid the behavior described here](https://academia.stackexchange.com/questions/109937/how-can-i-avoid-being-intolerant-and-unsupportive-of-diversity-at-scientific-mee) has been posted.
---
In recent news, two academics are at odds over this incident [full article here](https://www.chronicle.com/article/He-Makes-a-Joke-She-Isn-t/243350):
>
> The fuss started when [Prof. X] and [Prof. Y] ended up in the same crowded elevator during a conference at a Hilton in San Francisco last month. [Prof. Y] said she offered to press the floor buttons for people in the elevator, whom she described as mostly conference attendees and all, except one other woman, white middle-aged men. Instead of saying a floor, [Prof. X] smiled and asked for the women’s lingerie department "and all his buddies laughed," [Prof. Y] wrote in a complaint, the details of which he disputed, to the association later that day.
>
>
>
This incident has escalated to the point that the academic organization that organized the conference has decided to sanction Prof. X.
I don't understand why the joke was funny, but that's not really important. I would like to understand why it was offensive. Specifically, I'm wondering
* **In what way was this comment offensive?**
The bullets above are not rhetorical or sarcastic; I am completely sincere. I am worried because I don't understand precisely what was offensive, so I fear that I might do something similar. I have wondered whether the remark was offensive because:
* It referred to underwear
* It referred to women (in any way) and was cause for laughter
* There is some unstated assumption about his reason for supposedly going to a lingerie department
But I really have no idea, and I want to understand. I could not find an answer in any of the news pieces on this incident.
*I realize that this question might get closed as off-topic. However, I think it is wrong to assume that no part of this is specific to academic culture (if that's the case, that's part of the answer). Certainly it occurred in a uniquely academic environment, and is a dispute between academics and an academic society, that seems to jeopardize at least one academic career.*
**Please refrain from using this as a place to express your opinion on who is right in this dispute. That's not what I'm asking.** | 2018/05/15 | [
"https://academia.stackexchange.com/questions/109789",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/92788/"
] | **tl;dr**: The joke was funny because it was absurd and taboo (made people uncomfortable). It was "offensive" because it may have been intended to make the person operating the elevator feel embarrassed or singled-out. Avoid making jokes that make people feel singled-out.
How is the joke funny?
----------------------
As other answers have pointed out, the joke is funny because it makes reference to a time when elevator operators were the norm and people would call out the desired floor in a department store by asking for a specific department. It is an absurd (out-of-place) comment to make in the context (the present day, and not in a department store). Often, absurdity is funny.
There is, however, another layer to the humour. People will often laugh when in an uncomfortable situation. The joke is uncomfortable because of the floor that was asked for: ladies lingerie. In some cultures (I can say Canada and the UK for sure) the topic of undergarments, especially ladies undergarments, is [**taboo**](https://en.wikipedia.org/wiki/Taboo) and therefore not supposed to be discussed in "polite society".
In what way was the comment offensive?
--------------------------------------
I think other answers are close, but slightly miss the mark. The reason I think the joke is offensive is because, whether it was intended or not, it made the person operating the elevator uncomfortable or embarrassed. On a more subtle note the reason is **context**.
The person operating the elevator may have felt like they were targeted by the joke. They asked an innocent question "What floor?" and the joker replies with the less-than-innocent answer "Ladies lingerie". We can only speculate as to the intentions of the joker, but it is clear that while the *joke* may have been directed to everyone in the elevator, the *answer* was directed to the person operating the elevator. Add the fact that the person operating the elevator was a woman, and it doesn't seem so far-fetched to think that she may have felt targeted by the joke.
To further consider this point: why was the department "ladies lingerie" chosen? The joker could have asked for "the hardware department" or "men's clothing" or "sporting goods" and the joke would have drawn a few chuckles. "Ladies lingerie" was chosen because it is taboo, and it is *extra* taboo because it is a man directing the comment at a woman. More discomfort = more likely to provoke laughs (even though the people in the elevator might feel more uncomfortable than tickled).
Finally, consider the context: a male dominated space. I can say from personal experience (as a man) that it is not uncommon for a group of men to direct lewd or taboo comments at women (or sometimes a young/innocent-seeming man) to provoke embarrassment. Heck, I'm guilty of doing it myself, before I realized how it makes the target of the joke feel! It is likely that the person operating the elevator experienced this sort of behaviour many times before and assumed (perhaps rightly) that the joke was targeted at her and was intended to make her feel embarrassed.
*Making someone feel embarrassed for your personal entertainment = bullying. Bullying should not be tolerated, especially in a professional setting.*
If it was an elevator full of women and a woman made the joke, the context would be different and the person operating the elevator may not have felt singled-out. Similarly if it was entirely men. However, even in these contexts it is possible for the joke to be construed as bullying, especially if the target of the joke is someone that the joker knows would feel embarrassed.
How do I avoid offending people in a similar way?
-------------------------------------------------
Avoid jokes involving topics that make people uncomfortable, especially when telling jokes to strangers or acquaintances. Generally avoid taboo topics of whatever culture you are in and especially avoid jokes that might make someone feel targeted or singled-out based on race, skin colour, sexuality, gender, *etc*. | I think the main reason why this joke gave offense has already been covered in Najib Idrissi's answer, i.e. the lingerie/sex-object angle, but there's another aspect to it:
>
> When [Prof. X] was young, in the 1950s, he said, it was a "standard
> gag line" to ask the elevator operator for the hardware or lingerie
> floor as though one were in a department store.
>
>
>
Elevator operators are almost entirely obsolete now, but back in that era, many hotels, stores, and office buildings had an employee whose job was to work the elevators for guests. It was a junior role, similar to a valet or a store greeter.
So part of the "joke" here is that Prof. X is talking to Prof. Y, his professional peer, as if she was a junior hotel employee - an occupation which carries much less status than "professor".
Women in academia have had a long struggle to be treated with the same respect as their male peers, and there's still a long way to go. ([One example of many](https://www.npr.org/sections/ed/2016/01/25/463846130/why-women-professors-get-lower-ratings)). Because of that situation, it's a bad idea for a male academic to make jokes which rely on reducing the social status of his female peer; this amplifies the "merely sex objects" aspect of the joke that Najib Idrissi discussed.
A lot of comedians invoke the rule "Never punch down" - in other words, don't make fun of people or groups whose social standing is lower, or less secure, than your own. |
9,294,603 | I am playing with fragments in Android.
I know I can change a fragment by using the following code:
```
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();
MyFragment myFragment = new MyFragment(); //my custom fragment
fragTrans.replace(android.R.id.content, myFragment);
fragTrans.addToBackStack(null);
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();
```
My question is, in a Java file, how can I get the currently displayed Fragment instance? | 2012/02/15 | [
"https://Stackoverflow.com/questions/9294603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959734/"
] | You can query which fragment is loaded into your Activities content frame, and retrieve the fragment class, or fragment 'simple name' (as a string).
```
public String getCurrentFragment(){
return activity.getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getSimpleName();
}
```
Usage:
```
Log.d(TAG, getCurrentFragment());
```
Outputs:
```
D/MainActivity: FragOne
``` | ```
public Fragment getVisibleFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
```
This works for me. You need to perform a null check before you iterate through the fragments list. There could be a scenario that no fragments are loaded on the stack.
The returning fragment can be compared with the fragment you want to put on the stack. |
1,703,980 | Suppose I have a static variable declared inside a function in C.
If I call that function multiple times, does the static variable get re-allocated in memory every time the function is called?
If it does get re-allocated, why is the last value always maintained?
Example:
```
void add()
{
static int x = 1;
x++;
printf("%d\n",x);
}
int main()
{
add(); // return 2
add(); // return 3
add(); // return 4
}
``` | 2009/11/09 | [
"https://Stackoverflow.com/questions/1703980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | No - static variables are basically globals that live within the local namespace. | No, the variable is not reallocated everytime.
It is like having a global variable, but it only has local scope; i.e., you can only reference it from inside of that function. |
53,139,121 | Should I give width and Height for an object like button while setting layout?
If I use Greater than or equal to option, It expands the button in bigger screens?
How to make a button stay in same size regardless of the device its being viewed?
Is it a good practise to design like this ? or the object should get bigger for bigger screens?
Sorry about too many questions. Just breaking my head for days.
Thanks in Advance Guys | 2018/11/04 | [
"https://Stackoverflow.com/questions/53139121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10602954/"
] | Generally speaking, it's quite a bad practice to set width and height for a button. Because the size of its content might expand depending on the user's settings (accessibility settings, for instance).
It's better just to set the **top+leading** *OR* **top+trailing** *OR* **bottom+leading**, etc...
This is mostly sufficient to make the button "look the same" on different devices (it will indeed be a little bigger on bigger screens).
And remember, as of constraints, less is better than many. When your component is placed and its constraints are all blue, test if it works as you expect and if yes, don't add more constraints. As beginners, we tend to over-constraint and it generates issues. | It mostly depends on yours app design.
Many built-in UIKit views (including buttons) have their own (intrinsic) size. So it is not necessary to define size explicitly, but you can do this if you want. Remember that you shouldn't make excessive use of expicit sizes as this can lead to non-adaptive design.
In most cases it's worth to allow view to have its intrinsic height but constrain its width in some way (for example, in percents to superview's width, set minimum/maximum allowed value etc). But in any case you should define position where your view will be displayed. |
24,229,442 | I am retrieving columns names from a SQL database through Java. I know I can retrieve columns names from `ResultSet` too. So I have this sql query
```
select column_name from information_schema.columns where table_name='suppliers'
```
The problem is I don't know how can I get columns names from `ResultSet` and my code is
```
public void getAllColumnNames() throws Exception{
String sql = "SELECT column_name from information_schema.columns where table_name='suppliers'";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
// extract values from rs
}
``` | 2014/06/15 | [
"https://Stackoverflow.com/questions/24229442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495272/"
] | 1) Instead of `PreparedStatement` use `Statement`
2) After executing query in `ResultSet`, extract values with the help of `rs.getString()` as :
```
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
rs.getString(1); //or rs.getString("column name");
}
``` | For those who wanted more better version of the resultset printing as util class
This was really helpful for printing resultset and does many things from a single [util](https://github.com/htorun/dbtableprinter)... thanks to Hami Torun!
In this class `printResultSet` uses `ResultSetMetaData` in a generic way have a look at it..
```
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public final class DBTablePrinter {
/**
* Column type category for CHAR, VARCHAR
* and similar text columns.
*/
public static final int CATEGORY_STRING = 1;
/**
* Column type category for TINYINT, SMALLINT,
* INT and BIGINT columns.
*/
public static final int CATEGORY_INTEGER = 2;
/**
* Column type category for REAL, DOUBLE,
* and DECIMAL columns.
*/
public static final int CATEGORY_DOUBLE = 3;
/**
* Column type category for date and time related columns like
* DATE, TIME, TIMESTAMP etc.
*/
public static final int CATEGORY_DATETIME = 4;
/**
* Column type category for BOOLEAN columns.
*/
public static final int CATEGORY_BOOLEAN = 5;
/**
* Column type category for types for which the type name
* will be printed instead of the content, like BLOB,
* BINARY, ARRAY etc.
*/
public static final int CATEGORY_OTHER = 0;
/**
* Default maximum number of rows to query and print.
*/
private static final int DEFAULT_MAX_ROWS = 10;
/**
* Default maximum width for text columns
* (like a VARCHAR) column.
*/
private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;
/**
* Overloaded method that prints rows from table tableName
* to standard out using the given database connection
* conn. Total number of rows will be limited to
* {@link #DEFAULT_MAX_ROWS} and
* {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
* the width of text columns (like a VARCHAR column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
*/
public static void printTable(Connection conn, String tableName) {
printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method that prints rows from table tableName
* to standard out using the given database connection
* conn. Total number of rows will be limited to
* maxRows and
* {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
* the width of text columns (like a VARCHAR column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
* @param maxRows Number of max. rows to query and print
*/
public static void printTable(Connection conn, String tableName, int maxRows) {
printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method that prints rows from table tableName
* to standard out using the given database connection
* conn. Total number of rows will be limited to
* maxRows and
* maxStringColWidth will be used to limit
* the width of text columns (like a VARCHAR column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
* @param maxRows Number of max. rows to query and print
* @param maxStringColWidth Max. width of text columns
*/
public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
if (conn == null) {
System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
return;
}
if (tableName == null) {
System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
return;
}
if (tableName.length() == 0) {
System.err.println("DBTablePrinter Error: Empty table name!");
return;
}
if (maxRows
* ResultSet to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
* to limit the width of text columns.
*
* @param rs The ResultSet to print
*/
public static void printResultSet(ResultSet rs) {
printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method to print rows of a
* ResultSet to standard out using maxStringColWidth
* to limit the width of text columns.
*
* @param rs The ResultSet to print
* @param maxStringColWidth Max. width of text columns
*/
public static void printResultSet(ResultSet rs, int maxStringColWidth) {
try {
if (rs == null) {
System.err.println("DBTablePrinter Error: Result set is null!");
return;
}
if (rs.isClosed()) {
System.err.println("DBTablePrinter Error: Result Set is closed!");
return;
}
if (maxStringColWidth columns = new ArrayList(columnCount);
// List of table names. Can be more than one if it is a joined
// table query
List tableNames = new ArrayList(columnCount);
// Get the columns and their meta data.
// NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
for (int i = 1; i maxStringColWidth) {
value = value.substring(0, maxStringColWidth - 3) + "...";
}
break;
}
// Adjust the column width
c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
c.addValue(value);
} // END of for loop columnCount
rowCount++;
} // END of while (rs.next)
/*
At this point we have gone through meta data, get the
columns and created all Column objects, iterated over the
ResultSet rows, populated the column values and adjusted
the column widths.
We cannot start printing just yet because we have to prepare
a row separator String.
*/
// For the fun of it, I will use StringBuilder
StringBuilder strToPrint = new StringBuilder();
StringBuilder rowSeparator = new StringBuilder();
/*
Prepare column labels to print as well as the row separator.
It should look something like this:
+--------+------------+------------+-----------+ (row separator)
| EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME | (labels row)
+--------+------------+------------+-----------+ (row separator)
*/
// Iterate over columns
for (Column c : columns) {
int width = c.getWidth();
// Center the column label
String toPrint;
String name = c.getLabel();
int diff = width - name.length();
if ((diff % 2) == 1) {
// diff is not divisible by 2, add 1 to width (and diff)
// so that we can have equal padding to the left and right
// of the column label.
width++;
diff++;
c.setWidth(width);
}
int paddingSize = diff / 2; // InteliJ says casting to int is redundant.
// Cool String repeater code thanks to user102008 at stackoverflow.com
String padding = new String(new char[paddingSize]).replace("\0", " ");
toPrint = "| " + padding + name + padding + " ";
// END centering the column label
strToPrint.append(toPrint);
rowSeparator.append("+");
rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
}
String lineSeparator = System.getProperty("line.separator");
// Is this really necessary ??
lineSeparator = lineSeparator == null ? "\n" : lineSeparator;
rowSeparator.append("+").append(lineSeparator);
strToPrint.append("|").append(lineSeparator);
strToPrint.insert(0, rowSeparator);
strToPrint.append(rowSeparator);
StringJoiner sj = new StringJoiner(", ");
for (String name : tableNames) {
sj.add(name);
}
String info = "Printing " + rowCount;
info += rowCount > 1 ? " rows from " : " row from ";
info += tableNames.size() > 1 ? "tables " : "table ";
info += sj.toString();
System.out.println(info);
// Print out the formatted column labels
System.out.print(strToPrint.toString());
String format;
// Print out the rows
for (int i = 0; i
* Integers should not be truncated so column widths should
* be adjusted without a column width limit. Text columns should be
* left justified and can be truncated to a max. column width etc...
*
\* See also:
\* java.sql.Types
\*
\* @param type Generic SQL type
\* @return The category this type belongs to
\*/
private static int whichCategory(int type) {
switch (type) {
case Types.BIGINT:
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return CATEGORY\_INTEGER;
case Types.REAL:
case Types.DOUBLE:
case Types.DECIMAL:
return CATEGORY\_DOUBLE;
case Types.DATE:
case Types.TIME:
case Types.TIME\_WITH\_TIMEZONE:
case Types.TIMESTAMP:
case Types.TIMESTAMP\_WITH\_TIMEZONE:
return CATEGORY\_DATETIME;
case Types.BOOLEAN:
return CATEGORY\_BOOLEAN;
case Types.VARCHAR:
case Types.NVARCHAR:
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
case Types.CHAR:
case Types.NCHAR:
return CATEGORY\_STRING;
default:
return CATEGORY\_OTHER;
}
}
/\*\*
\* Represents a database table column.
\*/
private static class Column {
/\*\*
\* Column label.
\*/
private String label;
/\*\*
\* Generic SQL type of the column as defined in
\*
\* java.sql.Types
\* .
\*/
private int type;
/\*\*
\* Generic SQL type name of the column as defined in
\*
\* java.sql.Types
\* .
\*/
private String typeName;
/\*\*
\* Width of the column that will be adjusted according to column label
\* and values to be printed.
\*/
private int width = 0;
/\*\*
\* Column values from each row of a `ResultSet`.
\*/
private List values = new ArrayList();
/\*\*
\* Flag for text justification using `String.format`.
\* Empty string (`""`) to justify right,
\* dash (`-`) to justify left.
\*
\* @see #justifyLeft()
\*/
private String justifyFlag = "";
/\*\*
\* Column type category. The columns will be categorised according
\* to their column types and specific needs to print them correctly.
\*/
private int typeCategory = 0;
/\*\*
\* Constructs a new `Column` with a column label,
\* generic SQL type and type name (as defined in
\*
\* java.sql.Types
\* )
\*
\* @param label Column label or name
\* @param type Generic SQL type
\* @param typeName Generic SQL type name
\*/
public Column(String label, int type, String typeName) {
this.label = label;
this.type = type;
this.typeName = typeName;
}
/\*\*
\* Returns the column label
\*
\* @return Column label
\*/
public String getLabel() {
return label;
}
/\*\*
\* Returns the generic SQL type of the column
\*
\* @return Generic SQL type
\*/
public int getType() {
return type;
}
/\*\*
\* Returns the generic SQL type name of the column
\*
\* @return Generic SQL type name
\*/
public String getTypeName() {
return typeName;
}
/\*\*
\* Returns the width of the column
\*
\* @return Column width
\*/
public int getWidth() {
return width;
}
/\*\*
\* Sets the width of the column to `width`
\*
\* @param width Width of the column
\*/
public void setWidth(int width) {
this.width = width;
}
/\*\*
\* Adds a `String` representation (`value`)
\* of a value to this column object's {@link #values} list.
\* These values will come from each row of a
\*
\* ResultSet
\* of a database query.
\*
\* @param value The column value to add to {@link #values}
\*/
public void addValue(String value) {
values.add(value);
}
/\*\*
\* Returns the column value at row index `i`.
\* Note that the index starts at 0 so that `getValue(0)`
\* will get the value for this column from the first row
\* of a
\* ResultSet.
\*
\* @param i The index of the column value to get
\* @return The String representation of the value
\*/
public String getValue(int i) {
return values.get(i);
}
/\*\*
\* Returns the value of the {@link #justifyFlag}. The column
\* values will be printed using `String.format` and
\* this flag will be used to right or left justify the text.
\*
\* @return The {@link #justifyFlag} of this column
\* @see #justifyLeft()
\*/
public String getJustifyFlag() {
return justifyFlag;
}
/\*\*
\* Sets {@link #justifyFlag} to `"-"` so that
\* the column value will be left justified when printed with
\* `String.format`. Typically numbers will be right
\* justified and text will be left justified.
\*/
public void justifyLeft() {
this.justifyFlag = "-";
}
/\*\*
\* Returns the generic SQL type category of the column
\*
\* @return The {@link #typeCategory} of the column
\*/
public int getTypeCategory() {
return typeCategory;
}
/\*\*
\* Sets the {@link #typeCategory} of the column
\*
\* @param typeCategory The type category
\*/
public void setTypeCategory(int typeCategory) {
this.typeCategory = typeCategory;
}
}
}
```
This is the scala version of doing this... which will print column names and data as well in a generic way...
```
def printQuery(res: ResultSet): Unit = {
val rsmd = res.getMetaData
val columnCount = rsmd.getColumnCount
var rowCnt = 0
val s = StringBuilder.newBuilder
while (res.next()) {
s.clear()
if (rowCnt == 0) {
s.append("| ")
for (i <- 1 to columnCount) {
val name = rsmd.getColumnName(i)
s.append(name)
s.append("| ")
}
s.append("\n")
}
rowCnt += 1
s.append("| ")
for (i <- 1 to columnCount) {
if (i > 1)
s.append(" | ")
s.append(res.getString(i))
}
s.append(" |")
System.out.println(s)
}
System.out.println(s"TOTAL: $rowCnt rows")
}
``` |
55,756,647 | I recently updated my Android Studio (and I'm pretty sure the Gradle version), and now I've been getting a bunch of errors when trying to compile my project. Here's the one that is plaguing me at the moment:
```
Duplicate class android.support.v4.app.INotificationSideChannel found in modules classes.jar (androidx.core:core:1.0.1) and classes.jar (com.android.support:support-compat:26.1.0)
```
This is followed by lots of similar ones.
I tried removing all uses of `com.android.support` in favor of androidx (see [here](https://developer.android.com/jetpack/androidx/migrate) for what I was using the replace things), but `com.android.support` libraries are still being used, even when I delete the libraries (they're just remade once I try to compile again).
[Here's](https://pastebin.com/raw/W7xrRzU8) a link to the full error I get. | 2019/04/19 | [
"https://Stackoverflow.com/questions/55756647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7492795/"
] | Like others says, the solution is to migrating to AndroidX, it works for me. However, it isn´t an easy way and it requires a bit of pacience... These are the steps that I did:
* First, is **very important** that you do all this changes in a different branch or you make a backup of your project.
* You need to have the Android Gradle Plugin Version 3.5.1. So, in *build.gradle* set:
```
dependencies {
classpath 'com.android.tools.build:gradle:3.5.1'
}
```
* Migrate to AndroidX using Android Studio Tool : *Refactor --> Migrate to AndroidX...*
* When it finishes, it has done all pertinents modification, but posibly you can´t deploy the project correctly because you find any errors. These are the problems that I found and the solutions:
* If you use *Kotlin*, in build.gradle set:
```
buildscript {
ext.kotlin_version = '1.3.10'
}
```
and
```
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
```
* If you use *destination* method, add "file" parameter: `destination file("$reportsDir/checkstyle/checkstyle.xml")`
* If you use *Butterknife*, use 10.0.0 version
* Finally, *Build --> Clean Project* and *Build --> Rebuild Project* | This solution from here worked the best for me. Migrating to androidX
<https://developer.android.com/jetpack/androidx/migrate>
>
> With Android Studio 3.2 and higher, you can migrate an existing
> project to AndroidX by selecting Refactor > Migrate to AndroidX from
> the menu bar.
>
>
> The refactor command makes use of two flags. By default, both of them
> are set to true in your gradle.properties file:
>
>
> `android.useAndroidX=true` The Android plugin uses the appropriate
> AndroidX library instead of a Support Library.
> android.enableJetifier=true The Android plugin automatically migrates
> existing third-party libraries to use AndroidX by rewriting their
> binaries.
>
>
> |
115,782 | There is the following statement in Jeffery Archer’s fiction “The Fourth Estate,” of which I admit I’m a terribly slow reader:
>
> “The tactics made it possible for Armstrong Communication to declare a
> profit of 90,000 the year he and Hahn (co-owner) parted, and a year
> later the Manchester Guardian named Richard Armstrong Young
> Entrepreneur of the Year. Charlotte reminded him that he was nearer
> forty than thirty. “True,” he replied, “but never forget that all my
> rivals **had a twenty-year start on** me.” - P359
>
>
>
I surmise “a twenty-year start on me” equals ““a twenty-year head start on me.”
Is it customary to omit ‘head’ of the idiom, ‘have a head start on’ by replacing it with a placeholder such as X-year / mile / pound/ class, and grade as used here, when quantification is required? | 2013/06/04 | [
"https://english.stackexchange.com/questions/115782",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/3119/"
] | I think this should be treated like any other multi-word phrase. Use two words when it's a noun phrase:
>
> The go live will be this weekend
>
>
>
And a hyphen when it's an adjectival phrase:
>
> We're preparing for your go-live transition.
>
>
>
Now, unless *Go Live* or *Go-Live* is a proper name, I don't see any reason it should be capitalized. | The word **activate** would convey the intent and I would encourage you to use it.
Consistency in terminology as a defense only goes so far and I don't believe it will be enough to earn your audience's forgiveness for using a phrase like "the go live" or "your go live"
>
> Preparing for your software/website activation
>
>
> |
8,042,212 | In my program using java nio, the socketchannel.write() becomes very slow when it tries to write 10 KB messages consecutively. The measured time for writing a complete 10 KB message is between 160 ms and 200 ms. But the time for writing a complete 5 KB message is only takes 0.8 ms.
In the selector, I only have Selection.OP\_READ and do not handle Selection.OP\_WRITE. When a large complete message is received, it is written to another receiver 4 times.
Is anyone accounter same problem? There is a post about socketchannel.write() slow. My question is how to alternate change between OP\_READ and OP\_WRITE?
If I add an inerval e.g, 150 ms, the response time is reduced. Is there any way to find when the buffer is full so I can let the program waits. My operating system is windows xp.
Thanks.
I follow EPJ suggestion by checking the number of written bytes. But the response time is still high. I post part of my code here and would like to examine whether there is wrong with my code.
// this is the writeData() part using nio:
```
while (buffer.hasRemaining()) {
try {
buffer.flip();
n = socket.write(buffer);
if(n == 0) {
key.interestOps(SelectionKey.OP_WRITE);
key.attach(buffer);
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
buffer.compact();
}
}
if(buffer.position()==0) {
key.interestOps(SelectionKey.OP_READ);
}
``` | 2011/11/07 | [
"https://Stackoverflow.com/questions/8042212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1028519/"
] | If write takes more than 20 micro-seconds, I would suggest you have a buffer full issue. I assume you are using blocking NIO. When the send buffer is not full it usually takes between 5 - 20 micro-seconds. In the past I have configured my server to kill any slow consumer which takes 2 ms to write. (Possibly a bit aggressive. ;)
You could try increasing the size of the send buffer (Socket.setSendBufferSize(int), which is also available for SocketChannels), but it would appear you are trying to send more data than your bandwidth allows.
10 KB is not a large message, the typical send buffer size is 64 KB, so for it to be full you would need to have 6-7 messages unsent. This might explain way 5KB is relatively fast. | I suggest that your reading process is slow and that this is causing its receive buffer to back up, which is causing your send buffer to back up, which stalls your sends.
Or else you haven't written the code correctly for non-blocking mode. If you get a zero result from the write() method, you must (a) change the interestOps to OP\_WRITE and (b) return to your select loop. When you get OP\_WRITE you must then repeat the write; if you wrote all the data, change the interestOps back to OP\_READ, otherwise leave everything as is and wait for the next OP\_WRITE. If you attempt to loop while writing in non-blocking mode even in the presence of zero-length writes you will just spin, wasting CPU cycles and time.
Modulo bugs:
```
while (buffer.position() > 0)
{
try
{
buffer.flip();
int count = ch.write(buffer);
if (count == 0)
{
key.interestOps(SelectionKey.OP_WRITE);
break;
}
}
finally
{
buffer.compact();
}
}
if (buffer.position() == 0)
{
key.interestOps(SelectionKey.OP_READ);
}
``` |
30,505,225 | When using css, how can I specify a nested class.
Here is my `html` code:
```
<div class="box1">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Collapsable</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div><!-- /.box-tools -->
</div><!-- /.box-header -->
<div class="box-body">
<p><i class="fa fa-phone"></i><span style=""> Phone : 0800 000 000</span></p>
<p><i class="fa fa-home"></i><span style=""> Web : http://www.example.com</span></p>
<p><i class="fa fa-map-marker"></i><span style=""> Map : example map address</span></p>
<p><i class="fa fa-envelope"></i><span style=""> Email : example@address.com</span></p>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
```
This `css` code works correctly for the all the `html` on the page:
```
<style type="text/css">
i{width: 30px;}
</style>
```
How can I specify the `i` `class` in the `box1` `box-body` class?
Here is the code that I have tried:
```
<style type="text/css">
box1 box-body i{width: 30px;}
</style>
```
Thanks in advance. | 2015/05/28 | [
"https://Stackoverflow.com/questions/30505225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3736648/"
] | The classes in your CSS need periods before them. Note `i` doesn't since it's an element not a class.
```
<style type="text/css">
.box1 .box-body i{width: 30px;}
</style>
``` | You just need to know how css selectors work. [Here](http://www.w3schools.com/cssref/css_selectors.asp) is brief description about css selectors.
In your case,
```
.box .box-body i{
width:30px;
}
```
space between two selectors defines second element is child of first.
In your case, element i is child element of element which has box-body class. and that element is child element of class which has .box class. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.