qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
16,035,976 | I create a loop in Wordpress with the condition like this:
1. Display a specific post format (example: video)
2. Limiting the post number. In this case, I only want to display 2 posts.
Here my code:
```
<?php $i = 1; if (have_posts()) : while (have_posts() && $i < 3) : the_post(); ?>
<?php get_template_part( 'content-video', get_post_format() ); ?>
<?php $i++; endwhile; ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
```
I already have file name content-video.php.
Unfortunately, the loop does not work. Only displayed the first post, not a specific post (video post format) with template from content-video.php.
Appreciate for any help, or alternative code. Thanks in advance. | 2013/04/16 | [
"https://Stackoverflow.com/questions/16035976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098167/"
] | You can [use `Assume`](http://junit.sourceforge.net/javadoc/org/junit/Assume.html) to turn tests on/off conditionally:
>
> A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information.
>
>
> |
13,456,834 | I need to execute the following function in a specific context.
```
setTimeout(function () {
myFunction();
}, 1000 * 60);
var changeDateFormat = function () {
console.log(this); // this should be $('.myClass')
// but I need to set it from setTimeout
// any hints
};
```
P.S.:
I am using Underscore.js and jQuery. | 2012/11/19 | [
"https://Stackoverflow.com/questions/13456834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113216/"
] | You can use [jQuery.proxy](http://api.jquery.com/jQuery.proxy/).
```
setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60);
```
Here's an example: <http://jsfiddle.net/UwUQD/1/>
As James said you can also use `apply` as jQuery does internally:
```
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
```
The first `apply` argument is the execution context (what you'll be able to access using `this`) and the second argument are other arguments you want to pass to myFunction. The `call` function is the same, but accepts additional arguments a bit differently.
---
**Or use [bind](http://underscorejs.org/#bind) in Underscore.js**
```
setTimeout(_.bind(myFunction, $(".myClass")), 100);
```
<http://jsfiddle.net/UwUQD/3/> |
38,753,092 | Say I have two dataframes like the following:
```
n = c(2, 3, 5, 5, 6, 7)
s = c("aa", "bb", "cc", "dd", "ee", "ff")
b = c(2, 4, 5, 4, 3, 2)
df = data.frame(n, s, b)
# n s b
#1 2 aa 2
#2 3 bb 4
#3 5 cc 5
#4 5 dd 4
#5 6 ee 3
#6 7 ff 2
n2 = c(5, 6, 7, 6)
s2 = c("aa", "bb", "cc", "ll")
b2 = c("hh", "nn", "ff", "dd")
df2 = data.frame(n2, s2, b2)
# n2 s2 b2
#1 5 aa hh
#2 6 bb nn
#3 7 cc ff
#4 6 ll dd
```
I want to merge them to achieve the following result:
```
#n s b n2 s2 b2
#2 aa 2 5 aa hh
#3 bb 4 6 bb nn
#5 cc 5 7 cc ff
#5 dd 4 6 ll dd
```
Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2.
I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr.
Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once. | 2016/08/03 | [
"https://Stackoverflow.com/questions/38753092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962535/"
] | A coupld of problems: 1) you have built a couple of dataframes with factors which has a tendency to screw up matching and indexing, so I used stringsAsFactors =FALSE in hte dataframe calls. 2) you have an ambiguous situation with no stated resolution when both s2 and b2 have matches in the s column (as does occur in your example):
```
> df2[c("s")] <- list( c( df$s[pmax( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)]))
> df2
n2 s2 b2 s
1 5 aa hh aa
2 6 bb nn bb
3 7 cc ff ff
4 6 ll dd dd
> df2[c("s")] <- list( c( df$s[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)]))
> df2
n2 s2 b2 s
1 5 aa hh aa
2 6 bb nn bb
3 7 cc ff cc
4 6 ll dd dd
```
Once you resolve the ambiguity to your satiusfaction just use the same method to extract and match the "b"s:
```
> df2[c("b")] <- list( c( df$b[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)]))
> df2
n2 s2 b2 s b
1 5 aa hh aa 2
2 6 bb nn bb 4
3 7 cc ff cc 5
4 6 ll dd dd 4
```
Modified df's:
```
> dput(df)
structure(list(n = c(2, 3, 5, 5, 6, 7), s = c("aa", "bb", "cc",
"dd", "ee", "ff"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n",
"s", "b"), row.names = c(NA, -6L), class = "data.frame")
> dput(df2)
structure(list(n2 = c(5, 6, 7, 6), s2 = c("aa", "bb", "cc", "ll"
), b2 = c("hh", "nn", "ff", "dd"), s = c("aa", "bb", "cc", "dd"
), b = c(2, 4, 5, 4)), row.names = c(NA, -4L), .Names = c("n2",
"s2", "b2", "s", "b"), class = "data.frame")
```
One step solution:
```
> df2[c("s", "c")] <- df[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE), c("s", "b")]
> df2
n2 s2 b2 s c
1 5 aa hh aa 2
2 6 bb nn bb 4
3 7 cc ff cc 5
4 6 ll dd dd 4
``` |
33,095,072 | How can I launch a new Activity to a Fragment that is not the initial fragment? For example, the following code is wrong. I want to launch the MainActivity.class AT the SecondFragment.class. Seems simple enough but cannot find an answer anywhere. All help is greatly appreciated!
```
public void LaunchSecondFragment(View view) {
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click));
Intent intent = new Intent(this, SecondFragment.class);
startActivity(intent);
}
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33095072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950598/"
] | So, before starting an activity you have to do something like:
```
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("launchSecondFragment", true)
startActivity(intent)
```
and in your MainActivity onCreate()
```
if(getIntent().getBooleanExtra("launchSecondFragment", false)) {
//do fragment transaction to second fragment
} else {
//do fragment transaction to the first fragment
}
```
**UPDATE**
So, here is the clever way to do it.
First of all create enum in your MainActivity.class
```
public enum FragmentNames {
FIRST_FRAGMENT,
SECOND_FRAGMENT
}
```
then define a string constant for getting and putting this extra(also in MainActivity)
```
public static final String FRAGMENT_EXTRA = "fragmentExtra";
```
So now when you start an activity you should do it like this:
```
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.FRAGMENT_EXTRA, MainActivity.FragmentNames.SECOND_FRAGMENT);
startActivity(intent);
```
And catch in your MainActivity onCreate() method:
```
FragmentNames name = getIntent().getSerializableExtra(FRAGMENT_EXTRA);
switch(name) {
case FIRST_FRAGMENT:
//do stuff
break;
case SECOND_FRAGMENT:
//do stuff
break;
default:
//load default fragment(FirstFragment for example)
}
```
What else is cool about enums? You mentioned that you are using this intents to define current item of your ViewPager. Well, good news, enums have ordinal().
Basically you can do something like:
```
mViewPager.setCurrentItem(name.ordinal());
```
In this case ordinal() of the FIRST\_FRAGMENT is 0 and ordinal of SECOND\_FRAGMENT is 1.
Just don't forget to check for nulls :)
Cheers. |
39,787,004 | ```
<%
if(session == null) {
System.out.println("Expire");
response.sendRedirect("/login.jsp");
}else{
System.out.println("Not Expire");
}
%>
<%
HttpSession sess = request.getSession(false);
String email = sess.getAttribute("email").toString();
Connection conn = Database.getConnection();
Statement st = conn.createStatement();
String sql = "select * from login where email = '" + email + "' ";
ResultSet rs = st.executeQuery(sql);
%>
```
I tried to redirect the login.jsp page when session is expired.
But I am geeting error in "String email = sesss.getAttribute("email").toString();".
So anyone please help me to solve this error.
Basically I want to redirect to login.jsp page when the session is expired. | 2016/09/30 | [
"https://Stackoverflow.com/questions/39787004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5533485/"
] | TimeSpan can be negative. So just substract the TimeSpan for 4PM with current [TimeOfDay](https://msdn.microsoft.com/en-us/library/system.datetime.timeofday), if you get negative value, add 24 hours.
```
var timeLeft = new TimeSpan(16, 0, 0) - DateTime.Now.TimeOfDay;
if (timeLeft.Ticks<0)
{
timeLeft = timeLeft.Add(new TimeSpan(24,0,0))
}
``` |
770,179 | I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete.
For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay.
Here's the code I have:
```
$ch = curl_init();
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
// Only calling the head
curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
$content = curl_exec ($ch);
curl_close ($ch);
```
Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp>
The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away.
What am I missing? | 2009/04/20 | [
"https://Stackoverflow.com/questions/770179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39539/"
] | Try simplifying it a little bit:
```
print htmlentities(file_get_contents("http://www.arstechnica.com"));
```
The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests.
**EDIT**:
Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code:
```
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
```
Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang.
**SECOND EDIT**:
Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code:
```
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
```
With this:
```
curl_setopt($ch, CURLOPT_NOBODY, true);
```
Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly. |
41,292,734 | First off, this is my first post, so if I incorrectly posted this in the wrong location, please let me know.
So, what we're trying to accomplish is building a powershell script that we can throw on our workstation image so that once our Windows 10 boxes are done imaging, that we can click on a powershell script, have it pull the key from the BIOS, and automagically activate it. That being said, here is the script that we've put together from various sources.
---
```
(Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | out-file c:\license.txt
$computer = gc env:computername
$key = get-content c:\license.txt
$service = get-wmiObject -query “select * from SoftwareLicensingService” -computername $computer
$service.InstallProductKey($key) <--------THIS IS WHERE IT FAILS
$service.RefreshLicenseStatus()
```
---
We start running into the issues on the line `$service.InstallProductKey($key)`. It seems, that no matter how we try to invoke that, it will consistently fail with the error "Exception calling "InstallProductKey"". I've even replaced the variable (`$key`) with the specific activation key, and it STILL fails with the same error.
The reason we have it outputting to a license txt file part way through is so that we can verify that the command is indeed pulling the product key (which it is).
At this point, I'm not sure where to go. It seems that people have tried to do this before, however, nobody has really wrapped up their posting with what worked and/or what didn't. I can't imagine that this is impossible, but I'm also not fond of wasting anymore time than needed, so anybody that has any insight into this issue, I'd be very grateful.
We've gotten it to work on two machines that were previously activated, and later deactivated, but on new machines that have been freshly imaged, and have yet to be activated, it will fail every time. | 2016/12/22 | [
"https://Stackoverflow.com/questions/41292734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7332516/"
] | Two things as per my observation:
```
(Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | out-file c:\license.txt
```
I don't think that it is returning any value to your license.txt.
If yes, then I would like you to see if there is any space before and after the license key. You can use *trim* during getting the content from the file.
Second thing, when you are getting the content from the file make sure it is not separating into multiple lines. In that case, you have to cast it as string like **[String]$key** or you can call **toString()** method for this.
One more important thing is to refresh after the installation.
```
$service.RefreshLicenseStatus()
```
**Note:** Make sure you are running the shell in elevated mode.
**Alternative: Try Hardcoding the values and see the result**
```
$key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" # hardcode the key
$computer= "Computer01" # Hardcode the computer
$service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()
```
For further thing ,please post the exact error.
Hope it helps...!!! |
23,567,099 | I have an query related to straight join the query is correct but showing error
```
SELECT table112.id,table112.bval1,table112.bval2,
table111.id,table111.aval1
FROM table112
STRAIGHT_JOIN table111;
```
Showing an error can anybody help out this | 2014/05/09 | [
"https://Stackoverflow.com/questions/23567099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3612276/"
] | There is missing the join condition.
```
SELECT table112.id,table112.bval1,table112.bval2,
table111.id,table111.aval1
FROM table112
STRAIGHT_JOIN table111 ON table112.id = table111.id
``` |
35,219,203 | ```
import iAd
@IBOutlet weak var Banner: ADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
Banner.hidden = true
Banner.delegate = self
self.canDisplayBannerAds = true
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
self.Banner.hidden = false
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("Error")
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
}
```
Hello,
I am currently developing an iOS app with Xcode 7.2, Swift 2.0, and iOS 9.2. I have implemented iAds, and it works perfectly. However in my region the fill rate is not high, and I would like to use Google's AdMob to advertise on my app, as a backup. I would like for the AdMob banner ad to show up when iAd does not receive an ad. Note that I am new to Swift, and have no knowledge of Objective-C. Thanks. | 2016/02/05 | [
"https://Stackoverflow.com/questions/35219203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843135/"
] | Your connection string looks like it's not in line with what's specified in the [documentation](https://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx).
Try changing your connection string from:
```
"jdbc:sqlserver://localhost:1433;sa;VMADMIN#123;"
```
To:
```
"jdbc:sqlserver://localhost:1433;user=sa;password={VMADMIN#123};"
``` |
29,804,680 | I am working with `ViewPager` i.e on top of the `MainActivity` class and the `Viewpager` class extends fragment.
The problem is that, normally when we need a class to return some `result` then while passing the `intent` we use `startActivityforresult(intent,int)` hence it passes the result captured in the secondactivity the class from where it's been called.
**But as i am working with viewpager on top of the mainactivity and i am using `floating action button`, when i click the button to open the second activity it returns the result to the mainactivity but not the viewpager class.**
>
> **So my question is how can i pass the result taken from the secondactivity to my desired class?**
>
>
>
**Update::**
`MainActivity.java`
this is my main class which is using the intent as well as receiving the result from the second activity class `ActivityTwo`
What i have done here is
```
startActivityForResult(intent,1);
public void onActivityresult(i,j,intent){MyFragment fragment;
fragment.onActivityReusult(i,j,intent);//Here i have passes the values
received by this class to the fragment class where i need the values but it's not working
}
``` | 2015/04/22 | [
"https://Stackoverflow.com/questions/29804680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4578454/"
] | Some suggested improvements:
```
BEGIN {
split("KS .07 MO .08",tmp)
for (i=1;i in tmp;i+=2)
taxRate[tmp[i]] = tmp[i+1]
fmtS = "%12s%s\n"
fmtF = "%12s$%.2f\n"
}
NR>1 {
name=$1" "$2
state=$3
payRate=$4
hoursWorked=$5
overtime=$6
grossPay=(hoursWorked+(overtime*1.5))*payRate
tax = grossPay* taxRate[state]
netPay = grossPay-tax
printf fmtS, "Name", "State"
printf fmtS, name, state
printf fmtF, "Gross Pay:", grossPay
printf fmtF, "Taxes:", tax
printf fmtF, "Net Pay:", netPay
}
END {
print "\n-complete-"
}
``` |
6,030,137 | I am trying to build a WCF service that allows me to send large binary files from clients to the service.
However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)
**The Error I get if I try to send the 4.91MB file is:**
**Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
**Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive.
**Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
**Inner Exception Message:** An existing connection was forcibly closed by the remote host
This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.
I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.
I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.
**Service Web.Config**
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DragDrop.Service.ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
**Client (Asp.net page) Web.Config**
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="debuggingBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>
``` | 2011/05/17 | [
"https://Stackoverflow.com/questions/6030137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402186/"
] | *(While I agree that [streaming transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx) would be preferrable, the below should make it work without any other changes)*
You also need to increase the maximum message length in the Web.config:
```
<configuration>
<system.web>
<httpRuntime maxMessageLength="409600"
executionTimeoutInSeconds="300"/>
</system.web>
</configuration>
```
This will set the maximum message length to 400 MB (parameter is in kB). Check [this MSDN page](http://msdn.microsoft.com/en-us/library/aa528822.aspx) for more information. |
4,608,257 | I evaluated the integral as follow, $$\int\_0^\pi \cos^3x dx=\int\_0^\pi(1-\sin^2x)\cos xdx$$
Here I used the substitution $u=\sin x$ and $du=\cos x dx$ and for $x\in [0,\pi]$ we have $\sin x\in [0,1]$ Hence the integral is,
$$\int\_0^11-u^2du=u-\frac{u^3}3\large\vert ^1\_0=\small\frac23$$But the answer I got is wrong since if I evaluate the indefinite integral $\int \cos^3x dx$ I get $\sin x-\dfrac{\sin^3x}{3}$ and now if I apply the interval $[0,\pi]$ I get $\int\_0^\pi \cos^3x dx=0$.
My question is why I got the wrong value in my approach and how to fix it? | 2022/12/30 | [
"https://math.stackexchange.com/questions/4608257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/794843/"
] | The substitution rule can only be applied if the substitution is by a monotonous function. This is not the case for the sine on $[0,\pi]$. You would have to split the domain and apply the substitution rule separately on the intervals $[0,\frac\pi2]$ and $[\frac\pi2,\pi]$.
In the other way you computed the primitive or anti-derivative and then applied the fundamental theorem of infinitesimal calculus. In this case there are no restrictions by monotonicity. |
44,887,617 | I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really
```
<?php if($usrn['verified'] == 1): { ?>
<i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i>
<?php } endif; ?>
<?php
$usern = protect($_GET['usern']);
$sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'");
if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); }
$row = mysql_fetch_array($sql);
?>
``` | 2017/07/03 | [
"https://Stackoverflow.com/questions/44887617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8248870/"
] | Just Remove Override Method like this
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_and_add, menu);
return true;
}
```
This Override Method is responsible to for creating three dote as you mention it's really `OptionMenu`. If you don't want it, don't override `onCreateOptionsMenu`method.
Alternative
-----------
Don't Inflate the menu xml. Just block the line like this
```
//getMenuInflater().inflate(R.menu.search_and_add, menu);
```
other code can remain same. No problem at all.. |
49,438,437 | I am working on this game on checkio.org. Its a python game and this level I need to find the word between two defined delimiters. The function calls them. So far I have done alright but I can't get any more help from google probably because I don't know how to ask for what i need.
Anyways I am stuck and I would like to know where I am messing this up.
```
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
# your code here
s = text
#find the index for begin and end
b = s.find(begin) + len(begin)
c = s.find(end,b)
#if there is a beginning delimiter return string from between
if begin in s:
return s[b:c]
# if the begin is not the only return until end delimiter
elif begin not in s:
return s[:-c]
#if the ending delimiter isnt there return from beinning to end of string
elif end not in s:
return s[b:]
#if both delimiters are missing just return the text
elif begin or end not in s:
return s
if __name__ == '__main__':
# print('Example:')
# print(between_markers('What is >apple<', '>', '<'))
# These "asserts" are used for self-checking and not for testing
assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
assert between_markers("<head><title>My new site</title></head>",
"<title>", "</title>") == "My new site", "HTML"
assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
print('Wow, you are doing pretty good. Time to check it!')
```
I am stuck here wondering where I am wrong.
`elif begin not in s:
return s[:c]`: is where its going to hell. `return s[:c]` in theory should return everything up to `c` but it cuts off one letter before the end of the string and every slice i use cuts it off by one character. this `assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'` gives me `h` not `hi`. Using `[:-c]` fails me on the previous assert...
Any pointers are welcome. | 2018/03/22 | [
"https://Stackoverflow.com/questions/49438437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `expand` method is equivalent to flatMap in Dart.
```
[1,2,3].expand((e) => [e, e+1])
```
What is more interesting, the returned `Iterable` is lazy, and calls fuction for each element every time it's iterated. |
18,383,773 | I'm facing the problem described in [this question](https://stackoverflow.com/questions/4031857/way-to-make-java-parent-class-method-return-object-of-child-class) but would like to find a solution (if possible) without all the casts and @SuppressWarning annotations.
A better solution would be one that builds upon the referenced one by:
* removing @SuppressWarning
* removing casts
Solutions presented here will be graded with 2 points based on the criteria. Bounty goes to solution with most points or the "most elegant" one if there is more than one with 2 points. | 2013/08/22 | [
"https://Stackoverflow.com/questions/18383773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586682/"
] | No cast, no @SuppressWarning, few lines only:
```java
public abstract class SuperClass<T extends SuperClass<T>> {
protected T that;
public T chain() {
return that;
}
}
public class SubClass1 extends SuperClass<SubClass1> {
public SubClass1() {
that = this;
}
}
public class SubClass2 extends SuperClass<SubClass2> {
public SubClass2() {
that = this;
}
}
``` |
45,993,468 | I'm using angular 4 and I try to get data from 2 endpoints but I have a problem understanding rxjs.
with this code I can only get list of students and users only.
```
getStudent() {
return this.http.get(this.url + this.student_url, this.getHeaders()).map(res => res.json());
}
getUsers() {
return this.http.get(this.url + this.users_url, this.getHeaders()).map(res => res.json());
}
```
Let's say this is data :
Student
```
[{"ID" : 1 , "SchoolCode": "A150", "UserID": 1 },
{"ID" : 5 , "SchoolCode": "A140" , "UserID": 3},
{"ID" : 9 , "SchoolCode": "C140" , "UserID": 4}]
```
User
```
[{"ID" : 1 ,"Name": "Rick" , "FamilyName" , "Grimes" },
{"ID" : 4 ,"Name": "Carle" , "FamilyName" , "Grimes" }]
```
I want to get first all students then compare UserID if it's the same as user then I combine both objects into one until I get an array like this :
```
{"ID" : 1 , "SchoolCode": "A150","Name": "Rick" , "FamilyName" , "Grimes" }
```
I think I should use flatmap but I did try write code but it dosen't work for me and I didn't find an example with such logic.
Could you please help me. | 2017/09/01 | [
"https://Stackoverflow.com/questions/45993468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8525484/"
] | You can use the `switchMap` operator (alias of `flatMap`) in the following code :
```
// Observables mocking the data returned by http.get()
const studentObs = Rx.Observable.from([
{"ID" : 1 , "SchoolCode": "A150", "UserID": 1 },
{"ID" : 5 , "SchoolCode": "A140" , "UserID": 4},
{"ID" : 9 , "SchoolCode": "C140" , "UserID": 3}
]);
const userObs = Rx.Observable.from([
{"ID" : 1, "Name": "Rick" , "FamilyName": "Grimes" },
{"ID" : 3, "Name": "Tom" , "FamilyName": "Cruise" },
{"ID" : 4, "Name": "Amy" , "FamilyName": "Poehler" }
]);
// Return an observable emitting only the given user.
function getUser(userID) {
return userObs.filter(user => user.ID === userID);
}
studentObs
.switchMap(student => {
return getUser(student.UserID).map(user => {
// Merge the student and the user.
return Object.assign(student, {user: user});
})
})
.subscribe(val => console.log(val));
```
Check out this JSBin: <http://jsbin.com/batuzaq/edit?js,console> |
23,130,785 | I have a query as follows
```
SELECT s.`uid` FROM `sessions` s
```
(this was an extended query with a LEFT JOIN but to debug i removed that join)
FYI the full query was
```
SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id`
```
There are three results in the sessions table, for ease sake i'll just list the uid
```
| UID |
| 0 |
| 0 |
| 1 |
```
when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code:
```
$sql = "SELECT s.`uid` FROM `sessions` s";
$result = $acpDB->query($sql);
$staffList = array();
if ($result->num_rows > 0) {
while ($data = $result->fetch_assoc()) {
var_dump($data);
$staffList[] = array(
'username' => $data['username'],
'email' => $data['email'],
);
}
}
```
I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work.
The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class?
Any help would be greatly appreciated
Dan | 2014/04/17 | [
"https://Stackoverflow.com/questions/23130785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/780128/"
] | You can add a meta tag to your page header to prevent mobile safari turning telephone numbers into links
```
<meta name="format-detection" content="telephone=no">
``` |
10,701,493 | I need to get div id and its child class name by using div name . But div Id will be different and unique all the time.
**HTML**
```
<div class="diagram" id="12" >
<div class="121">
...
</div>
</div>
<div class="diagram" id="133" >
<div class="33">
...
</div>
</div>
<div class="diagram" id="199" >
<div class="77">
...
</div>
</div> So on..
```
JQUERY
```
$(function(){
//i need to pass to values to the function in the following way
o.circle("12","121");
o.circle("133","33");
o.circle("199","77");
//So on..
});
```
Please help me out | 2012/05/22 | [
"https://Stackoverflow.com/questions/10701493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383645/"
] | ```
$('div.diagram').each(function() {
// this.id -> get the id of parent i.e div.diagram
// $('div:first', this) -> get the first child of diagram, here this refers to diagram
// $('div:first', this).attr('class') -> get the class name of child div
o.circle(this.id, $('div:first', this).attr('class'));
});
```
If you want to try this on any event, then try:
example:
```
// I assumed a click event
$('div.diagram').on('click', function() {
o.circle(this.id, $('div:first', this).attr('class'));
});
``` |
19,588,606 | I am using this code to search for a specific file pattern recursively in a given directory:
```
if (file.isDirectory()) {
System.out.println("Searching directory ... "
+ file.getAbsoluteFile());
if (file.canRead()) {
System.out.println("Can read...");
if (file.listFiles() == null) {
System.out.println("yes it is null");
}
for (File temp : file.listFiles()) { // Problemetic line
if (temp.isDirectory()) {
search(temp);
} else {
// code to find a file
}
}
}
```
Above code outputs me like this (also I get exception):
```
Searching directory ... C:\swsetup\SP46840\Lang\zh-TW
Can read...
Searching directory ... C:\System Volume Information
Can read...
yes it is null
```
Exception is:
```
Exception in thread "main" java.lang.NullPointerException
at Demo.search(Demo.java:61)
at Demo.search(Demo.java:63)
```
In my code the line is pointing to : `(file.listFiles())`, because it is trying to get list of files from system directories like "System Volume Information". I assume because it's a system directory, so some problem maybe happening which I am not aware.
My question is:
* How to handle this scenario, so that even `NullPointerException` occurs my `foreach` loop continues?
* Or better how to avoid exception in first place (like by checking if it is a system directory etc)?
Can anyone please guide me in this? Note: This is happening in Windows XP (I have tested earlier in Windows 7 few months back but I assume issue was not occurring there) | 2013/10/25 | [
"https://Stackoverflow.com/questions/19588606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506071/"
] | Try this:
```
if (file.isDirectory()) {
System.out.println("Searching directory ... "
+ file.getAbsoluteFile());
if (file.canRead()) {
System.out.println("Can read...");
if (file.listFiles() == null) {
System.out.println("yes it is null");
} else { /* add the else */
for (File temp : file.listFiles()) { // Problemetic line
if (temp.isDirectory()) {
search(temp);
} else {
// code to find a file
}
}
}
}
``` |
45,433,817 | I try to make server-side processing for [DataTables](https://datatables.net) using Web API. There are two actions in my Web API controller with same list of parameters:
```
public class CampaignController : ApiController
{
// GET request handler
public dtResponse Get(int draw, int start, int length)
{
// request handling
}
// POST request handler
public void Post(int draw, int start, int length)
{
// request handling
}
}
```
If I use GET method to send AJAX request to the server, the `Get` action is activated. However, if I use POST method, then neither action are activated.
I tried to change POST handler signature to
```
public void Post([FromBody]object value)
{
// request handling
}
```
In this case the `value` is `null`. Note, the `HttpContext.Current.Request.Form` collection isn't empty. The `draw`, `start`, `length` variables are exist in this collection. Thus, I think the trouble is in model binding, but I cannot fix it. Help me, please. | 2017/08/01 | [
"https://Stackoverflow.com/questions/45433817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7914637/"
] | The only workaround is to get the keycode and cast it to String:
```
var str = '';
var el = document.getElementById('#test');
document.addEventListener('keypress', function(event) {
const currentCode = event.which || event.code;
let currentKey = event.key;
if (!currentKey) {
currentKey = String.fromCharCode(currentCode);
}
str += currentKey;
event.preventDefault();
el.innerHTML = str;
})
``` |
55,780,439 | Hi guys I am totally new in oop in python. I am trying to write a class of students that gets the number of students, their ages, their heights and their weights and store these information as 3 separate lists.
I aim to compute the average of ages and weights as well as heights. I don't have any problem so far.
In the next step I want to compare the average age of two instances of the class plus the average of the weights.
As it's an exercise in oop I should do it by a method of the class.
But, I don't know that is it possible to do it using a method in the original class (class School) or I should create a subclass to compare the attributes of two instances of the School class.
Any help is really appreciated.
Here is my code:
```
class School:
avg_age = 0
avg_heigt = 0
avg_weight = 0
def __init__(self):
self.n =int(input())
self.list_ages = [float(x) for x in input().split(" ")]
self.list_higt = [float(x) for x in input().split(" ")]
self.list_weight = [float(x) for x in input().split(" ")]
def get_av(self):
School.avg_age = sum(self.list_ages) / len(self.list_ages)
School.avg_heigt = sum(self.list_higt)/len(self.list_higt)
Scoohl.avg_weight = sum(self.list_weight)/len(self.list_weight)
return("{},{},{}".format(School.avg_age,School.avg_heigt,School.avg_weight))
``` | 2019/04/21 | [
"https://Stackoverflow.com/questions/55780439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10781523/"
] | You mix class attributes and instance attributes. Class attributes are *shared* between instances:
```
class Banks:
total = 0
def __init__(self,name,money):
self.name=name
self.money=money
Banks.total += money
b1 = Banks("one",100)
b2 = Banks("two",5000000)
# prints 5000100 - all the money of all banks,
# does not help you comparing avgs ov instances at all
print(b1.total)
```
Output:
```
5000100
```
You need seperated averages per instance and a function that compares one instance (`self`) agiant an`other` instance:
```
class School:
def __init__(self):
# self.n =int(input()) # not needed - use len(one of your lists)
list_ages = [float(x) for x in input("Gimme ages, space seperated: ").split()]
list_hight = [float(x) for x in input("Gimme hights, space seperated: ").split()]
list_weight = [float(x) for x in input("Gimme weights, space seperated: ").split()]
# shortest list downsizes all other lists
self.list_ages, self.list_hight, self.list_weight = zip(
*zip( list_ages,list_hight,list_weight ))
def get_av(self):
self.avg_age = sum(self.list_ages) / len(self.list_ages)
print(self.avg_age)
self.avg_height = sum(self.list_hight) / len(self.list_hight)
print(self.avg_height)
self.avg_weight = sum(self.list_weight) / len(self.list_weight)
print(self.avg_weight)
return self.avg_age, self.avg_height, self.avg_weight
def compare(self,other):
self.get_av()
other.get_av()
print("Our pupils are younger: ", self.avg_age < other.avg_age)
print("Our pupils are smaller: ", self.avg_height < other.avg_height)
print("Our pupils are lighter: ", self.avg_weight < other.avg_weight)
c = School() # 4 5 6 22 44 66 88 99 20.2 20.2 20.2 20.2 20.2 20.2
d = School() # 100 100 100
c.compare(d)
```
Output (formatted with newlines in between):
```
Gimme ages, space seperated: 4 5 6
Gimme hights, space seperated: 22 44 66 88 99
Gimme weights, space seperated: 20.2 20.2 20.2 20.2 20.2 20.2
Gimme ages, space seperated: 100
Gimme hights, space seperated: 100
Gimme weights, space seperated: 100
5.0
44.0
20.2
100.0
100.0
100.0
Our pupils are younger: True
Our pupils are smaller: True
Our pupils are lighter: True
```
More info:
* [What is the difference between class and instance attributes?](https://stackoverflow.com/questions/207000/what-is-the-difference-between-class-and-instance-attributes)
* [python class documentation](https://docs.python.org/3/tutorial/classes.html#class-objects) |
177,528 | I downloaded and enabled translations for my Drupal core and modules using these Drush commands:
```
drush dl l10n_update && drush en -y $_
drush language-add lt && drush language-enable $_
drush l10n-update-refresh
drush l10n-update
```
I got almost everything translated, and in "Administration » Configuration » Regional and language" I see that I have almost 60% of translations to Lithuanian.
However, not everything is translated. For example, harmony forum module thread reply;
[](https://i.stack.imgur.com/Z15GP.png)
```
<ul class="post-links links--inline"><li class="show_replies first"><a href="/forumas/" id="post-1-show-replies" class="post-show-replies ajax-processed" data-thread-id="1" data-post-id="1">2 replies</a></li>
<li class="reply"><a href="/forumas/post/add?field_harmony_thread=1&field_harmony_post_is_reply_to=1" id="post-1-reply" title="Reply directly to this post" class="reply-link" data-thread-id="1" data-post-id="1">Atsakyti</a></li>
<li class="reply_as_new_thread"><a href="/forumas/thread/add?field_harmony_thread_cont_from=1" id="post-1-reply-as-new" title="Create a new thread as a reply to this post" class="reply-link" data-thread-id="1" data-post-id="1">Reply as a new thread</a></li>
<li class="flag-harmony_likes last"><span><span class="flag-wrapper flag-harmony-likes flag-harmony-likes-1">
<a href="/forumas/flag/flag/harmony_likes/1?destination=thread/1&token=zOnI9qp9K92XqmzqfCM8P-0n7f_FEMQKzumwX_A4xb4" title="" class="flag flag-action flag-link-toggle flag-processed" rel="nofollow"><span class="count">(0)</span> <span class="text">Like</span></a><span class="flag-throbber"> </span>
</span>
</span></li>
</ul>
```
and user profile statistics
[](https://i.stack.imgur.com/t6ear.png)
```
<div class="field field--name-field-harmony-thread-count field--type-number-integer field--label-above">
<div class="field__label">Thread count: </div>
<div class="field__items">
</div>
<div class="field field--name-field-harmony-post-count field--type-number-integer field--label-above">
<div class="field__label">Post count: </div>
<div class="field__items">
</div>
```
How can I edit these strings to be translated? | 2015/10/14 | [
"https://drupal.stackexchange.com/questions/177528",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/50624/"
] | Here is a custom function I use in update hooks, to translate some missing translations, just in case you want to do this programmatically:
```php
function translateString($source_string, $translated_string, $langcode) {
$storage = \Drupal::service('locale.storage');
$string = $storage->findString(array('source' => $source_string));
if (is_null($string)) {
$string = new SourceString();
$string->setString($source_string);
$string->setStorage($storage);
$string->save();
}
// If exists, replace
$translation = $storage->createTranslation(array(
'lid' => $string->lid,
'language' => $langcode,
'translation' => $translated_string,
))->save();
}
```
To implement it you can do the following (i.e. in a update hook):
```php
function my_module_update_8000() {
translateString(
'The original String',
'My translated String to german thats why the next parameter is "de"',
'de'
);
}
``` |
5,914,978 | I am currently in the planning stages for a fairly comprehensive rewrite of one of our core (commercial) software offerings, and I am looking for a bit of advice.
Our current software is a business management package written in Winforms (originally in .NET 2.0, but has transitioned into 4.0 so far) that communicates directly with a SQL Server backend. There is also a very simple ASP.NET Webforms website that provides some basic functionality for users on the road. Each of our customers has to expose this site (and a couple of existing ASMX web services) to the world in order to make use of it, and we're beginning to outgrow this setup.
As we rewrite this package, we have decided that it would be best if we made the package more accessible from the outside, as well as providing our customers with the option of allowing us to host their data (we haven't decided on a provider) rather than requiring them to host SQL Server, SQL Server Reporting Services, and IIS on the premises.
Right now, our plan is to rewrite the existing Winforms application using WPF, as well as provide a much richer client experience over the web. Going forward, however, our customers have expressed an interest in using tablets, so we're going to need to support iOS and Android native applications as clients, as well.
The combination of our desire to offer off-site hosting (without having to use a VPN architecture) and support clients on platforms that are outside of the .NET ecosystem has led us to the conclusion that all of our client-server communication should take place through our own service rather than using the SQL Server client (since we don't want to expose that to the world and SQL Server drivers do not exist, to my knowledge, for some of those platforms).
Right now, our options as I see them are:
* Write a completely custom service that uses TCP sockets and write everything (authentication, session management, serialization, etc.) from scratch. This is what I know the most *about*, but my assumption is that there's something better.
* Use a WCF service for transport, and either take care of authentication and/or session management myself, or use something like durable services for session management
My basic question is this:
### What would be the most appropriate choice of overall architecture, as well as specific features like ASP.NET authentication or Durable Services, to provide a stateful, persistent service to WPF, ASP.NET, iOS, and Android clients? | 2011/05/06 | [
"https://Stackoverflow.com/questions/5914978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82187/"
] | *(I am working on the assumption that by "stateful" you mean session-based).*
I guess one big question is: Do you want to use SOAP in your messaging stack?
You may be loathe to, as often there is no out-of-box support for SOAP on mobile platforms (see: [How to call a web service with Android](https://stackoverflow.com/questions/297586/how-to-call-web-service-with-android)). No doubt its similarly painful with iOS. Calling SOAP from a browser ("ASP.NET") can't be fun. I'm not even sure its possible!
Unfortunately if you aren't using SOAP, then that quickly rules out most of WCFs standard Bindings. Of the one that remains, "[Web HTTP](http://msdn.microsoft.com/en-us/library/bb412169.aspx)", sessions are not supported because obviously HTTP is a stateless protocol. You can actually add session support by hand using a solution [based on Cookies](http://msdn.microsoft.com/en-us/library/bb412169.aspx).
You could use the TCP transport (it supports sessions), and build you own channel stack to support a non-SOAP encoding (for example [protocol-buffers](http://code.google.com/p/protobuf-net/)), but even then you need to be careful because the TCP transport places special 'framing' bytes in it, so that would make interop non-trivial.
What sort of state do you need to store in your sessions? Maybe there are alternative approaches? |
14,530,617 | I am new to CSS/HTML and I am having some trouble adjusting the width of my page. I'm sure the solution is very simple and obvious lol.
On this page: <http://www.bodylogicmd.com/appetites-and-aphrodisiacs> - I am trying to set the width to 100% so that the content spans the entire width of the page. The problem I am running into is that when I try to add inline CSS, the external stylesheet called in the head is superseding the inline. I am using Joomla, so the editor let's edit the body, not the head (unless I create a custom module that rewrites code for the head).
I do not want to re-write/edit the external (main) stylesheet, since I am using this page for a contest and it is only running for about 1 month.
Anyone have any ideas how I can achieve this using inline CSSS and what the code would be?
Any help is greatly appreciated!! | 2013/01/25 | [
"https://Stackoverflow.com/questions/14530617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012426/"
] | ```
#main, #content, .landing-wrapper, #column2 .box2 {width: auto;}
#column2 {width: auto; float: none;}
```
You should be able to place this in the head of your template's index.php, though I would personally add it to the bottom of the theme's main stylesheet. How long it's there isn't a factor. |
36,096,204 | How do I create a Custom Hook Method in a Subclass?
No need to duplicate Rails, of course -- the simpler, the better.
My goal is to convert:
```
class SubClass
def do_this_method
first_validate_something
end
def do_that_method
first_validate_something
end
private
def first_validate_something; end
end
```
To:
```
class ActiveClass; end
class SubClass < ActiveClass
before_operations :first_validate_something, :do_this_method, :do_that_method
def do_this_method; end
def do_that_method; end
private
def first_validate_something; end
end
```
Example in Module: <https://github.com/PragTob/after_do/blob/master/lib/after_do.rb>
Rails #before\_action: <http://apidock.com/rails/v4.0.2/AbstractController/Callbacks/ClassMethods/before_action> | 2016/03/19 | [
"https://Stackoverflow.com/questions/36096204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5298869/"
] | Here's a solution that uses `prepend`. When you call `before_operations` for the first time it creates a new (empty) module and prepends it to your class. This means that when you call method `foo` on your class, it will look first for that method in the module.
The `before_operations` method then defines simple methods in this module that first invoke your 'before' method, and then use `super` to invoke the real implementation in your class.
```ruby
class ActiveClass
def self.before_operations(before_method,*methods)
prepend( @active_wrapper=Module.new ) unless @active_wrapper
methods.each do |method_name|
@active_wrapper.send(:define_method,method_name) do |*args,&block|
send before_method
super(*args,&block)
end
end
end
end
class SubClass < ActiveClass
before_operations :first_validate_something, :do_this_method, :do_that_method
def do_this_method(*args,&block)
p doing:'this', with:args, and:block
end
def do_that_method; end
private
def first_validate_something
p :validating
end
end
SubClass.new.do_this_method(3,4){ |x| p x }
#=> :validating
#=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>}
```
---
If you want to make the idea by @SteveTurczyn work you must:
1. receive the args params in the block of `define_method`, not as arguments to it.
2. call `before_operations` AFTER your methods have been defined if you want to be able to alias them.
```ruby
class ActiveClass
def self.before_operations(before_method, *methods)
methods.each do |meth|
raise "No method `#{meth}` defined in #{self}" unless method_defined?(meth)
orig_method = "_original_#{meth}"
alias_method orig_method, meth
define_method(meth) do |*args,&block|
send before_method
send orig_method, *args, &block
end
end
end
end
class SubClass < ActiveClass
def do_this_method(*args,&block)
p doing:'this', with:args, and:block
end
def do_that_method; end
before_operations :first_validate_something, :do_this_method, :do_that_method
private
def first_validate_something
p :validating
end
end
SubClass.new.do_this_method(3,4){ |x| p x }
#=> :validating
#=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>}
``` |
30,065,899 | I know the logic/syntax of the code at the bottom of this post is off, but I'm having a hard time figuring out how I can write this to get the desired result. The first section creates this dictionary:
```
sco = {'human + big': 0, 'big + loud': 0, 'big + human': 0, 'human + loud': 0, 'loud + big': 0, 'loud + human': 0}
```
Then, my intention is to loop through each item in the dictionary "cnt" once for x and then loop through the dictionary a second time for x each time the item has the same value as (cnt[x][1]) but a different key (cnt[x][0]), creating a string that will match the format "%s + %s" found in the dictionary "sco." It should then find the key in sco that matches the key assigned to the variable dnt and increment the value for that key in sco by 1.
```
# -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = cnt[x][0]
who = cnt[x][1]
for x in cnt:
if cnt[x][0] != upd and cnt[x][1] == who:
cpg = cnt[x][0]
dnt = '%s + %s' % (upd, cpg)
for i in sco:
if sco[i][0] == dnt:
sco[i][1] += sco[i][1]
print sco
```
Currently, printing sco results in no change to any of the values. The desired outcome of the code is this:
```
{'human + big': 1, 'big + loud': 0, 'big + human': 1, 'human + loud': 2, 'loud + big': 0, 'loud + human': 2}
```
Any help is greatly appreciated!
The revised code is this:
```
# -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = cnt[0]
who = cnt[1]
for x in cnt:
if cnt[0] != upd and cnt[1] == who:
cpg = cnt[0]
dnt = '%s + %s' % (upd, cpg)
sco[dnt] += 1
print sco
```
The following code does what I intended. Thank you to @dermen & @abarnert:
```
# -*- coding: utf-8 -*-
import itertools
sho = ('human', 'loud', 'big')
sco = {}
for a,b in itertools.permutations(sho, 2):
sco["{0} + {1}".format(a,b)] = 0
cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')]
for x in cnt:
upd = x[0]
who = x[1]
for x in cnt:
if x[0] != upd and x[1] == who:
cpg = x[0]
dnt = '%s + %s' % (upd, cpg)
sco[dnt] += 1
print sco
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30065899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4652988/"
] | The actual problem is that, instead of adding 1 to the values, you're doubling them:
```
sco[i][1] += sco[i][1]
```
And no matter how many times you add 0 to 0, it's still 0.
To add 1, just use `+= 1`.
---
But you've got another problem, at least in the code you posted. Each `sco[i]` value just a number, not a list of two things, the second of which is a number. So what you really want is:
```
sco[i] += 1
```
And similarly, the keys aren't `sco[i][0]`, they're just `i`.
---
And you've got a third problem. This one doesn't actually *break* your code, it just makes it more complicated, harder to understand, and slower… but that's still worth fixing.
The whole point of dictionaries is that you don't have to iterate them to search for a key, you just look up the key directly. So, instead of this:
```
for i in sco:
if i == dnt:
sco[i] += 1
```
… just do this:
```
sco[dnt] += 1
```
It's simpler, harder to get wrong, and more efficient, all at the same time.
---
I can't promise there are no other errors in your code, but you definitely need to fix these three, on top of whatever else is wrong, and I'm pretty sure the first one is the one that happens to be causing the specific problem you asked about. |
17,143,401 | What I'm having is that this error is displayed when I wanted to copy a exe debug project that I have created (which works witout any problems) to another machine (the error message is displayed).
According to the [question posted previously](https://stackoverflow.com/questions/7904213/msvcp100d-dll-missing), the best solution to get rid of the error message is to make a release and not a debug in the Configuration Manager.
Doing that, and when rebuilding the project with the RELEASE one, I'm having new errors in my project which were not included when doing the DEBUG.
For instance, one of them is :
```
Error 2 error C1083: Cannot open include file: 'opencv\highgui.h': No such file or directory c:\...\projects\...\ex\opencv.h 4
23 IntelliSense: identifier "IplImage" is undefined c:\...\ex.cpp 80
```
Any feedbacks? | 2013/06/17 | [
"https://Stackoverflow.com/questions/17143401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2441175/"
] | MSVCP100.dll is part of the Microsoft Visual Studio 10 runtime. MSVCP100d.dll is the debug build of the same dll - useful for running your program in debug mode.
<http://www.microsoft.com/en-us/download/details.aspx?id=5555>
Basically it is a relatively new package and is not guaranteed to be on all systems, especially Windows XP, so you can distribute the required DLL files or the entire runtime with your program. EDIT: Keep in mind that debug builds are not meant to be distributed, so your program should not contain debug dll-s either such as MSVCP100d.dll.
Try downloading it, and then see what happens.
Also check out [this question.](https://stackoverflow.com/questions/12799783/visual-studio-2010-runtime-libraries) |
43,704,514 | I would like to factor an equation by completing the square:
```
>>>> import sympy
>>>> x, c = symbols('x c')
>>>> factor(x**2 - 4*x - 1)
x**2 - 4*x - 1
```
However, I was expecting to see:
```
(x - 2)**2 - 5
```
How can this be done in sympy? | 2017/04/30 | [
"https://Stackoverflow.com/questions/43704514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | In a circumstance like that you can get the factors using `solve`:
```
>>> solve(x**2-4*x-1)
[2 + sqrt(5), -sqrt(5) + 2]
```
I would not expect `factor` to give me the factors in the form suggested in the question. However, if you really want to 'complete the square' sympy will do the arithmetic for you (you need to know the steps) but not much more, AFAIK. |
40,298,290 | In MSDN, "For **reference types**, an explicit cast is required if you need to convert from a base type to a derived type".
In wiki, "In programming language theory, a **reference type is a data type that refers to an object in memory**. A pointer type on the other hand refers to a memory address. Reference types can be thought of as pointers that are implicitly dereferenced." which is the case in C.
How to explain the memory storing procedure when considering explicit casting for reference type in C#? | 2016/10/28 | [
"https://Stackoverflow.com/questions/40298290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902173/"
] | First of all don't try to write all your code in a single statement. Its is easier to debug using multiple statements:
```
itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0));
```
Can easily be written as:
```
Object value = showItem.getValueAt(rowCount, 0);
itemCode.setText( value.toString() );
```
Note there is no need to invoke the getSelectedRow() method twice since you have a variable that contains that value.
Then you can always add some debug code like:
```
Object value = showItem.getValueAt(rowCount, 0);
System.out.println( value.getClass() );
```
to see what type of Object your table has in that cell. |
7,900 | [The Axis of Awesome](http://en.wikipedia.org/wiki/The_Axis_of_Awesome) has a song called "4 Chords", a medley of various songs all written, or so it's claimed, using the same four chords.
Now, from what I understand, a chord is just a bunch of tones played at the same time so they sound like one. For example, a 300 Hz note and a 500 Hz note played simultaneously will be a 100 Hz sound (because 100 is the greatest common factor of 300 and 500) with a lot of nuance in it, and that's called a chord. So the songs in the medley all have the same chords, that is, the same sounds with the same… what I called nuances.
They don't.
Never mind the lyrics: there are clearly more than four sounds in any of the songs when sung: just listen to 'em. But even watching the keyboardist's hands on the electronic keyboard (for [the one segment where you get to do so for any significant length of time](http://www.youtube.com/watch?v=oOlDewpCfZQ#t=310s) (warning, foul language in that clip)), you can see he hits more than four chords.
What gives? Am I hearing and seeing wrong, or is my definition of *chord* wrong, or is Axis of Awesome lying, or is there some explanation of how the songs in this medley are considered to have but four chords even though they have more? | 2012/11/27 | [
"https://music.stackexchange.com/questions/7900",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/400/"
] | **tl;dr - your definition of chord is wrong.**
Your initial assumption
>
> a 300 Hz note and a 500 Hz note played simultaneously will be a 100
> Hz sound
>
>
>
is unfortunately incorrect.
When you play a 300Hz note and a 500Hz note what you will get is a 300Hz note, and a 500Hz note, **and** a 200Hz note (the difference between them) **and** an 800Hz note (the sum of the two frequencies) (Have a listen to the demos on **[this page](http://www.animations.physics.unsw.edu.au/jw/beats.htm)** for examples)
In addition to that, a chord can have any number of notes in it (typically on a piano it usually has 10 or less notes, and on a guitar you're usually expecting 6 or less)
And finally, a chord can be played in many different ways, so if I wanted to I could play a 4 chord song using 20 different variations of that chord.
**Update** After watching the actual video, the keyboard player is only playing 4 chords, and not really playing any variations of them. He is sometimes accenting certain notes more than the others, but the 4 chord shapes he is using are consistent throughout that segment. He is hitting and releasing **keys**, sure, but only as parts of the same chords. |
56,606,827 | Currently working on a very basic three table/model problem in Laravel and the proper Eloquent setup has my brain leaking.
COLLECTION -> coll\_id, ...
ITEM -> item\_id, coll\_id, type\_id, ...
TYPE -> type\_id, ...
I can phrase it a thousand ways but cannot begin to conceptualize the appropriate Eloquent relationships:
COLLECTIONS have many ITEMS, each ITEM has a TYPE. Or, an ITEM belongs to a single COLLECTION, TYPES are associated with many ITEMS.
To me COLLECTION and ITEM are key, while TYPE is really additional reference data on a given ITEM; basically a category for the item.
My objective is to build a solution where users create COLLECTIONS, add ITEMS to those COLLECTIONS, and those ITEMS are associated with one of many TYPES (which they will also define).
I know this example isn't far from other Author, Book, Category; or City, State, Country examples but implementing those model frameworks doesn't build the full connection from COLLECTION<->ITEM<->TYPE and most obviously fails when trying to associate TYPES within a COLLECTION.
Models:
COLLECTION
```
class Collection extends Model
{
protected $guarded = [];
public function items()
{
return $this->hasMany(Item::class);
}
public function types()
{
return $this->hasManyThrough(Type::class, Item::class);
}
}
```
ITEM
```
class Item extends Model
{
public function collection()
{
return $this->belongsTo(Collection::class);
}
public function type()
{
return $this->belongsTo(Type::class);
}
}
```
TYPE
```
class Type extends Model
{
public function item()
{
return $this->hasMany(Item::class);
}
}
```
These models have COLLECTION<->ITEM in both directions working well, but the wheels fall off when I try to integrate TYPE. Depending on the 1000 variations I've tried I either get NULL in Tinker or it's looking for an ITEM\_ID in TYPE which doesn't and shouldn't exist.
What would a solution be to update the model to accurately reflect ITEMS having one TYPE and the eventual set of TYPES within a COLLECTION?
Thanks in advance!
---
UPDATE: Working *nested* solution - the primary response solution was showing 2 relations at COLLECTION, no nesting:
```
class Collection extends Model
{
protected $guarded = [];
public function items()
{
return $this->hasMany(Item::class);
}
```
```
class Item extends Model
{
public function collection()
{
return $this->hasOne(Collection::class);
}
public function type()
{
return $this->belongsto(Type::class);
}
}
```
```
class Type extends Model
{
public function items()
{
return $this->hasMany(Item::class);
}
}
```
```
$collection->load('items.type');
dd($collection);
```
```
Collection {#280 ▼
#guarded: []
#connection: "mysql"
#table: "collections"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
**#relations: array:1** [▼
"items" => Collection {#285 ▼
#items: array:2 [▼
0 => Item {#288 ▼
#connection: "mysql"
#table: "items"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:13 [▶]
#original: array:13 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
**#relations: array:1** [▼
"type" => Type {#296 ▶}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => Item {#289 ▶}
]
}
]
``` | 2019/06/15 | [
"https://Stackoverflow.com/questions/56606827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11558094/"
] | `HasManyThrough` isn't the right relationship between Collection and Type. `HasManyThrough` is kind of like chaining 2 `HasMany` relationships together:
```
Country -> State -> City
```
Notice how the arrows all go one way. That's because City has a foreign key to State, and State has a foreign key to Country.
Your relationship looks like this:
```
Collection -> Item <- Type
```
So Item has foreign keys to both Collection and Type. In this case, the relationship between Collection and Type is actually `BelongsToMany`, and the Item table is the join table.
<https://laravel.com/docs/5.8/eloquent-relationships#many-to-many>
```php
class Collection extends Model
{
protected $guarded = [];
public function items()
{
return $this->hasMany(Item::class);
}
public function types()
{
// Substitute your table and key names here
return $this->belongsToMany(Type::class, 'items_table', 'coll_id', 'type_id');
}
}
class Type extends Model
{
public function items()
{
return $this->hasMany(Item::class);
}
public function collections()
{
// Substitute your table and key names here
return $this->belongsToMany(Collection::class, 'items_table', 'type_id', 'coll_id');
}
}
class Item extends Model
{
public function collection()
{
return $this->belongsto(Collection::class);
}
public function type()
{
return $this->belongsto(Type::class);
}
}
```
If you want to get collections with their items, and the corresponding type under each item, you can do:
```
Collection::with(['items.type'])->get();
``` |
58,545,828 | I know that JAWS, by default, will ignore `<span/>` tags. My team got around that issue. Now, however, we have some content that is displayed using `<span/>` tags where the text displayed for sighted users doesn't play well with JAWS reading the information out. In our specific case, it would be international bank account numbers, which can contain letters. In this case, instead of reading individual digits, JAWS attempts to read the content as a word, resulting in predictably poor output.
So, a couple of questions:
1. Given that this is part of a large page that I have neither the time nor the permission to refactor, is there a way to get this working within the constraints I've described?
2. If you were to write a page like this from scratch, what's the best practice for crafting the page such that I would have the ability to supply "alternate" text for read-only, non-interactive content?
If it helps, the outcome I'm envisioning is something like this:
`<span id="some-label" aria-label="1 2 3 4 5 A">12345A</span>`
We have been unable to come up with any combination of techniques that would have JAWS read: "1 2 3 4 5 A" instead of reading "12345A" as a single word. | 2019/10/24 | [
"https://Stackoverflow.com/questions/58545828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394484/"
] | The technical answer is always the same, and has been repeated many times here and elsewhere: **aria-label has no effect if you don't also assign a role**.
Now, for the more user experience question, I'm blind myself, and I can tell you, it may not be a good idea to force a spell out of each digit individually.
* We are used in having account, telephone, etc. numbers grouped
* IF we want a spell out of each digit individually, Jaws has the function: insert+up arrow twice quickly. Other screen readers have similar shortcuts.
* My native language is french, not english. Although I'm on an english page, I may want to have numbers spoken in french, because it's easier for me. BY forcing a label, you prevent me from hearing numbers in french.
* And probably the best argument: what are you going to say if you were to give your account number on the phone ? Will you say "one two three four five", "twelve thousend thirty hundred twenty one", "twelve thirty four five", something else ? Doing this litle exercise is likely to give you a good label to put in, but several people are probably going to give you different answers. |
44,878,541 | I have a few activities:
* Splash screen
* Login
* Registration
* Dashboard
If the user has never logged in, it will go like this:
>
> Splash screen > Login > Registration > Dashboard
>
>
>
When I `back` from the Dashboard, it should exit the app, skipping through the other activities.
`noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration.
If the user has previously logged on, it should go like this:
>
> Splash screen > Dashboard
>
>
>
If the user logs out, perhaps to use another account, then it should go:
>
> Dashboard > Login > Dashboard
>
>
>
But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard.
Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful.
I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways? | 2017/07/03 | [
"https://Stackoverflow.com/questions/44878541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1402526/"
] | Java defines two types of streams, byte and character.
The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits.
In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter.
PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods
in the same way as you used them with System.out.
```
PrintWriter printWriter = new PrintWriter(System.out,true);
char aa = '\u0905';
printWriter.println("aa = " + aa);
``` |
24,662,079 | I am trying to make all the table cells equal to the image size, but for some reason, they won't be set to it.
<http://jsfiddle.net/gzkhW/>
HTML(shortened a bit)
```
<table>
<tr>
<td><img src="http://i.imgur.com/CMu2qnB.png"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
```
CSS
```
table {
border:1px solid black;
}
td {width:206px;
height:214px;
border:1px solid black;
}
``` | 2014/07/09 | [
"https://Stackoverflow.com/questions/24662079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077972/"
] | You would like to do these:
1. You can directly select using `.slide`.
2. Check the length of `nextUp` instead.
Try this, seems to be a workaround:
**JS**
```
$('.next').click(function() {
var current = $('.slide');
var nextUp = $('.slide').next('.hello');
if( nextUp.length == 0 ) {
$('div.hello:first').addClass('slide');
$('div.hello:last').removeClass('slide');
}
else {
$(nextUp).addClass('slide');
$(current).removeClass('slide');
}
});
```
**[JSFIDDLE DEMO](http://jsfiddle.net/c4ZNm/15/)** |
17,373,866 | I wrote an android library for some UI utilities. I have a function that return ImageView. But, my problem is that I want that the resource of the drawable image, will be in the project that contains the library. I will explain...
I want that the ImageView will always take the drawable with the source name: `R.drawable.ic_img_logo` (and only this name). This resource will not actually be in the library. But the project that contains the library will contains also drawable with the resource name `R.drawable.ic_img_logo`.
I know that this thing works with id (of views), you can create file call `ids.xml` and define some ids in the file that others can use them, and you will recognize them.
But how can I do this with drawables? | 2013/06/28 | [
"https://Stackoverflow.com/questions/17373866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725836/"
] | I found the answer. You need to create a file called `drawables.xml` in the library. Then inside it write:
```
<resource>
<item name="ic_img_logo" type="drawable" />
</resource>
```
Its make fake resource `R.drawable.ic_img_logo`. Then if the project that include the library have drawable called `ic_img_logo`. The library be able to access to this drawable, because it will be the same resource. |
60,817,243 | I have large data files formatted as follows:
```
1 M * 0.86
2 S * 0.81
3 M * 0.68
4 S * 0.53
5 T . 0.40
6 S . 0.34
7 T . 0.25
8 E . 0.36
9 V . 0.32
10 I . 0.26
11 A . 0.17
12 H . 0.15
13 H . 0.12
14 W . 0.14
15 A . 0.16
16 F . 0.13
17 A . 0.12
18 I . 0.12
19 F . 0.22
20 L . 0.44
21 I * 0.68
22 V * 0.79
23 A * 0.88
24 I * 0.88
25 G * 0.89
26 L * 0.88
27 C * 0.81
28 C * 0.82
29 L * 0.79
30 M * 0.80
31 L * 0.74
32 V * 0.72
33 G * 0.62
```
What I'm trying to figure out how to do is loop through each line in the file and, if the line contains an asterisk, begin finding a subsequent range that satisfies this condition. Additionally it would be nice to output the largest range in a file.
So for this example, the desired output would look like:
```
1-4,21-33 13
```
Thanks for any assistance! | 2020/03/23 | [
"https://Stackoverflow.com/questions/60817243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441735/"
] | There are several way to perform this.
One solution is to read the file line by line. I advise you to have a look at this very good [tutorial](https://stackabuse.com/read-a-file-line-by-line-in-python/) on how to read file.
Once you did it, you can try the following:
* Iterate over each line of the file:
+ If there is an `*` in the line:
+ Then:
- keep the index (this a starting point)
- read the lines while there is an "\*" in the line
- keep the index (this a end point)
+ read next line
In Python:
```py
# your file path
filepath = 'test.txt'
with open(filepath) as fp:
line = fp.readline()
# Count the line index
cnt = 1
# Output storing deb and end index
output = []
# While there are lines in the file (e.g. the end of file not reached)
while line:
# Check if the current line has a "*"
if "*" in line:
# If yes, keep the count value, it's the starting point
deb = cnt
# Iterate while there are "*" in line
while "*" in line:
cnt += 1
line = fp.readline()
# END while (e.g end of file or there is no "*" in the line
# Add the starting index and end index to the output
output.append({"deb" : deb, "end": cnt - 1})
# Read next line
cnt += 1
line = fp.readline()
print(output)
# [{'deb': 1, 'end': 4}, {'deb': 21, 'end': 33}]
``` |
19,056,546 | I want to create an HTML Message to send an email in PHP.
```
$message = $mess0 . "</br>" . $mess1 . "</br>" . $mess2 . "</br>" . $mes1 . "</br></br>" . $mes2 . "</br>" . $mes23 . "</br></br>" . $mes3 . "</br></br>" . $mes4 . "</br>" . $mes5 . "</br>" . $mes6 . "</br>" . $mes7 . "</br>" . $mes8 . "</br>" . $mes9 . "</br></br>" . $mes10 ;
$message = <html><body><p>$message</p></body></html>;
```
Here are some variables.
I am getting the following error.
>
> Parse error: syntax error, unexpected '<' in /home/thevowaa/public\_html/iphoneapp/webservice/file.php on line 214
>
>
> | 2013/09/27 | [
"https://Stackoverflow.com/questions/19056546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921872/"
] | Add HTML tags between double quotes.
```
$message = "<html><body><p>".$message."</p></body></html>";
``` |
23,859,259 | I would like to ask a question about "foreach loop" in PHP. Towards the bottom of the code below, the "while" loop accesses elements from an array individually. How can I rewrite the BODY of the while loop using a "foreach" loop?
```
<?php
require_once('MDB2.php');
$db = MDB2::connect("mysql://mk:[email protected]/mk");
if(PEAR::iserror($db)) die($db->getMessage());
$sql = "SELECT courses.ID,courses.Name,staff.Name
FROM courses,staff
WHERE courses.Coordinator=staff.id
and courses.ID = \"$course\"";
$q = $db->query($sql);
if(PEAR::iserror($q)) die($q->getMessage());
while($row = $q->fetchRow()){
echo "<tr><td>$row[0]</td>\n";
echo "<td>$row[1]</td>\n";
echo "<td>$row[2]</td></tr>\n";
}
}
?>
</table>
</body></html>
``` | 2014/05/25 | [
"https://Stackoverflow.com/questions/23859259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975787/"
] | If you dereference a `char **`, you should get a pointer to `char`. There are no pointers in a `char[3][10]`. They're just not interchangeable.
It works for a one-dimensional `char *` array because the array name implicitly converts to a pointer to the first element in this context, and if you dereference a `char *` you get a `char`, and that's exactly what your one-dimensional `char` array contains.
The line of thinking that "if it works for a one-dimensional array, shouldn't it work for a two-dimensional array?" is just invalid, here.
To make what you want to do work, you'd have to create `char *` arrays, like so:
```
#include <stdio.h>
void fn(int argc, char ** argv) {
printf("argc : %d\n", argc);
for (int i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);
}
}
int main(void) {
char * var3[3] = { "arg1", "argument2", "arg3" };
char * var4[4] = { "One", "Two", "Three", "Four" };
fn(3, var3);
fn(4, var4);
return 0;
}
```
which outputs:
```
paul@local:~/src/c/scratch$ ./carr
argc : 3
arg1
argument2
arg3
argc : 4
One
Two
Three
Four
paul@local:~/src/c/scratch$
```
An alternative is to declare your function as accepting an array of (effectively a pointer to) 10-element arrays of `char`, like so:
```
#include <stdio.h>
void fn(int argc, char argv[][10]) {
printf("argc : %d\n", argc);
for (int i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);
}
}
int main(void) {
char var3[3][10] = { "arg1", "argument2", "arg3" };
char var4[4][10] = { "arg1", "argument2", "arg3", "arg4" };
fn(3, var3);
fn(4, var4);
return 0;
}
```
but this obviously requires hard-coding the sizes of all dimensions except the leftmost, which is usually less desirable and flexible. `char argv[][10]` in the parameter list here is another way of writing `char (*argv)[10]`, i.e. declaring `argv` as a pointer to array of `char` of size `10`. |
1,300,792 | In Windows I would like to be able to run a script or application that starts an another application and sets its size and location. An example of this would be to run an application/script that starts notepad and tells it to be 800x600 and to be in the top right corner. Does anyone have any ideas regardless of language? | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143074/"
] | Do you mean something like this:
```
$ xterm -geometry 135x35+0+0
```
which puts an xterm at the top-left of the screen (`+0+0`) and makes it 135 columns by 35 lines? Most X apps take a -geometry argument with the same syntax (though often in pixels, not characters like xterm), and you can obviously put that in a shell script.
Alternatively, if the program is already running, the xwit command can be used to move it:
```
xwit -move 0 0 -columns 135 -id $WINDOWID
```
That will move the xterm its running in to the top-left corner of the screen, and make it 135 columns wide. It works on any window, not just xterms. For example:
```
xwit -move 0 0 -id 0x6600091
```
just moved my browser window. You can find window IDs with `xwininfo`, `xlsclients`, or several others. |
7,847,778 | I send a invite ,Below code is used to give you the request id. I'm the sender A. I send invite to b.I can get the request\_id but how to get the A UID.
```
//get the request ids from the query parameter
$request_ids = explode(',', $_REQUEST['request_ids']);
//build the full_request_id from request_id and user_id
function build_full_request_id($request_id, $user_id) {
return $request_id . '_' . $user_id;
}
//for each request_id, build the full_request_id and delete request
foreach ($request_ids as $request_id)
{
echo ("reqeust_id=".$request_id."<br>");
$full_request_id = build_full_request_id($request_id, $user_id);
echo ("full_request_id=".$full_request_id."<br>");
try {
$delete_success = $facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;}
else {
echo "Delete failed".$full_request_id;}
}
catch (FacebookApiException $e) {
echo "error";}
}
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7847778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Set it: `$user_id_A = $facebook->getUser();`
Here's some info about the getUser() method: <https://developers.facebook.com/docs/reference/php/facebook-getUser/> |
1,645,166 | image naturalWidth return zero... that's it, why ?
```
var newimage = new Image();
newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg';
var width = newimage.naturalWidth;
alert (width);
```
HELP, i dont know why !
\*\*\* that path is good, the image show up ! | 2009/10/29 | [
"https://Stackoverflow.com/questions/1645166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71830/"
] | I'd guess it's because you're not waiting for the image to load - try this:
```
var newimage = new Image();
newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg';
newimage.onload = function()
{
var width = this.naturalWidth;
alert(width);
}
``` |
544,156 | When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys).
How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password? | 2013/10/06 | [
"https://serverfault.com/questions/544156",
"https://serverfault.com",
"https://serverfault.com/users/109581/"
] | In git version 2.3 there's an environment variable `GIT_TERMINAL_PROMPT` which when set to `0` will disable prompting for credentials.
You can get more info about it in `man git` (after updating to git version `2.3`) or in [this blog post on github](https://github.com/blog/1957-git-2-3-has-been-released).
Examples:
* `git clone https://github.com/some/non-existing-repo` will prompt for username & password
* `GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo` will fail without prompting for username & password |
2,963,436 | I have the following:
```
echo time()."<br>";
sleep(1);
echo time()."<br>";
sleep(1);
echo time()."<br>";
```
I wrote the preceding code with intention to echo `time()."<br>"` ln 1,echo `time()."<br>"` ln 4, wait a final second and then echo the final `time()."<br>"`. Altough the time bieng echoed is correct when it comes to the intervals between time(), all echo functions are echoeing after the total of the waiting period/parameters in each sleep function.
This is how the script runs:
* Excutes.
* Waits 2 secons.
* echoes
1275540664
1275540665
1275540666
Notice the correct incrementation in `time()` being echoed. My question is why is it not behaving like expected to where it echoes, waits a second, echoes again, waits one final second and then echos the last parameter?
I know my question is a little confusing due to my wording, but i will try my hardest to answer any comments regarding this, thanks. | 2010/06/03 | [
"https://Stackoverflow.com/questions/2963436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98204/"
] | You have output buffering turned on.
It is more efficient for PHP to buffer up output and write it all to the browser in one go than it is to write the output in small bursts. So PHP will buffer the output and send it all in one go at the end (or once the buffer gets to a certain size).
You can manually flush the buffer by calling [flush()](http://www.php.net/manual/en/function.flush.php) after each call to `echo` (though I wouldn't recommend this is a "real" app - but then again, I wouldn't recommend calling `sleep` in a regular app, either!). |
34,458,383 | Sorry if the Question Title is a bit off, couldn't think of something more descriptive.
So I have 2 Domains: `aaa.com` and `bbb.com`.
I want my second domain `bbb.com` to redirect always to `aaa.com` EXCEPT IF it has a certain path: `bbb.com/ct/:id`
Both domains right now hit the same Heroku App.
So in my `Application Controller` I guess, or Routes I, have to scan the request URL and if it contains `/ct/:id` let it continue to the controller action, if not redirect to aaa.com.
Or can I somehow Set up the the DNS to only redirect if the `ct/:id` is not in the url ?
Basically I want to achieve that a User can't navigate the App from `bbb.com` except if the specific url `bbb.com/ct/:id` is present.
I'm using GoDaddy as a Registar and have 2 Cnames set up to my Heroku Apps.
How do I accomplish this behavior ? | 2015/12/24 | [
"https://Stackoverflow.com/questions/34458383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1609496/"
] | I prefer to do your redirects in an actual controller and not in the route file so you can write a controller spec for it.
```
# app/controllers/application_controller.rb
before_action :redirect_bbb_to_aaa
def redirect_bbb_to_aaa
if request.host == "http://bbb.com"
redirect_to some_aaa_path unless request.url == "http://bbb.com/ct/:id"
end
end
``` |
28,374,712 | I have a class:
```
public class NListingsData : ListingData, IListingData
{
private readonly IMetaDictionaryRepository _metaDictionary;
//Constructor.
public NListingsData(IMetaDictionaryRepository metaDictionary)
{
_metaDictionary = metaDictionary;
}
//Overridden function from abstract base class
public override List<Images> Photos
{
get
{
var urlFormat = _metaDictionary.GetDictionary(CommonConstants.ImagesUrlFormat, this.Key);
var imgs = new List<Images>();
for (var i = 0; i < PhotosCount; i++)
{
imgs.Add(new Images
{
Url = string.Format(urlFormat, this.MNumber, i)
});
}
return imgs;
}
set { }
}
}
```
The metaDictionary is injected by Autofac.
I am executing a query with Dapper and I try to materialize NListingsData. This is what I am using:
```
string sqlQuery = GetQuery(predicates); //Select count(*) from LView; select * from lView;
//Use multiple queries
using (var multi = _db.QueryMultipleAsync(sqlQuery,
new
{
//The parameter names below have to be same as column names and same as the fields names in the function: GetListingsSqlFilterCriteria()
@BedroomsTotal = predicates.GetBedrooms(),
@BathroomsTotalInteger = predicates.GetBathrooms()
}).Result)
{
//Get count of results that match the query
totalResultsCount = multi.ReadAsync<int>().Result.Single();
//Retrieve only the pagesize number of results
var dblistings = multi.ReadAsync<NListingsData>().Result; // Error is here
}
return dblistings;
```
I get the error
```
A parameterless default constructor or one matching signature (System.Guid ListingId, System.String MLSNumber, System.Int32 BedroomsTotal, System.Double BathroomsTotalInteger) is required for CTP.ApiModels.NListingsData materialization
```
Does my class that I use to materialize with dapper must always be parameterless?
Now, I could create a simple DataModel then map to my ViewModel. But is that the only way to do it? | 2015/02/06 | [
"https://Stackoverflow.com/questions/28374712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475882/"
] | Just add an additional private, parameterless, constructor. This will get picked by Dapper. |
203,829 | We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow.
The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions? | 2013/07/05 | [
"https://softwareengineering.stackexchange.com/questions/203829",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/79820/"
] | I would like to point out that Entity Framework (full name: [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx)) is an ORM (Object Relational Mapper) that uses ADO.NET under the hood for connecting to the database. So the question "should we use ADO.NET or EF?" doesn't really make sense in that respect. Unless you re-architect your application, adding EF to the mix is simply adding another layer on top of ADO.NET.
I sincerely doubt that ADO.NET is the source of your performance problems, however. It sounds like the problem exists in your stored procedures themselves.
I think [Luc Franken's comments](https://softwareengineering.stackexchange.com/questions/203829/ado-net-or-ef-for-a-point-of-sale-system#comment398288_203829) are on the right track, though. You need to measure and determine exactly where the delays are happening. Then concentrate on fixing exactly that problem. Anything else is groping around in the dark. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | In MVC there are no longer Code-Behind classes. What you want is a Partial.
You'd use it like so:
```
<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %>
```
If this Menu is going to be in all of your pages you can make your controllers subclass a custom controller class that always fills the Menu data first.
If messing with the MVC inheritance hierarchy is overkill you can also make a MenuController class and use the RenderAction in your view/master:
```
<% Html.RenderAction<MenuController>(x => x.MainMenu()); %>
``` |
277,955 | I have 10 servers running on Ubuntu 14.04 x64. Each server has a few Nvidia GPUs. I am looking for a monitoring program that would allow me to view the GPU usage on all servers at a glance. | 2016/04/20 | [
"https://unix.stackexchange.com/questions/277955",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16704/"
] | [munin](http://munin-monitoring.org/) has at least one [plugin](http://munin-monitoring.org/browser/munin-contrib/plugins/gpu/nvidia_gpu_) for monitoring nvidia GPUs (which uses the `nvidia-smi` utility to gather its data).
You could setup a `munin` server (perhaps on one of the GPU servers, or on the head node of your cluster), and then install the `munin-node` client and the nvidia plugin (plus whatever other plugins you might be interested in) on each of your GPU servers.
That would allow you to look in detail at the munin data for each server, or see an overview of the nvidia data for all servers. This would include graphs charting changes in, e.g., GPU temperature over time
Otherwise you could write a script to use ssh (or [pdsh](https://computing.llnl.gov/linux/pdsh.html)) to run the `nvidia-smi` utility on each server, extract the data you want, and present it in whatever format you want. |
28,185,048 | I've read several guides on how to use GTK+ for a GUI in C programs and I came across [this tutorial](https://wiki.gnome.org/Projects/GTK+/OSX/Building) for getting GTK+ on my system. Here's everything I ran, line by line:
```
chmod +x gtk-osx-build-setup.sh
./gtk-osx-build-setup.sh
cd ~/.local/bin
./jhbuild build python
./jhbuild bootstrap
./jhbuild build meta-gtk-osx-bootstrap
./jhbuild build meta-gtk-osx-core
```
At this point, I had not discovered the `pkg-config` tick hack for compiling C programs with GTK headers, so when I ran `gcc main.c -o main` I simply got the error `main.c:1:10: fatal error: 'gtk/gtk.h' file not found`, but I had found [another tutorial](https://developer.gnome.org/jhbuild/stable/getting-started.html.en) (Command-F "jhbuild build gtk+") that suggested I do this, so I ran:
```
./jhbuild build gtk+
```
After that, I finally found other sources that suggested to run the following commands to check if my system could find the packages, so when I run `pkg-config gtk+-3.0 --cflags` I get:
```
-D_REENTRANT -I/opt/local/include/gtk-3.0 -I/opt/local/include/at-spi2-atk/2.0 -I/opt/local/include/at-spi-2.0 -I/opt/local/include/dbus-1.0 -I/opt/local/lib/dbus-1.0/include -I/opt/local/include/gtk-3.0 -I/opt/local/include/gio-unix-2.0/ -I/opt/local/include -I/opt/local/include/cairo -I/opt/local/include/pango-1.0 -I/opt/local/include/harfbuzz -I/opt/local/include/pango-1.0 -I/opt/local/include/atk-1.0 -I/opt/local/include/cairo -I/opt/local/include/pixman-1 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include/libpng16 -I/opt/local/include -I/opt/local/include/gdk-pixbuf-2.0 -I/opt/local/include/libpng16 -I/opt/local/include/glib-2.0 -I/opt/local/lib/glib-2.0/include -I/opt/local/include
```
And when I run `pkg-config gtk+-3.0 --libs` I get:
```
-L/opt/local/lib -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpangoft2-1.0 -lpango-1.0 -lm -lfontconfig -lfreetype -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lintl
```
My `main.c` contains the following code from [this tutorial](https://developer.gnome.org/gtk3/stable/gtk-getting-started.html#id-1.2.3.3):
```
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Window");
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
When I run `gcc -Wall -Wextra -Werror `pkg-config gtk+-3.0 --cflags` main.c -o main `pkg-config gtk+-3.0 --libs``, `main` is created with no warnings or anything, but when I run `./main` I get this warning, and the program ends instantly:
```
(main:93199): Gtk-WARNING **: cannot open display:
```
My computer is a Mid 2012 MacBook Pro running OS X 10.9.5 with a 2.9 GHz Intel Core i7 processor (I really have no idea how much of that information is necessary for this). I just want to resolve this warning so I can get a simple window to display without any problems.
**UPDATE:** I noticed that I installed gtk+ instead of gtk+-3.0, so I ran `~/.local/bin/jhbuild build gtk+-3.0` to install it. When I run `~/.local/bin/jhbuild info gtk+-3.0`, I get:
```
Name: gtk+-3.0
Module Set: gtk-osx
Type: autogen
Install version: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Install date: 2015-01-27 23:49:55
URL: http://ftp.gnome.org/pub/GNOME/sources/gtk+/3.14/gtk+-3.14.5.tar.xz
Version: 3.14.5
Tree-ID: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Sourcedir: ~/gtk/source/gtk+-3.14.5
Requires: glib, pango, atk, gdk-pixbuf, gobject-introspection
Required by: meta-gtk-osx-gtk3, goocanvas2, gtkmm3
After: meta-gtk-osx-bootstrap
Before: gtk-mac-integration
```
I still get the same error, however, even after re-compiling the C program. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28185048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541563/"
] | My recommendation is to extract the meaningful portions of each handler into methods that can be called independently and can have useful return values. This is particularly important for your second button's handler, since the handler for button1 also depends on it.
Upon extracting the code, you can transform the extracted method into a boolean function, and can depend upon the return value to continue your process.
```
private void button1_click(object sender, EventArgs e)
{
ThingToDoForButton1();
}
private void button2_click(object sender, EventArgs e)
{
ThingToDoForButton2();
}
private void ThingToDoForButton1()
{
// do something
if (ThingToDoForButton2())
{
// do something else
}
}
private bool ThingToDoForButton2()
{
//Do something
if(/* some condition */) return false;
//Do something else
return true;
}
```
Of course, it is up to you to provide meaningful names for your methods, once extracted, and to consider breaking down your code into additional smaller functions if the "do something" and "do something else" parts are not insignificant. |
33,818 | I recently bought a Sandisk Cruzer USB drive. Part of the drive (6.66 MB) is formatted with CDFS and shows as a CD drive.
Why do they do this ? Is it to protect the software on that part of the disk to trick the OS (Vista) into not overwriting or amending, because it thinks this is a read-only CD ?
Is the 6.66 MB significant. Apart from being associated with the Devil ?
How can I format a partition on a USB drive to be CDFS ?
Why would I want to do something like that myself on my other flash drives ?
I'm a programmer, so how can I leverage this new knowledge ? Any Ideas ? | 2009/09/01 | [
"https://superuser.com/questions/33818",
"https://superuser.com",
"https://superuser.com/users/7891/"
] | This is part of the U3 software that comes on it. It is garbage and I always remove it, the link for the removal tool is here:<http://u3.com/support/default.aspx#CQ3>
Keep in mind, this will format your drive. |
59,994,928 | We are using the excellent Tabulator JS library. We poll our server at intervals to refresh the data in our table. We are trying to achieve the following behaviour when this happens.
1. Update the existing data in the table
2. Add any new rows that "Match" the current filters
3. Remove any rows that have changed and don't match the filters
4. Keep the existing scroll position
5. Keep any selected rows.
6. If the filters are removed show the latest data.
There are 3 methods to update Tabulator
<http://tabulator.info/docs/4.5/update>
1. SetData (we use this when we first fetch)
2. updateData
3. updateOrAddData (we use this on repeated fetches but row edits don't get filtered out)
4. replaceData
In the documents is mentions that 'replaceData' will update existing table data with out resetting the scroll position or selected rows, this does not seem to be the case. 'updateData' does update the data and leaves the scroll pos and selected rows as is, BUT it does not apply the filters, for example if a row is updated out of the scope of the current filter it still shows?
Our code right now:
```
if (replace) {
table.updateOrAddData(data); //replaceData
} else {
table.setData(data);
}
```
We need the table to update and meet our requirements in my above points 1-6. I would expect one of the methods listed (replace, update) would do this and in the docs it seems they should, but in our tests this fails. How can we achieve the desired results?
We are using version 4.5 downgraded from 4.4.
Edit:
So for example if we update the table with data and one of the rows in the table does not exist in the new data, that update does not persist. Unless we use setData which resets the scroll position, undoes all selected rows and so on. | 2020/01/30 | [
"https://Stackoverflow.com/questions/59994928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141347/"
] | The latest version of Tabulator, 4.9, adds a [refreshFilter](http://tabulator.info/docs/4.9/filter#manage) function. This should accomplish most of your request.
My own testing also show that the sorters are also refreshed by this function.
`table.refreshFilter();` |
7,037,273 | I looking for way to animate text with jQuery.
I want to display 'logging in...' message where 3 dots should be hidden on page load and after every lets say 300ms 1 dot to become visible. Which all together should create animation.
Is there any jQuery function created to do exact that or I will have to right my own?
Any suggestions much appreciated. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7037273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616643/"
] | This can be done rather nicely with a jQuery plugin. This makes it re-usable and configurable.
Something like this is simple enough. It has 3 defaults, which can be overriden
* **text** defaulted to "Loading"
* **numDots** the number of dots to count up to before recycling back to zero, defaults to 3
* **delay** the delay inbetween adding new dots. defaults to 300ms
```
(function($) {
$.fn.elipsesAnimation = function(options) {
var settings = $.extend({}, { //defaults
text: 'Loading',
numDots: 3,
delay: 300
}, options);
var currentText = "";
var currentDots = 0;
return this.each(function() {
var $this = $(this);
currentText = settings.text;
$this.html(currentText);
setTimeout(function() {
addDots($this);
}, settings.delay);
});
function addDots($elem) {
if (currentDots >= settings.numDots) {
currentDots = 0;
currentText = settings.text;
}
currentText += ".";
currentDots++;
$elem.html(currentText);
setTimeout(function() {
addDots($elem);
}, settings.delay);
}
}
})(jQuery);
```
Usage could then be
```
// Writes "Hello World", counts up to 10 dots with a 0.5second delay
$('#testDiv').elipsesAnimation ({text:"Hello World",numDots:10,delay:500});
```
And a live example: <http://jsfiddle.net/6bbKk/> |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Like my answer [here](https://christianity.stackexchange.com/questions/5049/did-adam-and-eves-progeny-commit-incest), you need to keep the chronology right. There is no levitical law at the time of Abraham.
Thus, even if he did marry his sister, remember that he was breaking no covenantal restriction on doing so. As I said in that answer, you don't convict someone of a crime *ex post facto*. |
719,342 | I have no idea how to solve these two, any help?
$\mathtt{i)}$ $$\frac{1}{2\pi i}\int\_{a-i\infty}^{a+i\infty}\frac{e^{tz}}{\sqrt{z+1}}dz$$ $$ a,t\gt0$$
$\mathtt{ii)}$
$$ \sum\_{n=1}^\infty \frac{\coth (n\pi)}{n^3}=\frac{7\pi^3}{180}$$ | 2014/03/20 | [
"https://math.stackexchange.com/questions/719342",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/135386/"
] | I'll do (i). Consider the contour integral
$$\oint\_C dz \frac{e^{t z}}{\sqrt{z+1}}$$
where $C$ is the contour consisting of the line $\Re{z}=a$, $\Im{z} \in [-R,R]$; a circular arc of radius $R$ from $a+i R$ to $R e^{i \pi}$; a line from $R e^{i \pi}$ to $((1+\epsilon) e^{i \pi}$; a circle arc about $z=-1$ of radius $\epsilon$ from $((1+\epsilon) e^{i \pi}$ to $((1+\epsilon) e^{-i \pi}$; a line from $((1+\epsilon) e^{-i \pi}$ to $R e^{-i \pi}$; and a circular arc of radius $R$ from $R e^{-i \pi}$ to $a-i R$. Note that the integrals over all the circular arcs vanish as $R \to \infty$ and $\epsilon \to 0$. Thus we have, by Cauchy's theorem:
$$ \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} + e^{i \pi} e^{-t} \int\_{\infty}^0 dx \, \frac{e^{-t x}}{e^{i \pi/2} \sqrt{x}}+ e^{-i \pi} e^{-t} \int\_{\infty}^0 dx \, \frac{e^{-t x}}{e^{-i \pi/2} \sqrt{x}} =0$$
Thus,
$$\frac1{i 2 \pi} \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} = \frac{1}{\pi} e^{-t} \int\_0^{\infty} dx \, x^{-1/2} \, e^{-x t} $$
Using a substitution $x=u^2$ and a rescaling in the integral, we find that
$$\frac1{i 2 \pi} \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} = \frac{e^{-t}}{\sqrt{\pi t}}$$ |
15,007,104 | I have a script I'm writing that makes a connection to a SOAP service. After the connection is made, I need to pass in a the username/pass with every command I send. The problem I have is that when I use read-host to do this, my password is shown in cleartext and remains in the shell:
```
PS C:\Users\Egr> Read-Host "Enter Pass"
Enter Pass: MyPassword
MyPassword
```
If I hide it with -AsSecureString, the value can no longer be passed to the service because it is now a System.Security.SecureString object:
```
PS C:\Users\gross> Read-Host "Enter Pass" -AsSecureString
Enter Pass: **********
System.Security.SecureString
```
When I pass this, it does not work. I don't care about the passwords being passed to the service in cleartext, I just don't want them sticking around on a user's shell after they enter their password. Is it possible to hide the Read-Host input, but still have the password stored as cleartext? If not, is there a way I can pass the System.Security.SecureString object as cleartext?
Thanks | 2013/02/21 | [
"https://Stackoverflow.com/questions/15007104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776890/"
] | $Password is a Securestring, and this will return the plain text password.
```
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
``` |
39,713,134 | I have a circle, consisting of 12 arc segments and I want to allow the user to see the transition from the start pattern to the end pattern. (there will be many start and end patterns).
I have included the transition property in the css file, so that is not the issue.
Here is my code so far:
```
function playAnimations(){
console.log("gets inside playanimations")
var totalLength = document.getElementsByClassName("container")[0].children.length
console.log(totalLength)
for(var i = 0; i < totalLength; i++){
var current_pattern = document.getElementsByClassName("container")[0].children[i]
for(var j = 0; j < 12; j++){
$('#LED' + (j+1) ).css('transition-duration', '0s');
$('#LED' + (j+1) ).css({fill: current_pattern.children[1].children[j].style.backgroundColor});
}
for(var k = 0; k < 12; k++){
$('#LED' + (k+1) ).css('transition-duration', "" + current_pattern.children[3].children[0].value + "ms");
$('#LED' + (k+1) ).css({fill: current_pattern.children[2].children[k].style.backgroundColor});
}
}
}
```
The outer for loop traverses through all the patterns while the inner two for loops traverse through the start and end values for that particular pattern. The problem I am having is that I only see the end colors on the circle and not the start colors.
Does anyone know a good workaround or what I could possibly do to rectify this issue? Any feedback or help is appreciated. | 2016/09/26 | [
"https://Stackoverflow.com/questions/39713134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162438/"
] | Give your Elements a `transition-delay` value. Of course a different one for each, like this
```
#LED1 {
transition-delay: 0.1s;
}
#LED2 {
transition-delay: 0.2s;
}
...
#LED2 {
transition-delay: 1.2s;
}
```
That should do it. You should be able to set the `transition-duration` directly in the **CSS** as well, no need for JavaScript I think.
Is there a special reason to have 2 inner for loops? Shouldn't one doing both be sufficient? |
4,299,089 | I'm working on a journaling system in C# at our local church, but I've run into trouble with the database connection when storing birth dates. According to [MSDN](http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx?appId=Dev10IDEF1&l=EN-US&k=k%28SYSTEM.DATETIME%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&rd=true) the earlist date possible to represent is January 1st year 1. How am I supposed to record the birth date of Jesus Christ and earlier personalities that are important us? | 2010/11/28 | [
"https://Stackoverflow.com/questions/4299089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523204/"
] | You are going to have to roll your own class to handle BC dates in .NET, and store them in the database either as strings or as separate fields for year, month day (depending on what accuracy is required) if you require searching and sorting to be performed on the database side (which I assume you would).
SQL Server's support for dates is more restrictive than .NET's (it only goes back as far as 1753 or 1752 or thereabouts).
[This blog post](http://blog.flipbit.co.uk/2009/03/representing-large-ad-and-bc-dates-in-c.html) is one possible implementation, albeit a pretty limited one as it only stores the year. But I am sure you could modify it as necessary for your needs. For instance, it could probably do well to implement some interfaces such as IComparable, IEquatable, IFormattable and possibly IConvertible as well if you're keen so it can better interact with the rest of the framework. |
19,814,890 | well this is my problem..
```
<html>
<body>
<marquee id="introtext" scrollamount="150" behavior="slide" direction="left">
<p>
this is the sliding text.
</p>
</marquee>
</body>
</html>
```
What chrome does is just weard.
it repeats the "marquee" action after 4 seconds.
what can i do to prevent this? or just fully disable this marquee but still keep this id ,
because this is used for other css effects?
sincerely,
santino | 2013/11/06 | [
"https://Stackoverflow.com/questions/19814890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2960837/"
] | try loop="0" :
```
<marquee id="introtext" scrollamount="150" behavior="slide" direction="left" loop="0">
``` |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instance variables are shared by all methods in the class. When one method changes the data, another method can be affected by it. It means that you can't understand any one method on its own since it is affected by the code in the other methods in the class. The order in which methods are called can affect the outcome. The methods may not be reentrant. That means that if the method is called, again, before it finishes its execution (say it calls a method that then calls it, or fires an event which then a listener calls the method) then it may fail or behave incorrectly since the data is shared. If that wasn't enough potential problems, when you have multithreading, the data could be changed while you are using it causing inconsistent and hard to reproduce bugs (race conditions).
Using local variables keeps the scope minimized to the smallest amount of code that needs it. This makes it easier to understand, and to debug. It avoids race conditions. It is easier to ensure the method is reentrant. It is a good practice to minimize the scope of data. |
494,571 | I am currently studying for the GRE Physics subject test by working through published past tests. My question is about problem 44 from the test GR8677:
>
> [](https://i.stack.imgur.com/DzNMT.png)
>
>
> $44.$ A uniform stick of length $L$ and mass $M$ lies on a frictionless horizontal surface. A point particle of mass $m$ approaches the stick with speed $v$ on a straight line perpendicular to the stick that intersects the stick at one end, as shown above. After the collision, which is elastic, the particle is at rest. The speed $V$ of the center of mass of the stick after the collision is
>
> (A) $\frac{m}{M}v$
>
> (B) $\frac{m}{M+m}v$
>
> (C) $\sqrt{\frac{m}{M}}v$
>
> (D) $\sqrt{\frac{m}{M+m}}v$
>
> (E) $\frac{3m}{M}v$
>
>
>
My approach was to first write down expressions for the conservation of energy, linear momentum, and angular momentum. The problem states that the particle is at rest after the collision, which simplifies the equations:
$$\frac{1}{2} m v^2 = \frac{1}{2} M V^2 + \frac{1}{2} I \omega^2$$
$$m v = M V$$
$$\frac{1}{2} L m v = I \omega$$
where $I=ML^2/12$ is the moment of inertia of the stick about its CM and $\omega$ is the stick's angular velocity. The most natural next step is to solve the linear momentum equation, giving us the correct answer (A). This is the solution used [here](http://physics-problems-solutions.blogspot.com/2014/04/classical-mechanics-elastic-collision.html) and [here](http://grephysics.net/ans/8677/44).
However, adhering to my penchant for valuing understanding above efficiency, I attempted to verify this answer by combining the other two conservation equations. I solved the angular momentum equation for $\omega$ to obtain $$\omega = \frac{L m v}{2 I}.$$ I then solved the energy equation for $V$ and substituted in this result: $$V^2 = \frac{1}{M}(m v^2 - I \omega^2)$$ $$= \frac{1}{M}\left( m v^2 - I \left( \frac{L m v}{2 I} \right)^2 \right)$$ $$= \frac{1}{M}\left( m v^2 - \frac{(L m v)^2}{4 I} \right)$$ $$= \frac{m v^2}{M}\left( 1 - \frac{L^2 m}{4 (M L^2 / 12)} \right)$$ $$= \frac{m v^2}{M} \left( 1 - 3\frac{m}{M} \right)$$ $$\Longrightarrow V = v \sqrt{ \frac{m}{M} \left( 1 - 3\frac{m}{M} \right) }$$ $$= v \frac{m}{M} \sqrt{ \frac{M}{m} - 3 }$$
I see several problems with this result. First, it does not immediately resemble any of the answers, though it can be made to match either (A) or (E) with a choice of $M/m=4$ or $M/m=12$, respectively. Second, if $M/m < 3$, the velocity of the stick becomes imaginary which (to me) does not have an obvious physical interpretation. I also do not see why there should be any restriction on the mass ratio in the first place.
**Is this approach illegitimate or does it contain an error? If so, why/where? If not, why does the result not coincide with the first approach?**
In the first solution link above, there are many comments going back-and-forth on the reasons for the discrepancy but, frustratingly, no conclusion. Any insights would be greatly appreciated. | 2019/07/31 | [
"https://physics.stackexchange.com/questions/494571",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/237071/"
] | The GRE question seems to be erroneous. You see, if one specifies that the collision is elastic then they cannot also specify what would be the speed of the ball (the mass $m$) after the collision. That over-constraints the problem. That is the reason you are finding inconsistencies in your two ways to approach the problem. Put another way, there are two variables $V$ and $ω$ but there are three equations. So, it is expected that one would find inconsistent solutions.
The correct way to pose the question would be to either delete the word elastic (then the kinetic energy equation goes away and we have two equations for two variables) or to keep the word elastic but do not specify what happens to the ball after the collision (then we will have three variables to solve out of three equations). |
59,344,426 | The input can only include two chemical elements: `C` and `H`
The program must control.
How can I provide that?
```
if (formul.Contains('C') == true && formul.Contains('H') == true)
return true;
```
When my input is `HCA` it is still true. I want it only includes `C` and `H`. | 2019/12/15 | [
"https://Stackoverflow.com/questions/59344426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12278081/"
] | ```cs
using System.Linq; \\put this on top
return formul.All(c => c == 'C' || c == 'H');
```
This will return `true` if all characters of `formul` string are either 'C' or 'H' |
12,091 | Concerning "[Uranium-series dating](https://en.wikipedia.org/wiki/Uranium%E2%80%93thorium_dating)", also known as "Uranium-thorium dating".
Uranium is present in deposits, "typically at levels of between a few parts per billion and few parts per million by weight", according to the wikipedia article on the subject.
As an example, with carbon dating, the amount of carbon-14 originally present in any given sample is consistent with the amount of carbon-14 created by the activity of sunlight in the atmosphere.
How do we know how much uranium-234 was in any given sample of rock when it was created/deposited? | 2017/08/15 | [
"https://earthscience.stackexchange.com/questions/12091",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/10777/"
] | The chemistry of lead is very different from that of uranium and thorium. There are key kinds of rock that could not possibly have been formed with even the smallest amount of primordial lead. The lithophilic nature of uranium and thorium means that those same kinds of rock could easily have readily accepted primordial uranium or thorium.
Any lead in those kinds of rocks must necessarily be the result of decay of uranium or thorium after the rock formed. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | Put all of your "state" data in one place and use a [pickle](http://docs.python.org/library/pickle.html).
>
> The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1](http://docs.python.org/library/pickle.html) or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
>
>
> |
54,186,894 | We are using .NET Core 2.1 and Entity Framework Core 2.1.1
I have the following setup in Azure West Europe
* Azure SQL Database
-- Premium P2 250 DTU
-- Public endpoint, no VNET peering
-- "Allow access to Azure Services" = ON
* Azure Functions
-- Consumption Plan
-- Timeout 10 Minutes
* Azure Blob storage
-- hot tier
Multiple blobs are uploaded to Azure Blob storage, Azure Functions (up to 5 concurrently) are fired via Azure Event Grid. Azure Functions check structure of the blobs against metadata stored in Azure SQL DB. Each blob contains up to 500K records and 5 columns of payload data. For each record Azure Functions makes a call against Azure SQL DB, so no caching.
I am getting often, when multiple blobs are processed in parallel (up to 5 asynchronous Azure Functions call at the same time), and when the blob size is larger 200K-500K records, the following transient and connection errors from .NET Core Entity Framework:
1.
An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
2.
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)
3.
Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. This failure occurred while attempting to connect to the routing destination. The duration spent while attempting to connect to the original server was - [Pre-Login] initialization=13633; handshake=535; [Login] initialization=1; authentication=0; [Post-Login] complete=156; The duration spent while attempting to connect to this server was - [Pre-Login] initialization=5679; handshake=2044;
4.
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)
5. Server provided routing information, but timeout already expired.
At the same time there are any/no health events reported for the Azure SQL Database during the test, and the metrics look awesome: MAX Workers < 3.5%, Sum Successful Connections < 35, MAX Sessions Percentage < 0.045%, Max Log UI percentage < 0.024%, Sum Failed Connections = 0, MAX DTU < 10%, Max Data IO < 0.055%, MAX CPU < 10%.
Running connection stats on Azure SQL DB (sys.database\_connection\_stats\_ex): No failed, aborted or throttled connections.
```
select *
from sys.database_connection_stats_ex
where start_time >= CAST(FLOOR(CAST(getdate() AS float)) AS DATETIME)
order by start_time desc
```
Has anyone faced similar issues in combintation with .Net Core Entity Framework and Azure SQL Database. Why I am getting those transient errors, why Azure SQL Database metrics look so good not reflecting at all that there are issues?
Thanks a lot in advance for any help.
```
using Microsoft.EntityFrameworkCore;
namespace MyProject.Domain.Data
{
public sealed class ApplicationDbContextFactory : IApplicationDbContextFactory
{
private readonly IConfigurationDbConfiguration _configuration;
private readonly IDateTimeService _dateTimeService;
public ApplicationDbContextFactory(IConfigurationDbConfiguration configuration, IDateTimeService dateTimeService)
{
_configuration = configuration;
_dateTimeService = dateTimeService;
}
public ApplicationDbContext Create()
{
//Not initialized in ctor due to unit testing static functions.
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(_configuration.ConfigurationDbConnectionString).Options;
return new ApplicationDbContext(options, _dateTimeService);
}
}
}
``` | 2019/01/14 | [
"https://Stackoverflow.com/questions/54186894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10871024/"
] | I've found this good documentation around sql database transient errors:
* [Working with SQL Database connection issues and transient errors](https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connectivity-issues)
From the documentation:
>
> A transient error has an underlying cause that soon resolves itself. An occasional cause of transient errors is when the Azure system quickly shifts hardware resources to better load-balance various workloads. Most of these reconfiguration events finish in less than 60 seconds. During this reconfiguration time span, you might have connectivity issues to SQL Database. Applications that connect to SQL Database should be built to expect these transient errors. To handle them, implement retry logic in their code instead of surfacing them to users as application errors.
>
>
>
Then it explains in details how to build retry logic for transient errors.
Entity Framework with SQL server implements a retry logic:
```
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer("<connection string>", options => options.EnableRetryOnFailure());
}
```
You can find more information here:
* [EF Core - Connection Resiliency](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency) |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. |
132,551 | I have a Ubuntu 9.10 server. I have installed apache2 and php5 using the apt-get commands.
How does one install php extensions? Are there commands like apt-get to get them? Or should I manually look for the files on the php website and set them up in the php.ini?
More specifically, I need mcrypt, curl and gd.
Thanks | 2010/04/15 | [
"https://serverfault.com/questions/132551",
"https://serverfault.com",
"https://serverfault.com/users/24213/"
] | All you need to do is:
```
sudo apt-get install php5-mcrypt php5-curl php5-gd
```
If you need to check what is installed php-wise you can:
```
dpkg --list | grep php
```
EDIT: Removed sudo in the command above as it's not needed with dpkg --list. |
7,924,782 | I'm searching for following issue i have.
The class file names of our project are named logon.class.php
But the interface file for that class is named logon.interface.php
My issue i have is that when the autoload method runs I should be able to detect if it is a class call or an interface call.
```
<?php
function __autoload($name){
if($name === is_class){
include_once($name.'class.php');
}elseif ($name === is_interface){
include_once($name.'interface.php');
}
}
?>
``` | 2011/10/28 | [
"https://Stackoverflow.com/questions/7924782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896201/"
] | You can use [ReflectionClass::isInterface](http://au.php.net/manual/en/reflectionclass.isinterface.php) to determine if the class is an interface.
```
$reflection = new ReflectionClass($name);
if ($reflection->isInterface()){
//Is an interface
}else{
//Not an interface
}
```
In your case, you would probably have to use `file_exist` first on `$name.interface.php` and `$name.class.php` to determine if they exist, require the one that exists, then check if it's an interface.
However, my opinion is that this might cause problems down the track. What if you have `MyClass.class.php` and `MyClass.interface.php`? |
270,438 | ```
Around[100.123456, 0.12]
```
gives
```
100.12±0.12
```
But
```
Around[100.123456, 0.42]
```
gives
```
100.1±0.4
```
why not `100.12±0.42`. What is the rule for `Around` to show number of significant digits in uncertainty?
**Update**
I found it seems that `Around` take 35 as a boundary for uncertainty, no matter what the value is. So
```
Around[1, 0.35]
```
gives
```
1.00±0.35
```
and
```
Around[1, 0.36]
```
gives
```
1.0±0.4
```
But the problem is I did not see rule like this in the definite guide GUM(Guide to the Expression of Uncertainty in Measurement). Is there other reference has this rule for uncertainty report? | 2022/07/06 | [
"https://mathematica.stackexchange.com/questions/270438",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4742/"
] | TL;DR
=====
The number of significant figures displayed both for the value and its uncertainty depends on the value of the uncertainty. The details are not documented, but there seems to be a threshold around $0.35\* 10^n$
##### EDIT
An important comment by Greg Hurst
>
> The threshold seems to be 35.5, not 35, and is set with
> `Language`UncertaintyDump`$UDT == 35.5` (on V13.2 at least). You can
> change the value of this variable to move the threshold elsewhere. –
>
>
>
Scope
=====
As pointed out by @JimB, this is a display-only issue, the internal representation of the values is not changed.
Wolfram usually does not document the details of the internal implementations of Mathematica. So the scope of the answer necessarily is restricted to what is documented and what can be observed. I will not engage on speculation.
Documentation
=============
The documentation for [`Around`](https://reference.wolfram.com/language/ref/Around.html) [reads](https://reference.wolfram.com/language/ref/Around.html?view=all#:%7E:text=the%20numbers%20faithfully.-,Around%5Bx,right%20of%20the%20decimal%20point%20as%20is%20shown%20in%20%CE%B4.,-In%20Around%5B)
>
> `Around[x,δ]` displays with one or two digits of the uncertainty δ shown; x is shown with the same number of digits to the right of the decimal point as is shown in δ.
>
>
>
[](https://i.stack.imgur.com/0AUhk.png)
Other display formats exist too
>
> `Around[x,δ]` is typically displayed as `x±δ`. If `δ` is very small compared to `x`, as in `Around[1.2345678,0.0000012]`, it is instead displayed in a form like `1.23456(78±12)`.
>
>
>
[](https://i.stack.imgur.com/rKATD.png)
That is the extent of the explanation provided, details of the implementation are not explained.
Expected behaviour
==================
The criteria should be to keep the *Precision* and *Accuracy* coherent. There is no point in having many decimal points that are within the uncertainty of the value.
The number of significant figures (precision) should be dependent upon the uncertainty of the value (accuracy).
Observed behaviour
==================
One can observe that once is decided the number of significant digits on the value, the uncertainty is also displayed with the same number of significant digits, as expected and discussed in the previous title.
The seems to be a preferred threshold
```
TableForm[
Around[100.11111111111, #]&/@{0.035, 0.036, 0.35,0.36,3.5, 3.6 }
]
```
[](https://i.stack.imgur.com/vp3ZH.png) |
27,863,830 | Is there a way using `CSS3` or `javascript` to highlight a table row containing 2 elements where each table element is highlighted a different background color upon hovering over that row?
So for example you have a table row with two values like
```
1.45 | 2.56
```
and the table element containing `1.45` would have a blue background and element containing `2.56` would be red.
At the moment I have it so it changes the background color for the entire row like so:
```
.graph-table tbody > tr:hover {
background-color: #6ab1b0;
}
``` | 2015/01/09 | [
"https://Stackoverflow.com/questions/27863830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3922295/"
] | Use [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-ch) selector, like this:
```css
td {
padding: 15px;
}
tr:hover td {
background-color: red;
color: white;
cursor:pointer;
}
tr:hover td:nth-child(1) {
background-color: blue;
}
```
```html
<table>
<tr>
<td>2.00</td>
<td>3.45</td>
</tr>
</table>
``` |
1,317,256 | I'm trying to learn BNF and attempting to assemble some Z80 ASM code. Since I'm new to both fields, my question is, am I even on the right track? I am trying to write the format of Z80 ASM as EBNF so that I can then figure out where to go from there to create machine code from the source. At the moment I have the following:
```
Assignment = Identifier, ":" ;
Instruction = Opcode, [ Operand ], [ Operand ] ;
Operand = Identifier | Something* ;
Something* = "(" , Identifier, ")" ;
Identifier = Alpha, { Numeric | Alpha } ;
Opcode = Alpha, Alpha ;
Int = [ "-" ], Numeric, { Numeric } ;
Alpha = "A" | "B" | "C" | "D" | "E" | "F" |
"G" | "H" | "I" | "J" | "K" | "L" |
"M" | "N" | "O" | "P" | "Q" | "R" |
"S" | "T" | "U" | "V" | "W" | "X" |
"Y" | "Z" ;
Numeric = "0" | "1" | "2" | "3"| "4" |
"5" | "6" | "7" | "8" | "9" ;
```
Any directional feedback if I am going wrong would be excellent. | 2009/08/22 | [
"https://Stackoverflow.com/questions/1317256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385364/"
] | Old-school assemblers were typically hand-coded in assembler and used adhoc parsing techniques to process assembly source lines to produce actual assembler code.
When assembler syntax is simple (e.g. always OPCODE REG, OPERAND) this worked well enough.
Modern machines have messy, nasty instruction sets with lots of instruction variations and operands, which may be expressed with complex syntax allowing multiple index registers to participate in the operand expression. Allowing sophisticated assembly-time expressions with fixed and relocatable constants with various types of addition operators complicates this. Sophisticated assemblers allowing conditional compilation, macros, structured data declarations, etc. all add new demands on syntax. Processing all this syntax by ad hoc methods is very hard and is the reason that parser generators were invented.
Using a BNF and a parser generator is very reasonable way to build a modern assembler, even for a legacy processor such as the Z80. I have built such assemblers for Motorola 8 bit machines such as the 6800/6809, and am getting ready to do the same for a modern x86. I think you're headed down exactly the right path.
\*\*\*\*\*\*\*\*\*\* EDIT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
The OP asked for example lexer and parser definitions.
I've provided both here.
These are excerpts from real specifications for a 6809 asssembler.
The complete definitions are 2-3x the size of the samples here.
To keep space down, I have edited out much of the dark-corner complexity
which is the point of these definitions.
One might be dismayed by the apparant complexity; the
point is that with such definitions, you are trying to *describe* the
shape of the language, not code it procedurally.
You will pay a significantly higher complexity if you
code all this in an ad hoc manner, and it will be far
less maintainable.
It will also be of some help to know that these definitions
are used with a high-end program analysis system that
has lexing/parsing tools as subsystems, called the
[The DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html). DMS will automatically build ASTs from the
grammar rules in the parser specfication, which makes it a
lot easier to buid parsing tools. Lastly,
the parser specification contains so-called "prettyprinter"
declarations, which allows DMS to regenreate source text from the ASTs.
(The real purpose of the grammer was to allow us to build ASTs representing assembler
instructions, and then spit them out to be fed to a real assembler!)
One thing of note: how lexemes and grammar rules are stated (the metasyntxax!)
varies somewhat between different lexer/parser generator systems. The
syntax of DMS-based specifications is no exception. DMS has relatively sophisticated
grammar rules of its own, that really aren't practical to explain in the space available here. You'll have to live with idea that other systems use similar notations, for
EBNF for rules and and regular expression variants for lexemes.
Given the OP's interests, he can implement similar lexer/parsers
with any lexer/parser generator tool, e.g., FLEX/YACC,
JAVACC, ANTLR, ...
\*\*\*\*\*\*\*\*\*\* LEXER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.lex: Lexical Description for M6809
-- Copyright (C) 1989,1999-2002 Ira D. Baxter
%%
#mainmode Label
#macro digit "[0-9]"
#macro hexadecimaldigit "<digit>|[a-fA-F]"
#macro comment_body_character "[\u0009 \u0020-\u007E]" -- does not include NEWLINE
#macro blank "[\u0000 \ \u0009]"
#macro hblanks "<blank>+"
#macro newline "\u000d \u000a? \u000c? | \u000a \u000c?" -- form feed allowed only after newline
#macro bare_semicolon_comment "\; <comment_body_character>* "
#macro bare_asterisk_comment "\* <comment_body_character>* "
...[snip]
#macro hexadecimal_digit "<digit> | [a-fA-F]"
#macro binary_digit "[01]"
#macro squoted_character "\' [\u0021-\u007E]"
#macro string_character "[\u0009 \u0020-\u007E]"
%%Label -- (First mode) processes left hand side of line: labels, opcodes, etc.
#skip "(<blank>*<newline>)+"
#skip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
#precomment "<comment_line><newline>"
#preskip "(<blank>*<newline>)+"
#preskip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
-- Note that an apparant register name is accepted as a label in this mode
#token LABEL [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoLabelList ?)
>>
%%OpcodeField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Opcode field tokens
#token 'ABA' "[aA][bB][aA]"
<< (GotoEOLComment ?) >>
#token 'ABX' "[aA][bB][xX]"
<< (GotoEOLComment ?) >>
#token 'ADC' "[aA][dD][cC]"
<< (GotoABregister ?) >>
#token 'ADCA' "[aA][dD][cC][aA]"
<< (GotoOperand ?) >>
#token 'ADCB' "[aA][dD][cC][bB]"
<< (GotoOperand ?) >>
#token 'ADCD' "[aA][dD][cC][dD]"
<< (GotoOperand ?) >>
#token 'ADD' "[aA][dD][dD]"
<< (GotoABregister ?) >>
#token 'ADDA' "[aA][dD][dD][aA]"
<< (GotoOperand ?) >>
#token 'ADDB' "[aA][dD][dD][bB]"
<< (GotoOperand ?) >>
#token 'ADDD' "[aA][dD][dD][dD]"
<< (GotoOperand ?) >>
#token 'AND' "[aA][nN][dD]"
<< (GotoABregister ?) >>
#token 'ANDA' "[aA][nN][dD][aA]"
<< (GotoOperand ?) >>
#token 'ANDB' "[aA][nN][dD][bB]"
<< (GotoOperand ?) >>
#token 'ANDCC' "[aA][nN][dD][cC][cC]"
<< (GotoRegister ?) >>
...[long list of opcodes snipped]
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoOperandField ?)
>>
#token '#' "\#" -- special constant introduction (FDB)
<< (GotoDataField ?) >>
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token CHARACTER [CHARACTER] "<squoted_character>"
<< (= ?:Lexeme:Literal:Character:Value (TokenStringCharacter ? 2))
(= ?:Lexeme:Literal:Character:Format (LiteralFormat:MakeCompactCharacterLiteralFormat 0 0)) ; nothing special about character
(GotoOperandField ?)
>>
%%OperandField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Tokens signalling switch to index register modes
#token ',' "\,"
<<(GotoRegisterField ?)>>
#token '[' "\["
<<(GotoRegisterField ?)>>
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '//' "\/\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '</' "\<\/"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>/' "\>\/"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
-- Notice that an apparent register is accepted as a label in this mode
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
>>
%%Register -- operand field for TFR, ANDCC, ORCC, EXG opcodes
#skip "<hblanks>"
#ifnotoken << (GotoRegisterField ?) >>
%%RegisterField -- handles registers and indexing mode syntax
-- In this mode, names that look like registers are recognized as registers
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
#token '[' "\["
#token ']' "\]"
#token '--' "\-\-"
#token '++' "\+\+"
#token 'A' "[aA]"
#token 'B' "[bB]"
#token 'CC' "[cC][cC]"
#token 'DP' "[dD][pP] | [dD][pP][rR]" -- DPR shouldnt be needed, but found one instance
#token 'D' "[dD]"
#token 'Z' "[zZ]"
-- Index register designations
#token 'X' "[xX]"
#token 'Y' "[yY]"
#token 'U' "[uU]"
#token 'S' "[sS]"
#token 'PCR' "[pP][cC][rR]"
#token 'PC' "[pP][cC]"
#token ',' "\,"
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '<|' "\<\|"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>|' "\>\|"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
... [snip]
%% -- end M6809.lex
```
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* PARSER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.ATG: Motorola 6809 assembly code parser
-- (C) Copyright 1989;1999-2002 Ira D. Baxter; All Rights Reserved
m6809 = sourcelines ;
sourcelines = ;
sourcelines = sourcelines sourceline EOL ;
<<PrettyPrinter>>: { V(CV(sourcelines[1]),H(sourceline,A<eol>(EOL))); }
-- leading opcode field symbol should be treated as keyword.
sourceline = ;
sourceline = labels ;
sourceline = optional_labels 'EQU' expression ;
<<PrettyPrinter>>: { H(optional_labels,A<opcode>('EQU'),A<operand>(expression)); }
sourceline = LABEL 'SET' expression ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),A<opcode>('SET'),A<operand>(expression)); }
sourceline = optional_label instruction ;
<<PrettyPrinter>>: { H(optional_label,instruction); }
sourceline = optional_label optlabelleddirective ;
<<PrettyPrinter>>: { H(optional_label,optlabelleddirective); }
sourceline = optional_label implicitdatadirective ;
<<PrettyPrinter>>: { H(optional_label,implicitdatadirective); }
sourceline = unlabelleddirective ;
sourceline = '?ERROR' ;
<<PrettyPrinter>>: { A<opcode>('?ERROR'); }
optional_label = labels ;
optional_label = LABEL ':' ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),':'); }
optional_label = ;
optional_labels = ;
optional_labels = labels ;
labels = LABEL ;
<<PrettyPrinter>>: { A<firstlabel>(LABEL); }
labels = labels ',' LABEL ;
<<PrettyPrinter>>: { H(labels[1],',',A<otherlabels>(LABEL)); }
unlabelleddirective = 'END' ;
<<PrettyPrinter>>: { A<opcode>('END'); }
unlabelleddirective = 'END' expression ;
<<PrettyPrinter>>: { H(A<opcode>('END'),A<operand>(expression)); }
unlabelleddirective = 'IF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFDEF' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFDEF'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFUND' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFUND'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'INCLUDE' FILENAME ;
<<PrettyPrinter>>: { H(A<opcode>('INCLUDE'),A<operand>(FILENAME)); }
unlabelleddirective = 'LIST' expression ;
<<PrettyPrinter>>: { H(A<opcode>('LIST'),A<operand>(expression)); }
unlabelleddirective = 'NAME' IDENTIFIER ;
<<PrettyPrinter>>: { H(A<opcode>('NAME'),A<operand>(IDENTIFIER)); }
unlabelleddirective = 'ORG' expression ;
<<PrettyPrinter>>: { H(A<opcode>('ORG'),A<operand>(expression)); }
unlabelleddirective = 'PAGE' ;
<<PrettyPrinter>>: { A<opcode>('PAGE'); }
unlabelleddirective = 'PAGE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('PAGE'),A<operand>(HEADING)); }
unlabelleddirective = 'PCA' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCA'),A<operand>(expression)); }
unlabelleddirective = 'PCC' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCC'),A<operand>(expression)); }
unlabelleddirective = 'PSR' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PSR'),A<operand>(expression)); }
unlabelleddirective = 'TABS' numberlist ;
<<PrettyPrinter>>: { H(A<opcode>('TABS'),A<operand>(numberlist)); }
unlabelleddirective = 'TITLE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('TITLE'),A<operand>(HEADING)); }
unlabelleddirective = 'WITH' settings ;
<<PrettyPrinter>>: { H(A<opcode>('WITH'),A<operand>(settings)); }
settings = setting ;
settings = settings ',' setting ;
<<PrettyPrinter>>: { H*; }
setting = 'WI' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'DE' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'M6800' ;
setting = 'M6801' ;
setting = 'M6809' ;
setting = 'M6811' ;
-- collects lines of conditional code into blocks
conditional = 'ELSEIF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSEIF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional[1])); }
conditional = 'ELSE' EOL else ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSE'),A<eol>(EOL)),CV(else)); }
conditional = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
conditional = sourceline EOL conditional ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(conditional[1])); }
else = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
else = sourceline EOL else ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(else[1])); }
-- keyword-less directive, generates data tables
implicitdatadirective = implicitdatadirective ',' implicitdataitem ;
<<PrettyPrinter>>: { H*; }
implicitdatadirective = implicitdataitem ;
implicitdataitem = '#' expression ;
<<PrettyPrinter>>: { A<operand>(H('#',expression)); }
implicitdataitem = '+' expression ;
<<PrettyPrinter>>: { A<operand>(H('+',expression)); }
implicitdataitem = '-' expression ;
<<PrettyPrinter>>: { A<operand>(H('-',expression)); }
implicitdataitem = expression ;
<<PrettyPrinter>>: { A<operand>(expression); }
implicitdataitem = STRING ;
<<PrettyPrinter>>: { A<operand>(STRING); }
-- instructions valid for m680C (see Software Dynamics ASM manual)
instruction = 'ABA' ;
<<PrettyPrinter>>: { A<opcode>('ABA'); }
instruction = 'ABX' ;
<<PrettyPrinter>>: { A<opcode>('ABX'); }
instruction = 'ADC' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','A')),A<operand>(operandfetch)); }
instruction = 'ADC' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','B')),A<operand>(operandfetch)); }
instruction = 'ADCA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCA'),A<operand>(operandfetch)); }
instruction = 'ADCB' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCB'),A<operand>(operandfetch)); }
instruction = 'ADCD' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCD'),A<operand>(operandfetch)); }
instruction = 'ADD' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','A')),A<operand>(operandfetch)); }
instruction = 'ADD' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','B')),A<operand>(operandfetch)); }
instruction = 'ADDA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADDA'),A<operand>(operandfetch)); }
[..snip...]
-- condition code mask for ANDCC and ORCC
conditionmask = '#' expression ;
<<PrettyPrinter>>: { H*; }
conditionmask = expression ;
target = expression ;
operandfetch = '#' expression ; --immediate
<<PrettyPrinter>>: { H*; }
operandfetch = memoryreference ;
operandstore = memoryreference ;
memoryreference = '[' indexedreference ']' ;
<<PrettyPrinter>>: { H*; }
memoryreference = indexedreference ;
indexedreference = offset ;
indexedreference = offset ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '--' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '-' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '++' ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '+' ;
<<PrettyPrinter>>: { H*; }
offset = '>' expression ; -- page zero ref
<<PrettyPrinter>>: { H*; }
offset = '<' expression ; -- long reference
<<PrettyPrinter>>: { H*; }
offset = expression ;
offset = 'A' ;
offset = 'B' ;
offset = 'D' ;
registerlist = registername ;
registerlist = registerlist ',' registername ;
<<PrettyPrinter>>: { H*; }
registername = 'A' ;
registername = 'B' ;
registername = 'CC' ;
registername = 'DP' ;
registername = 'D' ;
registername = 'Z' ;
registername = indexregister ;
indexregister = 'X' ;
indexregister = 'Y' ;
indexregister = 'U' ; -- not legal on M6811
indexregister = 'S' ;
indexregister = 'PCR' ;
indexregister = 'PC' ;
expression = sum '=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '</' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>/' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '#' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum ;
sum = product ;
sum = sum '+' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '-' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!!' product ;
<<PrettyPrinter>>: { H*; }
product = term '*' product ;
<<PrettyPrinter>>: { H*; }
product = term '||' product ; -- wrong?
<<PrettyPrinter>>: { H*; }
product = term '/' product ;
<<PrettyPrinter>>: { H*; }
product = term '//' product ;
<<PrettyPrinter>>: { H*; }
product = term '&' product ;
<<PrettyPrinter>>: { H*; }
product = term '##' product ;
<<PrettyPrinter>>: { H*; }
product = term ;
term = '+' term ;
<<PrettyPrinter>>: { H*; }
term = '-' term ;
<<PrettyPrinter>>: { H*; }
term = '\\' term ; -- complement
<<PrettyPrinter>>: { H*; }
term = '&' term ; -- not
term = IDENTIFIER ;
term = NUMBER ;
term = CHARACTER ;
term = '*' ;
term = '(' expression ')' ;
<<PrettyPrinter>>: { H*; }
numberlist = NUMBER ;
numberlist = numberlist ',' NUMBER ;
<<PrettyPrinter>>: { H*; }
``` |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | There's a much simpler solution right now:
```
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
```
This way, the `http` package automatically knows: "Ah, I shouldn't follow any redirects", but does not throw any error. From the comment in the source code:
>
> As a special case, if CheckRedirect returns ErrUseLastResponse,
> then the most recent response is returned with its body
> unclosed, along with a nil error.
>
>
> |
33,511,462 | I have to write a code that counts the number of odd numbers, even numbers, and zeros in a multi-digit long variable, here is what I have so far:
```
#include <iostream>
using namespace std;
int lab14(long num, int &even, int &odd, int &zero){
while (num > 0){
long w = num;
w = num%10;
if (w % 2 == 1){
odd++;
}
else if (w % 2 == 0 && w != 0){
even++;
}
else if (w == 0 ){
zero++;
}
num = num/10;
}
return odd;
return even;
return zero;
}
int main() {
int even = 0, odd = 0, zero = 0;
int num;
cout << "#############################" << endl;
cout << "## Even, odd, zero counter " << endl;
bool flag = true;
while (flag){
cout << "## Please enter a #: "; cin >>num;
lab14(num, even, odd, zero);
cout << "## Even numbers: "<< even << endl
<< "## Odd Numbers: " << odd << endl
<< "## Zeros: " << zero << endl;
cout << "## Enter 1 to go again, 0 to exit: "; cin >> flag ; cout << endl;
}
return 0;
}
```
For some reason, I'm getting really weird outputs. Can anyone help me out, for example:
```
## Please enter a #: 245
## Even numbers: 3
## Odd Numbers: 13
## Zeros: 0
## Enter 1 to go again, 0 to exit: 1
## Please enter a #: 342
## Even numbers: 5
## Odd Numbers: 14
## Zeros: 0
## Enter 1 to go again, 0 to exit:
``` | 2015/11/04 | [
"https://Stackoverflow.com/questions/33511462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505001/"
] | As I mentioned in my [comment](https://stackoverflow.com/questions/33511461/how-do-i-dereference-this-hash-in-perl#comment54806600_33511461), you're flattening a list when you create `%hash`. The fat comma (`=>`) is a synonym for the comma that causes barewords on the left to be interpreted as strings, but it doesn't matter in this case because you've already got a string on the left. In effect, your hash assignment really looks like this:
```
my %hash = ("a", 1, 2, 3, "b", 3, 4, 5);
```
It looks like you were trying to assign arrays to `a` and `b`, but in Perl, hash values are always scalars, so you need to use references to anonymous arrays instead:
```
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
```
It's also worth noting that your subroutine is making a shallow copy of the hash reference you pass in, which may have unintended/unforeseen consequences. Consider the following:
```
use Data::Dump;
sub giveMeARef {
my %hash = %{$_[0]};
pop(@{$hash{a}});
}
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
dd(\%hash);
giveMeARef(\%hash);
dd(\%hash);
```
Which outputs:
```
{ a => [1, 2, 3], b => [3, 4, 5] }
{ a => [1, 2], b => [3, 4, 5] }
``` |
38,708,129 | I have a QML file that imports a JavaScript library:
```
import "qrc:/scripts/protobuf.js" as PB
```
This library [modifies the 'global' object](https://github.com/dcodeIO/protobuf.js/blob/master/dist/protobuf.js#L29) during setup. Simplified, the JS library is:
```
.pragma library
(function(global){
global.dcodeIO = global.dcodeIO || {};
global.dcodeIO.ProtoBuf = {}; // In reality, a complex object
})(this);
```
On Windows and Linux this works as expected; later in my QML file I write `var ProtoBuf = PB.dcodeIO.ProtoBuf;` and it finds the `dcodeIO` property added to the 'global' object and properly gives me the object I need.
However, on another platform, the same code does not work. I get an error that it `cannot read property ProtoBuf of undefined`. I add debugging lines to my QML and see:
```
console.log(PB.dcodeIO); //-> undefined
for (var k in PB) console.log(k,PB[k]); //-> (no enumerable properties logged)
```
Yet, the JavaScript code in the library is loaded and runs. Within the library if I add `console.log(global.dcodeIO)` after the line linked above I see `[object Object]`.
What might the difference be? How can I determine why Qt is running my JavaScript file, but not successfully associating the global object with `PB`? | 2016/08/01 | [
"https://Stackoverflow.com/questions/38708129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405017/"
] | The points listed under [JavaScript Environment Restrictions](http://doc.qt.io/qt-5/qtqml-javascript-hostenvironment.html#javascript-environment-restrictions) could be relevant here:
>
> JavaScript code cannot modify the global object.
>
>
> In QML, the global object is constant - existing properties cannot be modified or deleted, and no new properties may be created.
>
>
> ...
>
>
> Any attempt to modify the global object - either implicitly or explicitly - will cause an exception. If uncaught, this will result in an warning being printed, that includes the file and line number of the offending code.
>
>
>
Although you said it's working on two platforms, just not a third, so perhaps your usage is correct and it's a bug.
There's also this point:
>
> Global code is run in a reduced scope.
>
>
>
Though that point seems to be about accessing QML objects from the loaded script.
The documentation has always been unclear to me on this subject. <http://doc.qt.io/qt-5/qjsengine.html#globalObject> says:
>
> Returns this engine's Global Object.
>
>
> By default, the Global Object contains the built-in objects that are part of ECMA-262, such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code. Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.
>
>
>
Which seems to contradict the restriction listed above. There's also [this](http://doc.qt.io/qt-5/qtqml-javascript-qmlglobalobject.html):
>
> Note: The globalObject() function cannot be used to modify the global object of a QQmlEngine. For more information about this, see JavaScript Environment Restrictions.
>
>
> |
56,412,227 | My angular 7 app is running using `ng serve` on port 4200. I have a node server running inside of a docker container, located at localhost:8081.
I have verified that the server is up, and accessible, using postman. The url was `localhost:8081/login`. I was able to receive the data I expected when the POST request was submitted.
When I click the login button in my login.html form, it calls `onSubmit()` from the login component class. This calls `login()`, which then calls a function from the authentication service which creates a POST request to `localhost:8081/login`.
**login.component.ts**
```
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private authenticationService: AuthenticationService) { }
loginForm = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
ngOnInit() {
}
// Called when login form submits
onSubmit() {
this.login();
}
login() : void {
this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value);
}
}
```
**authentication.service.ts**
```
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../models/user';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
private currentUser: Observable<User>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(email: string, password: string) {
return this.http.post<any>('localhost:8081/login', {email, password})
.pipe(map(user => {
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
```
Finally, my node server's endpoint that is being called.
**account.js**
```
// Verifies that the email and password exist in the database.
app.post('/login', (req, res) => {
console.log("in login post");
res.json({ firstName: 'test', lastName: 'user', email: '[email protected]', password: 'pass' });
});
```
I removed the other logic so that I can test this with the simplest case; just returning hard coded values.
When I make the request with postman, I see that "in login post" is logged. However, when I make the request from Angular, "in login post" is NOT logged.
Why can I not reach the endpoint from Angular, but I can from postman? The address & port are the same. | 2019/06/02 | [
"https://Stackoverflow.com/questions/56412227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5237611/"
] | As mentioned by @Austaras, an `Observable` must have at least one active subscription in order to execute it.
You must subscribe to the `login()` method of `AuthenticationService` in the `LoginComponent`
```
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private authenticationService: AuthenticationService) { }
loginForm = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
ngOnInit() {
}
// Called when login form submits
onSubmit() {
this.login();
}
login() : void {
this.authenticationService
.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value)
.subscribe( // <-- Subscription required here
(res) => {
console.log(res);
});
}
}
```
Read more about [Observables](https://medium.com/@luukgruijs/understanding-creating-and-subscribing-to-observables-in-angular-426dbf0b04a3) |
65,379,890 | I have a database with four tables and I want my PHP to execute the query dynamically for one of these tables, based on the user's input.
```
$company = $_POST['company'];
$model = $_POST['model'];
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "ref";
if ($company == "ford") {
$table = "ref_ford";
} else if ($company = "hyundai") {
$table == "ref_hyundai";
} else if ($company = "renault") {
$table == "ref_renault";
} else {
$table = "ref_fiat";
}
```
With this code, PHP doesn´t recognize the table, as when I selected it manually
```
$table = "ref_ford"
```
it does the query correctly.
I´ve also tried several different comparisons, both `==`and `===`, as well as,
```
$company == $_POST["ford"]
```
Any idea on how can I select the table based on the user's input?
```
<select name="company">
<option value = "ford">Ford</option>
<option value = "hyundai">Hyundai</option>
<option value = "renault">Renault</option>
<option value = "fiat">Fiat</option>
</select>
``` | 2020/12/20 | [
"https://Stackoverflow.com/questions/65379890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14857827/"
] | The problem has already been pointed out (in your if-statements, you have `=` when it should be `==` and `==` where it should be `=`) so I just wanted to show a, in my opinion, cleaner way of doing the same thing.
I would be to use an array for this. It's not only easier to read the relationships, but it also makes it easier to add/remove companies. Just add/remove them from the array.
```
$companyTables = [
'ford' => 'ref_ford',
'hyundai' => 'ref_hyundai',
'renault' => 'ref_renault',
'fiat' => 'ref_fiat',
];
// This will return the correct table if the array key exists, otherwise default to `fiat`.
$table = $companyTables[$company] ?? $companyTables['fiat'];
```
This would do the same as your current `if/else`'s. |
14,468,001 | Output I'm getting:
* The base array
* 7290 5184 6174 8003 7427 2245 6522 6669 8939 4814 The
* Sorted array
* -33686019 2245 4814 5184 6174 6522 6669 7290 7427 8003
* Press any key to continue . . .
I have no idea where this, -33686019, number is coming from. I've posted all of the code because I really don't know what could be causing it.
The Bubble Sort:
```
#include "Sorting.h"
double Sorting::bubbleSort( int size )
{
//Make a copy of our "master key" array for us to sort
int *toSort = whichArray(size);
int *theArray = copyArray( toSort, size );
double time;
cout << "The base array" << endl;
for(int i = 0; i < 10; i++ )
{
cout << theArray[i] << endl;
}
//The sort
//Begin time
timer.startClock();
bool swapped = true;
int temp = 0;
while( swapped == true )
{
swapped = false;
for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
{
/*temp = theArray[i+1];
theArray[i+1] = theArray[i];
theArray[i] = temp;*/
swap(theArray[i + 1], theArray[i]);
swapped = true;
}
}
}
time = timer.getTime();
cout << "The Sorted array" << endl;
for(int x = 0; x < 10; x++ )
{
cout << theArray[x] << endl;
}
return time;
}
```
The Sorting Class:
```
#ifndef SORTING_H
#define SORTING_H
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//^For random numbers
#include <iostream>
#include "TimerSystem.h"
#include <iomanip>
using namespace std;
class Sorting
{
private:
//The below pointers will point to arrays that hold the data sets
int *n10;
int *n100;
int *n1000;
int *n10000;
TimerSystem timer;
double runs[4][4];
public:
Sorting();
~Sorting(){};
//Testing functions
void printArray();
void print2DArray();
void dryRun();
//Data manging and creating
int randomNumGen();
int* arrayGen( int size );//Returning a pointer
int* copyArray( int *toCopy, int size );//Makes an array that the program can sort. The leaves the original array intact
int* whichArray( int size );
void datasetRun( int whichSort );//Does three runs of a sort and gets the average for all 4 array sizes
//Sorts
double bubbleSort( int size );
};
#endif
```
Other Called Functions:
```
#include "Sorting.h"
int Sorting::randomNumGen()
{
int randomNumber = rand() % 10000 + 1;
if( randomNumber > 10000 || randomNumber < 0 )
{
system("pause");
}
return randomNumber;
}
int* Sorting::arrayGen( int size )
{
int *theArray= new int[size];
for( int i = 0; i < size; i++ )
{
theArray[i] = randomNumGen();
}
return theArray;
}
int* Sorting::copyArray( int *toCopy, int size )
{
int *newArray = new int[size];
for( int i = 0; i < size; i++ )
{
newArray[i] = toCopy[i];
}
return newArray;
}
int* Sorting::whichArray( int size )
{
if( size == 10 )
{
return n10;
}
else if( size == 100 )
{
return n100;
}
else if( size == 1000 )
{
return n100;
}
else if( size == 10000 )
{
return n1000;
}
return NULL;
}
void Sorting::datasetRun( int whichSort )
{
//1: Bubble
//2: Insertion
//3: Selection
//4: Shell
//5: Quick
//6: Merge
int col = 0;
int row = 0;
int set = 10;
bool runDone = false;
if( whichSort == 1 )
{
for( int row = 0; row < 4; row++ )
{
for( int col = 0; col < 4; col++ )
{
runs[row][col] = bubbleSort( set );
}
//set = set * 10;
}
}
}
//Constructor
Sorting::Sorting()
{
//For the random number generator
srand( time(NULL) );
n10 = arrayGen( 10 );
n100 = arrayGen( 100 );
n1000 = arrayGen( 1000 );
n10000 = arrayGen( 10000 );
}
//Functions for testing
void Sorting::printArray()
{
int size = 10000;
for( int i = 0; i < size; i++ )
{
cout << n10000[i] << " ";
}
}
void Sorting::print2DArray()
{
for( int height = 0; height < 4; height++ )
{
for( int width = 0; width < 4; width++ )
{
cout << runs[height][width] << endl;
}
cout << "\n\n";
}
}
```
The Main Function:
```
#include "Sorting.h"
void main()
{
//Makes the numbers easily readable
cout.setf(ios::fixed | ios::showpoint);
cout.precision(16);
Sorting theSorting;
//theSorting.printArray();
//cout << theSorting.bubbleSort( 10 ) << endl;
//theSorting.datasetRun(1);
//theSorting.print2DArray();
theSorting.bubbleSort( 10 );
system("pause");
}
``` | 2013/01/22 | [
"https://Stackoverflow.com/questions/14468001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715979/"
] | The following bit is not correct:
```
for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
```
It is accessing one beyond the boundary of the array. The `for` loop should probably be:
```
for( int i = 0; i < size - 1; i++ )
``` |
701,086 | I am running a 10.04LTE server where I do want to upgrade openssl for apache.
Therefore I downloaded openssl 1.0.2c and apache 2.2.29 and compiled both. The server is starting, but is using the old ssl version:
```
curl --head http://localhost
HTTP/1.1 200 OK
Date: Mon, 22 Jun 2015 06:00:06 GMT
Server: Apache/2.2.29 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8k
Last-Modified: Sun, 18 Mar 2012 19:56:07 GMT
```
However, Openssl is installed in new version:
```
/usr/local/ssl/bin/openssl version
OpenSSL 1.0.2c 12 Jun 2015
```
While the original version stayes in place:
```
openssl version
OpenSSL 0.9.8k 25 Mar 2009
```
I compiled apache with:
```
./configure --with-included-apr --prefix=/usr/local/apache2 --enable-so
--enable-rewrite --with-ssl=/usr/local/ssl --enable-ssl=shared
--enable-deflate --enable-expires --enable-headers
```
Apache did not start before I included:
```
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so
```
According to the mod ssl website this is only available for apache 1.x
Not sure what is going wrong here. Thank you for any help! | 2015/06/23 | [
"https://serverfault.com/questions/701086",
"https://serverfault.com",
"https://serverfault.com/users/84332/"
] | The problem is that your Apache installation is unable to link the shared libraries of your new OpenSSL installation. Run the command `ldd /usr/local/apache/modules/mod_ssl.so` (with the apporpriate path to your mod\_ssl.so). You'll see that mod\_ssl.so is not linking to the libraries in `/usr/local/ssl/lib`
You have a couple options to fix the problem:
**Option #1 - Link in the libraries:**
Open `/etc/ld.so.conf.d/local.conf` for editing and add the following line: `/usr/local/openssl/lib`
Re-compile Apache (remember to `make clean`) and it should work.
If that doesn't work. You could also try specifying `LDFLAGS` directly with your `configure` command:
```
LDFLAGS=-L/usr/local/ssl/lib \ ./configure --with-included-apr --prefix=/usr/local/apache2 --enable-so
--enable-rewrite --with-ssl=/usr/local/ssl --enable-ssl=shared
--enable-deflate --enable-expires --enable-headers
```
**Option #2 - Upgrade the system OpenSSL:**
Re-install OpenSSL with the config line `./config --prefix=/usr --openssldir=/usr/local/openssl shared`
When the prefix is not specified in your config line, the OpenSSL installer will default to `/usr/local/ssl`.
Quick install instructions:
```
cd /usr/local/src
wget https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz
tar -zxf openssl-1.0.2*
cd openssl-1.0.2*
./config --prefix=/usr --openssldir=/usr/local/openssl shared
make
make test
make install
``` |
10,864,333 | Here's a strange one. We have a Google App Engine (GAE) app and a custom domain <http://www.tradeos.com> CNAME'd to ghs.google.com. In China we regularly get no response whatsoever from the server for 20 minutes or so then it works fine for a a while, sometimes for a few hours.
Other non-Chinese sites like CNN seem to work continuously so it's not a general problem with the international Internet going down. From other countries we see no problem.
By the way the non-custom Google domains x.appspot.com don't seem to be accessible at all presumably blocked by the Great Firewall.
Any ideas? Thanks! | 2012/06/02 | [
"https://Stackoverflow.com/questions/10864333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176505/"
] | Read portions of bytes to byte array and store them in new files when buffer is full or it is end of file.
For example (code is not perfect, but it should help understanding the process)
```
class FileSplit {
public static void splitFile(File f) throws IOException {
int partCounter = 1;//I like to name parts from 001, 002, 003, ...
//you can change it to 0 if you want 000, 001, ...
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
String fileName = f.getName();
//try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
String filePartName = String.format("%s.%03d", fileName, partCounter++);
File newFile = new File(f.getParent(), filePartName);
try (FileOutputStream out = new FileOutputStream(newFile)) {
out.write(buffer, 0, bytesAmount);
}
}
}
}
public static void main(String[] args) throws IOException {
splitFile(new File("D:\\destination\\myFile.mp4"));
}
}
```
myFile.mp4 size=12,7 MB
After split I had 13 files
* `myFile.mp4.001` - `myFile.mp4.012` with size 1 MB
* `myFile.mp4.013` with size 806 KB
---
If you want to merge these files you can use
```
public static void mergeFiles(List<File> files, File into)
throws IOException {
try (FileOutputStream fos = new FileOutputStream(into);
BufferedOutputStream mergingStream = new BufferedOutputStream(fos)) {
for (File f : files) {
Files.copy(f.toPath(), mergingStream);
}
}
}
```
You can also create some additional methods to make your life easier. For instance method which will create list of files containing separated parts based on name (and location) of one of these files.
```
public static List<File> listOfFilesToMerge(File oneOfFiles) {
String tmpName = oneOfFiles.getName();//{name}.{number}
String destFileName = tmpName.substring(0, tmpName.lastIndexOf('.'));//remove .{number}
File[] files = oneOfFiles.getParentFile().listFiles(
(File dir, String name) -> name.matches(destFileName + "[.]\\d+"));
Arrays.sort(files);//ensuring order 001, 002, ..., 010, ...
return Arrays.asList(files);
}
```
With that method we can overload `mergeFiles` method to use only one of the files `File oneOfFiles` instead of whole list `List<File>` (we will generate that list based on one of the files)
```
public static void mergeFiles(File oneOfFiles, File into)
throws IOException {
mergeFiles(listOfFilesToMerge(oneOfFiles), into);
}
```
You can also overload these methods to use `String` instead of `File` (we will wrap each String in File when needed)
```
public static List<File> listOfFilesToMerge(String oneOfFiles) {
return listOfFilesToMerge(new File(oneOfFiles));
}
public static void mergeFiles(String oneOfFiles, String into) throws IOException{
mergeFiles(new File(oneOfFiles), new File(into));
}
``` |
35,015,850 | Given that I have a `Supervisor` actor which is injected with a `child` actor how do I send the child a PoisonPill message and test this using TestKit?
Here is my Superivisor.
```
class Supervisor(child: ActorRef) extends Actor {
...
child ! "hello"
child ! PoisonPill
}
```
here is my test code
```
val probe = TestProbe()
val supervisor = system.actorOf(Props(classOf[Supervisor], probe.ref))
probe.expectMsg("hello")
probe.expectMsg(PoisonPill)
```
The problem is that the `PoisonPill` message is not received.
Possibly because the probe is terminated by the `PoisonPill` message?
The assertion fails with
```
java.lang.AssertionError: assertion failed: timeout (3 seconds)
during expectMsg while waiting for PoisonPill
``` | 2016/01/26 | [
"https://Stackoverflow.com/questions/35015850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532383/"
] | I think this [Testing Actor Systems](http://doc.akka.io/docs/akka/current/scala/testing.html) should answer your question:
**Watching Other Actors from Probes**
A TestProbe can register itself for DeathWatch of any other actor:
```
val probe = TestProbe()
probe watch target
target ! PoisonPill
probe.expectTerminated(target)
``` |
2,573,501 | * Given a triangle $\mathrm{A}\left(2,0\right),\ \mathrm{B}\left(1,3\right),\
\mathrm{C}\left(5,2\right)\ \mbox{with}\ \rho\left(x,y\right) = x$; I need to find it's centre of mass ?.
* I know I need to integrate the density formula over the region, but I don't understand how to get the limits for the integrals to calculate the area.
* Do I need to find formulas for the lines and somehow use those ?. | 2017/12/19 | [
"https://math.stackexchange.com/questions/2573501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/392788/"
] | Denote by $\;AB,AC,BC\;$ the respective lines on which the sides $\;AB,AC,BC\;$ lie, thus:
$$\begin{cases}AB:\;y=-3x+6\\{}\\AC:\;y=\cfrac23x-\cfrac43\\{}\\BC:\;y=-\cfrac14x+\cfrac{13}4\end{cases}$$
You should try to do a diagram, and then you need for the mass you need the integrals
$$M=\int\_1^2\int\_{-3x+6}^{-\frac14x+\frac{13}4} x\,dy\,dx+\int\_2^5\int\_{\frac23x-\frac43}^{-\frac14x+\frac{13}4}x\,dy\,dx$$
Take it from here. |
27,778,593 | I am trying to install node.js on Red Hat Enterprise Linux Server release 6.1 using the following command:
```
sudo yum install nodejs npm
```
I got the following error:
```
Error: Package: nodejs-0.10.24-1.el6.x86_64 (epel)
Requires: libssl.so.10(libssl.so.10)(64bit)
Error: Package: nodejs-devel-0.10.24-1.el6.x86_64 (epel)
Requires: libcrypto.so.10(libcrypto.so.10)(64bit)
Error: Package: nodejs-0.10.24-1.el6.x86_64 (epel)
Requires: libcrypto.so.10(libcrypto.so.10)(64bit)
Error: Package: nodejs-devel-0.10.24-1.el6.x86_64 (epel)
Requires: libssl.so.10(libssl.so.10)(64bit)
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
```
I tried the following command as well:
```
sudo yum install -y nodejs
```
I am getting the following error:
```
Error: Package: nodejs-0.10.24-1.el6.x86_64 (epel)
Requires: libssl.so.10(libssl.so.10)(64bit)
Error: Package: nodejs-0.10.24-1.el6.x86_64 (epel)
Requires: libcrypto.so.10(libcrypto.so.10)(64bit)
```
How should I install it? I want to install the latest version. | 2015/01/05 | [
"https://Stackoverflow.com/questions/27778593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4088696/"
] | NodeJS provides a setup script that must run before you install it with yum
```
curl -sL https://rpm.nodesource.com/setup | bash -
```
Then the yum command should work
```
yum install -y nodejs
```
<https://github.com/joyent/node/wiki/installing-node.js-via-package-manager#enterprise-linux-and-fedora> |
1,521,394 | How can I send mail to Gmail using Perl? Here's what I'm trying:
```
my $mailer = Email::Send->new(
{
mailer => 'SMTP::TLS',
mailer_args => [
Host => 'smtp.gmail.com',
Port => 587,
User => 'xxx',
Password => 'xxx',
]
}
);
use Email::Simple::Creator; # or other Email::
use File::Slurp;
@arrIrc = read_file("$ircFile");
my $email = Email::Simple->create(
header => [
From => 'xxx',
To => "$configList{email}",
Subject => "The summary of logfile $channelName",
],
body => "@arrIrc",
);
``` | 2009/10/05 | [
"https://Stackoverflow.com/questions/1521394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184311/"
] | Use [Net::SMTP::SSL](http://search.cpan.org/perldoc/Net::SMTP::SSL) to talk to GMail.
See [MIME::Lite inline images](http://www.perlmonks.org/?node_id=784574) on [Perlmonks](http://www.perlmonks.org) for an example. |
44,643,750 | Consider the following code snippet:
```
[1]> (symbol-value '+)
NIL
[2]> +
(SYMBOL-VALUE '+)
[3]> (symbol-value '/)
((SYMBOL-VALUE '+))
[4]> (symbol-value '+)
(SYMBOL-VALUE '/)
[5]> *
(SYMBOL-VALUE '/)
```
So, according to my observation,
* symbol-value of `+` is the last input to the REPL.
* symbol-value of `/` is the last output of the REPL in parenthesis.
* symbol-value of `*` is the last output of the REPL as it is.
---
What is the reason for this?
----------------------------
There seems to be little reason for checking what was your last input, last output, as it is already on the REPL.
So, is there any specific reason for this behaviour of these operators?
Is there any historical significance of these operator's `symbol-value`?
Any help appreciated. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44643750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5345646/"
] | According the the [HyperSpec](http://www.lispworks.com/documentation/HyperSpec/Body/v__stst_.htm):
>
> The variables \*, \*\*, and \*\*\* are maintained by the Lisp read-eval-print loop to save the values of results that are printed each time through the loop.
>
>
> The value of \* is the most recent primary value that was printed, the value of \*\* is the previous value of \*, and the value of \*\*\* is the previous value of \*\*.
>
>
>
For [/ and friends](http://www.lispworks.com/documentation/HyperSpec/Body/v_sl_sls.htm):
>
> The variables /, //, and /// are maintained by the Lisp read-eval-print loop to save the values of results that were printed at the end of the loop.
>
>
> The value of / is a list of the most recent values that were printed, the value of // is the previous value of /, and the value of /// is the previous value of //.
>
>
>
And finally for [+ and friends](http://www.lispworks.com/documentation/HyperSpec/Body/v_pl_plp.htm):
>
> The variables +, ++, and +++ are maintained by the Lisp read-eval-print loop to save forms that were recently evaluated.
>
>
> The value of + is the last form that was evaluated, the value of ++ is the previous value of +, and the value of +++ is the previous value of ++.
>
>
>
You are asking:
>
> What is the reason for this?
>
>
>
REPL is an interactive *textual* environment: in many of such systems, like unix shells, there is always some convenient way of repeating the last command, or using the last value, without having to copy explicitly such values or re-enter them (consider for instance old textual terminals, where no copy/paste operation was available). So these variables are a relic of such era (but, in spite of that, still useful to lazy people like me, that first try to get a certain value, and then, for instance, assign to a global variable such value with a simple keystroke `*`, instead of having to copy and paste the value printed). |
26,897,502 | I have to segregate the even and odd numbers in a 2D array in java in two different rows (even in row 1 and odd in row two). I have included the output of my code bellow here is what I have:
```
class TwoDimensionArrays {
public static void main(String[] args) {
int sum = 0;
int row = 2;
int column = 10;
int[][] iArrays = new int[row][column];
for(int rowCount = 0; rowCount < iArrays.length /*&& rowCount % 2 == 0*/; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length /*&& columnCount % 2 != 0*/; columnCount++) {
if(columnCount % 2 != 0 /*&& rowCount % 2 == 0*/) {
iArrays[rowCount][columnCount] = columnCount + 1;
}
}
}
System.out.println("The array has " + iArrays.length + " rows");
System.out.println("The array has " + iArrays[0].length + " columns");
for(int rowCount = 0; rowCount < iArrays.length; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length; columnCount++) {
System.out.print(iArrays[rowCount][columnCount] + " ");
sum += iArrays[rowCount][columnCount];
}
System.out.println();
}
System.out.println("The sum is: " +sum);
}
}
//OUTPUT//
/*The array has 2 rows
The array has 10 columns
0 2 0 4 0 6 0 8 0 10
0 2 0 4 0 6 0 8 0 10
The sum is: 60*/
```
Can anyone lend a hand?
Thank you in advance. | 2014/11/12 | [
"https://Stackoverflow.com/questions/26897502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4092147/"
] | Instead of passing over the list twice try this:
```
for(int v = 0; v < 20; v++) {
iArrays[v % 2][(int)v/2] = v;
}
```
This will set `iArrays` to:
```
[[0,2,4,6,8,10,12,14,16,18],
[1,3,5,7,9,11,13,15,17,19]]
```
What is happening is the `row` is being set to the remainder of `v % 2` (`0` if `v` is even, `1` if `v` is odd) and the `col` is being set to the corresponding index (with the cast to `int` to drop any fraction). You can even generalize it like this:
```
public static int[][] group(int groups, int size){
int[][] output = new int[groups][size];
for(int value = 0; value < (groups*size); value++) {
output[value % groups][(int)value/groups] = value;
}
return output;
}
```
Then a call to `group(2, 10)` will return:
```
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
``` |
54,241,950 | This is my first question in Stackoverflow and I am not a professional developer, so be kind guys :) If any additional information is needed, just let me know.
So, I am trying to create a flatlist for a delivery man showing his daily itinerary. In this example he has 4 address to go to. When he arrives at the first place, in this case "METAL", he should press the yellow button. Pressing the yellow button should disable it and chage its background color, but just for the first place "METAL".
Right now, when i press the yellow button it disables and changes the background color for all buttons in the flatlist, I am not sure how to target just the one button that was clicked.
I attached some pictures to show whats going on. The last picture is just an example of what I want.
<https://imgur.com/a/G1S0ap4>
This's what the code first loads
[](https://i.stack.imgur.com/o0mUS.jpg)
This is what happens when i press the yellow button. All buttons have been disabled
[](https://i.stack.imgur.com/pfRWg.jpg)
This is what i wanted it to do, disable just the button that i actually clicked on
[](https://i.stack.imgur.com/Hm7eZ.jpg)
```
this.state = {disablearrived: false,
disablesuccess: false,
disablenotdelivered: false,
showView: true,
fadeAnim: new Animated.Value(0),
colorarrived: '#E5C454',
colorsuccess: '#52D273',
colornotdelivered: '#E94F64',
data: [
{ id: "1", custid: "1111111111111", name: "METAL", nf: "166951" },
{ id: "2", custid: "222222222222", name: "BRUNO", nf: "166952" },
{ id: "3", custid: "8248632473", name: "Doc Hudson" },
{ id: "4", custid: "8577673", name: "Cruz Ramirez" },
],
};
onPressButtonarrived(item) {
// Alert.alert('Chegada às: '+new Date().toLocaleTimeString('pt-BR', {timeZone: 'America/Sao_Paulo'}))
this.setState({ disablearrived: true })
this.setState({ colorarrived: '#D6D6D6' })
}
render() {
return (
<View style={{ backgroundColor: '#252525'}}>
<View>
<Text style={styles.normalblue}>Bem vindo, Victor</Text>
<Text style={styles.normalblue}>Estas são suas entregas de dia</Text>
</View>
<FlatList
data={this.state.data}
extraData={this.state}
keyExtractor={item => item.id}
renderItem={({ item }) => {
return (
<View style={{backgroundColor: '#484848', borderBottomColor: '#252525', borderBottomWidth: 20}}>
<Text style={styles.bigyellow}>{item.name}</Text>
<Text style={styles.smallblue}>{item.add}, {item.addnumber}</Text>
<Text style={styles.normalyellow}>NF {item.nf}</Text>
<View style={styles.containercontent}>
<View style={{backgroundColor: this.state.colorarrived, justifyContent: 'center', flex: 1}}>
<TouchableHighlight style={styles.buttonview}
onPress={() => {this.onPressButtonarrived(item)}} disabled={this.state.disablearrived}>
<View style={styles.btnIcon}>
<Icon name="location" size={30} />
<Text>Chegada</Text>
</View>
</TouchableHighlight>
</View>
<View style={{backgroundColor: this.state.colorsuccess, justifyContent: 'center', flex: 1}}>
<TouchableHighlight style={styles.buttonview}
onPress={() => {this.onPressButtonsuccess(item)}} disabled={this.state.disablesuccess}>
<View style={styles.btnIcon}>
<Icon name="check" size={30} />
<Text>Entregue</Text>
</View>
</TouchableHighlight>
</View>
{this.state.showView && (
<View style={{backgroundColor: this.state.colornotdelivered, justifyContent: 'center', flex: 1}}>
<TouchableHighlight style={styles.buttonview}
onPress={() => {this.onPressButtonnotdelivered(item)}} disabled={this.state.disablenotdelivered}>
<View style={styles.btnIcon}>
<Icon name="block" size={30} />
<Text>Não Entregue</Text>
</View>
</TouchableHighlight>
</View>
)}
</View>
</View>
);
}}
/>
</View>
);
}
``` | 2019/01/17 | [
"https://Stackoverflow.com/questions/54241950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075757/"
] | You can also try with one another approach as shown below.
```
Create Table Result(Id int, Title Varchar(10), Category Varchar(10), SubCategory Varchar(10), Value Int)
Insert Into Result Values(1, 'Part-1','CatX', 'A', 100),
(2 ,'Part-1','CatX', 'B', 0),
(3 ,'Part-1','CatX', 'C', 50),
(4 ,'Part-1','CatY', 'A', 100),
(5 ,'Part-1','CatY', 'B', 0),
(6 ,'Part-1','CatY', 'C', 100),
(7 ,'Part-2','CatM', 'A', 30),
(8 ,'Part-2','CatM', 'B', 10),
(9 ,'Part-2','CatM', 'C', 100),
(10 ,'Part-2','CatN', 'A', 50),
(11 ,'Part-2','CatN', 'B', 10),
(12 ,'Part-2','CatN', 'C', 80)
Select Title, SubCategory, AVG(Value) as Average from Result
Group By Title, SubCategory
Select Title, SubCategory, SUM(Value) / COUNT(*) as Average
From Result Group By Title, SubCategory
```
The output in both case is as shown below which are same.
[](https://i.stack.imgur.com/aOeCG.png)
You can find the live demo [**Live Demo Here**](https://rextester.com/SHC11303) |
35,079,608 | I have an unordered dynamic list with same class list items. and I want to group the same class list items into one ul in the main ul.
How can I group same class list items?
I want to convert the below dynamic list
```
<ul>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
<li class="a2">Some Content</li>
<li class="a2">Some Content</li>
<li class="a3">Some Content</li>
</ul>
```
into this
```
<ul>
<li>A1
<ul>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
<li class="a1">Some Content</li>
</ul>
</li>
<li>A2
<ul>
<li class="a2">Some Content</li>
<li class="a2">Some Content</li>
</ul>
</li>
<li>A3
<ul>
<li class="a3">Some Content</li>
</ul>
</li>
</ul>
``` | 2016/01/29 | [
"https://Stackoverflow.com/questions/35079608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5740672/"
] | Here a solution for you:
HTML:
```
<ul id="BaseNode">
<li class="a1">A</li>
<li class="a1">B</li>
<li class="a1">C</li>
<li class="a1">D</li>
<li class="a2">E</li>
<li class="a2">F</li>
<li class="a3">G</li>
</ul>
```
---
jQuery:
```
$(document).ready(function(){
var lis = $("#BaseNode > LI");
var as = { };
$.each(lis, function(i, el){
var c = $(el).attr("class");
if(as[c] == null) {
as[c] = new Array();
}
as[c].push(el);
});
$("#BaseNode").empty();
$.each(as, function(i, el) {
var li = $("<li>" + i.toUpperCase() + "</li>");
var ul = $("<ul></ul>");
$(ul).append(el);
$(li).append(ul);
$("#BaseNode").append(li);
});
});
```
I created also a [jsFiddle](https://jsfiddle.net/3hm6yczh/1/) where you can see the result. I added an `ID` to first `UL` only for convenience. |
11,324,750 | I have table `types` and i want to build `selectbox` with all values from this table
In my controller i wrote this code
```
$allRegistrationTypes = RegistrationType::model()->findAll();
$this->render('index', array('allRegistrationTypes' => $allRegistrationTypes))
```
How build selectbox in view file ? | 2012/07/04 | [
"https://Stackoverflow.com/questions/11324750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221313/"
] | Well then its pretty simple all you need to do is first create List Data like
```
CHtml::ListData(allRegistrationTypes,'value you want to pass when item is selected','value you have to display');
```
for ex
```
typeList = CHtml::ListData(allRegistrationTypes,'id','type');
```
now remember both ***id and type are fields in table***
now all you have to do is if you are using form then
```
<?php echo $form->dropDownList($model, 'type_id', $typeList, array('empty'=>'Select a tyoe')); ?>
```
and if you need multiple you can pass `multiple => multiple` in the array as htmlOptions |
42,164,949 | Hello I am new at c# and I am doing a small game that I need to play mp3 files.
I've been searching about this and using wmp to do it, like this:
```
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = @"c:\somefolder\project\music.mp3";
myplayer.controls.play();
```
I am able to play the file successfully with the full path of the mp3 file. The problem is that I can't find a way to use the file directly from the project folder, I mean, if I copy the project to another computer the path of the mp3 file will be invalid and no sound will be played. I feel that I am at a dead end now, so if someone can help me I would appreciate it! Thanks in advance | 2017/02/10 | [
"https://Stackoverflow.com/questions/42164949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7547069/"
] | I think that your problem is the way you use `getResource()` :
```
Paths.get(getClass().getResource(filepath).toURI());
```
You use a relative classpath (that is relative to the the current class location) to retrieve the `"extrapack-renew.sql"` file.
It means that this resource has to be located inside this path in your jar to be retrieved.
If the resource is not located inside the current class path, the path used to retrieve the resource should start with a `"/"` character in order to specify an absolute name of the resource:
```
Paths.get(getClass().getResource("/"+filepath).toURI());
```
Of course if you use maven, `extrapack-renew.sql` should be in
the `src/main/resources/secure` folder of the source project so that `"/secure/extrapack-renew.sql"` be a resource in the classpath. |
26,433,429 | I have an app that has a textbox, validation control and a button. The problem is that if someone copies text from a word document inside the textbox, some of the special characters won't be allowed because of the validation control. But if I delete those special characters and we typed them, the validation control works. Is there a way to convert that text to plain text or rich text inside the textbox? | 2014/10/17 | [
"https://Stackoverflow.com/questions/26433429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3896029/"
] | Copy the text into a `visibility: hidden` div with font styles equal to the textarea and a `max-width` that won't let it go beyond your number of columns. If the height of the hidden copy of the text exceeds your limit, remove the text that was added.
The following is *close* to what you need. Unfortunately, it doesn't nix the 5th row (after hitting enter on the 4th row) until you type something on it, and it can leave a couple characters on the 5th row (if you wrap to the 5th row from the 4th row). I'm uncertain how to refine the technique further.
```js
var $measure = $('#measure');
var $input = $('#input');
var $output = $('#measurement');
var existingText = '';
$input.on('keyup', function(event) {
$measure.html($input.val());
$output.val($measure.width() + 'x' + $measure.height() + 'px');
if ($measure.height() > 60) {
$input.val(existingText.trim());
$measure.html(existingText.trim());
}
existingText = $input.val();
});
```
```css
#measure
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: pre-wrap;
/* set font style equal to style of textarea */
font-family: monospace;
font-size: 13px;
letter-spacing: normal;
line-height: normal;
word-spacing: 0;
word-wrap: break-word;
max-width: 221px;
border: 1x solid black;
margin: 2px;
padding: 2px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input" cols="30" rows="4"></textarea>
<div id="measure"></div>
<br>
<input type="text" disabled="disabled" id="measurement"/>
``` |
27,477,558 | Here is the code for back button. I want to kill other activities by back button but its not working in one activity, but I have other activities and without one activity its working fine. Please help me out.
```
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
``` | 2014/12/15 | [
"https://Stackoverflow.com/questions/27477558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4294246/"
] | Might be this code will help you:
```
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
``` |
74,247,005 | In [this post](https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain) it is mentioned that I can create a custom Promise with `setTimeout` like below:
```js
const delay = t => new Promise(resolve => setTimeout(resolve, t));
```
My operation needs to be executed after 100ms so `t` will be `100` in my scenario.
I'm confused on how to use this though. The normal format of a Promise is `new Promise (resolve, reject)` but in the `delay` function only the `resolve` has been defined.
Here's my attempt:
```js
function numbersValidation(number1, number2) {
if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
throw new Error('Only numbers are allowed');
}
}
function add(number1, number2) {
numbersValidation(number1, number2);
return number1 + number2;
}
const addPromise = (number1, number2) => {
delay(100)
.then(result => result = add(number1, number2));
.catch(err => reject(err));
};
// -----Test------
describe.only('promise calculator', () => {
it('add works fine', done => {
calculator.addPromise(1, 2).then(result => {
try {
assert.equal(3, result);
done();
} catch (e) {
done(e);
}
});
});
});
// AssertionError [ERR_ASSERTION]: 3 == false
```
This is quite wrong since my IDE is complaining about the structure, but can someone please point me in the right direction on how to use the delay function so that I make my `addPromise` function work?
Thank you | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19640633/"
] | We could do
```
nafilt_persample.ngsrep <- Map(function(dat, nm),
{
dat[c("lCI", "uCI")] <- nm[dat$Hugo_Symbol]
dat
},
nafilt_persample.ngsrep, cint)
```
Or with `for` loop
```
for(nm in names(nafilt_persample.ngsrep))
{
nafilt_persample.ngsrep[[nm]][c("lCI", "uCI")] <-
cint[[nm]][nafilt_persample.ngsrep[[nm]]$Hugo_Symbol]
}
``` |
5,474,767 | I'm trying to solve [this problem.](https://stackoverflow.com/questions/5461191/creating-screens-and-underlying-data-access-layer-dynamically-on-android) I was wondering if it's possible to use ORMLite (or modify it) to support this use case ?
Thanks. | 2011/03/29 | [
"https://Stackoverflow.com/questions/5474767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306346/"
] | Just use [db4o](http://www.db4o.com/android/) and forget all the sql and mappings hassle. Model your objects and persist them directly. |
35,161,201 | I have gone through almost all posts for this error. But i was unable for figure out the issue.
I have tried to change build.gradle repositories to mavenCentral() and have also tried make changes in app.gradle. I just though of adding volley into my app, from then the sync is getting failed.
I have also tried file->Invalidate caches/Restart.
I feel there is some problem with getDefaultProgaurdFile. as I can see it is underlined.
Please help me on this.
Thanks
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.six30labs.cms"
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
```
<http://postimg.org/image/4kv7qh7cr/>
<http://postimg.org/image/azlbyum2b/> | 2016/02/02 | [
"https://Stackoverflow.com/questions/35161201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4994472/"
] | ```
insert into table_a (f1, f2, f3, f4, f5, f6)
select f1, f2, f3, f4, f5, f6
from (
(
select $1, $2, $3, f4, f5, f2, 1
from table_a
where <conditionals>
order by <ordering>
limit 1
) s
union all
select $1, $2, $3, '', '', null, 2
) s (f1, f2, f3, f4, f5, f6, o)
order by o
limit 1
``` |
48,862,529 | I understand [why control characters are illegal in XML 1.0](https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0), but still I need to store them somehow in XML payload and I cannot find any recommendations about escaping them. I cannot upgrade to XML 1.1.
How should I escape e.g. [SOH character](https://en.wikipedia.org/wiki/C0_and_C1_control_codes#SOH) (`\u0001` - standard separator for FIX messages)?
The following doesn't work:
```
<data></data>
``` | 2018/02/19 | [
"https://Stackoverflow.com/questions/48862529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4647853/"
] | One way is to use processing instructions: `<?hex 01?>`. But that only works in element content, not in attributes. And of course the processing instruction needs to be understood by the receiving application.
You could also use elements: `<hex value="01"/>` but elements are visible in an XSD schema or DTD, while processing instructions are hidden.
Another approach is that if a piece of payload can contain such characters, then put the whole payload in Base64 encoding. |
49,160,125 | I have and Application which has a **singleton** that stores information across the whole app. However, this is creating some data race issues when using the singleton from different threads.
Here there is a very dummy and simplistic version of the problem:
**Singleton**
```
class Singleton {
static var shared = Singleton()
var foo: String = "foo"
}
```
**Use of the singleton** (from the AppDelegate for simplicity)
```
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
DispatchQueue.global().async {
var foo = Singleton.shared.foo // Causes data race
}
DispatchQueue.global().async {
Singleton.shared.foo = "bar" // Causes data race
}
return true
}
}
```
Is there any way to ensure that a singleton is thread safe, so it can be used from anywhere in the app without having to worry about which thread you are in?
This question is **not** a duplicate of [Using a dispatch\_once singleton model in Swift](https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift) since (if I understood it correctly) in there they are addressing the problem of accessing to the singleton object itself, but not ensuring that the reading and writing of its properties is done thread safely. | 2018/03/07 | [
"https://Stackoverflow.com/questions/49160125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5761878/"
] | Thanks to @rmaddy comments which pointed me in the right direction I was able to solve the problem.
In order to make the property `foo` of the `Singleton` thread safe, it need to be modified as follows:
```
class Singleton {
static let shared = Singleton()
private init(){}
private let internalQueue = DispatchQueue(label: "com.singletioninternal.queue",
qos: .default,
attributes: .concurrent)
private var _foo: String = "aaa"
var foo: String {
get {
return internalQueue.sync {
_foo
}
}
set (newState) {
internalQueue.async(flags: .barrier) {
self._foo = newState
}
}
}
func setup(string: String) {
foo = string
}
}
```
Thread safety is accomplished by having a computed property `foo` which uses an `internalQueue` to access the "real" `_foo` property.
Also, in order to have better performance `internalQueue` is created as concurrent. And it means that it is needed to add the `barrier` flag when writing to the property.
What the `barrier` flag does is to ensure that the work item will be executed when all previously scheduled work items on the queue have finished. |
60,772,541 | This seems so simple I'm embarrassed to ask.
I have a file with an unknown number of lines but at least 20. I always want to move lines 4-6 to lines 1-3.
So this:
```
A
B
C
D
E
F
G
H
```
becomes this:
```
D
E
F
A
B
C
G
H
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60772541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13093997/"
] | ```
$Lines = 'A'..'H'
$Lines[3..5],$Lines[0..2],$Lines[6..99]
```
or
```
$Lines[3,4,5,0,1,2,6,7,8,9]
```
For details, see: [about arrays](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7) |
21,563,414 | I am using aptana studio v 3.4.2.201308081805 on windows 7, I know that v 3.5 is available because I was prompted to update to 3.5 on a different computer.
I have not received the update prompt on my macbook air or on my work computer. Does anyone know how to force aptana to update to v 3.5? | 2014/02/04 | [
"https://Stackoverflow.com/questions/21563414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1922932/"
] | Aptana has removed version 3.5 due to several bugs.
Current stable version is 3.4.2
You can check here [Aptana download](http://www.aptana.com/products/studio3/download) |
62,315 | After watching the thirteen films in the *Marvel Cinematic Universe*, I've been wondering if there is a longer running series of films that maps out a continuous storyline.
[I've found this article on Wikipedia](https://en.wikipedia.org/wiki/List_of_film_series_with_more_than_twenty_entries), but I am unsure if any of these film series have reboots, or even if they follow a continuous plotline/timeline.
The *James Bond* series of films features a reboot, but even before *Casino Royale* there didn't seem to be much of a continual plotline across the entire series of films (despite the recurring characters, organisations and themes).
To explain what I mean by continuous plotline, I am going by the following criteria:
* Films set in the same "universe" or setting
* A continuous timeline of events depicted by the films (although not necessarily in sequence)
* Each film should intentionally reference at least one of the other films that preceded it
* Preferably at least one of the characters should be shared across more than one of the films in the series
* Reboots or remakes break the continuous plotline, so these cannot be included (but they can be ignored if subsequent films continue the original plotline)
The important part here is the continuous timeline of events. If a film can be placed somewhere in the timeline of a series without causing issues (eg. characters being revived without explanation, previously destroyed places suddenly restored without explanation, massive jumps in time for the setting and yet the characters don't age without explanation), then it is part of the continuous timeline. Otherwise that film breaks the timeline and cannot be included.
I am more than happy to accept parts of a film series. For example if twenty of the thirty or more *Godzilla* films all follow these criteria, then I would accept those twenty films as a continuous plotline.
I can think of several film series that fit these criteria, the *Star Wars* and *Harry Potter* film series are two examples. But I am looking for the longest series of films that fits my criteria of a continuous plotline or timeline of events.
Films don't have to be direct sequels/prequels to fit into my criteria - films in the same setting but chronologically spread out, and therefore with different characters would fit the bill so long as they kept to a continuous timeline of events. Also, I would accept foreign language films and films that are TV movies or straight to DVD films. | 2016/10/24 | [
"https://movies.stackexchange.com/questions/62315",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/30280/"
] | According to [Wikipedia's entry for *Blondie* (the comic strip)](https://en.wikipedia.org/wiki/Blondie_(comic_strip)), of the 28 movies made based on the strip, at least the first 14 were a continuous series meeting your definition:
>
> Blondie was adapted into a long-running series of 28 low-budget theatrical B-features, produced by Columbia Pictures. *[...]*
>
>
> Columbia was careful to maintain continuity, so each picture progressed from where the last one left off. Thus the Bumstead children grew from toddlers to young adults onscreen. *[...]*
>
>
> In 1943 Columbia felt the series was slipping, and ended the string with It's a Great Life and Footlight Glamour, deliberately omitting "Blondie" from the titles to attract unwary moviegoers. After 14 Blondies, stars Singleton and Lake moved on to other productions. During their absence from the screen, Columbia heard from many exhibitors and fans who wanted the Blondies back. The studio reactivated the series, which ran another 14 films until discontinued permanently in 1950.
>
>
>
So this is definitely 14, and most likely all 28; I note that the entry for Larry Sims (the child actor who plays Dagwood & Blondie's son Alexander) is listed as appearing in all 28 films along with the two main stars, Penny Singleton and Arthur Lake. |
29,774,038 | Why is this query returning an error. I am trying to load the code for table as a constant string, the flag for data again a constant string, the time of insertion and the counts for a table. I thought, let me try and run the secelct before writing the inserts.
But for some reason, it fails listing column names from tables from where I am trying to get a count. All i need is two constant values, one date and one count. Tried by removing the groupby as well, throws another error.
**hive -e "select "WEB" as src\_cd, "1Hr" as Load\_Flag, from\_unixtime((unix\_timestamp(substr(sysDate, 0, 11), 'dd/MMM/yyyy')), 'MM/dd/yyyy') as time, count(\*)
from weblog
where year=2015 and month=04 and day=17
group by src\_cd, load\_flag, time
;**
"
OK
Time taken: 1.446 seconds
FAILED: SemanticException [Error 10004]: Line 4:9 Invalid table alias or column reference 'src\_cd': (possible column names are: clientip, authuser, sysdate, clfrequest.........(and so on) year, month, day) | 2015/04/21 | [
"https://Stackoverflow.com/questions/29774038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725647/"
] | The double quotes on the literals is a problem. Here is a simpler version that I tested successfully:
```
hive -e "select 'WEB' , '1Hr' , from_unixtime((unix_timestamp(substr(sysDate, 0, 11), 'dd/MMM/yyyy')), 'MM/dd/yyyy') as time, count(*) from weblog where year=2015 and month=04 and day=17 group by 1,2 , from_unixtime((unix_timestamp(substr(sysDate, 0, 11), 'dd/MMM/yyyy')), 'MM/dd/yyyy') ; "
``` |
43,123 | I'm getting aversion when someone do things that I don't like. This happens when a person do and not on natural things like rain. But It is hard to recorgnise it as aversion because that aversion is not towards a person. I just don't like certain actions that affect me (Only the things that affects me in someway). I don't want to hit someone or to hurt someone. So I always try to avoid such situations. But It is not always possible and that avoiding proccess makes suffering, makes doubts. So, How can I stop avoiding things ? How can I practise more acceptance ? How can I face anything without getting aversion? | 2020/11/03 | [
"https://buddhism.stackexchange.com/questions/43123",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/17744/"
] | Very good question, focused on real and useful problem.
Mind generates aversion when things go contrary to what it believes is "right". This belief is called "attachment". For example you believe that only certain weather is good and that it should be that same weather most of the time.
So the first technique is to remember this as soon as you feel aversion (basically, as soon as you feel emotionally disturbed): "what is my attachment in this case?". Once you identify the attachment you should think: "this attachment is a cause of suffering and an obstacle to Enlightenment, I shall let it go". And then you should make effort to let go of that attachment. "I shall not be attached to what I think is good weather. I should enjoy all weather as it is."
The second technique is to turn problems into blessings by changing your perspective. Here's how. Every time you have some unpleasant experience, tell to yourself: "this is actually a blessing because it gives me chance to practice Dharma and reach Enlightenment." Thinking like this will immediately turn a negative experience into a positive, happy event. Instead of experiencing suffering your mind will be elated.
Initially, you may tend to keep forgetting these instructions. If that happens you will react automatically as you always did. That's okay, keep practicing, keep trying to remember. (This is called mindfulness.)
Eventually you will reach a point when the problems themselves will serve as automatic reminders. At which point the game is won: what was previously triggering aversion will now trigger recollection of Dharma. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.