qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
25,321,224 | I have two linQ queries below and am wondering if there's a way to combine both of them. Essentially I have a list of strings. Then from that list of strings, I want to create a new list of object and order it based on a property of the object. This new list of object, which has been ordered, will then be returned.
```
var dirs = from file in myList
select new DirectoryInfo(file);
var dirOrdered = from file in dirs
orderby file.CreationTime ascending
select file;
```
Is it possible to use one var and have it be done in one query instead of two separate queries? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25321224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835622/"
] | You can do something like this:
```
var dirs = from file in myList
let fileInfo = new DirectoryInfo(file)
orderby fileInfo.CreationTime ascending
select fileInfo;
``` | Yes, you can try something like this:
```
var dirs = (from file in myList
select new DirectoryInfo(file)).OrderBy(x => x.CreationTime);
``` |
37,503,435 | I have an android app that I created and it keeps getting the "App Has Stopped" error and cannot find help anywhere. Can someone please help.
My Codes are below
Main Activity
```
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView = (WebView)findViewById(R.id.webView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.mybrockvillenews.com/");
webView.setWebViewClient(new WebViewClient());
}
@Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
} else {
super.onBackPressed();
}
}}
```
Activity Main .xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mylondonnews.knowbrockvilleuser.mybrockvillenews.MainActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/webView2"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
```
Android Manifest
```
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
```
How do I fix this please? Have have created new app again and again same way and get the same error.
My Logcat is below
```
05-28 16:30:40.771 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
05-28 16:30:40.781 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews I/InjectionManager: Inside getClassLibPath caller
05-28 16:30:41.161 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews D/InjectionManager: InjectionManager
05-28 16:30:41.161 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews D/InjectionManager: fillFeatureStoreMap com.mylondonnews.knowbrockvilleuser.mybrockvillenews
05-28 16:30:41.161 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews I/InjectionManager: Constructor com.mylondonnews.knowbrockvilleuser.mybrockvillenews, Feature store :{}
05-28 16:30:41.161 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews I/InjectionManager: featureStore :{}
05-28 16:30:41.301 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews D/AndroidRuntime: Shutting down VM
05-28 16:30:41.301 32193-32193/com.mylondonnews.knowbrockvilleuser.mybrockvillenews E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mylondonnews.knowbrockvilleuser.mybrockvillenews, PID: 32193
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mylondonnews.knowbrockvilleuser.mybrockvillenews/com.mylondonnews.knowbrockvilleuser.mybrockvillenews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2968)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3233)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6873)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:190)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:172)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:512)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:184)
at com.mylondonnews.knowbrockvilleuser.mybrockvillenews.MainActivity.<init>(MainActivity.java:10)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2958)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3233)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6873)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
``` | 2016/05/28 | [
"https://Stackoverflow.com/questions/37503435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6287974/"
] | One must not initialize a `View` on class level. The line
`private WebView webView = (WebView)findViewById(R.id.webView);` must be like:
```
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize WebView after setContentView()
webView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.mybrockvillenews.com/");
webView.setWebViewClient(new WebViewClient());
}
@Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
} else {
super.onBackPressed();
}
}
}
```
You are using `WebView` and trying to display a website in it. So, in simple words, you are missing permission. Add INTERNET permission.
`<uses-permission android:name="android.permission.INTERNET"/>` | Try to change the code from:
```
public class MainActivity extends AppCompatActivity {
private WebView webView = (WebView)findViewById(R.id.webView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.mybrockvillenews.com/");
webView.setWebViewClient(new WebViewClient());
}
```
to:
```
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.mybrockvillenews.com/");
webView.setWebViewClient(new WebViewClient());
}
```
If still has the force close, take the logcat log or dumpstate log to check, the logs should has the fatal exception infomations. |
204,007 | I am using QGIS 2.16 / Windows 10.
I have a point shapefile which I have been using for a little while that has always been editable.
Today I was editing the layer, saved my edits and left my computer for a few hours. When I came back I was not able to toggle the editing button on the toolbar and when I right click on the layer it longer has toggle editing as an option.
I have googled the problem every way I can think of and have not been able to find an answer to why the layer is suddenly un-editable or how to fix this. | 2016/07/29 | [
"https://gis.stackexchange.com/questions/204007",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/14355/"
] | It happened the same to me. Sometimes QGIS (2.18.11) blocks the edition when you "save as..." your project.
Just remove the shp from the box and import it again. That should work. If not, save your layer as a new shp.
It also happens with duplicate layers. | I imported my point files as a delimininated text layer (originally) and was unable to edit. If you then save layer as a shapefile or export as a geopackage, this might help. It did for me but mine was originally a different file format |
17,052,344 | I know it's a new feature and this may not be possible, but I would love to be able to use an Asset Catalog to organize my assets, but I access all of my images programmatically. How would I access my images, now? Do I still access them by their file names like so:
`[UIImage imageNamed:@"my-asset-name.png"];`
Seemingly, the Asset Catalog doesn't reference the extension, so would it be more efficient to access it without the ".png"?
The reason I am asking instead of testing for myself is that even after removing my assets and Asset Catalog, then cleaning the build folder, I can still access my assets in my application. This is preventing me from testing the Asset Catalog, when I implement it.
After looking through the Asset Catalog, I found the "Contents.json" for each asset and it's formatted like so:
```
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x",
"filename" : "my-asset@2x.png"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
```
I'm still unsure of how I should be accessing it, but maybe this will help? | 2013/06/11 | [
"https://Stackoverflow.com/questions/17052344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292230/"
] | Also Apple has added new way to get image from assets with Swift 3, It is calling as *'Image Literal'* and work as below:
 | **Swift**
You can get a reference to an image in your asset catelog with
```
UIImage(named: "myImageName")
```
You don't need to include the extension. |
7,672,511 | Is there anyone that can clearly define these levels of testing as I find it difficult to differentiate when doing TDD or unit testing. Please if anyone can elaborate how, when to implement these? | 2011/10/06 | [
"https://Stackoverflow.com/questions/7672511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493290/"
] | Briefly:
**Unit testing** - You unit test each individual piece of code. Think each file or class.
**Integration testing** - When putting several units together that interact you need to conduct Integration testing to make sure that integrating these units together has not introduced any errors.
**Regression testing** - after integrating (and maybe fixing) you should run your unit tests again. This is regression testing to ensure that further changes have not broken any units that were already tested. The unit testing you already did has produced the unit tests that can be run again and again for regression testing.
**Acceptance tests** - when a user/customer/business receive the functionality they (or your test department) will conduct Acceptance tests to ensure that the functionality meets their requirements.
You might also like to investigate white box and black box testing. There are also performance and load testing, and testing of the "'ilities" to consider. | Can't comment (reputation to low :-| ) so...
@Andrejs makes a good point around differences between environments associated with each type of testing.
Unit tests are run typically on developers machine (and possibly during CI build) with mocked out dependencies to other resources/systems.
Integration tests by definition have to have (some degree) of availability of dependencies; the other resources and systems being called so the environment is more representative. Data for testing may be mocked or a small obfuscated subset of real production data.
UAT/Acceptance testing has to represent the real world experience to the QA and business teams accepting the software. So needs full integration and realistic data volumes and full masked/obfuscated data sets to deliver realistic performance and end user experience.
Other "ilities" are also likely to need the environment to be as close as possible to reality to simulate the production experience e.g. performance testing, security, ... |
944,509 | Apple provides the NSArchiver and NSUnachriver for object serialization / deserialization, but this can not handle any custom xml schema. So filling an object structure with the data of any custom xml schema has to be made manually.
Since the iPhone developer community is rapidly growing, a lot of newbie programmer are despairing to deal with the available xml parsing possibilities.
The iPhone SDK only provides NSXmlParser for xml parsing, which is more useful to read certain parts of an xml file, than filling a whole object structure, which really is a pain.
The other possibility is the famous libxml library, which is written in ANSI C - not easy to use for someone who starts programming with objective-c and never learned proper C before. Event there are a lot of wrappers available, dealing with xml can be a pain for newbies.
And here my idea takes place. An XmlSerializer library which fills an object structure automatically could makes it a lot easier and increase the app quality for many programmers.
My Idea should work like this:
**The xml file**
```
<Test name="Michael" uid="28">
<Adress street="AlphaBetaGammastrasse 1" city="Zürich" postCode="8000" />
<Hobbies>
<Hobby describtion="blabla"/>
<Hobby describtion="blupblup"/>
</Hobbies>
</Test>
```
**The classes to fill**
```
@interface Test : NSObject {
NSString *name;
Adress *adress;
NSArray *hobbies;
int uid;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, retain) Adress *adress;
@property (nonatomic, retain) NSArray *hobbies;
@property (nonatomic, readwrite) int uid;
@end
@interface Adress : NSObject {
NSString *street;
NSString *city;
int postCode;
}
@property (nonatomic, copy) NSString *street;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, readwrite) int postCode;
@end
```
**How the xml serializer should work**
```
NSError *error = nil;
XMLSerializer *serializer = [[XMLSerializer alloc] init];
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TestFile" ofType:@"xml"]];
Test *test = [serializer deserializeWithData:data error:&error];
```
To fill the object structure needs only one line of code:
```
Test *test = [serializer deserializeWithData:data error:&error];
```
This would be so easy to use that any newbie programmer could use it. For more advanced usage the serializer could be configurable.
What do you think, would this be a helpful and popular library for iPhone and OSX Applications?
Edit:
You can see the project [here](http://code.google.com/p/orxml/), but it is fare away from release. | 2009/06/03 | [
"https://Stackoverflow.com/questions/944509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90745/"
] | The NSKeyedArchiver works precisely because it doesn't try to map onto an XML schema. Many, many XML schemas are badly designed (i.e. they're translating an in-memory object structure to an external representation format). The key problem is that the documents should be designed to make sense from a document perspective, and that that would then need to map onto whatever memory layout you wanted for your objects. Ever seen XML documents with lots of 'refid' attributes referring to other parts of the doc? Those are usually transliterated from a relational database which is just sticking angled brackets on the resultset.
So starting by assuming a one-to-one mapping between an XML document and its code representation is pretty much doomed in all but the simplest cases. Just consider where we would be today with HTML if it had been designed around the C++ objects that were used to instantiate the document in the first browser ... (well, more like Objective-C, but hey ...)
The point about NSKeyedArchiver is that you can evolve the data structure without breaking the ability to load older versions. It's unbelievably difficult to do that (properly) using some kind of automated instance-var-to-element mapping. | What you are describing is buried inside of the [ObjectiveResource](http://github.com/yfactorial/objectiveresource/tree/1.1) [implementations](http://github.com/lgalabru/objectiveresource/blob/cb12c9772314088c26e66c921ae17754f9d9b89b/src/Classes/NSObject+ObjectiveResource.m), and it supports both JSON and XML. It should be pretty easy to fork that and slim it down to just the parsing by throwing out all the connection management. |
2,493 | In Mahayana Buddhism we can see various artistic expressions: Thangka and Songs of Milarepa in Tibetan Buddhism, Chinese and Japanese art also were influenced heavily by Buddhism. Is there any forms of art practiced by Theravada monks? Do you know of any monks who were painters or poets? | 2014/08/05 | [
"https://buddhism.stackexchange.com/questions/2493",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/563/"
] | [The arts](http://buddhistartnews.wordpress.com/what-is-buddhist-art/)—be it painting, sculpture, architecture, calligraphy, etc.—have certainly flourished in the Theravada communities of the Southern Buddhist countries (Sri Lanka, Myanmar, Thailand, Laos, and Cambodia). See, for example, [this section](http://en.wikipedia.org/wiki/Buddhist_art#Southern_Buddhist_art) of the Wikipedia article on Buddhist art or [this chapter](http://theravadaciv.org/enlightened-ways-the-many-streams-of-buddhist-art-in-thailand/) of the book *Enlightened Ways: The Many Streams of Buddhist Art in Thailand*. And [here is a gallery](http://www.terragalleria.com/pictures-subjects/theravada-buddhist-temples/) of pictures that might be of interest. With regard to poetry, be sure to check out the [Theragata](http://www.accesstoinsight.org/tipitaka/kn/thag/index.html) and the [Therigata](http://www.accesstoinsight.org/tipitaka/kn/thig/index.html). | Householder,
`Is there any forms of art practiced by Theravada monks?`
Yes, the art of taming ones own mind. What ever art aside of this will for the most cases not be conform to Vinaya, not to speak of Dhamma-practice, and is for the most not allowed, not to speak of teaching such, trade or make favors with such.
Monks may paint demons, corpse, things which increase samvega in their Uposatha Hall. Nice looking things, if receiving, need to be "destroyed" of their shine and color.
Most decorations, if not simple done by lay people without involving of Bhikkhus, are actually not really allowed by the Buddha.
There might be cases where monks "[teach by pictures](http://zugangzureinsicht.org/html/lib/authors/buddhadasa/dhammawithpictures_en.html)", being assisted by artists. They may get engaged in erecting Chetis (relict buildings, graves of the Buddhas relics and those of his monks) to increase faith.
What ever else, even if broad usual to give favors for a live or trade..., one does well not to regard it as proper and allowed. Also sightseen and attending galleries, parks, guiding for such... is not proper for monastics, even formulated as rule for nuns.
Additions and discussion on it can be found here: [[Q&A] Buddha-images are allowed by the Buddha (at least by monks)?](http://sangham.net/index.php/topic,9363.msg19284.html#msg19284)
*(Note that this is not given for trade, exchange, stacks, entertainment and akusala deeds, but as a share of merits and to continue such for release)* |
59,332,653 | I am dealing with this example of Javascript code:
```
const real_numbers_array = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
//Karkoli že je increment, sedaj postane funkcija.
const increment = (
function(){
//Namesto zgornjega "function()" dobimo "increment"
return function increment (a1,a2 = 1){
return a1 + a2;
}
})();
console.log(increment(5,2));
console.log(increment(5));
```
Where we have a constant `increment` to which we assign an anonymous function `function()` which returns function `increment()` with two arguments of which second has a default value and those two arguments are summed up.
So far I understand this. But at the end there is `})();` and I don't know what is the meaning of the last empty `()`.
By default this code returns this:
[](https://i.stack.imgur.com/ZwzLn.png)
And if I omit the `()` I get:
[](https://i.stack.imgur.com/VEaja.png)
So what is the point of `()` at the end? Does anonymous function `function()` actually return only `increment` and we add `()` to get `increment()`. If this is so, why doesn't anonymous function return function as `increment()`. This is a default notation for functions afterall...
Is this some sort of an arrow function treachery? =) | 2019/12/14 | [
"https://Stackoverflow.com/questions/59332653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689242/"
] | I am not sure that I understood your question correctly, but out of the box, you can use TypeORM (assuming you use a SQL DB, Mongoose works similarly, though). The repository functions return a `Promise<>`, so you could use something like this (from the [docs](https://docs.nestjs.com/techniques/database)):
```
return this.photoRepository
.find()
.then(result => {//... your callback code goes here...
});
```
You could wrap this code in a `function getModifiedResult(cb){}` and pass the callback into it. Secondly, Remember that `async/await` is just syntactic sugar for promises, so the above is equivalent to:
```
result = await this.photoRepository.find();
cbAction = //... do something with your result here
return cbAction;
```
Again, you could just wrap this.
Another idea is to wrap the promise in an Observable, using the RxJS `from` operator (`fromPromise` for RxJS versions < 6). You can then put your callback into the subscription:
```
//... Note that this returns a subscription for you to unsubscribe.
return from(this.photoRepository
.find()
.then(result => result))
.subscribe(result => //... your callback code
);
```
If you go down that route, however, it may be worthwhile to modify your results using RxJS operators, like `map, switchMap,...`. | This is not much to do with Nest itself, it's just how you write your code and handle whatever libraries you might have. Let's say you have your database fetching function with a callback:
```
function findUsersWithCallback(function callback() {
// do something with db
callback(err, results);
});
```
You can wrap this into a promise-like function with, say, `util.promisify`
```
const findUsersPromisified = require('util').promisify(findUsersWithCallback);
```
What's left is to use your standard Nest provider:
```
@Injectable() UsersService {
findUsers() {
return findUsersPromisified();
}
}
```
Now your UsersService behaves like the rest of the framework, and your old callback-based code is nicely wrapped so you can safely ignore it. |
35,967,050 | I have an array of my class type "Room". There are two constructors for Room, a default and a custom. I want to call a specific constructor when initializing elements of my Room array. Neither default or custom works. I'm getting this error:
No operator "=" matches these operands, operand types are Room = Room\*
Here's my code:
btw rooms is a Room pointer type
```
void RoomManager::createRooms()
{
rooms = new Room[numOfRooms];
for (int i = 0; i < numOfRooms; i++)
{
rooms[i] = new Room();
}
}`
```
How should I go about this?
Thanks | 2016/03/13 | [
"https://Stackoverflow.com/questions/35967050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925067/"
] | I got this error when tried to install app directly from Android Studio.
It was due to certificate mismatch, since I used release certificate for setting up the app in Play Console, while Android Studio signs the app with debug certificate by default.
Installing app via adb resolved the error.
<https://developers.google.com/games/services/android/quickstart#step_4_test_your_game>
>
> Make sure to run an APK that you exported and signed with a
> certificate that matches one of the certificates you used during the
> application setup in Google Play Console.
>
>
> | This happened to me, auth errors in ADB, among them:
`android Warn Auth [GoogleAuthUtil] GoogleAuthUtil`
Because, like mentioned above, I had a debug build running on phone previously. So I fully uninstalled the app on my phone, and the next [Build and Run] ran successfully. |
1,059,857 | I see [here](https://www.centos.org/centos-stream/) that EOL for Centos 8 Stream is 2024-05-31.
Probably I'm not getting something but I understand it is upstream of RHEL 8 which has EOL in 2029.
What's happening in 2024? | 2021/04/09 | [
"https://serverfault.com/questions/1059857",
"https://serverfault.com",
"https://serverfault.com/users/627257/"
] | Centos 8 Stream is a separate thing, not really trying to be a direct equivalent of RHEL 8 (not in terms of the packaged software or timeline).
Centos 8 (non-"stream") was supposed to track RHEL 8 and presumably would have matched the RHEL 8 EOL date if the project hadn't been killed off.
From the [Centos FAQ](https://centos.org/distro-faq/#q6-will-there-be-separateparallelsimultaneous-streams-for-8-9-10-etc) (emphasis added):
>
> ### Q6: Will there be separate/parallel/simultaneous streams for 8, 9, 10, etc?
>
>
> A: Each major release will have a branch, similar to how CentOS
> Linux is currently structured; however, CentOS Stream is designed to
> focus on RHEL development, so only the latest Stream will have the
> marketing focus of the CentOS Project.
>
>
> Because RHEL development cycles overlap, there will be times when
> there are multiple code branches in development at the same time.This
> allows users time to plan migrations and development work without
> being surprised by sudden changes.
>
>
> **Specifically, since the RHEL release cadence is every 3 years, and the
> full support window is 5 years, this gives an overlap of approximately
> 2 years between one stream and the next.**
>
>
>
Ie, the Centos 9 Stream should appear when RHEL 9 releases and coexist with Centos 8 Stream until RHEL 8 Full Support ends.
My understanding is that if you run Centos 8 Stream, you are expected to transition to Centos 9 Stream during that overlap (while [RHEL 8 continues to be maintained in it's Maintenance Support phase for another 5 years after that time](https://access.redhat.com/support/policy/updates/errata#Overview)). | What will happen is RHEL 8 Full Support ends, which is the EOL for CentOS Stream 8.
CentOS Stream versions do not have a 10 year life, more like 5 years. As the testing repo for RHEL, Red Hat wants you to keep QAing features, and has no interest in providing 5 additional years of security updates for free. |
1,449,343 | I have 2 27'' displays: 4K and FullHD native resolutions.
If I set 1920\*1080 on the 4K display, the image looks blurry in comparison with FullHD native display.
I would not be surprised with any other resolutions, because I understand that pixels are physical squares, so if a ratio between 2 numbers is not a whole number, we could see artifacts.
But in this particular case FullHD is exactly 2 times smaller than 4K on each dimention. So each dot in 1920\*1080 image should take exactly 4 physical pixels on 4K display and I do not see any reason for blur.
So why the blurriness appears? | 2019/06/16 | [
"https://superuser.com/questions/1449343",
"https://superuser.com",
"https://superuser.com/users/653005/"
] | This problem has a long history. You may see an NVIDIA feature request dating
from the year 2012 at
[Nonblurry Upscaling at Integer Ratios](https://forums.geforce.com/default/topic/844905/geforce-drivers/-feature-request-nonblurry-upscaling-at-integer-ratios/),
still today without any answer or solution.
In short: The video adapter uses a more sophisticated algorithm than simple
pixel multiplication (two pixels for one), which works well for many tasks
but not very good for this too-simple task.
Most advice you will find for the problem would be to replace the display adapter
and/or monitor, which is not very practical.
One person has [claimed](https://johnstechpages.com/node/11) success in this
task. I quote below part of his advice (with small modifications):
>
> You have to convince Windows that your display supports HD as a native
> resolution. This can easily be done by using CRU (Custom Resolution
> Utility) authored by ToastyX and can be found here:
>
>
> <https://www.monitortests.com/forum/Thread-Custom-Resolution-Utility-CRU>
>
>
> It was as simple as adding 1920x1080, rebooting, and selecting that
> resolution. I added it to detailed and standard resolutions and all
> is well in that department.
>
>
>
I have not tried this solution and so cannot vouch that it works. | I know this post is old, but I spent hours on this issue today, and finally find a solution that worked for me, so I wanted to share.
For me, the solution was to go in the NVIDIA Control Panel, select the blurry screen, use NVIDIA Color settings and select : "Output color depth: 10 bpc" (the default was 8).
I has been a life changer, my screen is sharp again. |
26,403,927 | ```
#include <windows.h>
#include <pkfuncs.h>
#define WATCHDOG_NAME L"wd_critproc"
#define WATCHDOG_PERIOD 5000 // milliseconds
#define WATCHDOG_WAIT_TIME 2000 // milliseconds
//WDOG_NO_DFLT_ACTION, WDOG_KILL_PROCESS, WDOG_RESET_DEVICE
#define WATCHDOG_DEFAULT_ACTION WDOG_RESET_DEVICE
#define MAX_COUNT 10
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
HANDLE hWatchDogTimer=NULL;
LPCWSTR pszWatchDogName=WATCHDOG_NAME;
DWORD dwPeriod=WATCHDOG_PERIOD;
DWORD dwWait=WATCHDOG_WAIT_TIME;
DWORD dwDefaultAction=WATCHDOG_DEFAULT_ACTION;
DWORD dwCount=0;
BOOL bRet=FALSE;
wprintf((TEXT("[critproc] Critical process start\r\n")));
wprintf((TEXT("[critproc] Calling CreateWatchDogTimer...\r\n")));
//createwatchdogtimer api is being called here
hWatchDogTimer =
CreateWatchDogTimer(pszWatchDogName, dwPeriod,dwWait, dwDefaultAction,0,0);
if (! hWatchDogTimer)
{
wprintf((TEXT("[critproc] Invalid NULL handle, leaving app\r\n")));
return 1;
}
//checking if the error already exists then same watchdog timer is not called
if (GetLastError()==ERROR_ALREADY_EXISTS)
{
wprintf((TEXT("[critproc] WatchDog with this name already exists,
leaving app\r\n")));
return 1;
}
wprintf((TEXT("[critproc] Valid handle returned [0x%08x]\r\n")),
hWatchDogTimer);
wprintf((TEXT("[critproc] Starting watchdog timer...\r\n")));
bRet = StartWatchDogTimer(hWatchDogTimer,0);
if (! bRet)
{
wprintf((TEXT("[critproc] StartWatchDogTimer failed,
GetLastError returned 0x%x\r\n")),GetLastError());
CloseHandle(hWatchDogTimer);
return 1;
}
wprintf((TEXT("[critproc] Watchdog timer started successfully\r\n")));
dwCount=0;
while ((dwCount++)<MAX_COUNT)
{
BOOL bRetVal=0;
wprintf((TEXT("[critproc] Refreshing watchdog timer... [%d]\r\n")),dwCount);
bRetVal = RefreshWatchDogTimer(hWatchDogTimer,0);
if (!bRetVal)
{
wprintf((TEXT("[critproc] Failed to refresh watchdog timer,
GetLastError returned 0x%x\r\n")),GetLastError());
CloseHandle(hWatchDogTimer);
return 1;
}
Sleep(1000);
}
wprintf((TEXT("[critproc] Stopping watchdog timer refresh\r\n")));
dwCount=0;
while (++dwCount)
{
wprintf((TEXT("[critproc] The watchdog should timeout in \
a few seconds... [%d]\r\n")),dwCount);
Sleep(1000);
}
wprintf((TEXT("[critproc] Leaving app (should never be here)\r\n")));
CloseHandle(hWatchDogTimer);
return 0;
}
``` | 2014/10/16 | [
"https://Stackoverflow.com/questions/26403927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4128080/"
] | First determine and finalize what this class template `TriMaps` is expected to do. In C++, you must initialize a reference to something. You probably need a non-reference type (or a pointer type). Consider:
```
template <typename Map>
struct TriMaps
{
Map next;
Map prev;
Map curr;
};
```
Usage:
```
TriMaps<int> IntMaps;
vector<TriMaps<int>> iv;
```
If you need two template type argument, you can do this way:
```
template <typename MapType1, typename MapType2>
struct TriMaps
{
MapType1 a;
Maptype2 b;
};
```
Usage:
```
TriMaps<int, float> IntMaps;
vector<TriMaps<int, float>> iv;
```
**EDIT:**
Carefully understand that following simple class **will not** compile.
```
class TriMap
{
int & ref_int;
};
```
One approach is to refer a global variable (just to make it compile), or take an `int&` via a constructor.
```
// Approach 1
int global;
class TriMap
{
int & ref_int;
public:
TriMap() : ref_int(global) {}
};
// Approach 2
class TriMap
{
int & ref_int;
public:
TriMap(int & outer) : ref_int(outer) {}
};
``` | You can't have a `std::vector` of different type
but if you can have base class
```
struct TriMapBase { virtual ~TriMapBase() = default; };
template <typename Map> struct TriMaps : TriMapBase { /* Your implementation */ };
```
Then you may have:
```
TriMapBase<std::map<int, int>> mapint;
TriMapBase<std::map<int, char>> mapchar;
std::vector<TriMapBase*> v = {&mapint, &mapchar};
```
but you have to use virtual functions
or `dynamic_cast` to retrieve the correct type afterward...
or use |
178,401 | What is 'falls' or 'individual falls' here? It is difficult for me to find the right word for 'falls' which has many meanings.
>
> I think they convincingly showed that genetically this **individual
> falls** halfway between the Neanderthal and Denisovan fossils found in
> the same cave,
>
>
> | 2018/09/02 | [
"https://ell.stackexchange.com/questions/178401",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/80300/"
] | to fall [somewhere] between x and y means:
to come somewhere between x and y. It is used with time periods.
Of course, you would have to know when the Neanderthals were running around and when the Denisovans were running around. The time periods. The text assumes you know the time periods of those two categories of the genus homo.
His birthday seems **to fall between a Friday and Monday**, every year. Isn't that amazing?
to fall, to come at a certain time or place in time or on a graph.
to fall is also used with graphs to designate where some amount or numerical value is located. | * >
> 2 falls between 1 and 3 on a ruler.
>
>
>
* >
> This model falls between the base model and the luxury model.
>
>
>
On any sort of *continuum*, to **fall** means to occupy a specific place on the continuum. |
132 | For an example of a question I was thinking of, I wanted to know how I could use the pencil tool in the midi editor of Studio One to change the pitch of notes. This isn't really related to sound design directly, but I feel it's a little too niche to ask over on superuser. [This question](https://sound.stackexchange.com/questions/24062/how-can-i-map-midi-controller-faders-to-midi-cc-values-through-software-in-cubas), which I asked on AVP and got migrated here, is similar, but since it was part of a big migration I'm not sure if it's *really* on topic.
Would this type of question about how to accomplish *task* with *specific digital audio workstation* be kosher for this site? | 2014/03/13 | [
"https://sound.meta.stackexchange.com/questions/132",
"https://sound.meta.stackexchange.com",
"https://sound.meta.stackexchange.com/users/6609/"
] | Nope. Learning to use basic daw tools is not at all sound design.
How to do it should be kosher IF the question was asked not from a usability standpoint but from a conceptual standpoint.
As in "I built the sequence up like THIS to accomplish THAT (type of feeling or creative solution), but I don't quite get it to work this way in ProTools. Any suggestions on how to do this differently?"
That is indeed a question in search of a specific technical/how-to answer. But based on a conceptual approach and seeking guidance on what to do next. | i'll go first: no they are not, unless you want the RTFMs and down-votes. |
316,921 | I'm looking for an equivalent to the following proverb which states, "The cactus is only visited when he has prickly pears." It means something like "He is only visited when he has money." I can't think of any in English to be equal. | 2016/03/31 | [
"https://english.stackexchange.com/questions/316921",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/168146/"
] | Proverbs 14:20 reads
>
> The poor are shunned even by their neighbors, but the rich have many
> friends.
>
>
>
[[New International Version](http://biblehub.com/proverbs/14-20.htm)]
But this is far more transparent, and one version even helpfully [!] puts 'friends' in scare quotes. I think I'll start using the translation of the Mexican proverb. | In the American Blues tradition, the expression
>
> Nobody knows you when you['re] down and out
>
>
>
has been a familiar refrain for [almost a hundred years](https://en.wikipedia.org/wiki/Nobody_Knows_You_When_You're_Down_and_Out). On YouTube, you can hear [Bessie Smith's 1929 version](https://www.youtube.com/watch?v=6MzU8xM99Uo) of the blues song of that name. The sense of the expression is, of course, that everyone is your friend—and is happy to help you spend your money—when you're rich, but no one wants to associate with you if they can't derive any material benefit from it. |
4,281,424 | I've got safe/sanitized HTML saved in a DB table.
How can I have this HTML content written out in a Razor view?
It always escapes characters like `<` and ampersands to `&`. | 2010/11/25 | [
"https://Stackoverflow.com/questions/4281424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/520640/"
] | Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.
```
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
```
Results in
```
(<b><script>console.log('insert')</script>Hello</b>)
``` | Complete example for using template functions in RazorEngine (for email generation, for example):
```
@model SomeModel
@{
Func<PropertyChangeInfo, object> PropInfo =
@<tr class="property">
<td>
@item.PropertyName
</td>
<td class="value">
<small class="old">@item.OldValue</small>
<small class="new">@item.CurrentValue</small>
</td>
</tr>;
}
<body>
@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }
</body>
``` |
57,200,052 | **Target** : if the **8th (or n of )** of character in string **match condition**, **then update in new column**
**By word in a single string :**
```
# if i want to check the 3rd character
IN[0]: s = "apple"
s[2]
OUT[0]: 'p'
```
**Code** :
```
tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"])
tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE",
pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN",
pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE")))
```
**Problem** :
Apparently `[7]` is not a python practice
**In R data.table :**
```
tt[grepl("J",str_sub(CC,8,8)),
"NAME":="JANICE"]
tt[grepl("K",str_sub(CC,8,8)),
"NAME":="KELVIN"] # .... can achieve by doing like this
```
How can i do this in Python ? | 2019/07/25 | [
"https://Stackoverflow.com/questions/57200052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8935953/"
] | Use Regex.
**Ex:**
```
import re
s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401"
m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%"
if m:
print(m.group(1))
```
**Output:**
```
1.08
``` | Use string find operation:
**Example**
```
my_string="2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401"
fst = my_string.find("DDD=")
snd = my_string.find("%")
if fst >= 0 and snd >= 0
print(my_string[fst+4,snd])
```
**Output**
```
1.08
```
Or you can use split:
**Example**
```
my_string="2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401"
(fst,snd) = my_string.split("DDD=");
(trd,fourth) = snd.split("%");
print(trd)
```
**Output**
```
1.08
``` |
6,172,451 | I am developing an application wherein I get the latitude, longitude in my android device and post them to a web server.
and in a web application I show the location details with the help of google maps.
Here I have huge collection of lat long values which i loop it in my jsp and create multiple markers with info windows.
Now the problem is that I need to show the location name of the particular latitude and longitude in the Info Window of google maps.
Can anyone help me with the google maps script or how can i get the location name from the lat long values in my android phone itself, so that I can post that to my web server. | 2011/05/30 | [
"https://Stackoverflow.com/questions/6172451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/746921/"
] | ```
StringBuilder _homeAddress = null;
try{
_homeAddress = new StringBuilder();
Address address = null;
List<Address> addresses = _coder.getFromLocation(_lat,_lon,1);
for(int index=0; index<addresses.size(); ++index)
{
address = addresses.get(index);
_homeAddress.append("Name: " + address.getLocality() + "\n");
_homeAddress.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
_homeAddress.append("Admin Area: " + address.getAdminArea() + "\n");
_homeAddress.append("Country: " + address.getCountryName() + "\n");
_homeAddress.append("Country Code: " + address.getCountryCode() + "\n");
_homeAddress.append("Latitude: " + address.getLatitude() + "\n");
_homeAddress.append("Longitude: " + address.getLongitude() + "\n\n");
}
}
catch(Exception e){
}
``` | ```
private String getAddress() {
GPSTracker gps = new GPSTracker(ProductList.this);
Geocoder geocoder = new Geocoder(ProductList.this, Locale.getDefault());
String address="";
try {
List<Address> addresses = geocoder.getFromLocation(gps.getLatitude(), gps.getLongitude(), 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
//optional
/* add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();*/
Log.e("Location", "Address" + add);
address=add;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return address;
}
``` |
14,217,216 | ```
#include <stdlib.h>
struct timer_list
{
};
int main(int argc, char *argv[])
{
struct foo *t = (struct foo*) malloc(sizeof(struct timer_list));
free(t);
return 0;
}
```
Why the above segment of code compiles (in gcc) and works without problem while I have not defined the foo struct? | 2013/01/08 | [
"https://Stackoverflow.com/questions/14217216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581085/"
] | because in your code snippet above, the compiler doesn't need to know the size of `struct foo`, just the size of a **pointer** to `struct foo`, which is independent of the actual definition of the structure.
Now, if you had written:
```
struct foo *t = malloc(sizeof(struct foo));
```
That would be a different story, since now the compiler needs to know how much memory to allocate.
Additionally, if you at an point you try to access a member of a `struct foo*` (or dereference a pointer to a foo):
```
((struct foo*)t)->x = 3;
```
The compiler would also complain, since at this point it needs to know the offset into the structure of `x`.
---
As an aside, this property is useful to implement an [Opaque Pointer](http://en.wikipedia.org/wiki/Opaque_pointer). | "And what about free(t)? Can the compiler free the memory without knowing the real size of the struct?"
No, compiler doesn't free anything. Free() is just a function with input parameter void \*. |
32,120 | I'm building a test suite with Cucumber on Java + Maven + jUnit and I need to pass a username and a password to the test suite so it can log in to the application under test.
I don't like the idea of hardcoding the credentials, so I thought maybe I should be passing them as arguments when running the maven command, or maybe I can add them in the pom.xml somewhere and then read them in the code. But I don't know how to do either. Or maybe there's a third option that I haven't thought of... | 2018/02/16 | [
"https://sqa.stackexchange.com/questions/32120",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/25971/"
] | There is a feature called **Scenario Outline** for data driven tests in cucumber.
It can be used in this scenario to pass different user/passwords as data to the test as parameters.
[](https://i.stack.imgur.com/K6ouF.png) | I've found that [keychain](https://github.com/conormcd/osx-keychain-java) and secret stash can help with these - plugins that can access your operating system's credential storage.
The documentation should give you more information, but essentially, you store your passwords in your OS's password manager, and then call the plugin's library to get the passwords like an api. |
57,057,162 | \*\*There is a paragraph in the div class container, how can i hide the text before "-"? \*\*
```html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor - incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</body>
</html>
``` | 2019/07/16 | [
"https://Stackoverflow.com/questions/57057162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | in js
```
var element = document.querySelector('.container p')
if(element){
element.innerText = element.innerText.replace(/.*- /, '');
// if you need non greedy regexp use /.*?- / instead
}
``` | just put the content before - in a span.
and then apply display: none to span.
```
span{
display: none;
}
``` |
4,797,418 | Is there any method I can override that will allow me to use print statements / pdb / etc. to keep track of every time an instance of my class is allocated? While unpickling some objects I am seeming to get some that never have either `__setstate__` or `__init__` called on them. I tried overriding `__new__` and printing out the id of every object I make in `__new__`, but I am still encountering objects with ids that were never printed.
Edit: here is my code I use for altering (instrumenting) `__new__` of my class and all of its super-classes except for `object` itself:
```
class Allocator:
def __init__(self, my_class):
self.my_class = my_class
self.old_new = my_class.__new__
def new(self, * args, ** kargs):
rval = self.old_new(*args, ** kargs)
#rval = super(self.my_class,cls).__new__(cls)
print 'Made '+str(self.my_class)+' with id '+str(id(rval))
return rval
def replace_allocator(cls):
if cls == object:
return
setattr(cls,'__new__',Allocator(cls).new)
print cls.__base__
try:
for parent in cls.__base__:
replace_allocator(parent)
except:
replace_allocator(cls.__base__)
```
I call replace\_allocator on my classes' parent class as soon as it is imported in the main script. My class has a custom `__new__` to begin with, which also prints out the id. | 2011/01/25 | [
"https://Stackoverflow.com/questions/4797418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378469/"
] | (This is more of a comment than an answer.)
Quoting Guido's [Unifying types and classes in Python 2.2](http://www.python.org/download/releases/2.2.3/descrintro/#__new__):
>
> There are situations where a new instance is created without calling `__init__` (for example when the instance is loaded from a pickle). There is no way to create a new instance without calling `__new__` (although in some cases you can get away with calling a base class's `__new__`).
>
>
>
If you are using new-style classes (descendants of `object`), `__new__()` should always be called. I don't think the obscure cases "you can get away with calling a base class's `__new__`" in will happen accidently, though I don't know what these cases actually are.
And just to add an example:
```
In [1]: class A(object):
...: def __new__(cls):
...: print "A"
...: return object.__new__(cls)
...:
In [2]: A()
A
Out[2]: <__main__.A object at 0xa3a95cc>
In [4]: object.__new__(A)
Out[4]: <__main__.A object at 0xa3a974c>
``` | Not sure if this can help you, but Python's garbage collector has [introspective capabilities](http://docs.python.org/library/gc.html) that might be worth taking a look at. |
53,631,167 | I have a logic app which triggers my HTTP endpoint every 15 minutes. Then the endpoint connects to SharePoint using Rest API and gets the data from specific list which is then added to my db.
But to get the data from SharePoint, i need access token. Do i need to write logic to get access token in the endpoint itself? or is there any to pass access token from my logic app while triggering my endpoint ? | 2018/12/05 | [
"https://Stackoverflow.com/questions/53631167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215594/"
] | The error indicates that the Interval value has reached zero.
So these lines are executed several times until it crashes:
```
if (score > 0 && score % 1000 == 0)
{
GameTimer.Interval -= 20;
}
```
And that is because the condition is met in every interval after the timer passes the condition once.
Define your logic outside the timer code and you'll be fine:
```
void Score(int value){
score += value;
if (score <= 0) return;
if(score % 1000 == 0)
{
GameTimer.Interval -= 20;
//if(GameTimer.Interval <= 0) I suppose level is already finished...
}
}
```
edited
------
mjwills pointed out this issue that the interval still may hit zero. So you must write your code in a manner that eliminates this risk.
a non-linear reduction makes more sense in this case:
```
void Score(int value){
score += value;
if (score <= 0) return;
if(score % 1000 == 0)
{
GameTimer.Interval *= .9f;
if(GameTimer.Interval <= 0) GameTimer.Interval = 1;
}
}
``` | The tick rate cannot be less than or equal to 0.
You could simply add an if statement to check that:
```
if (GameTimer.Interval <= 20) {
GameTimer.Interval = 1;
} else {
GameTimer.Interval -= 20;
}
```
However, this means that the timer interval will reach a limit after a certain score is reached. Also, the screen can't update that fast (1000 times a second). You should probably keep the frame rate at 30fps.
Therefore, to make the animation appear faster, do a larger proportion of the animation in each second. For example, to move something 1000 pixels to the right, don't move it 1 pixel every 1/1000 of a second. Instead, move it 50 pixels every 1/20 of a second.
From your comment:
>
> The issue is that I do not understand why interval is going below zero, the if statement is executed only once, and it immediately gives me that error.
>
>
>
Then you are executing the if statement more than once. My guess is that you are running it in the timer tick event handler. Once your score reaches a multiple of 1000, that if statement will be run every time the timer ticks, until your score changes.
To fix this, you can put the code in the setter of the score. |
66,877,894 | I use Selenium Webdriver in a python script to download sites from my webpage and convert them into PNGs:
```
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
options = Options()
options.headless = False
SITE = "http://localhost/something_I_want_to_convert_with_hi-resolution.html"
DPI = 2.5
profile = webdriver.FirefoxProfile()
profile.set_preference("layout.css.devPixelsPerPx", str(DPI))
driver = webdriver.Firefox(options=options, firefox_profile=profile)
driver.get(SITE)
...
```
This worked fine until last month when I still used Ubuntu 20.04. It created the images with the right font [like this](https://cards.incantata.de/cdn/orig/card_135.png).
I guess exactly since the Ubuntu upgrade Firefox cannot load the custom fonts, I have included via css in my site, anymore and it loads the default fonts instead now.
What could have changed that behaviour? Was there a recent update in Ubuntu 20.10 that changed the behaviour of Firefox?
I get this error in the console which is strange:
`Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/css/fonts/kramer__.TTF. (Reason: CORS header 'Access-Control-Allow-Origin' missing).`
it is strange, because the font is in the same domain (`localhost`) so there shouldn't be a CORS error.
The same site works fine in Chrome and loads the fonts. Also in Waterfox-classic it loads the fonts just fine.
I would like to add something like:
```
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
```
but I serve the site locally with [ZeroNet](https://zeronet.io/), which is html-, CSS- and JS-only, so I think, I cannot change the headers sent.
I tried in firefox `about:config`:
* disable `content.cors.disable` (empty string)
* `security.fileuri.strict_origin_policy` False
* `privacy.file_unique_origin` False
but none of those had any effect.
If I install the [access-control-allow-origin addon](https://addons.mozilla.org/de/firefox/addon/access-control-allow-origin/) and enable `Access-Control-Allow-Origin: *` it also works fine, (I added that as a **workaround** below.)
How do I set Firefox to ignore the Cross-Origin Request? | 2021/03/30 | [
"https://Stackoverflow.com/questions/66877894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069083/"
] | might be your container/zeronet updated or firefox updated after that you are facing issue
For Temporary Workaround in chrome for localhost you can add — disable-web-security while starting chrome
in firefox you can do the following :
about:config -> security.fileuri.strict\_origin\_policy -> false | ### Workaround
1. go to `about:preferences` and create a new empty profile
2. change to that profile in a new window
3. install the **Allow CORS: Access-Control-Allow-Origin** there
now change your python code to use that new profile with
```
profile = webdriver.FirefoxProfile("/home/your_user/.mozilla/firefox/your_new_profile")
```
This will start the profile, wich already has installed the addon that fixes the CORS problem. |
4,323 | The title says it all. How can I detect duplicates in my media library? | 2010/09/18 | [
"https://askubuntu.com/questions/4323",
"https://askubuntu.com",
"https://askubuntu.com/users/2192/"
] | You can use [fdupes](http://en.wikipedia.org/wiki/Fdupes) for that:
```
$ fdupes -r ~/Music
```
which gives you a list of all duplicate files.
You can easily install it with
```
sudo apt-get install fdupes
``` | Try **FSlint** or dupe gredtter
To install **FSlint** type in terminal (Ctrl-Alt-T)
```
sudo apt-get install fslint
```
hope this is useful.. |
73,845 | I need a numerical example to illustrate cases where $Cov(X\_1, X\_2) = 0$. Can you think of examples involving functions or matrices? | 2013/10/26 | [
"https://stats.stackexchange.com/questions/73845",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/31672/"
] | As a very simple example (maybe too simple?), consider $X,Y\in\{0,1\}$ with joint distribution defined by the table
```
Y \ X 0 1
0 1/4 1/4 1/2
1 1/4 1/4 1/2
1/2 1/2 1
```
This table also displays the marginal distributions of $X$ and $Y$. First, check that $X$ and $Y$ are independent. For example,
$$
\mathrm{Pr}(X=0,Y=0) = 1/4 = 1/2 \times 1/2 = \mathrm{Pr}(X=0)\,\mathrm{Pr}(Y=0) \, ,
$$
and so on. Now, compute the distribution of $Z=X+Y\in\{0,1,2\}$. For example,
$$
\mathrm{Pr}(Z=1) = \mathrm{Pr}(X=1,Y=0) + \mathrm{Pr}(X=0,Y=1) = 1/2 \, .
$$
Using these distributions, compute $\mathrm{Var}(X),\mathrm{Var}(Y)$, and $\mathrm{Var}(Z)$. | Obviously whenever $X\_1,X\_2$ are independent but I guess that's not the point.
My go-to for dependent rvs is $U$ uniform on $[0,1]$ and take $X\_1 = \sin(2\pi U), X\_2=\cos(2\pi U)$. This basically says that if you pick a point uniformly on the unit circle then the coordinate functions are uncorrelated. This fact boils down to showing
$$
\int\_0^{2\pi} \sin(t)\cos(t) \ dt = 0.
$$ |
51,331,261 | I am facing a small problem where I can not select the character ':' which are not between two digits before and after ':' . Here are the examples:
```
user1:18 (should match)
date:2018-06-28 16:12:09 (should match : after 'date')
dueDate:28 (should match)
details:none (should match)
```
In the demo I only got look for the two digits foward. Someone can help me, please?
[Demo](http://regexr.com/3sdvg) | 2018/07/13 | [
"https://Stackoverflow.com/questions/51331261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556720/"
] | The logically appropriate regex for this is
```
(?<!\d):|:(?!\d)
```
I.e. a `:` not preceded by a digit or a `:` not followed by a digit (which matches all `:` except those surrounded by digits on both sides).
It looks like `gsub` from `mutate` just calls Ruby's native `gsub`, which supports both look-ahead and look-behind (`(?! )` and `(?<! )`, respectively). | `/:[^\d]|[^\d]:/` matches any colon that is either preceded by a non-digit or followed by a non-digit. Is that good enough? |
28,210,525 | Say there is a string: `"first option<option 1/option 2/option 3>second option<option 5/option 6/option 7>selection{aaaaa/bbbbb/ccccc}{eeeeee/fffff/ggggg}other string"`
Now I want to get 3 `ArrayList`
one for string inside "<>":
```
{"option 1/option 2/option 3", "option 5/option 6/option 7"}
```
one for string inside "{}":
```
{"aaaaa/bbbbb/ccccc", "eeeeee/fffff/ggggg"}
```
and one for both outside <>/{} and inside <>/{}:
```
{"first option", "<option 1/option 2/option 3>", "second option", "<option 5/option 6/option 7>", "selection", "{aaaaa/bbbbb/ccccc}", "other string"}.
```
I understand I can get string inside braces with code like:
```
String Str = "first option<option 1/option 2/option 3>second option<option 5/option 6/option 7>selection{aaaaa/bbbbb/ccccc}{eeeeee/fffff/ggggg}other string"`;
Pattern patt = Pattern.compile("<(.*?)>");
Matcher mtchr_r = patt.matcher(Str);
while (mtchr_r.find()){
String ssssssss = mtchr_r.group ();
}
```
but how to match string outside braces? and furthermore, how to get third ArrayList in order? | 2015/01/29 | [
"https://Stackoverflow.com/questions/28210525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3386916/"
] | With the use of `\G` (asserts that the next match starts from where the last match ends), it is possible to do this in one pass:
```
\G(?:[^<>{}]++|<(?<pointy>[^<>]++)>|\{(?<curly>[^{}]++)\})
```
A simple break down of the regex above:
```
\G # Must start from where last match ends
(?:
[^<>{}]++ # Outside {} <>
| # OR
<(?<pointy>[^<>]++)> # Capture content inside < > in group named 'pointy'
| # OR
\{(?<curly>[^{}]++)\} # Capture content inside < > in group named 'curly'
)
```
Assuming there is no `<>` inside `<>` and there is no `{}` inside `{}`, and there is no unmatched `<>{}`, the regex above should split the string correctly.
The regex will stop at the first position where it encounters an invalid sequence, so in my example code below, I make sure that the position of the last match is at the end of the string.
Full example program (Java 7, but you can remove the named capturing group to make it run in previous versions of Java):
```
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SO28210525 {
private static final Pattern re = Pattern.compile("\\G(?:[^<>{}]++|<(?<pointy>[^<>]++)>|\\{(?<curly>[^{}]++)\\})");
public static void main(String[] args) {
String input = "first option<option 1/option 2/option 3>second option<option 5/option 6/option 7>selection{aaaaa/bbbbb/ccccc}{eeeeee/fffff/ggggg}other string";
Matcher matcher = re.matcher(input);
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<String> curly = new ArrayList<String>();
ArrayList<String> pointy = new ArrayList<String>();
int lastIndex = 0;
while (matcher.find()) {
tokens.add(matcher.group(0));
String inCurly = matcher.group("curly");
if (inCurly != null) {
curly.add(inCurly);
}
String inPointy = matcher.group("pointy");
if (inPointy != null) {
pointy.add(inPointy);
}
lastIndex = matcher.end(0);
}
if (lastIndex != input.length()) {
System.err.println("Invalid input");
} else {
System.out.println(tokens);
System.out.println(curly);
System.out.println(pointy);
}
}
}
```
In previous version of Java (6 and below), as an alternative, you can use `Matcher.start` or `Matcher.end` method to check whether a capturing group captures something or not.
However, in Java 7, the corresponding `Matcher.start` and `Matcher.end` methods for named capturing group are missing (only `Matcher.group` is available). The 2 methods are later added in Java 8. | ```
(?<=<)[^>]*(?=>)|(?<={)[^}]*(?=})
```
You can use this to get both strings inside `<>` and `{}`.See demo.
<https://regex101.com/r/pM9yO9/19>
Use this to get all separately including those outside.
```
(?<=<)[^>]*(?=>)|(?<={)[^}]*(?=})|[^<>{}]+
```
<https://regex101.com/r/pM9yO9/20> |
18,915,688 | I am currently writing a Spring batch where I am reading a chunk of data, processing it and then I wish to pass this data to 2 writers. One writer would simply update the database whereas the second writer will write to a csv file.
I am planning to write my own custom writer and inject the two itemWriters in the customItemWriter and call the write methods of both the item writers in the write method of customItemWriter. Is this approach correct? Are there any ItemWriter implementations available which meet my requirements?
Thanks in advance | 2013/09/20 | [
"https://Stackoverflow.com/questions/18915688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1303680/"
] | Java Config way SpringBatch4
```
@Bean
public Step step1() {
return this.stepBuilderFactory.get("step1")
.<String, String>chunk(2)
.reader(itemReader())
.writer(compositeItemWriter())
.stream(fileItemWriter1())
.stream(fileItemWriter2())
.build();
}
/**
* In Spring Batch 4, the CompositeItemWriter implements ItemStream so this isn't
* necessary, but used for an example.
*/
@Bean
public CompositeItemWriter compositeItemWriter() {
List<ItemWriter> writers = new ArrayList<>(2);
writers.add(fileItemWriter1());
writers.add(fileItemWriter2());
CompositeItemWriter itemWriter = new CompositeItemWriter();
itemWriter.setDelegates(writers);
return itemWriter;
}
``` | Here's a possible solution. Two writers inside a Composite Writer.
```
@Bean
public JdbcBatchItemWriter<XPTO> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<XPTO>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("UPDATE xxxx")
.dataSource(dataSource)
.build();
}
@Bean
public JdbcBatchItemWriter<XPTO> writer2(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<XPTO>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("UPDATE yyyyy")
.dataSource(dataSource)
.build();
}
@Bean
public CompositeItemWriter<XPTO> compositeItemWriter(DataSource dataSource) {
CompositeItemWriter<XPTO> compositeItemWriter = new CompositeItemWriter<>();
compositeItemWriter.setDelegates(Arrays.asList( writer(dataSource), writer2(dataSource)));
return compositeItemWriter;
}
@Bean
protected Step step1(DataSource datasource) {
return this.stepBuilderFactory.get("step1").
<XPTO, XPTO>chunk(1).
reader(reader()).
processor(processor()).
writer(compositeItemWriter(datasource)).
build();
}
``` |
49,320,862 | I assume that an ES6 class is an object as "everything" is objects in JavaScript. Is that a correct assumption? | 2018/03/16 | [
"https://Stackoverflow.com/questions/49320862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1283776/"
] | From the point of view of `Object Oriented Programming` *class* is **not** an *object*. It is an *abstraction*. And every object of that is a concrete instance of that abstraction.
From the point of view of JavaScript, *class* is an *object*, because *class* is a *ES6* feature and under it simple function is used. It is not just an abstraction in Javascript, but also an object by itself. And that function is an object. It has it's own properties and functions.
So speaking in Javascript not everything is an object. There are also primitive types - `number`, `string`, `boolean`, `undefined`, `symbol` from `ES6`. When you will use some methods with this primitive types except `undefined`, they will be converted into the objects.
You can see the below example.
```js
const str = 'Text';
const strObj = new String('Text');
console.log(str);
console.log(strObj.toString());
console.log(typeof str);
console.log(typeof strObj);
```
There is also one extra primitive type `null`, but checking it's type returns an *object*. This is a bug.
```js
console.log(typeof null);
``` | ES6 class is a function, and any function is an object:
```
(class {}).constructor === Function
(class {}) instanceof Function === true
(class {}) instanceof Object === true
```
Although not every object is `Object` instance:
```
Object.create(null) instanceof Object === false
```
The statement that everything is an object is not correct. That's an oversimplified way to say that some primitive values in JavaScript can be *coerced* to objects:
```
(1).constructor === Number
1 instanceof Number === false
```
But primitives aren't objects until they are *converted*:
```
Object(1) instanceof Number === true
Object(1) instanceof Object === true
```
And `null` and `undefined` can't be coerced at all:
```
null instanceof Object === false
Object(null) instanceof Object === true // conversion
(null).constructor // coercion error
typeof null === 'object' // JS bug
``` |
3,546 | I am new to this site and posted a question about RAID 10 configuration in CentOS Linux on the Unix & Linux portion of the site.
[Software RAID 10 Array Space Loss](https://unix.stackexchange.com/questions/207997/software-raid-10-array-space-loss)
@psusi, @Anthon, @Archemar, @slm put the question on hold as off-topic. I had to research what this meant and after reading through the help topics referenced in the hold notice, I'm really confused as to why that question is off topic for a Unix & Linux site.
Hopefully I'm putting this question in the right place... | 2015/06/08 | [
"https://unix.meta.stackexchange.com/questions/3546",
"https://unix.meta.stackexchange.com",
"https://unix.meta.stackexchange.com/users/118358/"
] | The terminology in that close reason can be confusing since it's covering a few different scenarios:
>
> off-topic → Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers.
>
>
>
The question as it was previously phrased was off-topic, in the sense that it was not reproducible for a variety of reasons.
1. Users here do not have access to your hosting provider's environment
2. The question lacked enough details to be answerable
So myself and others selected this close reason since it was the one that matched closely with the situation as it stood at that time. You've since provided more details per feedback from @frostschutz, which has improved things.
One of the primary functions of closing a question is to block it from eliciting many partial answers which are attempting to answer a question which hasn't been asked with enough specificity.
If you read through [what makes a good question](https://unix.stackexchange.com/help/how-to-ask) these 2 bullets are pretty crucial:
>
> **Be specific**
> If you ask a vague question, you’ll get a vague answer. But if you give us details and context, we can provide a useful answer.
>
>
> **Make it relevant to others**
> We like to help as many people at a time as we can. Make it clear how your question is relevant to more people than just you, and more of us will be interested in your question and willing to look into it.
>
>
>
**NOTE:** I've personally never cared for the term "close" on questions since it has a negative connotation. Comments and closing are however, the 2 primary methods users have with interacting with the questions posted on the site.
Hopefully this makes a bit more sense to you and welcome to U&L. Hopefully you'll not take this as a negative experience. Everyone here is generally eager to help and there can be a bit of a learning curve if you're new to the StackExchange sites.
We appreciate you taking the time to read through the help (this is one of the biggest frustrations to older users of the site 8-)). Hopefully you've gained insight into why you were having your particular problem, and how the site as a whole, functions. | You cannot know this, but it's a side effect of this site being part of the larger Stack Exchange network. These sites all have a few common close reasons (e.g. the question is so broad the answers would fill a book). One of the close reasons is "off topic". What is "off topic" is defined per-site.
Most sites on the network found out that there are a few types of questions which frequently crop up, but are not good for the site, because they cannot produce satisfactory answers, or because they lead to flame wars. So each site got custom close reasons too. The questions could mostly be defined by their topic. For example, Cooking.stackexchange.com has as a custom close reason "question about health and nutrition". So this is where the custom close reasons are sorted, under "off topic".
It so happens that Unix and Linux has a custom close reason of "can't be reproduced", which is not a topic-bound category. But because all sites in the network run on instances of the same software, the custom close reason appears under the "off topic" part.
Also, your question here is in the right place on Meta. I also see that your original question got improved, reopened and answered - thank you for participating in this process, it is what we'd like to happen to most of our closed questions (except for the handful which is beyond salvaging). |
7,457,057 | this has been bugging me for over a week now, I seriously need help with this one,
I am basically trying to get one of my navigation buttons to toggle the sub menu, open and closed, but when open change the homepage opacity to 50% and when closed back to 100%
I also need the Button to work in relation to another div, when the div is open and faded out, I need this to change the homepage opacity to 50% also.
Can anyone help please?
I've provided a link with a mockup of what I am trying to achieve, although in this mockup the 'Motors' div seems to automatically fadeOut, I am trying to get it so when you 're-click' on categories the 'Motors' div will fadeOut, Homepage will fadeIn at 50% opacity.
[Mockup of What I'm trying to achieve](http://jsfiddle.net/Djsquid/2jSya/)
PS I am a Jquery Beginner, and Now have no idea what to do.
Thank you.
---
hey guys thanks for answering,
The problem itself isn't actually the motors div automatically fading out, I seem to have that working correctly on my actual site.
The problem lies when the Motors div is open, and when I 're-click' on Categories I want the homepage to fadeIn at 50% opacity. But also maintain the toggle feature on the Catergories so the User can come off the menu at any given time.
I've had a think and could this be achieve by a Jquery If statement?
If the Sub menu is open then Fade the homepage to 50%? if so how would I write this in Jquery as I am baffled?
Thanks again for your input though. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7457057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/950555/"
] | If you want to change your current working directory for a script, then use the && between the CD and script so it will change directory and then if that's successful it will execute the second command.
```
mysql> SYSTEM cd /home && ls
``` | What you're looking for is the escape to shell command: `\!`
```
mysql>\! cd ./my_dir
```
You can even use it to escape to the shell completely and then come back to the mysql environment.
```
mysql>\! bash
bash>cd ./my_dir
bash>exit
mysql>SELECT * ALL FROM <table>;
``` |
6,410,494 | I am developing a visual C++ video capture application using DirectShow. When I checked the media subtype of the AM\_MEDIA\_TYPE structure of the Capture filter's Output pin, I could see that different webcams capture data in different formats such as MEDIASUBTYPE\_RGB24, MEDIASUBTYPE\_MJPG etc.
Is there any way I can tell the Output pin to output data in a common format like MEDIASUBTYPE\_RGB24? I don't want to include the deciphering of all the sub-types possible.
Request you to let me know if I have any way around to make all the Webcam captured data to a common type before passing it to the Encoder. | 2011/06/20 | [
"https://Stackoverflow.com/questions/6410494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807858/"
] | Besides [what raj correctly said](https://stackoverflow.com/q/6410492#6410562) about the error messages you'd receive if using `use 5.014` with an older version of Perl, you can find a list of features enabled reading the [source code of `feature`](http://cpan.uwinnipeg.ca/htdocs/perl/feature.pm.html#package-feature-). The relevant part is near the top:
```
my %feature_bundle = (
"5.10" => [qw(switch say state)],
"5.11" => [qw(switch say state unicode_strings)],
"5.12" => [qw(switch say state unicode_strings)],
"5.13" => [qw(switch say state unicode_strings)],
"5.14" => [qw(switch say state unicode_strings)],
);
```
The strict bit part is buried somewhat deeper in the code for the interpreter itself. If you look into [`pp_ctl.c` for tag v5.11.0](http://perl5.git.perl.org/perl.git/blob/96054f1230156cd59ef1d361884fb4cd0e8a0447:/pp_ctl.c#l3262):
```
/* If a version >= 5.11.0 is requested, strictures are on by default! */
if (PL_compcv && vcmp(sv, sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
PL_hints |= (HINT_STRICT_REFS | HINT_STRICT_SUBS | HINT_STRICT_VARS);
}
``` | The `use x.x.x` pragma **does** turn on some features, and it's easy enough to test this:
```
#!/usr/bin/env perl
use warnings;
use 5.14.0;
say "hello world!"
```
Runs great; outputs "hello world!".
```
#!/usr/bin/env perl
use warnings;
# use 5.14.0;
say "hello world!"
```
Flaming death; outputs this error message:
```
Unquoted string "say" may clash with future reserved word at foo line 5.
String found where operator expected at foo line 5, near "say "hello world!""
(Do you need to predeclare say?)
syntax error at foo line 5, near "say "hello world!""
Execution of foo aborted due to compilation errors.
```
I'm not, however, 100% sure which features are turned on as of 5.14.0. I believe that you get `say`, `state`, `switch`, `unicode_strings` and `strict`. |
71,914 | I saw this photograph by Ben Leshchinsky:
[](https://i.stack.imgur.com/kfU6R.jpg)
[Source](https://www.nationalgeographic.com/photography/photo-of-the-day/2014/10/lake-louise-banff/)
I understand that the photograph was taken from a high vantage point, but the rock face seems to be like a wall. What is disorienting is that it seems the background is "folded" over.
I have seen some other photos that use this technique too:
[](https://i.stack.imgur.com/eTHG5.jpg)
How is this done? | 2015/12/17 | [
"https://photo.stackexchange.com/questions/71914",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/11582/"
] | Looks like a very long lens to me, as the perspective looks very compressed.
It's often used on rows of picturesque houses hugging a hillside to make them all look like they are in the same plane, giving a very "painting-like" effect.
It's an effective artistic trick because as you've noticed, it looks very unlike what you would see with the naked eye.
EDIT: The wider crop of the desert image in the comments shows that if the landscape itself is weird enough, any photographic technique will make it continue to look weird :)
In fact, cropping will give an identical effect to a long lens, although obviously with a reduction in pixel resolution, which will be pretty dramatic if you are trying to duplicate the effect of a very long lens. | Perception is a mental activity that uses organized inputs. If the input received is not clearly organized, then the mind takes over and creates a most plausible organization for it before perceiving. In this instance, the high altitude, lack of perspective and clear sense of scale, the transition from the monochromatic ground to color water area do not seem to provide sufficient organized input and the mind is perceiving it as something sensible. I discussed a similar set of questions when a collection of my photographs were published in LensWork Magazine. The photographs were taken from commercial airline windows with an infrared camera, the lack of scale and what I called "minified" features made the mountains look like skin texture under microscope and the rivers like athletes veins. If you are curious about the collection, visit <http://goo.gl/7q91Dr> or do a Google search on "infrared earthscapes." You will have similar sensations due to the ambiguity of the stimuli. |
804,276 | While making some changes in `exim4`, I decided to use the monolithic config style. So as not to confuse myself, I deleted `/etc/exim4/conf.d/`. I now regret this and wish to switch back to the split config style.
However, no amount of `dpkg-recongifure`ing or `update-exim4.conf`ing will bring the files back. In fact, I am thoroughly confused by the configuration scheme for exim4 on ubuntu 16.04.
**Could someone tell me how to restore the split configuration files and remove `exim4.conf.template`?** (I don't mind if this reset my configuration, I can easily restore it).
Could someone please explain how exim decides which config files to load in which order? The manuals reference all sorts of default filenames. | 2016/09/20 | [
"https://serverfault.com/questions/804276",
"https://serverfault.com",
"https://serverfault.com/users/376317/"
] | I think you can just do this.
```
/usr/bin/mysqldump -h $mysql_host -u $mysql_username -p$mysql_password $mysql_database | gzip -9 -c > $backup_path/$today/$mysql_database-`date +%H%M`.sql.gz
``` | You can pipe it though **gzip** (or **bzip2**, **pbzip2**, **xz**, etc...) like so:
```
/usr/bin/mysqldump -h $mysql_host -u $mysql_username -p$mysql_password $mysql_database | gzip -c > $backup_path/$today/$mysql_database-`date +%H%M`.sql.gz
```
**zip** isn't the optimal tool for this job because it stores data as files in an archive (like tar + gzip), where the other tools just compress data.
mysqldump (`mysqldump -C`) also supports compressed communication which could perhaps make things transfer faster over the network. |
26,467 | The ability to title/attach an author to a published PDF file is in [`\hypersetup`](http://en.wikibooks.org/wiki/LaTeX/Hyperlinks) which is part of package `hyperref`. But it seems rather unintuitive to me that the `pdftitle`, `pdfauthor`, `pdfsubject` items are part of the `hyperref` package. Why is that?
A reason I can think of that they might have done this is because search engines will crawl through that data? | 2011/08/25 | [
"https://tex.stackexchange.com/questions/26467",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/5950/"
] | From my reading of OP's question, it sounds like he's asking, if Latex as an overall collection of software/ utilities were made by one person or group, why would they choose to put PDF titling in `hyperref`, a package seemingly with the more concise goal of providing hyper referencing?
So, the best answer might be to point out that Latex is a collections of SW/ utilities/ tools made by many independent groups, usually working without a higher-level organizing structure.
So, in this case, I suspect that kind of like Alan said above, whoever made `hyperref` probably felt this PDF titling/ author listing functionality wasn't easily accessible in any other package, and figured that since they knew how to do it anyway, they'd just throw it into `hyperref`.
It's not that somebody explicitly said "I'm going to put PDF titling in `hyperref` rather than some other more obvious package." | Actually PDF titling can be done using pdfLaTeX without any additional package. For example:
```
\documentclass{article}
\pdfinfo{
/Title (thesis.pdf)
/Creator (TeX)
/Producer (pdfTeX 1.40.0)
/Author (Stefan)
/Subject (Artificial intelligence and self-modifying TeX documents)
/Keywords (pdflatex,latex,pdftex,tex)}
\begin{document}
text
\end{document}
```
Hyperref provides an additional interface. Moreover, it can be used in DVI mode, encapsulating the PDF meta information by special commands within the DVI file, appearing in the PDF after conversion to PDF. |
3,770,100 | I'm trying to set a defaultValue to a ListPreference item.
Here is an sample of my preference.xml file:
```
<ListPreference android:key="notification_delay"
android:title="@string/settings_push_delay"
android:entries="@array/settings_push_delay_human_value"
android:entryValues="@array/settings_push_delay_phone_value"
android:defaultValue="????">
</ListPreference>
```
The two arrays:
```
<string-array name="settings_push_delay_human_value">
<item>every 5 minutes</item>
<item>every 10 minutes</item>
<item>every 15 minutes</item>
</string-array>
<string-array
name="settings_push_delay_phone_value">
<item>300</item>
<item>600</item>
<item>900</item>
</string-array>
```
When i go into the preference activity, no item of the ListPreference is selected. I've tried to set an int value like 1 in the "android:defaultValue" fied to select "10 minutes" but it does not work.
```
<ListPreference android:key="notification_delay"
android:title="@string/settings_push_delay"
android:entries="@array/settings_push_delay_human_value"
android:entryValues="@array/settings_push_delay_phone_value"
android:defaultValue="1">
</ListPreference>
```
Any Idea? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384483/"
] | In addition to Sven's answer, you have to call the setDefaultValues() method in the starting activity. This will set once all default values.
```
public class MainActivity extends Activity {
protected void onCreate(final Bundle savedInstanceState) {
// Set all default values once for this application
// This must be done in the 'Main' first activity
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
...
}
}
``` | If it is a valid value from the list, then re-install the app. It will work. |
16,267 | Why can't James, Laurent & Victoria "hear" Bella's heartbeat as they are standing in the field? In all of the books it is made quite clear that the vampires hear Bella's heartbeat whenever she's in close proximity to them. Any ideas? | 2012/05/06 | [
"https://scifi.stackexchange.com/questions/16267",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/-1/"
] | In Midnight Sun, Chapter 24, Blood, it shows that Edward had red eyes and that he used contacts to cover up. | Vampire not only have red or golden eyes color, it is said that they also have blue,green, etc. The color of their eyes show their best vampire power, for example, if a vampire have green eyes, they are very good in speed and so on. |
914,583 | I need to add a choice field to sharepoint that has values depending on the current selection.
Example:
if the current selection is Open then the options have to be 'open, and In progress
```
**Current selection | Possible selections**
Open | Open,In progress
In progress | In progress,To be communicates,rework
Rework | Rework,In Progress
```
...
That way i am forcing the user to follow some specific flow | 2009/05/27 | [
"https://Stackoverflow.com/questions/914583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64160/"
] | You can achieve this sort of behavior by editing your list's EditForm.aspx page and adding some JavaScript to the page.
Although I can't seem to find any examples for making dependant drop downs, there are a couple examples of modifying the EditForm to hide fields or make them readonly:
* [Making a field read-only](http://cakriwut.wordpress.com/2006/07/31/how-can-javascripters-create-custom-editform-without-understanding-caml-and-net/)
* [Hiding an entire row on the edit-form](http://www.cleverworkarounds.com/2008/02/07/more-sharepoint-branding-customisation-using-javascript-part-1/) | So these are 2 columns out of which one filters the other?
Sounds like a cascading drop down list, there are a few (commercial) solutions out there.
See
<http://cascddlistwithfilter.codeplex.com>
for a free one. |
49,142,180 | I am starting to learn how to handle multiple tabs in a browser using Selenium with Java. looks like my code below is not working.
```
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static void main(String[] args) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
//Get Data Policy
WebElement we= driver.findElement(By.linkText("Data Policy"));
//Click Data Policy link
we.click();
//Create an arrayList
ArrayList<String> s1= new ArrayList<String>(driver.getWindowHandles());
for(String s2:s1)
{
if(!(s2.equalsIgnoreCase(parent)))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
}
}
```
Please let me know how can I display the title 'Data Policy' without using
getWindowHandles(). | 2018/03/07 | [
"https://Stackoverflow.com/questions/49142180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9453967/"
] | I had a loader on the page that was showing until all the data was returning on the page:
```
public getData() {
this.loading = true;
this.homeService.getData().subscribe(response => {
this.resort = response;
this.loading = false;
this.error = false;
this.getMap();
}, error => {
this.loading = false;
this.error = true;
});
}
```
So even though ngAfterViewInit was running, the data from the database still wasn't back by the time that function ran, which was why it wasn't able to find the element as the actual data was hidden from an \*ngIf until this.loading was false. So to correct I'm just calling getMap() once the data has been returned, rather then in the AfterViewInit function.
I then had to wrap that getMap function in a setTimeout to ensure the \*ngIf was loading the content data before I was trying to access the element as well:
```
public getMap() {
setTimeout(() => {
// accessing element here
});
}
``` | Perhaps because `HomeComponent` has no `@Component` annotation?
For one thing, without `@Component`, there's no way for `HomeComponent` to know that home.component.html is its template, and if it doesn't know its template, it doesn't know `#gmap` is a view child. Simply matching templates to classes by naming convention or file location isn't enough. |
18,185,749 | i have two hbase input aliases:
```
X:
(a1,b2)
(a2,b2)
...
(an,bn)
Y:
(c1)
(c2)
...
(cn)
```
Now i want to "join" both aliases: the first line from X with the first line from Y. The final result should be:
```
RESULT:
(a1,b1,c1)
(a2,b2,c2)
...
(an,bn,cn)
```
How can I do that? | 2013/08/12 | [
"https://Stackoverflow.com/questions/18185749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653748/"
] | Use `.index()`
```
var index = $('.focus').index();
```
[**DEMO**](http://jsfiddle.net/7YPAn/)
**Specific list**
```
$('.mylist .focus').index()
```
[**DEMO**](http://jsfiddle.net/7YPAn/1/) | In pure JavaScript:
```
var index = 0;
var lis = document.getElementsByTagName('li');
for (var len = lis.length; index < len; ++index) {
if (lis[index].className.match(/\bfocus\b/)) {
break;
}
}
```
[(fiddle)](http://jsfiddle.net/nAKZF/) |
59,261,198 | I am writing a bash script that takes information from a text file called "studentlist.txt" and that text file gets passed to the script through a positional parameter. The text file contains firstname, lastname, and ID number. Using that information, I have to create a username and the username is a combination of First Name Initial, Full Last Name, and Last Four digits of the ID number. Afterwards I have to use the usernames created to delete users from the OS. So far, this what I coded thus far.
```
#! /bin/bash
studentlist=$1 ### Storing the Positional Parameter into the variable called studentlist
if [ $# != 0 ] ### If a positional parameter does exist, then do the following.
then
initial=`cat ${studentlist} | awk {'print $1'} | cut -c1`; ### Print the First Field in Studentlist, which is First Name for us. And we only care about the initial.
lastname=`cat ${studentlist} | awk {'print $2'}`; ### Print the Entire Last Name.
id=`cat ${studentlist} | awk {'print $3'} | grep -o '....$'`; ### Print only the Last Four Digits of the Student ID.
username="$initial$lastname$id" ### Concatenate all the variables to create the username.
fi
echo $username ### Print to the Screen all usernames created.
```
When I run the script, the following shows up on the terminal:
```
Welcome to the script Remove_Accounts
This script uses utilizes GetOpts, for more information on the script use the flag -h
J O L S K C B EDoe Raborn Gillan Bisram Escudero Espinal Ghamandi Zelma5678 6789 7891 8912 9123 1234 2345 3456
```
Which isn't what I want, I only want the full username to show up for which user. For example, the usernames should be showing up as the following:
```
JDoe5678
ORaborn6789
LGillan7891
SBisram8912
KEscudero9123
CEspinal1234
BGhamandi2345
EZelma3456
```
The text file "studentlist.txt", contains the following information:
>
> John Doe 12345678
>
>
> Oswaldo Raborn 23456789
>
>
> Lesia Gillan 34567891
>
>
> Sammy Bisram 45678912
>
>
> Kelvin Escudero 56789123
>
>
> Cecile Espinal 67891234
>
>
> Boris Ghamandi 78912345
>
>
> Evia Zelma 89123456
>
>
>
Any help would be greatly appreciated. I have been at this for a long but I can't seem to get it to work. Thank you! | 2019/12/10 | [
"https://Stackoverflow.com/questions/59261198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12509438/"
] | Is there any need to involve a shell script at all? `awk` alone can handle generating and outputting the combined names without any help from the shell. In your case:
```
$ awk 'NF==3{printf "%s%s%s\n", substr($1,1,1), $2, substr($3,5)}' studentlist.txt
JDoe5678
ORaborn6789
LGillan7891
SBisram8912
KEscudero9123
CEspinal1234
BGhamandi2345
EZelma3456
```
It does so without invoking any other subshell. If you need this information for further processing in your script, you can read the generated names into an array and have the user ID info available persistently within your script. All that requires is reading the names into an indexed array, e.g.
```
arr=($(awk 'NF==3{printf "%s%s%s\n", substr($1,1,1), $2, substr($3,5)}' studentlist.txt))
```
Where the call to `awk` was placed in a *command-substitution* that is then used to populate the elements of the indexed array.
Look things over and let me know if you have any further questions. | here is a working script:
```
#!/usr/bin/env bash
PATH_STUDENTS_FILE="studentlist.txt"
USERS_LIST=($(awk '{print substr($1,1,1) $2 substr($3,length($3)-3,length($3))}' "${PATH_STUDENTS_FILE}"))
for USER in "${USERS_LIST[@]}"
do
echo "Delete user account: ${USER}"
userdel -r "${USER}"
done
```
The result:
```
root@ubuntu:# ./script.sh
Delete user account: JDoe5678
Delete user account: ORaborn6789
Delete user account: LGillan7891
Delete user account: SBisram8912
Delete user account: KEscudero9123
Delete user account: CEspinal1234
Delete user account: BGhamandi2345
Delete user account: EZelma3456
``` |
3,337,868 | The question is: Which term of the geometric sequece $4,12,36,\ldots$ is equal to $78732.$
My process of working it out is:
$t\_n= t\_1\cdot r^{n-1}$
$78372 = 4\cdot3^{n-1}$
$78372 = 12^{n-1}$
From here onwards I am not sure on what to do. Like how do I go further into solving which term it is. Any steps or comments if I am on the right track or any help is appreciated | 2019/08/29 | [
"https://math.stackexchange.com/questions/3337868",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/669859/"
] | $$4\cdot3^{n-1}=78732$$ or
$$3^{n-1}=19683$$ (here was your mistake) or
$$n=1+\frac{\ln19683}{\ln3},$$
which gives $n=10.$
Also, it's better to learn that $$3^9=19683.$$ | Note that $78732 = 4\cdot3^{n-1}$ does not imply $78732 = 12^{n-1},$ as you wrote. Instead, from the first equation, divide both sides by $4$ to get $19683= 3^{n-1}.$ This says that $19683$ is some power of $3.$ Multiply both sides by $3$ to give $$3×19683 = 3^n.$$ Now taking logs to base $3$ gives $$1+\log{19683}=n,$$ which you may work out on a calculator. |
678,393 | ETA: When I ask "Why do you not use CPAN modules?", I am referring to the people who refuse to use **any** CPAN modules (including high quality ones like [DBI](http://search.cpan.org/dist/DBI/DBI.pm)). Not all CPAN code is of high quality, and it is fine to stay away from modules that are trivial or are based on experimental code (I got annoyed at a developer the other day for wanting to bring in [Time::Format](http://search.cpan.org/dist/Time-Format/lib/Time/Format.pm) just because he didn't know that strftime was in [POSIX](http://perldoc.perl.org/POSIX.html)).
Recently on [Perl Beginners](http://www.nntp.perl.org/group/perl.beginners/), someone want to know how to do something without resorting to the Perl module commonly suggested for that function. He or she did not want to install the module from CPAN. This made me think about the reasons I have seen people avoid using CPAN and I came up with five reasons for this behaviour and the solution for each one:
1. they scare you (answer, get over it)
2. they scare your sysadmins (answer, work around them by
installing in your home directory and use the lib pragma)
3. you are using a hosting service that prevents you from
installing modules (answer, get a better service, there
are cheap services that don't behave like morons)
4. the target machine doesn't necessarily have the needed
module (answer, use PAR or PAR::Packer)
5. the target machine is totally locked down (i.e. you login
to rbash and have to provide code to a third party for
inclusion on the box) (a combination of 4 and going through
the bureaucracy)
6. You are using an embedded version of Perl that can't load modules (no answer, you are stuck, but this is very rare)
So, if you don't use CPAN, why, and why are the answers above not adequate? Note, I am not asking why you don't install directly from CPAN on production boxen, I am asking why you avoid using the modules from CPAN (installing via packaging systems count as using CPAN to me). | 2009/03/24 | [
"https://Stackoverflow.com/questions/678393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78259/"
] | You may have the Perl scripting engine embedded in a host application (for example a webserver, or any complex application requiring scripting), and have a whole lot of restrictions in that embedded context, like not being able to load files. | This is an answer with the positive approach, i.e. it says how you can fix the restrictions keeping you from using CPAN modules: [Yes, even you can use CPAN](http://perlmonks.org/?node_id=693828). |
8,263,477 | So i have a NivoSlider on my page. My problem is that i want the first slide only to show for 2 seconds, and all the other slides for 5 seconds (first one is only some text "Product version 2 is here"). How can i do this? i didn't find any (good) documentation at <http://nivo.dev7studios.com/support/> .
here is what i tried:
```
<script type="text/javascript">
$(window).load(function() {
$('#slider').nivoSlider({
pauseTime:2000,
pauseOnHover: false,
controlNav:false,
directionNav:true,
directionNavHide:true,
effect:'sliceDown',
captionOpacity: 0.9,
afterChange: function(){$('#slider').nivoSlider().defaults({pauseTime:5000})}
});
});
</script>
```
the last line here `afterChange: function(){$('#slider').nivoSlider().defaults({pauseTime:5000})}` is called, but the my attemp to change the initial settings fails - it only destroys the animations (flips from one slide to the next without anim) and does not change the pause time.
does anyone know how to change the pause/delay between the slides during runtime? | 2011/11/24 | [
"https://Stackoverflow.com/questions/8263477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728410/"
] | I had this same problem as I had a page with 3 sliders on it, where we wanted 1 to change every 5 seconds, which meant while each one had a 15 second pauseTime, the second one needed a 5 second delay, and the 3rd needed a 10 second delay. I tried the above solutions and many others but couldn't get it to work with the mutliple sliders. I ended up fixing it by adding a new setting "recurPauseTime" and then adding the following to the nivo:animFinished function:
```
clearInterval(timer);
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.recurPauseTime);
```
This allowed me to set it up like:
slider1:
```
pauseTime: 5000,
recurPauseTime:15000
```
slider2:
```
pauseTime: 10000,
recurPauseTime:15000
```
slider3:
```
pauseTime: 15000,
recurPauseTime:15000
``` | I was having a similar problem. I'm using the fade transition, and it seems like the animSpeed is part of the pauseTime for all slides except the first slide. So, I had these settings:
```
effect: 'fade',
animSpeed: 3000,
pauseTime: 7000,
```
And it seemed like the first slide displayed for 7 seconds, then all subsequent slides display for just 4 seconds before the fade effect starts.
I tried Sinetheta's solution by setting the timeout to 4000, and it does make the transition start faster on the first slide, but now the second slide displays for a really long time. Now it looks like the second slide displays for the 7000 plus the 4000 before starting the transition.
Has anyone else seen this? Any solutions?
Thanks,
Jerri |
39,079,850 | I am learning Protractor and it seems great. But I'd like to run couple of specs on a single page opening. How can I achieve that? My problem is, a lot of stuff on my page is loaded via ajax, some by cascade.
Currently, I am running specs by using `wait` and `beforeEach`. Here's the code:
```
const br = browser;
const url = 'http://localhost:3000';
br.ignoreSynchronization = true;
describe('Component', () => {
beforeEach(() => { br.get(url); });
it ('should be present', () => {
expect(element(by.className('news-list__wrapper')).isPresent()).toBe(true);
});
it ('should render children', () => {
br.wait(() => {
return element(by.className('news-block')).isPresent();
}, 2500).then((r) => { if (r) { console.log('\n ✓ Component renders children') } });
});
it ('should render images', () => {
br.wait(() => {
return element.all(by.className('news-block__img')).first().isPresent();
}, 2500).then((r) => { if (r) { console.log('\n ✓ Component renders images') } });
});
it ('should load images', () => {
br.wait(() => {
return element(by.className('news-block__image--loaded')).isPresent();
}, 2500).then((r) => { if (r) { console.log('\n ✓ Component loads images') } });
})
})
```
What can I do? | 2016/08/22 | [
"https://Stackoverflow.com/questions/39079850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409674/"
] | One way to do it is as follows:
```
$text = 'test'
$found = $false
$infile = '.\a.txt'
$outfile = '.\b.txt'
Get-Content -Path $infile | % {
if ($_ -match $text)
{
$found = $true
"SQL.test = False"
}
else
{
$_
}
} | Out-File -filepath $outfile
if (!$found)
{
"SQL.test = False" |Out-File -filepath $outfile -Append
}
```
This can be optimized further, I'm sure.
Basically what this does is use `Get-Content` to retrieve each line in the text file, and pipe them to `Select-String`.
If the text is found, the line is changed, if not, the original line is returned.
If the text is not found, then it's appended.
If the text is found the output is:
```
SQL.test = False
wer.vul = 1
temp_RTE = False
user_admin = no
```
else
```
wer.vul = 1
temp_RTE = False
user_admin = no
SQL.test = False
``` | I think that this should work for you :)
```
# Get content from the original file
$TXT = Get-Content "C:\temp\New Text Document.txt"
#Path to new file
$NewTXT="C:\temp\newTxt.txt"
$i=0
$TXT|ForEach-Object {
if ($_ -match "test")
{($_ -replace $_,"SQL.test = False") | Out-File $NewTXT -Append
$i++ #increment}
else
{$_ | Out-File $NewTXT -Append}
}
If ($i -eq 0) #if $i=0 no "test" found, need to add new line "SQL.test = False"
{"SQL.test = False" | Out-File $NewTXT -Append}
``` |
18,533,362 | I want to rotate the entire table 90 degrees in the anticlockwise direction. ie. contents of td(row=ith,column=jth) should be transferred to the td(row = (total number of rows-j+1)th , column = ith). The text inside the div also should be rotated by 90degrees.
```
<table><tbody>
<tr><td>a</td><td>1</td><td>8</td></tr>
<tr><td>b</td><td>2</td><td>9</td></tr>
<tr><td>c</td><td>3</td><td>10</td></tr>
<tr><td>d</td><td>4</td><td>11</td></tr>
<tr><td>e</td><td>5</td><td>12</td></tr>
<tr><td>f</td><td>6</td><td>13</td></tr>
<tr><td>g</td><td>7</td><td>14</td></tr>
</tbody></table>
```
this table should be transformed to
```
<table><tbody>
<tr>
<td>8</td><td>9</td><td>10</td><td>11</td>
<td>12</td><td>13</td><td>14</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td>
<td>5</td><td>6</td><td>7</td>
</tr>
<tr>
<td>a</td><td>b</td><td>c</td><td>d</td>
<td>e</td><td>f</td><td>g</td>
</tr>
</tbody></table>
```
I can do this by javascript loops. But its very long. I want to know whether there is a more elegant way. Thanks in advance. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18533362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732631/"
] | >
> The text inside the div also should be rotated by 90degrees.
>
>
>
So basically you just want the whole thing to be rotated as a block?
Maybe you should just use CSS?
```
#myTable {
transform:rotate(270deg);
}
``` | try this **[DEMO](http://jsfiddle.net/pintu31/MRBQ8/3/)**
**reference : [Convert TD columns into TR rows](https://stackoverflow.com/questions/2730699/convert-td-columns-into-tr-rows) and modified `david` answer**
```
TransposeTable('myTable');
function TransposeTable(tableId)
{
var tbl = $('#' + tableId);
var tbody = tbl.find('tbody');
//var oldWidth = tbody.find('tr:first td').length;
var oldWidth = 0;
//calculate column length if there is 'td=span' added
$('tr:nth-child(1) td').each(function () {
if ($(this).attr('colspan')) {
oldWidth += +$(this).attr('colspan');
} else {
oldWidth++;
}
});
var oldHeight = tbody.find('tr').length;
var newWidth = oldHeight;
var newHeight = oldWidth;
var jqOldCells = tbody.find('td');
var newTbody = $("<tbody></tbody>");
for(var y=newHeight; y>=0; y--)
{
var newRow = $("<tr></tr>");
for(var x=0; x<newWidth; x++)
{
newRow.append(jqOldCells.eq((oldWidth*x)+y));
}
newTbody.append(newRow);
}
tbl.addClass('rotate');
tbody.replaceWith(newTbody);
}
```
as per `Robbert` suggestion
**CSS**
```
.rotate {
-moz-transform: rotate(-90.0deg); /* FF3.5+ */
-o-transform: rotate(-90.0deg); /* Opera 10.5 */
-webkit-transform: rotate(-90.0deg); /* Saf3.1+, Chrome */
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */
padding-right:50px;
}
``` |
32,745,866 | I have a RSpec test with this:
`within all('tr')[1] do
expect(page).to have_content 'Title'
expect(page).to have_content 'Sub Title'
end`
And it's failing at `expect(page).to have_content 'Title'` with the following error message:
`Element at 54 no longer present in the DOM`
I have not been able to find the exact meaning of what this error message means and this test is flakey, sometimes it passes, sometimes not. | 2015/09/23 | [
"https://Stackoverflow.com/questions/32745866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2690790/"
] | I would try using `one` and `mouseover`:
```
$('.sidebar-trigger').one('mouseover', function() {
$('.ui.sidebar').sidebar('show')
});
```
Then, when it has finished animating, reattach the event:
```
$(document).on('transitionend', function(event) {
$('.sidebar-trigger').one('mouseover', function() {
$('.ui.sidebar').sidebar('show')
});
});
```
I *think* what is happening is that the hover event is getting called multiple times - every time the element is hovered, then goes over a child element, and then goes back over the hover element, and things are getting mixed up at some point. So you need to only call `show` if it's not already shown. | Ok, my first answer was (of course) way too much work for what it really needed. The onVisible seems to work perfectly. Was that not working for you? Demo [HERE](http://jsfiddle.net/hrn8j0gq/)
Simply change 'onShow' to 'onVisible' in your sidebar setting:
```
$('.ui.sidebar').sidebar('setting', {
onVisible: function() {
$('.sidebar-trigger').hide();
},
onHidden: function() {
$('.sidebar-trigger').show();
}
});
```
As shown on the [Semantic UI site](http://semantic-ui.com/modules/sidebar.html#/settings), the onVisible fires when the animating starts. The onShow fires when the animating finishes. So what you were doing was hiding that blue / transparent bar when the animation was finally done (the .animating class noted in my previous answer), as opposed to when it starts. If you need further explanation please let me know. |
38,477 | I have started to notice my 2007 Honda Accord EX V6 wobbles, just slightly.
At 5 MPH, It's not very noticeable. When I accelerate to 19-20 MPH, I can definitely tell that it's wobbling. The wobble stops when you go over 20 MPH, but then it starts to vibrate again at 80 MPH.
It feels like it is coming from the rear. The whole car wobbles, not the steering wheel. I got all new tires, a wheel balance, and an alignment, but doesn't seem to fix it.
What should I check?
Update: So I found out that my front wheel is slightly bent on the inside and that was the reason why the car wobble and vibrate. | 2016/11/09 | [
"https://mechanics.stackexchange.com/questions/38477",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/23381/"
] | If you can feel the car wobbling at such low speeds and you've already put new tyres on it. You likely have bent rear wheel rim. | Your suspension is probably messed up. This is usually caused by driving with mismatched tires. For example, if you get a flat and just replace one tire, you will have mismatched tires. Once the suspension is messed up, you often end up having to replace a bunch of stuff. What happens is that all the seals get all broken and screwed up and start leaking grease, then eventually they fail.
When this happened to me I ended having to replace the rack and pinion assembly and the tie rod assemblies on my front end. This happened because I replaced just one tire on the car (never do that). |
29,778,809 | I am uploading images for our application to the server.
Is there any way to validate the extensions in client side by JS before submitting them to the server before uploading them to server?
I am using AngularJs to handle my front-end. | 2015/04/21 | [
"https://Stackoverflow.com/questions/29778809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2809423/"
] | You can use this simple javascript to validate. This code should be put inside a directive and on change of file upload control.
```
var extn = filename.split(".").pop();
```
Alternatively you can use javascript substring method also:
```
fileName.substr(fileName.lastIndexOf('.')+1)
``` | Here is the complete code for validating file extension usign AngularJs
```
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type='text/javascript'>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.setFile = function(element) {
$scope.$apply(function($scope) {
$scope.theFile = element.files[0];
$scope.FileMessage = '';
var filename = $scope.theFile.name;
console.log(filename.length)
var index = filename.lastIndexOf(".");
var strsubstring = filename.substring(index, filename.length);
if (strsubstring == '.pdf' || strsubstring == '.doc' || strsubstring == '.xls' || strsubstring == '.png' || strsubstring == '.jpeg' || strsubstring == '.png' || strsubstring == '.gif')
{
console.log('File Uploaded sucessfully');
}
else {
$scope.theFile = '';
$scope.FileMessage = 'please upload correct File Name, File extension should be .pdf, .doc or .xls';
}
});
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="file"
onchange="angular.element(this).scope().setFile(this)">
{{theFile.name}}
{{FileMessage}}
</div>
</body>
</html>
``` |
103,027 | I am looking for the origin of the phrase "break bread" meaning to eat (or, I expect, to share food). I know that it can be sourced to the book of Acts but I have also seen many websites which say that it is older than that, reflecting a biblical era practice of sharing food to solemnize a meal, just with no actual references. What language does the phrase come from or is it an invention directly into the English? | 2013/02/05 | [
"https://english.stackexchange.com/questions/103027",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/24436/"
] | Although it is seen in the Bible, I am sure we can find references in other Greek and Hebrew literature if one really put the effort in some database. I am from India, and I have heard the phrase "to break bread" in Hindi idioms like "to break breads for free", the idiom is used to malign someone that he is eating for free and not working or earning. So, to me, it is clear that it is an ancient Semitic or wider idiom for "eating food" or having a meal. English etymology will not give you the ancient results older than the Bible references because it is not from a modern language like English. As cited by other answer, the Wycliffe 14th century English translation might be the oldest, which too must be coming from Greek and Latin Bible. [Latin phrase](https://www.stepbible.org/?q=version=VulgJ%7Cversion=ESV%7Cversion=SBLG%7Cversion=LXX%7Creference=Acts.2.42%20Acts.2.46%20Acts.20.7%7Creference=Luke.24.35%201Cor.10.16&options=VGNUHV&display=INTERLEAVED) is *frangendum panem* Acts 20:7, and *fractione panis* Luke 24:35. It is clear the English phrase has its origin from the Scripture alone, as there couldn't have been any other older English translation of any ancient languages.
>
> [Acts 2:44-47 ESV] And all who believed were together and had all things in common. And they were selling their possessions and belongings and distributing the proceeds to all, as any had need. And day by day, attending the temple together and **breaking bread** in their homes, they received their food with glad and generous hearts, praising God and having favor with all the people. And the Lord added to their number day by day those who were being saved.
>
>
>
>
> [Matt 14:19-21 ESV] Then he ordered the crowds to sit down on the grass, and taking the five loaves and the two fish, he looked up to heaven and said a blessing. Then he **broke the loaves** and gave them to the disciples, and the disciples gave them to the crowds. And they all ate and were satisfied. And they took up twelve baskets full of the broken pieces left over. And those who ate were about five thousand men, besides women and children.
>
>
>
>
> Jeremiah 16:7 `ESV` No one shall **break bread** for the mourner, to comfort him for the dead, nor shall anyone give him the cup of consolation to drink for his father or his mother.
>
>
>
ASV: neither shall men break *bread*
KJV: Neither shall *men* tear *themselves*
LXX: ου μη in no way κλασθή should be broken άρτος bread
>
> JFB commentary: 7. **`tear themselves`**—rather, "break bread," namely, that eaten at the funeral-feast (Deut 26:14; Job 42:11; Ezek 24:17; Hos 9:4). "Bread" is to be supplied, as in La 4:4; compare "take" (food) (Ge 42:33).
> **`give . . . cup of consolation . . . for . . . father`**—It was the Oriental custom for friends to send viands and wine (the "cup of consolation") to console relatives in mourning-feasts, for example, to children upon the death of a "father" or "mother."
>
>
>
LXX supplied the word "bread" where it wasn't in the Hebrew, meaning "breaking" itself connoted, as a metonymy to eating.
[Isaiah 58:7](https://biblehub.com/parallel/isaiah/58-7.htm) LXX διάθρυπτε πεινῶντι τὸν ἄρτον σου
>
> `SLT` Is it not to break thy bread to the hungry, and thou shalt bring the wandering poor to thy house? when thou shalt see the naked and cover him; and thou shalt not hide from thy flesh.
>
>
>
We can now trace the phrase at least to 739 and 681 B.C, which is the date of prophet Isaiah. As for the word for "break" in the Isaiah verse, the old English versions use "deal the bread" in the sense of "share" or distribute. I had to find the most literal one (SLT) to demonstrate the exact use of "break bread". I used [Septuagint](https://en.wikipedia.org/wiki/Septuagint) (LXX), the Greek Old Testament translation which goes to third century BC. The Greek word for "break" is [διαθρύπτω](https://lsj.gr/wiki/%CE%B4%CE%B9%CE%B1%CE%B8%CF%81%CF%8D%CF%80%CF%84%CF%89) (see the root word [θρύπτω](https://lsj.gr/wiki/%CE%B8%CF%81%CF%8D%CF%80%CF%84%CF%89)) which means to crush, break in pieces. The Hebrew word is [*p̄ā·rōs*] (Strong's 6536)[6](https://biblehub.com/interlinear/isaiah/58-7.htm) here, which means to [break in two, divide.](https://biblehub.com/hebrew/6536.htm) Otherwise, the Greek NT, in consistency with Jeremiah 16:7, uses [κλάω](https://biblehub.com/greek/2806.htm) for "breaking" bread. | It also appears in Mark and Mathew. But the notion can also be seen in some of the Pre-socratic thinkers. |
29,306,386 | I am building a VB Parser and I have to parse VB classes as file.
Right now I'm proceeding like this:
```
Dim lines As List(Of String) = File.ReadAllLines(fileName).ToList()
```
Where `fileName` is the actual path of the vb class file to parse. However my main concern is that it actually get ALL the lines in the files.
So say that I have a vb.class that looks like this:
```
Public Class Class1VB
Friend item1 As String
Friend item2 As String
Friend item3 As String
Friend item4 As String
Friend item5 As String
Friend item6 As String
Public Sub New()
MyBase.new()
End Sub
Public Overrides Sub InstanciateVariables()
item1 = New String()
item2 = New String()
item3 = New String()
item4 = New String()
item5 = New String()
item6 = New String()
End Sub
End Class
#End Region
```
And I only want the item located in the `InstanciateVariables()` Sub in the `lines` array, is there a way to do that using `Linq` or any VB logic available? | 2015/03/27 | [
"https://Stackoverflow.com/questions/29306386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2021863/"
] | Unfortunately it seems to be an [unsupported feature](http://public.kitware.com/Bug/view.php?id=13007) (issue is "tracked" [here](https://gitlab.kitware.com/cmake/cmake/issues/13007), doesn't look like it will ever be handled).
But there's a workaround: you can use [configure\_file](http://www.cmake.org/cmake/help/latest/command/configure_file.html) to create a copy of the files with a uniform row endings before starting the comparison. For example:
```
configure_file(<input> <output> NEWLINE_STYLE CRLF)
```
Note that the option `COPYONLY` is not compatible with `NEWLINE_STYLE`, so you'll have to take care `configure_file` doesn't make any unintended variable substitution. | With [CMake 3.14](https://blog.kitware.com/cmake-3-14-0-available-for-download/) you can now do:
```
cmake -E compare_files --ignore-eol file1 file2
``` |
6,774,235 | I am using Selenium to test a web site which has HTTP Auth and now even SSL certificate.
As workaround for HTTP Basic Authentification I am using ChromeDriver - <http://code.google.com/p/selenium/wiki/ChromeDriver> and opening URLs in format
```
https://username:password@my-test-site.com
```
But now from security reasons, Client certificate needs to be installed on PC in order to log into that application.
However, ChromeDriver cannot see the "select certificate" prompt and I even cannot switch to it as Alert.
Did somebody solved this issue? | 2011/07/21 | [
"https://Stackoverflow.com/questions/6774235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/855636/"
] | Instead of installing the Client Certificate you could just tell Chrome to ignore the untrusted certificate error using the `--ignore-certificate-errors` command line switch.
To do this, create your instance of `ChromeDriver` as follows:
```
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));
driver = new ChromeDriver(capabilities);
``` | You can tell the Chrome browser to use a specific client certificate for a particual URL by adding a registry KEY with the following content:
```
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\AutoSelectCertificateForUrls\1 = "{\"pattern\":\"https://www.example.com\",\"filter\":{\"ISSUER\":{\"CN\":\"cn of issuer\"}}}"
```
You may add additional entries by adding additional keys under the same branch.
It's a little more complex on Linux as you need to modify the preferences which are in json format under the following location:
```
~/.config/chromium/Default/Preferences
```
It looks like the above option only works for machines joined to an Active Directory domain. In case the above steps don't work You may try using a preconfigured template to introduce the changes available for download from the following url: <https://www.chromium.org/administrators/policy-templates> |
56,595,080 | I want change the launcher icon but it doesn't change it.
I followed the instruction in other SO post.
What's wrong in my code?
Thanks in advance.
[](https://i.stack.imgur.com/uHquUl.jpg)[](https://i.stack.imgur.com/ApbIml.jpg)
This is the manifest:
```
application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
``` | 2019/06/14 | [
"https://Stackoverflow.com/questions/56595080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In short:
* You are changing the *legacy launcher PNG*, but you are viewing your app on a newer device which uses *adaptive launcher icons*.
---
Android API 26 introduced the concept of [Adaptive icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive). Instead of supplying the icon and background in one PNG (per DPI size), we now supply the icon as a "foreground" image, and the "background" resource seperately.
This allows the launcher app to choose whichever shape of background it is configured for, and use that with your icon overlaid.
For backwards compatibility, we still supply to usual PNG, which will be used on pre-API 26 devices. This is what you are changing, but the changes will not be visible on the device you are testing with as it is displaying adaptive icons.
Your change would be visible on an older device.
---
To use these new launchers, go to Android Studio menu `File... New... Image Assets`.
Choose "Launcher Icons (Adaptive and Legacy)" - this will show you the new UI giving you options to change the foreground, background and legacy resources.
---
Note that if you don't supply any of the adaptive resources, API 26-27 will display your legacy icon as you designed it.
API 28 changes that and your legacy icon will be shrunk by the launcher, and placed inside a default white background to match the style chosen. This would look as if you had chosen a white background layer and a smaller foreground layer in the adaptive wizard.
---
Here's the info from the Android Developer docs:
* [Adaptive icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) | Android API 26 introduced the concept of Adaptive icons. Instead of supplying the icon and background in one PNG (per DPI size), we now supply the icon as a "foreground" image, and the "background" resource seperately.
This allows the launcher app to choose whichever shape of background it is configured for, and use that with your icon overlaid.
For backwards compatibility, we still supply to usual PNG, which will be used on pre-API 26 devices. This is what you are changing, but the changes will not be visible on the device you are testing with as it is displaying adaptive icons.
Your change would be visible on an older device.
To use these new launchers, go to Android Studio menu File... New... Image Assets.
Choose "Launcher Icons (Adaptive and Legacy)" - this will show you the new UI giving you options to change the foreground, background and legacy resources.
Note that if you don't supply any of the adaptive resources, API 26-27 will display your legacy icon as you designed it.
API 28 changes that and your legacy icon will be shrunk by the launcher, and placed inside a default white background to match the style chosen. This would look as if you had chosen a white background layer and a smaller foreground layer in the adaptive wizard.
Here's the info from the Android Developer docs:
Adaptive icons |
346,547 | I have a center tap transformer that does 110 or 220VAC stepdown to two 6V rails (with opposing phases). On the 110/220 side there are what appear to be two separate rails, and the wiring diagram is a bit confusing to me:
[](https://i.stack.imgur.com/kZ8iy.jpg)
In order to use this on a 110VAC source and get the proper 6VAC output, how do I wire up the mains side? Per the diagram it seems like I would wire the mains to a single black/red set (with the other set tied off and insulated), or possibly tie them in parallel (black to black, red to red). Is the idea that for 220VAC input I'd tie the center black and red together and wire the 220 mains to the outer pair of wires? | 2017/12/24 | [
"https://electronics.stackexchange.com/questions/346547",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/8780/"
] | Your understanding is correct.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fZwVjC.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
*Figure 1. Primary and secondary windings.*
Note that the voltage between the two blue terminals will be 12 V AC.
You *could* use only one primary for 110 V operation but the maximum power you can draw from the transformer would be halved. | Parallel black to black. Parallel red to red. Apply 110 Vac between black and red. Take out 6 Vac between blue and yellow.
Yes, the idea for 230 V operation is to tie them in series. Very common arrangement to be able to have the same transformer for the world market. Dual 6 V secondaries is most probably to be able to get symmetrical + and - voltage DC around center ground on the secondary. |
11,273,684 | I am trying to sort the NSMutablArray values by Aa-Zz format in iPhone app. I have used the below code in my project.
```
for (id key in [dictionary allKeys])
{
id value = [dictionary valueForKey:key];
[duplicateArray addObject:value];
[value release];
value =nil;
NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES] autorelease];
NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
mutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
}
NSLog(@"mutableArray : %@", mutableArray);
[mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
```
The app getting crash with this error log: `[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance.`
But, i have searched and found the reason for the crash. My mutableArray values are like this,
```
(
{
Id = 00001;
Name = "ABCD";
},
{
Id = 00002;
Name = "BCDE";
},
{
Id = 00003;
Name = "ZXYS";
},
{
Id = 00004;
Name = "abcd";
},
{
Id = 00009;
Name = "bcde";
},
)
```
I want to sort this array valuse like **ABCD, abcd, BCDE, bcde, ZXYs**.
Can anyone please help to solve this. | 2012/06/30 | [
"https://Stackoverflow.com/questions/11273684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1005346/"
] | Gopinath. Please use this updated code in your project.
```
for (id key in [dictionary allKeys])
{
id value = [dictionary valueForKey:key];
[duplicateArray addObject:value];
[value release];
value =nil;
NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]autorelease];
NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
mutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
}
NSLog(@"mutableArray : %@", mutableArray);
```
I hope it will help you. Thanks. | ```
for (id key in [dictionary allKeys])
{
id value = [dictionary valueForKey:key];
[duplicateArray addObject:value];
}
NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]autorelease];
NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
NSArray* notAMutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
NSLog(@"notAMutableArray : %@", notAMutableArray);
```
I did not run this, but its a better start... |
86,669 | Hey fellow Photographers,
I've taken the below image today and info attached. Please review and comment on it which would help me to improve.
Exif :
Body : Nikon d5300
Lens : 50mm
Exposure : 1/400s
Aperture : f1.8
ISO : 100
No Flash
Photoshop Edits :
* Clarity been increased
* Adjusted whites/black/shadows
[](https://i.stack.imgur.com/RiI0h.jpg) | 2017/01/29 | [
"https://photo.stackexchange.com/questions/86669",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/59984/"
] | Yes, there is demand for it. Film sales seem to have hit the bottom and are picking up (from a low base). Instead of all the doom and gloom stories of a few years back there is a trickle of good news as well - especially the Black & White film scene is doing well, with several new emulsions introduced on the European market recently (Bergger, Ferrania, Foma Retropan, etc.)
Now when digital has become *the norm* you start seeing professionals shooting medium format film to differentiate themselves. This is especially true on the very competitive wedding market - a photographer with a big and shiny Hasselblad will make a different impression from your average Canikon shooter. Young brides are not exactly price sensitive, so the cost of film and scanning is not a big issue.
But to not sound too optimistic: there are hardly any new cameras being made. If you discount the toy and Lomo market there are no medium format film cameras being produced anymore; the glut of used gear and prices of second hand market make it impossible to make money by producing new top quality gear (although I hear the prices of used Contax 645's are close to what they were when new, so there is some hope yet). | There is absolutely a demand growing for medium format (MF) film photography (i can not speak for large format since i never touched it).
Sure, demand is not high as before, because there are many MF digital options in the market for every budget, do not think it's cheap; cheaper than hasselblads let's say).
However film and develop still costs a lot, enthusiasts, photography artists and some wedding photographers using MF film cameras. I started to see lots of wedding photographers using film cameras.
You can easily find MF films on the market, there are even specialised stores like ars-imago (italy-switzerland). There are even new brands coming up for MF films.
Cameras vary from plastic holgas to higher-end hasselblads. I can recommend pentax 645 series, which are quite affordable on the second hand market and have similar design like classic slr's however they are bit bulky. |
22,345,409 | I am create view pager with custom view pager adapter but when i run the project i can not see anything
```
public class CustomAdapter extends PagerAdapter {
private List<NewsObject> newsObjects;
private Activity mActivity;
private LayoutInflater inflater;
private ImageLoaderConfiguration imageConfig;
private ImageLoader imageLoader = ImageLoader.getInstance();
public CustomAdapter(List<NewsObject> newsObjects, Activity mActivity) {
super();
Log.d("Con :", "structor");
this.newsObjects = newsObjects;
this.mActivity = mActivity;
imageConfig = new ImageLoaderConfiguration.Builder(
mActivity.getApplicationContext()).build();
imageLoader.init(imageConfig);
}
@Override
public int getCount() {
return this.newsObjects.size();
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageViewPlus img_news_image;
TextView txt_news_title;
TextView txt_news_description;
inflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.detail_news_page, null);
img_news_image = (ImageViewPlus) viewLayout
.findViewById(R.id.img_detail_news_image);
txt_news_title = (TextView) viewLayout
.findViewById(R.id.txt_detail_news_title);
txt_news_description = (TextView) viewLayout
.findViewById(R.id.txt_detail_news_description);
Log.d("TAG :", "instantiateItem");
imageLoader.displayImage(newsObjects.get(position).getNews_image(),
img_news_image);
Toast.makeText(mActivity.getApplicationContext(),
Constantz.newsObjects.get(position).getNews_id() + "",
Toast.LENGTH_SHORT).show();
txt_news_title.setText(newsObjects.get(position).getNews_title());
txt_news_description.setText(newsObjects.get(position)
.getNews_description());
return viewLayout;
}
}
```
but the toast is displaying but i can not see any text on my application | 2014/03/12 | [
"https://Stackoverflow.com/questions/22345409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150318/"
] | write
```
container.addView(viewLayout);
```
before returning the view in `instantiateItem`
```
public Object instantiateItem(ViewGroup container, int position) {
ImageViewPlus img_news_image;
TextView txt_news_title;
TextView txt_news_description;
inflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.detail_news_page, null);
img_news_image = (ImageViewPlus) viewLayout
.findViewById(R.id.img_detail_news_image);
txt_news_title = (TextView) viewLayout
.findViewById(R.id.txt_detail_news_title);
txt_news_description = (TextView) viewLayout
.findViewById(R.id.txt_detail_news_description);
Log.d("TAG :", "instantiateItem");
imageLoader.displayImage(newsObjects.get(position).getNews_image(),
img_news_image);
Toast.makeText(mActivity.getApplicationContext(),
Constantz.newsObjects.get(position).getNews_id() + "",
Toast.LENGTH_SHORT).show();
txt_news_title.setText(newsObjects.get(position).getNews_title());
txt_news_description.setText(newsObjects.get(position)
.getNews_description());
container.addView(viewLayout);
return viewLayout;
}
``` | ```
<TabHost
......
<TabWidget
.....
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp" >
</FrameLayout>
<android.support.v4.view.ViewPager
``` |
232,571 | I have a second Radeon 5850 coming, and I'd like to see the performance that the second card offers. To do this, I'd like to try the game with Crossfire, disable it, and then try it with just a single card. Can this be done easily in software, or do I need to remove the bridge or (even worse) the second card? | 2011/01/13 | [
"https://superuser.com/questions/232571",
"https://superuser.com",
"https://superuser.com/users/25808/"
] | Head over to Catalyst Control Center, Crossfire tab & uncheck the checkmark against Crossfire.
 | Do it in the other direction man...I've had problems disabling crossfire and SLI without uninstalling the driver and re-install. Just saying. That's how I got it demonstrated though. |
48,121,050 | I write a program that read from text file.
I need to read the lines and do as follow the text.
for example:
>
> aaaa=3
>
>
> cccc=hi
>
>
> bbb=2
>
>
> ee=true
>
>
> print(bbb)
>
>
>
so my output will be:*2*
I use a template and write the "generic" function print.
but I'm looking for Data Structure that can save template from different type.
for example:
* my first organ contain variable **int** with key:aaaa value:3
* my second organ contain **string** key:cccc value:"hi"
* my Third organ contain **int** with key:bbb value:2
* my Fourth organ contain **bool** with key:ee value:true
I also need to be able to search them by key.
Any idea? | 2018/01/05 | [
"https://Stackoverflow.com/questions/48121050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9179230/"
] | To change to the project folder you can use the command **--chdir**.
Example:
```
gunicorn -w 2 -b 0.0.0.0:8000 --chdir /code/myproject myproject.wsgi
``` | Change this:
```
CMD gunicorn -w 3 -b 0.0.0.0:8080 wsgi --reload
```
to this:
```
CMD gunicorn -w 3 -b 0.0.0.0:8080 /full/path/to/wsgi --reload
```
where `/full/path/to/wsgi` is the absolute path of your app--I'm guessing it's `/usr/src/app/wsgi`?) |
69,724,626 | Hiyya,
So much like the title says, I've stumbled upon a issue where I cannot get two buttons that are inline centered, when one has more content than the other.
First and foremost, this is what it's currently looking like:
[](https://i.stack.imgur.com/cy2Do.png)
As we can see, the buttons seem okay in the perspective of the text immediately above and below, but since the black button has more text, it seems off in the perspective of the image.
The code is as follows (project is using ancient v2 Bootstrap):
```
<div class="row-fluid visible-desktop">
<div class="span6" style="text-align: right;">
<a href="#"><button type="button" class="btn btn-default">Ja, tack!</button></a>
</div>
<div class="span6" style="text-align: left;">
<a href="#"><button type="button" class="btn btn-inverse">Nej tack, avsluta</button></a>
</div>
</div>
```
Proposed solutions have been to set an uniformal width for the buttons (for example 200px), and while it technically works as a plan B, we'd like to consider other possibilities first. Another solution would be to simply not have the buttons inline, but such design changes shouldn't be necessary for something like this (atleast in my opinion/thought process).
We have also experimented with the "hack" of shifting the buttons to the left using margin-properties, but since we allow our clients/customers to change the text at their own discretion, this would not be viable either.
Thankful for any and all help/pointers! | 2021/10/26 | [
"https://Stackoverflow.com/questions/69724626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508613/"
] | Something like this should work, making it one div instead of two.
```
<div class="row-fluid visible-desktop">
<div class="span12" style="text-align: center;">
<a href="#"><button type="button" class="btn btn-default">Ja, tack!</button></a>
<a href="#"><button type="button" class="btn btn-inverse">Nej tack, avsluta</button></a>
</div>
</div>
```
Maybe fix the gap between between buttons with some margin, or wrap both buttons with a div that has some padding.
There are definitely better ways of doing this (without bootstrap) though :) | I would consider using a grid layout so that it can account of varying lengths of text. However, from a UI / UX point of view, equal button sizes in this scenario would look and feel much nicer.
```css
.wrapper {
width: 500px;
background: #ebebeb;
border: 1px solid #d9d9d9;
border-radius: 5px;
padding:10px;
text-align: center;
}
.button-wrapper {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
row-gap: 1.5rem;
column-gap: 1rem;
}
button {
box-sizing: border-box;
border-radius: 5px;
padding:5px;
grid-column: span 3 / span 3;
}
.button1 {
background: blue;
color: white;
}
.button2 {
background: black;
color: white;
}
```
```html
<div class="wrapper">
<p> Some text some text some text </p>
<p> Some text some text some text </p>
<div class="button-wrapper">
<button class="button1"> Ja, Tack! </button>
<button class="button2"> New tack, avsluta </button>
</div>
</div>
``` |
1,154 | Is it best to remove tags of closed questions? Or is it best to update their tags to keep them current, just like any other question? | 2015/03/31 | [
"https://softwarerecs.meta.stackexchange.com/questions/1154",
"https://softwarerecs.meta.stackexchange.com",
"https://softwarerecs.meta.stackexchange.com/users/8503/"
] | A good question I'm also thinking about from time to time: though "closed", those questions stay and are often kept as references – especially with "duplicates", which serve as pointers to the "originals"; which allows for finding those with different search patterns.
Still, I'd say: Unless worth re-opening for some reason, those should not be edited at all but kept as-is (if not even deleted at some point), for two reasons:
1. editing them pushes them into the review queue: to get your edit approved (unless you have enough rep), and for whether the question should be re-opened
2. editing them might bring them back to the "front page" as question with new activity
So unless there's a very good reason, I'd say refrain from editing closed questions. Just adding/removing/replacing a tag IMHO is not enough reason for that, usually ;) | Expanding a bit on Izzy's answer. Closed questions are of several types:
1. *Questions closed as duplicates*: These questions remain as a reference and serve as an additional link to direct search results to the answers of the original (sometimes even less popular) question. In this case, I think that the tags on such questions should be already pretty close to the original one, and ideally no editing is needed, unless it's to match the original, or a part of a tag cleanup
2. *Questions closed for reasons other than being a duplicate*: These questions are in a sort of a limbo, and I think that whether or not their tags should be edited/are worth editing depends on the fate of this question.
1. Questions that are going to be deleted ([See the conditions here](https://meta.stackexchange.com/a/92006/267247)) should not be edited unless you believe that your edit could save the question. In that case, you should also edit the title and/or body, and nominate it for reopening.
2. Questions that are staying, like upvoted ones or ones with accepted answers but are closed as too broad: I'm not sure what's the desired outcome from editing those. If the question can't be answered objectively, then it doesn't make much sense to help draw more attention to it.
**Conclusion:** I see very little reasoning behind minor edits on closed questions. I think they should only be edited when that can lead to their reopening, which usually means more than just editing the tags. An exception might be cleaning up tags deemed obsolete |
52,504,732 | I have the issue that my GPU memory is not released after closing a tensorflow session in Python. These three line suffice to cause the problem:
```
import tensorflow as tf
sess=tf.Session()
sess.close()
```
After the third line the memory is not released. I have been up and down many forums and tried all sorts of suggestions, but nothing has worked for me. For details please also see my comment at the bottom here:
<https://github.com/tensorflow/tensorflow/issues/19731>
Here I have documented the ways in which I mange to kill the process and thus release the memory, but this is not useful for long-running and automated processes. I would very much appreciate any further suggestions to try. I am using Windows.
EDIT: I have now found a solution that at least allows me to do what I am trying to do. I am still **NOT** able to release the memory, but I am able to 'reuse' it. The code has this structure:
```
import tensorflow as tf
from keras import backend as K
cfg=K.tf.ConfigProto()
#cfg.gpu_options.allow_growth=True #this is optional
cfg.gpu_options.per_process_gpu_memory_fraction = 0.8 #you can use any percentage here
#upload your data and define your model (2 layers in this case) here
for i in range(len(neuron1)):
for j in range(len(neuron2)):
K.set_session(K.tf.Session(config=cfg))
#train your NN for i,j
```
The first time the script enters the loop the GPU memory is still allocated (80% in the above example) and thus cluttered, however this code nonetheless seems to reuse the same memory somehow. I reckon the `K.set_session(K.tf.Session(config=cfg))` somehow destorys or resets the old session allowing the memory to be 'reused' within this context at least. Note that I am **not** using `sess.close()` or `K.clear_session()` or resetting the default graph explicitly. This still does not work for me. When done with the loops the GPU memory is still full. | 2018/09/25 | [
"https://Stackoverflow.com/questions/52504732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10414947/"
] | Refer to [this](https://github.com/tensorflow/tensorflow/issues/17048#issuecomment-367948448) discussion. You can reuse your allocated memory but if you want to free the memory, then you would have to exit the Python interpreter itself. | If I'm understanding correctly, it should be as simple as:
`from numba import cuda`
`cuda.close()` |
352,036 | I'm training a neural network but the training loss doesn't decrease. How can I fix this?
I'm not asking about overfitting or regularization. I'm asking about how to solve the problem where my network's performance doesn't improve on the **training set**.
---
This question is intentionally general so that other questions about how to train a neural network can be closed as a duplicate of this one, with the attitude that "if you give a man a fish you feed him for a day, but if you teach a man to fish, you can feed him for the rest of his life." See this Meta thread for a discussion: [What's the best way to answer "my neural network doesn't work, please fix" questions?](https://stats.meta.stackexchange.com/questions/5273/whats-the-best-way-to-answer-my-neural-network-doesnt-work-please-fix-quest)
If your neural network does not generalize well, see: [What should I do when my neural network doesn't generalize well?](https://stats.stackexchange.com/questions/365778/what-should-i-do-when-my-neural-network-doesnt-generalize-well) | 2018/06/19 | [
"https://stats.stackexchange.com/questions/352036",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/22311/"
] | Verify that your code is bug free
=================================
There's a saying among writers that "All writing is re-writing" -- that is, the greater part of writing is revising. For programmers (or at least data scientists) the expression could be re-phrased as "All coding is debugging."
Any time you're writing code, you need to verify that it works as intended. The best method I've ever found for verifying correctness is to break your code into small segments, and verify that each segment works. This can be done by comparing the segment output to what you know to be the correct answer. This is called [unit testing](https://en.wikipedia.org/wiki/Unit_testing). Writing good unit tests is a key piece of becoming a good statistician/data scientist/machine learning expert/neural network practitioner. There is simply no substitute.
**You have to check that your code is free of bugs before you can tune network performance!** Otherwise, you might as well be re-arranging deck chairs on the *RMS Titanic*.
There are two features of neural networks that make verification even more important than for other types of machine learning or statistical models.
1. Neural networks are not "off-the-shelf" algorithms in the way that random forest or logistic regression are. Even for simple, feed-forward networks, the onus is largely on the user to make numerous decisions about how the network is configured, connected, initialized and optimized. This means writing code, and writing code means debugging.
2. *Even when a neural network code executes without raising an exception, the network can still have bugs!* These bugs might even be the insidious kind for which the network will train, but get stuck at a sub-optimal solution, or the resulting network does not have the desired architecture. ([This is an example of the difference between a syntactic and semantic error](https://web.archive.org/web/20161201151434/https://wci.llnl.gov/codes/basis/manual/node53.html).)
This *Medium* post, "[How to unit test machine learning code](https://medium.com/@keeper6928/how-to-unit-test-machine-learning-code-57cf6fd81765)," by Chase Roberts discusses unit-testing for machine learning models in more detail. I borrowed this example of buggy code from the article:
```py
def make_convnet(input_image):
net = slim.conv2d(input_image, 32, [11, 11], scope="conv1_11x11")
net = slim.conv2d(input_image, 64, [5, 5], scope="conv2_5x5")
net = slim.max_pool2d(net, [4, 4], stride=4, scope='pool1')
net = slim.conv2d(input_image, 64, [5, 5], scope="conv3_5x5")
net = slim.conv2d(input_image, 128, [3, 3], scope="conv4_3x3")
net = slim.max_pool2d(net, [2, 2], scope='pool2')
net = slim.conv2d(input_image, 128, [3, 3], scope="conv5_3x3")
net = slim.max_pool2d(net, [2, 2], scope='pool3')
net = slim.conv2d(input_image, 32, [1, 1], scope="conv6_1x1")
return net
```
Do you see the error? Many of the different operations are not *actually used* because previous results are over-written with new variables. Using this block of code in a network will still train and the weights will update and the loss might even decrease -- but the code definitely isn't doing what was intended. (The author is also inconsistent about using single- or double-quotes but that's purely stylistic.)
The most common *programming* errors pertaining to neural networks are
* Variables are created but never used (usually because of copy-paste errors);
* Expressions for gradient updates are incorrect;
* Weight updates are not applied;
* [Loss functions are not measured on the correct scale](https://stats.stackexchange.com/questions/544337/same-loss-and-accuracy-on-epochs/544381#544381) (for example, cross-entropy loss can be expressed in terms of probability or logits)
* The loss is not appropriate for the task (for example, using categorical cross-entropy loss for a regression task).
* [Dropout is used during testing, instead of only being used for training.](https://stats.stackexchange.com/questions/551144/why-am-i-getting-different-results-on-a-prediction-using-the-same-keras-model-an/551158#551158)
* [Make sure you're minimizing the loss function $L(x)$, instead of minimizing $-L(x)$](https://stats.stackexchange.com/questions/562374/implementing-a-vae-in-pytorch-extremely-negative-training-loss/562402#562402).
* [Make sure your loss is computed correctly](https://stats.stackexchange.com/questions/565956/confused-with-binary-crossentrophy-vs-categorical-crossentropy/566066#566066).
Unit testing is not just limited to the neural network itself. You need to test all of the steps that produce or transform data and feed into the network. Some common mistakes here are
* `NA` or `NaN` or `Inf` values in your data creating `NA` or `NaN` or `Inf` values in the output, and therefore in the loss function.
* Shuffling the labels independently from the samples (for instance, creating train/test splits for the labels and samples separately);
* Accidentally assigning the training data as the testing data;
* When using a train/test split, the model references the original, non-split data instead of the training partition or the testing partition.
* Forgetting to scale the testing data;
* Scaling the testing data using the statistics of the test partition instead of the train partition;
* Forgetting to un-scale the predictions (e.g. pixel values are in [0,1] instead of [0, 255]).
* Here's an example of a question where the problem appears to be one of model configuration or hyperparameter choice, but actually the problem was a subtle bug in how gradients were computed. [Is this drop in training accuracy due to a statistical or programming error?](https://stats.stackexchange.com/questions/527045/drop-in-training-accuracy#comment970055_527045)
For the love of all that is good, *scale your data*
===================================================
The scale of the data can make an enormous difference on training. Sometimes, networks simply won't reduce the loss if the data isn't scaled. Other networks will decrease the loss, but only very slowly. Scaling the inputs (and certain times, the targets) can dramatically improve the network's training.
* Prior to presenting data to a neural network, **standardizing** the data to have 0 mean and unit variance, or to lie in a small interval like $[-0.5, 0.5]$ can improve training. This amounts to pre-conditioning, and removes the effect that a choice in units has on network weights. For example, length in millimeters and length in kilometers both represent the same concept, but are on different scales. The exact details of how to standardize the data depend on what your data look like.
* [Data normalization and standardization in neural networks](https://stats.stackexchange.com/questions/7757/data-normalization-and-standardization-in-neural-networks)
+ [Why does $[0,1]$ scaling dramatically increase training time for feed forward ANN (1 hidden layer)?](https://stats.stackexchange.com/questions/364735/why-does-0-1-scaling-dramatically-increase-training-time-for-feed-forward-an/364776#364776)
* **Batch or Layer normalization** can improve network training. Both seek to improve the network by keeping a running mean and standard deviation for neurons' activations as the network trains. It is not well-understood why this helps training, and remains an active area of research.
+ "[Understanding Batch Normalization](https://arxiv.org/abs/1806.02375v1)" by Johan Bjorck, Carla Gomes, Bart Selman
+ "[Towards a Theoretical Understanding of Batch Normalization](https://arxiv.org/abs/1805.10694v1)" by Jonas Kohler, Hadi Daneshmand, Aurelien Lucchi, Ming Zhou, Klaus Neymeyr, Thomas Hofmann
+ "[How Does Batch Normalization Help Optimization? (No, It Is Not About Internal Covariate Shift)](https://arxiv.org/abs/1805.11604v2)" by Shibani Santurkar, Dimitris Tsipras, Andrew Ilyas, Aleksander Madry
Crawl Before You Walk; Walk Before You Run
==========================================
Wide and deep neural networks, and neural networks with exotic wiring, are the Hot Thing right now in machine learning. But these networks didn't spring fully-formed into existence; their designers built up to them from smaller units. First, build a small network with a single hidden layer and verify that it works correctly. Then incrementally add additional model complexity, and verify that each of those works as well.
* Too *few* **neurons** in a layer can restrict the representation that the network learns, causing under-fitting. Too many neurons can cause over-fitting because the network will "memorize" the training data.
Even if you can prove that there is, mathematically, only a small number of neurons necessary to model a problem, it is often the case that having "a few more" neurons makes it *easier* for the optimizer to find a "good" configuration. (But I don't think anyone fully understands why this is the case.) I provide an example of this in the context of the XOR problem here: [Aren't my iterations needed to train NN for XOR with MSE < 0.001 too high?](https://stats.stackexchange.com/questions/351216/arent-my-iterations-needed-to-train-nn-for-xor-with-mse-0-001-too-high/351713#351713).
* Choosing the number of **hidden layers** lets the network learn an abstraction from the raw data. Deep learning is all the rage these days, and networks with a large number of layers have shown impressive results. But adding too many hidden layers can make risk overfitting or make it very hard to optimize the network.
* Choosing a clever **network wiring** can do a lot of the work for you. Is your data source amenable to specialized network architectures? Convolutional neural networks can achieve impressive results on "structured" data sources, image or audio data. Recurrent neural networks can do well on sequential data types, such as natural language or time series data. Residual connections can improve deep feed-forward networks.
Neural Network Training Is Like Lock Picking
============================================
To achieve state of the art, or even merely good, results, you have to set up all of the parts configured to work well *together*. Setting up a neural network configuration that actually learns is a lot like picking a lock: all of the pieces have to be lined up *just right.* Just as it is not sufficient to have a single tumbler in the right place, neither is it sufficient to have only the architecture, or only the optimizer, set up correctly.
Tuning configuration choices is not really as simple as saying that one kind of configuration choice (e.g. learning rate) is more or less important than another (e.g. number of units), since all of these choices interact with all of the other choices, so one choice can do well *in combination with another choice made elsewhere*.
This is a non-exhaustive list of the configuration options which are not also regularization options or numerical optimization options.
All of these topics are active areas of research.
* The network **initialization** is often overlooked as a source of neural network bugs. Initialization over too-large an interval can set initial weights too large, meaning that single neurons have an outsize influence over the network behavior.
* The key difference between a neural network and a regression model is that a neural network is a composition of many nonlinear functions, called **activation functions**. (See: [What is the essential difference between neural network and linear regression](https://stats.stackexchange.com/questions/259950/what-is-the-essential-difference-between-neural-network-and-linear-regression))
Classical neural network results focused on sigmoidal activation functions (logistic or $\tanh$ functions). A recent result has found that ReLU (or similar) units tend to work better because the have steeper gradients, so updates can be applied quickly. (See: [Why do we use ReLU in neural networks and how do we use it?](https://stats.stackexchange.com/questions/226923/why-do-we-use-relu-in-neural-networks-and-how-do-we-use-it)) One caution about ReLUs is the "dead neuron" phenomenon, which can stymie learning; leaky relus and similar variants avoid this problem. See
* [Why can't a single ReLU learn a ReLU?](https://stats.stackexchange.com/questions/379884/why-cant-a-single-relu-learn-a-relu)
* [My ReLU network fails to launch](https://stats.stackexchange.com/questions/188040/my-relu-network-fails-to-launch/)
There are a number of other options. See: [Comprehensive list of activation functions in neural networks with pros/cons](https://stats.stackexchange.com/questions/115258/comprehensive-list-of-activation-functions-in-neural-networks-with-pros-cons)
* Residual connections are a neat development that can make it easier to train neural networks. ["Deep Residual Learning for Image Recognition"](https://arxiv.org/abs/1512.03385)
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun In: CVPR. (2016). Additionally, changing the order of operations within the residual block can further improve the resulting network. "[Identity Mappings in Deep Residual Networks](https://arxiv.org/pdf/1603.05027v3.pdf)" by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun.
Non-convex optimization is hard
===============================
The objective function of a neural network is only convex when there are no hidden units, all activations are linear, and the design matrix is full-rank -- because this configuration is identically an ordinary regression problem.
In all other cases, the optimization problem is non-convex, and non-convex optimization is hard. The challenges of training neural networks are well-known (see: [Why is it hard to train deep neural networks?](https://stats.stackexchange.com/questions/262750/why-is-it-hard-to-train-deep-neural-networks)). Additionally, neural networks have a very large number of parameters, which restricts us to solely first-order methods (see: [Why is Newton's method not widely used in machine learning?](https://stats.stackexchange.com/questions/253632/why-is-newtons-method-not-widely-used-in-machine-learning)). **This is a very active area of research.**
* Setting the **learning rate** too large will cause the optimization to diverge, because you will leap from one side of the "canyon" to the other. Setting this too small will prevent you from making any real progress, and possibly allow the noise inherent in SGD to overwhelm your gradient estimates. See:
+ [How can change in cost function be positive?](https://stats.stackexchange.com/questions/364360/how-can-change-in-cost-function-be-positive/364366#364366)
* **Gradient clipping** re-scales the norm of the gradient if it's above some threshold. I used to think that this was a set-and-forget parameter, typically at 1.0, but I found that I could make an LSTM language model dramatically better by setting it to 0.25. I don't know why that is.
* **Learning rate scheduling** can decrease the learning rate over the course of training. In my experience, trying to use scheduling is a lot like [regex](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/): it replaces one problem ("How do I get learning to continue after a certain epoch?") with two problems ("How do I get learning to continue after a certain epoch?" and "How do I choose a good schedule?"). Other people insist that scheduling is essential. I'll let you decide.
* Choosing a good **minibatch size** can influence the learning process indirectly, since a larger mini-batch will tend to have a smaller variance ([law-of-large-numbers](/questions/tagged/law-of-large-numbers "show questions tagged 'law-of-large-numbers'")) than a smaller mini-batch. You want the mini-batch to be large enough to be informative about the direction of the gradient, but small enough that SGD can regularize your network.
* There are a number of variants on **stochastic gradient descent** which use momentum, adaptive learning rates, Nesterov updates and so on to improve upon vanilla SGD. Designing a better optimizer is very much an active area of research. Some examples:
+ [No change in accuracy using Adam Optimizer when SGD works fine](https://stats.stackexchange.com/questions/313278/no-change-in-accuracy-using-adam-optimizer-when-sgd-works-fine)
+ [How does the Adam method of stochastic gradient descent work?](https://stats.stackexchange.com/questions/220494/how-does-the-adam-method-of-stochastic-gradient-descent-work/220563#comment661981_220563)
+ [Why does momentum escape from a saddle point in this famous image?](https://stats.stackexchange.com/questions/308835/why-does-momentum-escape-from-a-saddle-point-in-this-famous-image)
* When it first came out, the Adam optimizer generated a lot of interest. But some recent research has found that SGD with momentum can out-perform adaptive gradient methods for neural networks. "[The Marginal Value of Adaptive Gradient Methods in Machine Learning](https://arxiv.org/abs/1705.08292)" by Ashia C. Wilson, Rebecca Roelofs, Mitchell Stern, Nathan Srebro, Benjamin Recht
* But on the other hand, this very recent paper proposes a new adaptive learning-rate optimizer which supposedly closes the gap between adaptive-rate methods and SGD with momentum. "[Closing the Generalization Gap of Adaptive Gradient Methods in Training Deep Neural Networks](https://arxiv.org/abs/1806.06763v1)" by Jinghui Chen, Quanquan Gu
>
> Adaptive gradient methods, which adopt historical gradient information to automatically adjust the learning rate, have been observed to generalize worse than stochastic gradient descent (SGD) with momentum in training deep neural networks. This leaves how to close the generalization gap of adaptive gradient methods an open problem. In this work, we show that adaptive gradient methods such as Adam, Amsgrad, are sometimes "over adapted". We design a new algorithm, called Partially adaptive momentum estimation method (Padam), which unifies the Adam/Amsgrad with SGD to achieve the best from both worlds. Experiments on standard benchmarks show that Padam can maintain fast convergence rate as Adam/Amsgrad while generalizing as well as SGD in training deep neural networks. These results would suggest practitioners pick up adaptive gradient methods once again for faster training of deep neural networks.
>
>
>
* Specifically for [triplet-loss](/questions/tagged/triplet-loss "show questions tagged 'triplet-loss'") models, there are a number of tricks which can improve training time and generalization. See: [In training a triplet network, I first have a solid drop in loss, but eventually the loss slowly but consistently increases. What could cause this?](https://stats.stackexchange.com/questions/475655/in-training-i-first-have-a-solid-drop-in-loss-but-eventually-the-loss-slowly-b)
Regularization
==============
Choosing and tuning network regularization is a key part of building a model that generalizes well (that is, a model that is not overfit to the training data). However, at the time that your network is struggling to decrease the loss on the training data -- when the network is not learning -- regularization can obscure what the problem is.
When my network doesn't learn, I turn off all regularization and verify that the non-regularized network works correctly. Then I add each regularization piece back, and verify that each of those works along the way.
This tactic can pinpoint where some regularization might be poorly set. Some examples are
* $L^2$ regularization (aka weight decay) or $L^1$ regularization is set too large, so the weights can't move.
* Two parts of regularization are in conflict. For example, it's widely observed that layer normalization and dropout are difficult to use together. Since either on its own is very useful, understanding how to use both is an active area of research.
+ "[Understanding the Disharmony between Dropout and Batch Normalization by Variance Shift](https://arxiv.org/abs/1801.05134v1)" by Xiang Li, Shuo Chen, Xiaolin Hu, Jian Yang
+ "[Adjusting for Dropout Variance in Batch Normalization and Weight Initialization](https://arxiv.org/abs/1607.02488v2)" by Dan Hendrycks, Kevin Gimpel.
+ "[Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)" by Günter Klambauer, Thomas Unterthiner, Andreas Mayr and Sepp Hochreiter
Keep a Logbook of Experiments
=============================
When I set up a neural network, I don't hard-code any parameter settings. Instead, I do that in a configuration file (e.g., JSON) that is read and used to populate network configuration details at runtime. I keep all of these configuration files. If I make any parameter modification, I make a new configuration file. Finally, I append as comments all of the per-epoch losses for training and validation.
The reason that I'm so obsessive about retaining old results is that this makes it very easy to go back and review previous experiments. It also hedges against mistakenly repeating the same dead-end experiment. Psychologically, it also lets you look back and observe "Well, the project might not be where I want it to be today, but I am making progress compared to where I was $k$ weeks ago."
As an example, I wanted to learn about LSTM language models, so I decided to make a Twitter bot that writes new tweets in response to other Twitter users. I worked on this in my free time, between grad school and my job. It took about a year, and I iterated over about 150 different models before getting to a model that did what I wanted: generate new English-language text that (sort of) makes sense. (One key sticking point, and part of the reason that it took so many attempts, is that it was not sufficient to simply get a low out-of-sample loss, since early low-loss models had managed to memorize the training data, so it was just reproducing germane blocks of text verbatim in reply to prompts -- it took some tweaking to make the model more spontaneous and still have low loss.) | The posted answers are great, and I wanted to add a few "Sanity Checks" which have greatly helped me in the past.
1) **Train your model on a single data point. If this works, train it on two inputs with different outputs.**
This verifies a few things. First, it quickly shows you that your model is able to learn by checking if your model can overfit your data. In my case, I constantly make silly mistakes of doing `Dense(1,activation='softmax')` vs `Dense(1,activation='sigmoid')` for binary predictions, and the first one gives garbage results.
If your model is unable to overfit a few data points, then either it's too small (which is unlikely in today's age),or something is wrong in its structure or the learning algorithm.
2) **Pay attention to your initial loss.**
Continuing the binary example, if your data is 30% 0's and 70% 1's, then your intial expected loss around $L=-0.3\ln(0.5)-0.7\ln(0.5)\approx 0.7$. This is because your model should start out close to randomly guessing.
A lot of times you'll see an initial loss of something ridiculous, like 6.5. Conceptually this means that your output is heavily saturated, for example toward 0. For example $-0.3\ln(0.99)-0.7\ln(0.01) = 3.2$, so if you're seeing a loss that's bigger than 1, it's likely your model is very skewed. This usually happens when your neural network weights aren't properly balanced, especially closer to the softmax/sigmoid. So this would tell you if your initialization is bad.
You can study this further by making your model predict on a few thousand examples, and then histogramming the outputs. This is especially useful for checking that your data is correctly normalized. As an example, if you expect your output to be heavily skewed toward 0, it might be a good idea to transform your expected outputs (your training data) by taking the square roots of the expected output. This will avoid gradient issues for saturated sigmoids, at the output.
3) **Generalize your model outputs to debug**
As an example, imagine you're using an LSTM to make predictions from time-series data. Maybe in your example, you only care about the latest prediction, so your LSTM outputs a single value and not a sequence. Switch the LSTM to return predictions at each step (in keras, this is `return_sequences=True`). Then you can take a look at your hidden-state outputs after every step and make sure they are actually different. An application of this is to make sure that when you're masking your sequences (i.e. padding them with data to make them equal length), the LSTM is correctly ignoring your masked data. Without generalizing your model *you will never find this issue*.
4) **Look at individual layers**
Tensorboard provides a useful way of [visualizing your layer outputs](https://jhui.github.io/2017/03/12/TensorBoard-visualize-your-learning/). This can help make sure that inputs/outputs are properly normalized in each layer. It can also catch buggy activations. You can also query layer outputs in keras on a batch of predictions, and then look for layers which have suspiciously skewed activations (either all 0, or all nonzero).
5) **Build a simpler model first**
You've decided that the best approach to solve your problem is to use a CNN combined with a bounding box detector, that further processes image crops and then uses an LSTM to combine everything. It takes 10 minutes just for your GPU to initialize your model.
Instead, make a batch of fake data (same shape), and break your model down into components. Then make dummy models in place of each component (your "CNN" could just be a single 2x2 20-stride convolution, the LSTM with just 2
hidden units). This will help you make sure that your model structure is correct and that there are no extraneous issues. I struggled for a while with such a model, and when I tried a simpler version, I found out that one of the layers wasn't being masked properly due to a keras bug. You can easily (and *quickly*) query internal model layers and see if you've setup your graph correctly.
6) **Standardize your Preprocessing and Package Versions**
Neural networks in particular are extremely sensitive to small changes in your data. As an example, two popular image loading packages are `cv2` and `PIL`. Just by virtue of *opening* a JPEG, both these packages will produce **slightly different** images. The differences are usually really small, but you'll occasionally see drops in model performance due to this kind of stuff. Also it makes debugging a nightmare: you got a validation score during training, and then later on you use a different loader and get different accuracy on the same darn dataset.
So if you're downloading someone's model from github, pay close attention to their preprocessing. What image loaders do they use? What image preprocessing routines do they use? When resizing an image, what interpolation do they use? Do they first resize and then normalize the image? Or the other way around? What's the channel order for RGB images?
The safest way of standardizing packages is to use a `requirements.txt` file that outlines all your packages just like on your training system setup, down to the `keras==2.1.5` version numbers. In theory then, using Docker along with the same GPU as on your training system should then produce the same results. |
73,083,174 | I'm trying to implement a function to send a a notification using FirebaseCloudMessaging, I got the Auth part, But seems there is an issue with the GuzzleHttp\Client and how it passes the `data` part
This is my code
```
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=<path-to-json-file>.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
$data = json_encode(
[
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
],
);
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
'json' => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);
dd($response);
}
```
I keep getting that response 400, INVALID\_ARGUMENT "The message is not set."
`Client error:` POST <https://fcm.googleapis.com/v1/projects/>/messages:send`resulted in a`400 Bad Request `response: { "error": { "code": 400, "message": "The message is not set.", "status": "INVALID_ARGUMENT", "details (truncated...)`
Although my data structure is being passed as [documented](https://firebase.google.com/docs/cloud-messaging/concept-options), what I'm missing here?
Note: I use Laravel, I hided the , etc. | 2022/07/22 | [
"https://Stackoverflow.com/questions/73083174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19601996/"
] | As, [rafaelc](https://stackoverflow.com/users/2535611/rafaelc) [mentioned](https://stackoverflow.com/questions/73083163/pandas-apply-converts-index-values-to-float-while-iterating#comment129076415_73083163):
This is an automatic conversion that pandas will do to optimize operations with row. If row contained both integers and floats, it'd need to be of dtype object, which removes most of the gain from using pandas in the first place. Now, having all floats brings a lot of performance power. Sometimes this automatic conversion is not possible, though. For example, if you had a column with string values, then there'd be no possibility other than holding row values with dtype=object, and you would see your index with ints.
**Solution** is,
Explicitly, do not reset\_index(). Access the index with row.name instead. | I expect this to happen because `pandas.Series` can have only one `dtype` and therefore 'int' is automagically converted to `float`.
As a workaround, this may work for you:
```
for i in df[df['b'].eq(0)].reset_index().itertuples(index=False): print(i)
```
Result:
```
Pandas(index=2, a=163, b=0.0, c=0.034)
Pandas(index=5, a=183, b=0.0, c=0.296)
```
Alternative:
```
from collections import namedtuple
for i in df[df['b'].eq(0)].reset_index().itertuples(index=False): print(i._asdict())
```
Result:
```
{'index': 2, 'a': 163, 'b': 0.0, 'c': 0.034}
{'index': 5, 'a': 183, 'b': 0.0, 'c': 0.296}
``` |
33,946,149 | I'm trying to get a list of installations based on a userID field. Currently this returns the error "at least one ID field (installationId,deviceToken) must be specified in this operation"
```
$url = 'https://api.parse.com/1/installations';
$user_id = "3014";
$APPLICATION_ID = 'xxxxxxxxxxxxxxxx';
$REST_API_KEY = 'xxxxxxxxxxxxxxxx';
$MASTER_KEY = 'xxxxxxxxxxxxxxxx';
$data = array
(
"where" => array(
"userID" => $user_id,
),
);
$_data = json_encode($data);
$headers = array(
'Content-Type: application/json',
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'X-Parse-Master-Key: ' . $MASTER_KEY,
'Content-Length: ' . strlen($_data),
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec($curl);
var_dump($response);
curl_close($ch);
```
Does anybody know where I'm going wrong?
Thanks | 2015/11/26 | [
"https://Stackoverflow.com/questions/33946149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1092872/"
] | [`docker compose`](https://github.com/docker/compose) is just a way to declare the container you have to start: ~~it has no notion of node or cluster~~, unless it launches swarm master and swarm nodes, but that is [`docker swarm`](https://docs.docker.com/swarm/))
Update July 2016, 7 months later: docker 1.12 blurs the lines and [includes a "swarm mode"](https://docs.docker.com/engine/swarm/).
It is vastly different from [kubernetes](http://kubernetes.io/), a google tool to manage thousands of containers groups as Pod, over tens or hundreds of machines.
A [Kubernetes Pod](http://kubernetes.io/v1.0/docs/user-guide/pods.html) would [be closer from a docker swarm](http://googlecloudplatform.blogspot.fr/2015/01/everything-you-wanted-to-know-about-Kubernetes-but-were-afraid-to-ask.html):
>
> Imagine individual Docker containers as packing boxes. The boxes that need to stay together because they need to go to the same location or have an affinity to each other are loaded into shipping containers.
>
> In this analogy, the packing boxes are Docker containers, and the shipping containers are Kubernetes pods.
>
>
>
As [commented below](https://stackoverflow.com/questions/33946144/what-are-the-differences-between-kubernetes-pods-and-docker-composes-composur/33946256#comment64413899_33946256) by [ealeon](https://stackoverflow.com/users/1686628/ealeon):
>
> I think pod is equivalent to compose except that kubernetes can orchestrated pods, whereas there is nothing orchestrating compose unless it is used with swarm like you've mentioned.
>
>
>
You can [launch kubernetes commands with docker-compose by the way](http://sebgoa.blogspot.fr/2015/04/1-command-to-kubernetes-with-docker.html).
[](https://i.stack.imgur.com/33iS2.jpg)
>
> In terms of how Kubernetes differs from other container management systems out there, such as Swarm, Kubernetes is the third iteration of cluster managers that Google has developed.
>
>
>
You can hear more about kubernetes in the [episode #3 of Google Cloud Platform Podcast](https://www.gcppodcast.com/post/episode-3-kubernetes-and-google-container-engine/).
While it is true both can create a multi-container application, a Pod also serves as a unit of deployment and horizontal scaling/replication, which docker compose does not provide.
Plus, you don't create a pod directly, but use controllers (like replication controllers).
POD lives within a larger platform which offers Co-location (co-scheduling), fate sharing, coordinated replication, resource sharing, and dependency management.
Docker-compose lives... on its own, with its `docker-compose.yml` file | There's a difference with respect to networking:
* Containers in a pod share the same IP address. From [kubernetes docs](https://kubernetes.io/docs/user-guide/pods/#resource-sharing-and-communication):
>
> The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost. Because of this, applications in a pod must coordinate their usage of ports. Each pod has an IP address in a flat shared networking space that has full communication with other physical computers and pods across the network.
>
>
>
* Containers in a docker-compose are assigned different IP addresses. See this [blog post](https://blog.alejandrocelaya.com/2017/04/21/set-specific-ip-addresses-to-docker-containers-created-with-docker-compose/) for more information. |
7,037,092 | Is it true that template code compiled and linked into a PE will increase in size compared to code without templates. I think each instances of templates used is packed orderly so it will output a match if required faster.
Sorry for the question I just don't know much about template. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7037092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/891341/"
] | The template itself doesn't take any space at all. It the instantiations of that template that do. A template is instantiated once you use it with a type parameter - `MyClass<int> mc`. An instantiation is created once for every type you use, so `MyClass<int> mc2` won't cause another instantiation, but rather use the existing one.
So it really depends on how many types you use with the templates. But that's no different that using different non-templated classes, which will also increase your code size. Bottom line - I wouldn't worry about it. | In addition to answers given by @Als and @eran:
Compiler and Linker would work collectively to find out code that is same for two or different data types for given class/functions, and if they find out similar code, that is **not-dependent** on datatype, they may create one copy of that code. The code might be a method of class, certain function or some part of method/function. |
13,962,743 | I have a form that give `Fname` and `Lname` and `Date` and a method to write this information to a file.
If `Fname` or `Lname` contain digit, the program should display an error message and not run all below statements ,(like write to file and generate random number and...), and not exit.
since i dont know how to do like this, in my code i write if Fname or Lname have digit, exit !
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
```
please help! | 2012/12/19 | [
"https://Stackoverflow.com/questions/13962743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900445/"
] | As a general rule, try to stay away from using `System.exit()` in GUI-driven applications. It'll just make the whole program quit, leaving the user wondering what happened. `System.exit()` is usually better suited for command line applications that want to provide an exit code to the shell and it's a parallel to the [system exit](http://msdn.microsoft.com/en-us/library/ms194959%28v=vs.80%29.aspx) calls available in most operating systems.
Try this:
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())) {
jLabel6.setText("First name error!");
return;
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
jLabel6.setText("Last name error!");
return;
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
``` | ```
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
```
should be
```
if(havedigit(getFName())) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
```
Search on Google about how to use JOptionPane.showMessageDialog. |
11,376,002 | I have developed a jsf application with following facets
* Dynamic Web Module 2.5
* Java 5
* JavaServer Faces 1.2
* Rich Faces 3.3.2
I have a page with an t:inputFileUpload component. it was working fine till i added ajax and rich faces components and taglibs to my page. As follows:-
```
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%>
<%@taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@taglib uri="http://richfaces.org/rich" prefix="rich"%>
...
<t:inputFileUpload...
```
All i want to ask is that, is it not possible that these taglibs can work together?
Thanks in advance. | 2012/07/07 | [
"https://Stackoverflow.com/questions/11376002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1353036/"
] | It should work fine as long as you don't submit the form by ajax. It's namely not possible to upload files by ajax using the `<t:inputFileUpload>`. So, you need to make sure that you submit the form by a synchronous (non-ajax) request.
You should also make sure that the Tomahawk's `ExtensionsFilter` is been registered in `web.xml` *before* RichFaces' `org.ajax4jsf.Filter`, otherwise it will consume the `multipart/form-data` request before Tomahawk's `ExtensionsFilter` get chance to do so.
Alternatively, you could drop Tomahawk's `<t:inputFileUpload>` and use RichFaces' own `<rich:fileUpload>` instead. It's able to simulate a "ajax look-a-like" file upload using Flash. | Please make sure that you have an "encrypeType" in your form.
```
<h:form enctype="multipart/form-data">
``` |
23,379,170 | I want to add arbitrary item to Pidgin menu. Let it be *Buddies → Show → Groups*. I want it to be checkbutton (like *Buddies → Show → Empty Groups*) with custom function associated. How can I do this?
* [In Pidgin 2.10.9](https://stackoverflow.com/a/23379171/2572082)
* [In Pidgin 3.0.0 (development branch)](https://stackoverflow.com/a/23382393/2572082) | 2014/04/30 | [
"https://Stackoverflow.com/questions/23379170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572082/"
] | *The following example is for Pidgin version 2.10.9. I believe there are not many changes in 3.0.0 (current development branch) so it will be applicable there too with minimal modifications.*
First of all, download Pidgin sources. In Ubuntu this is done simply by running
```
apt-get source pidgin
```
Which will fetch libpurple, pidgin and finch sources. Then go into `pidgin-2.10.9/pidgin/gtkblist.c` and find the line
```c
static GtkItemFactoryEntry blist_menu[] =
```
There you will see Gtk menu in text. Add the following line:
```c
{ N_("/Buddies/Show/_Groups"), NULL, pidgin_blist_show_groups_cb, 1, "<CheckItem>", NULL },
```
after
```c
{ N_("/Buddies/Show/_Empty Groups"), NULL, pidgin_blist_show_empty_groups_cb, 1, "<CheckItem>", NULL },
```
You can see that the line added is just the analog of after which it was added. The 3rd array member is the function responsible for updating menu item status.
Next, add the function you just specified, `pidgin_blist_show_groups_cb`. You can do it finding the `pidgin_blist_show_empty_groups_cb` and copying it's contents.
```c
static void pidgin_blist_show_groups_cb(gpointer data, guint action, GtkWidget *item)
{
pidgin_set_cursor(gtkblist->window, GDK_WATCH);
purple_prefs_set_bool(PIDGIN_PREFS_ROOT "/blist/show_groups",
gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(item)));
pidgin_clear_cursor(gtkblist->window);
}
```
Also, you need to set item status on startup. Find the function
```c
static void pidgin_blist_show(PurpleBuddyList *list)
```
and add
```c
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gtk_item_factory_get_item (gtkblist->ift, N_("/Buddies/Show/Groups"))),
purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/blist/show_groups"));
```
after
```c
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gtk_item_factory_get_item (gtkblist->ift, N_("/Buddies/Show/Empty Groups"))),
purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/blist/show_empty_groups"));
```
The adding preference `"/blist/show_groups"` as well as adding callback to it is explained in [How do I add custom preference into Pidgin?](https://stackoverflow.com/questions/23379642/how-do-i-add-custom-preference-into-pidgin). To test your changes, compile and install pidgin:
```none
sudo apt-get build-dep pidgin
cd pidgin-2.10.9/
fakeroot debian/rules binary
sudo dpkg -i ../pidgin_2.10.9-0ubuntu3.deb
``` | Pidgin-3.0.0
------------
There are some changes in the way which Pidgin generates menu in 3.0.0 version. First, there is new array `GtkToggleActionEntry blist_menu_toggle_entries[]`. You need to add there
```c
{ "ShowGroups", NULL, N_("_Groups"), NULL, NULL, G_CALLBACK(pidgin_blist_show_groups_cb), FALSE },
```
after
```c
{ "ShowEmptyGroups", NULL, N_("_Empty Groups"), NULL, NULL, G_CALLBACK(pidgin_blist_show_empty_groups_cb), FALSE },
```
And, there is `static const char *blist_menu`. You need to add
```c
"<menuitem action='ShowGroups'/>"
```
after
```c
"<menuitem action='ShowEmptyGroups'/>"
```
Then follow the instructions from [this answer](https://stackoverflow.com/a/23379171/2572082) skipping the very first. |
168,928 | Let's say that I have earned 100% of the trophies in *Borderlands 2* on the PS3. If I were to play the PS Vita version, would it register as a new *game* on my PSN, therefore allowing me to earn all the trophies again? Or rather, would it *stack* on top of my existing trophies?
And in the same line of question: Would it be possible to transfer the save files of my game from the PS3 to the PS Vita? That is, if thy use the same file format.
Thanks! | 2014/05/22 | [
"https://gaming.stackexchange.com/questions/168928",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/77107/"
] | No, PS3 and Vita have the same trophy list. There is cross save between PS3 and vita for Borderlands 2. | You will not re-earn trophies. |
70,006,819 | I have an application that is composed by different layers and written in three different languages: c++, bash and python
EDIT: on a Linux/Raspbian platform
Since now we are managing different build, platform depending, with different branches of sw development, but I'm trying to merge everything in a single branch to increase maintainability.
Do you know if there is a (and which is the better) method to share env settings between c++, bash and python?
The point is to distinguish if I'm building for platform A or platform B, and the only idea I have is have a different file per every language to set up. Is there a way to have a single point with the information? | 2021/11/17 | [
"https://Stackoverflow.com/questions/70006819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17439426/"
] | I fixed using a barrier and `app:barrierAllowsGoneWidgets="false"` and setting the right view constrained to the barrier
```
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/text2"
android:text="Left"
android:visibility="gone"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:text="Center"
android:visibility="gone"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideLine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintGuide_percent="0.5"
android:orientation="vertical"/>
<TextView
android:id="@+id/text3"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/barrier"
android:text="Right"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierAllowsGoneWidgets="false"
app:constraint_referenced_ids="text1,text2"
app:barrierDirection="end"/>
</androidx.constraintlayout.widget.ConstraintLayout>
``` | To solve the problem I will recommend you to use LinearLayout and the property weightSum. So it will be something like this:
```
<LinearLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="1"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Center"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="1"/>
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="1"/>
</LinearLayout>
``` |
68,286,020 | I am trying to create a registration form using Django as I have created the form and model on the website after clicking the submit it calls for the view as action provided to the form but it seems that no data is been inserted in the database and no error in the terminal as well. I have tried to find solutions but none of them worked. I am new in the field of python and web development.
below is the code that I have used on the website.
model.py
```
from django.db import models
class Writer(models.Model):
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=254)
contactnumber = models.IntegerField()
gender = models.CharField(max_length=30)
password = models.CharField(max_length=254)
date = models.DateField()
class Meta:
db_table = 'Writers'
```
below code are of my views.py
views.py
```
def createuser(request):
if request.method == 'POST':
username = request.POST.get('username')
first_name = request.POST.get('firstname')
last_name = request.POST.get('lastname')
email = request.POST.get('email')
contactnumber = request.POST.get('phonenumber')
gender = request.POST.get('gender')
password = contactnumber
if username == None or first_name == None or last_name == None or email == None or contactnumber == None or gender == None:
return render(request,"adminpanal/userregister.html",{'alert_flag': True})
else:
createnewuser = Writer(username=username,first_name=first_name,last_name=last_name,email=email,gender=gender,contactnumber=contactnumber,password=password,date=datetime.today())
createnewuser.save()
return redirect('/Blogdashboard/dashboard')
return HttpResponse("Doen,user created")
```
below are the Html form that I have used
```
<form action="/Blogdashboard/createuser" method="post" style="margin: 5px">
{% csrf_token %}
<div >
<label class="labelinput">Username</label>
<input name = "username" type="text" class="form-control" id="username" required>
</div>
<div >
<label class="labelinput">First name</label>
<input name = "firstname" type="text" class="form-control" id="firstname" required>
</div>
<div >
<label class="labelinput">Last name</label>
<input name = "lastname" type="text" class="form-control" id="lastname" required>
</div>
<div >
<label class="labelinput">Email id</label>
<input name = "email" type="email" class="form-control" id="email" required>
</div>
<div >
<label class="labelinput">Contact number</label>
<input name = "phonenumber" type="phone" class="form-control" id="phonenumber" required>
</div>
<div>
<label class="labelinput">Gender</label>
<select id="gender" name="gender" class="form-select " aria-label="Default select example" required>
<option selected>select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Transgender">Transgender</option>
</select>
</div>
<center>
<button type="submit" class="btn btn-primary" style="margin-top: 20px;" >New writer </button>
</center>
{% if alert %}
<script>alert("Please enter Your details blank feild are not allowed.")</script>
{% endif %}
</form>
```
As I have checked my terminal as well as my website live view it works fine all the data from the form are been received at the create user view and after submitting the form as I am been redirected to the dashboard as I have returned it, but no data is been inserted in the database as I have seen the terminal too there is no error on it. | 2021/07/07 | [
"https://Stackoverflow.com/questions/68286020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016907/"
] | Try using this:
```
createnewuser=Writer.objects.create_user(username,first_name,last_name,email,gender,contactnumber,password)
createnewuser.save()
```
You should use the default 'User' model of django.It will be easy for you | Question, why are you not using a ModelForm?
A modelform can do a lot of validation for you, such as checking for required fields and even custom validators?
See documentation: <https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/> |
18,423,124 | I'm under osx 10.8.4 and have installed gdb 7.5.1 with homebrew (motivation get a new gdb with new features such as --with-python etc... )
Long story short when I run debug within a c++ Eclipse project I get :
```
Error in final launch sequence
Failed to execute MI command:
-exec-run
Error message from debugger back end:
Unable to find Mach task port for process-id 46234: (os/kern) failure (0x5).
(please check gdb is codesigned - see taskgated(8))
Unable to find Mach task port for process-id 46234: (os/kern) failure (0x5).
(please check gdb is codesigned - see taskgated(8))
```
I have followed various suggestions for code signing
* <https://sourceware.org/gdb/wiki/BuildingOnDarwin>
* partly <http://www.noktec.be/archives/1251> with various adjusts
So I did:
1. Set up the certificate
2. Sign the gdb -> codesign -s gdb-cert /usr/local/bin/gdb
When I re-run debugging in Eclipse I get same error as above "(please check gdb is codesigned - see taskgated(8))".
If I set back the gdb to the older gdb (in the gdb preferences of Eclipse) /usr/libexec/gdb/gdb-i386-apple-darwin the debugging runs as expected.
Any solutions / hints out there ?
Thx
Pelle | 2013/08/24 | [
"https://Stackoverflow.com/questions/18423124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714339/"
] | None of this worked for me and I had to go with a long run.
Here is a full list of steps I've done to get it working.
1. Create a certificate to sign the gdb.
Unfortunately, system certificate gave me `Unknown Error = -2,147,414,007` which is very helpful, so I had to go with a workaround.
`Keychain Access -> Create certificate ->`
Pick `login`, `gdb-cert`, `Code Signing`
Copy/move certificate to the System keychain (enter password)
2. Select certificate (`gdb-cert`) click `Get info` -> `Trust Always`
3. Disable `startup-with-shell`
Enter in console: `set startup-with-shell off`
Remember configuration:
`echo "set startup-with-shell off" >>~/.gdbinit`
4. Enable Root User
Go to `System Preferences` -> `Users & Groups` -> `Unlock it` -> `Login Options` -> `Network Account Server` -> `Join` -> `Unlock it` -> `Edit` (menu) -> `Enable Root User`
5. `sudo killall taskgated`
6. Finally sign gdb
`codesign -fs gdb-cert "$(which gdb)"`
7. Disable Root User (Step 4)
8. Reboot if still does not work. (if nothing else works, most likely it works already)
PS. I ended up using `lldb` because it just works ([tutorial](https://lldb.llvm.org/tutorial.html)) | I can recommend to follow this gist:
<https://gist.github.com/gravitylow/fb595186ce6068537a6e9da6d8b5b96d#file-codesign_gdb-md>
With trick to overcome: `unknown error = -2,147,414,007` during Certificate Creation described here:
<https://apple.stackexchange.com/a/309123>
**Notes:**
Path for gdb installed as `homebrew` package should be something like: `/usr/local/Cellar/gdb/9.2/bin/gdb`
And `csrutil enable --without debug` will cause a message about `requesting unsupported configuration`, like here:
<https://totalfinder.binaryage.com/system-integrity-protection>
**Test:**
```
○ → sw_vers -productVersion
10.13.6
○ → gdb ./a.out
GNU gdb (GDB) 9.2
...
Thread 3 hit Breakpoint 1, main () at main.c:14
14 data_t d = {0};
``` |
20,467,617 | Following is code
```
class Hotel {
public int bookings;
public void book() {
bookings++;
}
}
public class Test extends Hotel{
public void book() {
bookings--;
}
public void book(int size) {
book();
super.book();
bookings += size;
}
public static void main(String... args) {
Hotel hotel = new Test();
hotel.book(2); // Compiler show error
System.out.print(hotel.bookings);
}
}
```
>
> **Erorr:** method book in class javaapplication1.Hotel cannot be applied to given types;
>
>
> required: no arguments
>
>
> found: int
>
>
> reason: actual and formal argument lists differ in length
>
>
>
**Why compiler is complaining? which rule of Method Overloading/Overriding compiler is applying?**
*Your response will be Appreciated !!!* | 2013/12/09 | [
"https://Stackoverflow.com/questions/20467617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2902950/"
] | `hotel` is of type `Hotel`, which **doesn't have** `book(int)` method.
If you want to call `book(int)` you need to change (or cast) `hotel`'s type to `Test`
```
Test hotel = new Test();
hotel.book(2); // No error
``` | Class `Hotal` is not aware of the method `public void book(int size)` , and for invocation you are using the reference of `Hotel`.
Runtime polymorphism is nothing but defining a contract for all who implement the base class/interface. This enable objects to interact with one another without knowing their exact type. In your case base class does not have contract for `book(int)` which is own property of sub classes.
As quick fix you can try some thing like this,
```
if(hotel instanceof Test){
((Test)hotel).book(2); // Compiler show error
}
```
or
```
Test hotel = new Test();
test.book(2);
```
How ever ideall, you should be declaring/defning this method in `Hotel` class |
58,019,275 | I am reading [this book](https://www.amazon.co.uk/Beginning-STM32-Developing-FreeRTOS-libopencm3/dp/1484236238) and I have come across this code:
```
static void
task1(void *args) {
int i;
(void)args;
for (;;) {
gpio_toggle(GPIOC,GPIO13);
for (i = 0; i < 1000000; i++)
__asm__("nop");
}
}
```
I understand all (relatively) except for line 5. What is `(void)args;` doing?
`args` is not used in the function body, and I know that if an argument is not used then one could write
```
static void
task2(void *args __attribute((unused))) {
// code here
}
```
which is not being done here. So what is `(void)` written like that doing? | 2019/09/19 | [
"https://Stackoverflow.com/questions/58019275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8896573/"
] | In general when one does not use an function argument, the compiler is likely to warn you about it. After all if you aren't going to use it why put it there in the first place?
In effect it is an artificial use of the argument that does nothing useful other than telling the compiler you know what you are doing, so "*Shatupalready with the warning*!"
**(void) args** works on all of the platforms that I have seen. I believe the **\_\_attribute((unused)**) is a gcc specific thing. | It's a compiler warning (`-W unused-variable` or `-W all`) they're suppressing by using it. You are correct in that `__attribute__((unused))` is a valid C macro to do what you're asking, but it's a matter of preference. It's also not supported by all C compilers.
Sources:
<http://www.keil.com/support/man/docs/armcc/armcc_chr1359124983230.htm>
<https://en.cppreference.com/w/cpp/compiler_support> |
23,867,903 | Now I have a directory with bunch files with format of name like "EXT2-401-B-140422-1540-1542.mp4", within which the "140422" part indicates the date. Now assume that this bunch of files have the dates like 140421, 140422, 140423...(for every date there are couple of files). Now I shall sort these files according to their dates, so I'd like to know how could I get these names (140421,140422,etc). I tried like this:
```
directory = new DirectoryInfo(camera_dir);
string[] date = new string[directory.GetFiles().Length];
foreach (FileInfo file in directory.GetFiles())
{
foreach(string name in date)
{
name = file.Name.Substring(11, 6);
}
}
```
And the error message is that I can't assign to name. So anybody could help? | 2014/05/26 | [
"https://Stackoverflow.com/questions/23867903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3433408/"
] | ```
directory = new DirectoryInfo(camera_dir);
string[] date = new string[directory.GetFiles().Length];
int i=0;
foreach (FileInfo file in directory.GetFiles())
{
name[i] = file.Name.Substring(11, 6);
i++;
}
``` | In fact you are asking two questions.
1. You cannot assign a variable from the `foreach`. Create a new one to store the name in.
2. For the second part, how to extract it: use this regex:
```
string s = Regex.Replace(file.Name, @"(.*?)\-(.*?)\-(.*?)\-(.*?)\-(.*)", "$4");
```
The `?` makes the regex non-greedy, meaning that this expression will find the text after the third dash. |
4,084,212 | Just switched from Cucumber+Webrat to Cucumber+Capybara and I am wondering how you can POST content to a URL in Capybara.
In Cucumber+Webrat I was able to have a step:
```
When /^I send "([^\"]*)" to "([^\"]*)"$/ do |file, project|
proj = Project.find(:first, :conditions => "name='#{project}'")
f = File.new(File.join(::Rails.root.to_s, file))
visit "project/" + proj.id.to_s + "/upload",
:post, {:upload_path => File.join(::Rails.root.to_s, file)}
end
```
However, the Capybara documentation mentions:
>
> The visit method only takes a single
> parameter, the request method is
> always GET.always GET.
>
>
>
How do I modify my step so that Cucumber+Capybara does a POST to the URL? | 2010/11/03 | [
"https://Stackoverflow.com/questions/4084212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216287/"
] | Capybara's `visit` only does GET requests. This is by design.
For a user to perform a `POST`, he must click a button or submit a form. There is no other way of doing this with a browser.
The correct way to test this behaviour would be:
```
visit "project/:id/edit" # This will only GET
attach_file "photo", File.open('cute_photo.jpg')
click_button 'Upload' # This will POST
```
If you want to test an API, I recommend using `spec/request` instead of cucumber, but that's just me. | With an application using RSpec 3+, you would not want to make an HTTP POST request with Capybara. Capybara is for emulating user behavior, and accepting the JS behavior and page content that results. An end user doesnt form HTTP POST requests for resources in your application, a user clicks buttons, clicks ajax links, drags n drops elements, submits web forms, etc.
Check out [this blog post](https://www.varvet.com/blog/capybara-and-testing-apis/) on Capybara and other HTTP methods. The author makes the following claim:
>
> Did you see any mention of methods like get, post or response? No? That’s because those don’t exist in Capybara. Let’s be very clear about this...Capybara is not a library suited to testing APIs. There you have it. Do not test APIs with Capybara. It wasn’t designed for it.
>
>
>
So, developing an API or not, if you have to make an explicit HTTP POST request, and it does not involve an HTML element and some sort of event (click, drag, select, focusout, whatever), then it shouldn't be tested with Capybara. If you can test the same feature by clicking some button, then do use Capybara.
What you likely want is [RSpec Request specs](https://relishapp.com/rspec/rspec-rails/v/3-5/docs/request-specs). Here you can make `post` calls, and any other HTTP method as well, and assert expectations on the response. You can also mock n stub objects and methods to assert expectations in regards to side effects and other behaviors that happen in between your request and the response.
```
# spec located in spec/requests/project_file_upload_spec.rb
require "rails_helper"
RSpec.describe "Project File Upload", type: :request do
let(:project) { create(:project) }
let(:file) { File.new(File.join(::Rails.root.to_s, 'path/to/file.ext')) } # can probably extract this to a helper...
it "accepts a file uploaded to a Project resource" do
post "project/#{project.id}/upload", upload_path: file
expect(response).to be_success
expect(project.file?).to eq(true)
# expect(project.file).not_to eq(nil)
expect(response).to render_template(:show)
end
end
``` |
34,605,163 | I'm using a select tag to create a currency menu , what I'm trying to do is get the value of the selector so i can turn it into a variable to use. I already tried various methods that were also posted on stack but I keep getting returned my line of code instead of the value of the currency.
this is my javascript.
```
function go(){
var sel = document.getElementById('userCurrency');
var userCurrency = sel.options[sel.selectedIndex].text;
}
var newP = $("<p>")
var userDate = ("#userDate")
var bitcoinApiUrl = "https://crossorigin.me/https://api.bitcoincharts.com/v1/markets.json";
$(document).ready(function(){
$(".btn").on("click", function(){
console.log(userCurrency)
$.ajax({
type: "GET",
url: bitcoinApiUrl,
dataType: "json",
success: function(currency) {
// loop through currency
for (var i = 0; i < currency.length; i++)
{
if(currency[i].currency == "USD")
{
var $tr = $("<tr />");
$tr.append( $("<td />").text(currency[i].volume) );
$tr.append( $("<td />").text(currency[i].latest_trade) );
$tr.append( $("<td />").text(currency[i].bid) );
$tr.append( $("<td />").text(currency[i].high) );
$("#theTable tbody").append($tr);
}
}
}
});
});
});
```
my html
```
<!-- currency select -->
<label class="">
<span class="">Pick a currency</span>
<select id="userCurrency" style="display: inline; width: auto; vertical-align: inherit;" onChange="go()">
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option>JPY</option>
<option>GBP</option>
<option>CHF</option>
<option>CAD</option>
<option>AUD</option>
<option>MXN</option>
<option>CNY</option>
<option>NZD</option>
<option>SEK</option>
<option>RUB</option>
<option>HKD</option>
<option>NOK</option>
<option>SGD</option>
<option>TRY</option>
<option>KRW</option>
<option>ZAR</option>
<option>BRL</option>
<option>INR</option>
</select>
</label>
<!-- select end -->
``` | 2016/01/05 | [
"https://Stackoverflow.com/questions/34605163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5451743/"
] | This can be done by using `$('#selectId option:selected').text();`.
```
$(document).ready(function(){
$(".btn").on("click", function(){
var userCurrency = $('#userCurrency option:selected').text();
console.log(userCurrency)
$.ajax({
type: "GET",
url: bitcoinApiUrl,
dataType: "json",
success: function(currency) {
// loop through currency
for (var i = 0; i < currency.length; i++)
{
if(currency[i].currency == "USD")
{
var $tr = $("<tr />");
$tr.append( $("<td />").text(currency[i].volume) );
$tr.append( $("<td />").text(currency[i].latest_trade) );
$tr.append( $("<td />").text(currency[i].bid) );
$tr.append( $("<td />").text(currency[i].high) );
$("#theTable tbody").append($tr);
}
}
}
});
});
});
```
Here is a [Fiddle](https://jsfiddle.net/oxrhey5d/) for the same. | you have to change.
```
document.getElementById('userCurrency');
```
to
```
document.getElementById('userCurrency').value;
```
to get the value of select box. |
3,074,452 | Is it best to program a game for the iPhone in Objective C or in C++.
What language would a game like Flight Control be written in?
What format should graphics be in to show properly and load quickly on the iPhone? | 2010/06/19 | [
"https://Stackoverflow.com/questions/3074452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370865/"
] | Games like Flight Control are usually written in Objective-C with some C calls to OpenGL and other C APIs. The graphics can be stored in PNG or JPEG. I would stay out of C++ unless I had to use some C++ code or had developers with good C++ knowledge. According to my experience the bottleneck is seldom in the language, so that you haven’t much to gain by switching to C++. | I appreciate everybody's quick response and expertise.
I am in the process of learning either C++ or Objective C and it looks as though Objective C is more direct to the iPhone.
My background is "gasp" COBOL85 (among other arcane languages). I would rather have someone already fluent in iPhone apps code the game, but I would guess the development costs would make that a little prohibitive. I do have a request for bid prepared, with "pseudocode", if someone out there would like to see it and give a quote. Meanwhile, there doesn't seem to be an advantage to C++
Ken clean37@hotmail.com |
29,797,367 | My inexperience has me here asking this question.
Can I pass a value to multiple `PHP` pages in `JQuery`?
Here is an example of what I am trying to do.
```
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
```
When the user changes a selection within a drop down list, a unique ID will be sent over to `displayfacilities.php`. I also need that ID in `updatefacilities.php` which is called from `displayfacilities.php`.
Is this a bad idea, or is there a better way? | 2015/04/22 | [
"https://Stackoverflow.com/questions/29797367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057853/"
] | Since the inner exception is an exception itself, perhaps you can just recurse and reuse the method you already have:
```
if (e.InnerException != null)
{
LogCompleteException(controllerName, actionName, e.InnerException);
}
```
If this does work, however, you will still be missing the EntityValidationErrors.
Another method, which I used recently is to just explicitly trap and log the exception where it occurs:
```
try
{
db.Add(something);
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
StringBuilder sb = new StringBuilder();
// collect some extra info about the exception before logging
foreach (var eve in ex.EntityValidationErrors)
{
sb.AppendLine(String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
sb.AppendLine(String.Format("Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
}
}
logger.Error("There was an error while trying to parse and save something!\n" + sb.ToString(), ex);
}
```
If you want the Exception.Data dictionary entries, you can add those as well:
```
foreach (DictionaryEntry entry in ex.Data)
{
// you will want to use a StringBuilder instead of concatenating strings if you do this
exceptionMessage = exceptionMessage + string.Format("Exception.Data[{0}]: {1}", entry.Key, entry.Value);
}
```
As for properties for Custom exception classes just as the EntityValidationErrors, I would just trap and parse those where they occur. Otherwise you would have to override ToString() on every exception type or use some reflection hackery to enumerate all the properties which would significantly clutter the logs with properties you dont care about. | you could use [elmah](https://code.google.com/p/elmah/) and the [log4net appender](https://www.nuget.org/packages/elmahappender_log4net_1.2.10/). Elmah logs catches all exceptions and can log them to a log4net instance. |
161,263 | I'm building a new SharePoint farm to test migration of old, old, old MOSS content to SP13. Using a migration tool to migrate content, but need recommendation for build sequence:
**Option 1:** build farm, build web app, apply all service packs, etc to get to current release, use migration tool to migrate old content to web app.
**Option 2:** build farm, apply all updates, SPack, etc, build web app, migrate old content to web app
or does it really matter? | 2015/11/02 | [
"https://sharepoint.stackexchange.com/questions/161263",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/48403/"
] | I have yet to actually deploy it - but I'm pretty sure it will still be around - at minimum to support upgrade.
1. It's not on the deprecated feature list <https://technet.microsoft.com/en-us/library/mt346112%28v=office.16%29.aspx?f=255&MSPPError=-2147217396>
2. They still exist in Office 365
3. The biggest reason - they still support database attach upgrades from 2013 - which may contain 2010 workflows. | What my understanding as Microsoft bring back InfoPath forms in sharePoint 2016. that's mean SharePoint 2010 Workflow will work as some of infopath services required for the Workflow in Sp 2010.
>
> This leads me to believe that SharePoint 2016 may still be able to run
> SharePoint 2010 Workflows like 2013 did by default. This is
> speculating that a SharePoint 2010 to 2016 migration is possible of
> course.
>
>
>
<http://en.share-gate.com/blog/sharepoint-2010-to-sharepoint-2016-migration-a-possibility> |
40,898,512 | I am using the Street View Javascript Api in a project, and I understand how to use heading to make the Google's panorama aim north.
Now I am also getting all the tiles that create this panorama and using them to create a 360° raw panorama image.
However, I want to know if there is a way to find out automatically where the north is in the raw panorama created.
For example, [](https://i.stack.imgur.com/aPpSR.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40898512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2578183/"
] | `INT` and `NUMERIC` isn't the same. `ISNUMERIC` is returning anything that *could* possibly be a numeric type `(INT, BIGINT, DECIMAL, FLOAT, MONEY)`.
Example: `SELECT ISNUMERIC('$')`
This isn't an `INT` but returns true because it is something that is correctly formatted as `MONEY`. `ISNUMERIC` also works on scientific notations.... `SELECT ISNUMERIC('1e4')` would result to true. The point i'm making is don't trust `ISNUMERIC` out right without understanding what it is evaluating, or all the possibilities. | You hit by chance one valid notation (I did not know this either):
```
SELECT CAST('45D-1' AS FLOAT) --4.5
SELECT CAST('45D-2' AS FLOAT) --0.45
SELECT CAST('45D-3' AS FLOAT) --0.045
SELECT CAST('45D+1' AS FLOAT) --450
SELECT CAST('45D+3' AS FLOAT) --45000
```
Produces the same results as
```
SELECT CAST('45e-1' AS FLOAT)
SELECT CAST('45e-2' AS FLOAT)
SELECT CAST('45e-3' AS FLOAT)
SELECT CAST('45e+1' AS FLOAT)
SELECT CAST('45e+3' AS FLOAT)
```
Obviously there is a scientific notation using the letter `d` in the same way as the more usual `e`.
Just add `.0` to your string and `ISNUMERIC` will return *no number*
```
DECLARE @s VARCHAR(100)='45D-1';
SELECT ISNUMERIC(@s+'.0')
```
(Works only, if your numbers haven't got decimals already...)
UPDATE
------
You might use `PATINDEX` to search for any occurance of a character not `0-9`:
```
DECLARE @s VARCHAR(100)='45D-1';
SELECT CASE WHEN PATINDEX('%[^0-9]%',@s)>0 THEN 'Nope!' ELSE 'Yeah!' END AS IsInt
``` |
170,308 | The cover was white and had a red swirly mask on it. I think the first book started with her flying. There were hunters and the main character got captured and they did experiments and locked them in cells and stuff.
I'm pretty sure that, before all that, they lived in this village thing hidden by people with magic or fog. | 2017/09/24 | [
"https://scifi.stackexchange.com/questions/170308",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/90272/"
] | Could this possibly be the [***Firelight***](https://www.goodreads.com/book/show/6448470-firelight) series by Sophie Jordan?
>
> Marked as special at an early age, Jacinda knows her every move is watched. But she longs for freedom to make her own choices. When she breaks the most sacred tenet among her kind, she nearly pays with her life. Until a beautiful stranger saves her. A stranger who was sent to hunt those like her. For Jacinda is a draki, a descendant of dragons whose greatest defense is her secret ability to shift into human form.
>
>
> Forced to flee into the mortal world with her family, Jacinda struggles to adapt to her new surroundings. The only bright light is Will. Gorgeous, elusive Will who stirs her inner draki to life. Although she is irresistibly drawn to him, Jacinda knows Will's dark secret: He and his family are hunters. She should avoid him at all costs. But her inner draki is slowly slipping away;if it dies she will be left as a human forever. She'll do anything to prevent that. Even if it means getting closer to her most dangerous enemy.
>
>
> Mythical powers and breathtaking romance ignite in this story of a girl who defies all expectations and whose love crosses an ancient divide.
>
>
> | Another possibility: The [***Talon***](https://www.goodreads.com/series/96817-talon) series by Julie Kagawa.
>
> The series revolves around dragons with the ability to disguise themselves as humans and an order of warriors sworn to eradicate them. The dragons of TALON and the Order of St. George have been at war with each other for centuries. The fabled creatures, whose existence is unknown by the general public, are determined to rule the world. Their foes, a legendary society of dragon slayers, are equally bent on driving the fabled beasts into extinction. However, when a young dragon and a hardened slayer unknowingly befriend each other, it has severe repercussions for both organizations.
>
>
>
Currently the titles in this series are: Talon, Rogue, Soldier, Legion, Inferno. |
36,052 | 1. **Why “Strings” are bad for Arduino?**
2. **Which is the most efficient and fastest solution to read and store the data from Accelerometer and GPS?**
---
***Stings are evil for Arduino***
---------------------------------
---
An Uno or other ATmega328-based board only has 2048 bytes SRAM.
The SRAM is composed by three parts:
1. The Static
2. The Heap
3. The Stack
**The Heap is where, randomly, a C++ string information is allocated.**
If I add an information to my C++ String the system copies itself and deletes the old copy leaving a hole in the heap, that grows up with the cycles.
When I wrote my first sketch for reading and writing the information from an MPU6050 and stored on a SD (whithout connecting to a GPS) I noticed that the sampling time was not constant.
[](https://i.stack.imgur.com/sdSXy.png)
Thanks to the feedback obtained in [this question](https://stackoverflow.com/questions/42351949/mpu-6050-sd-writing-frequency-arduino-is-not-constant-how-to-have-a-constant-w) on StackOverflow, I understood that the problem was my excessive use of strings, and now i understand why.
So I started to dig into this issue.
This was one of the first version of the code:
```
/******************************************************************************
CSV_Logger_TinyGPSPlus.ino
Log GPS data to a CSV file on a uSD card
By Jim Lindblom @ SparkFun Electronics
February 9, 2016
https://github.com/sparkfun/GPS_Shield
This example uses SoftwareSerial to communicate with the GPS module on
pins 8 and 9, then communicates over SPI to log that data to a uSD card.
It uses the TinyGPS++ library to parse the NMEA strings sent by the GPS module,
and prints interesting GPS information - comma separated - to a newly created
file on the SD card.
Resources:
TinyGPS++ Library - https://github.com/mikalhart/TinyGPSPlus/releases
SD Library (Built-in)
SoftwareSerial Library (Built-in)
Development/hardware environment specifics:
Arduino IDE 1.6.7
GPS Logger Shield v2.0 - Make sure the UART switch is set to SW-UART
Arduino Uno, RedBoard, Pro, Mega, etc.
******************************************************************************/
#include <SPI.h>
#include <SD.h>
#include <TinyGPS++.h>
#include<Wire.h>
#define ARDUINO_USD_CS 10 // uSD card CS pin (pin 10 on SparkFun GPS Logger Shield)
/////////////////////////
// Log File Defintions //
/////////////////////////
// Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
// and a 3 char suffix.
// Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
#define LOG_FILE_PREFIX "gpslog" // Name of the log file.
#define MAX_LOG_FILES 100 // Number of log files that can be made
#define LOG_FILE_SUFFIX "csv" // Suffix of the log file
char logFileName[13]; // Char string to store the log file name
// Data to be logged:
#define LOG_COLUMN_COUNT 15
char * log_col_names[LOG_COLUMN_COUNT] = {
"longitude", "latitude", "altitude", "speed", "course", "date", "time", "satellites","Acc.X","Acc.Y","Acc.Z","Gy.X","Gy.Y","Gy.Z","Temp"
}; // log_col_names is printed at the top of the file.
//////////////////////
// Log Rate Control //
//////////////////////
#define LOG_RATE 1000 // Log every 1 seconds
unsigned long lastLog = 0; // Global var to keep of last time we logged
/////////////////////////
// TinyGPS Definitions //
/////////////////////////
TinyGPSPlus tinyGPS; // tinyGPSPlus object to be used throughout
#define GPS_BAUD 9600 // GPS module's default baud rate
/////////////////////////////////
// GPS Serial Port Definitions //
/////////////////////////////////
// If you're using an Arduino Uno, Mega, RedBoard, or any board that uses the
// 0/1 UART for programming/Serial monitor-ing, use SoftwareSerial:
#include <SoftwareSerial.h>
#define ARDUINO_GPS_RX 9 // GPS TX, Arduino RX pin
#define ARDUINO_GPS_TX 8 // GPS RX, Arduino TX pin
SoftwareSerial ssGPS(ARDUINO_GPS_TX, ARDUINO_GPS_RX); // Create a SoftwareSerial
// Set gpsPort to either ssGPS if using SoftwareSerial or Serial1 if using an
// Arduino with a dedicated hardware serial port
#define gpsPort ssGPS // Alternatively, use Serial1 on the Leonardo
// Define the serial monitor port. On the Uno, Mega, and Leonardo this is 'Serial'
// on other boards this may be 'SerialUSB'
#define SerialMonitor Serial
const int MPU=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup()
{
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
SerialMonitor.begin(9600);
gpsPort.begin(GPS_BAUD);
SerialMonitor.println("Setting up SD card.");
// see if the card is present and can be initialized:
if (!SD.begin(ARDUINO_USD_CS))
{
SerialMonitor.println("Error initializing SD card.");
}
updateFileName(); // Each time we start, create a new file, increment the number
printHeader(); // Print a header at the top of the new file
}
void loop()
{
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
{
if ((lastLog + LOG_RATE) <= millis())
{ // If it's been LOG_RATE milliseconds since the last log:
if (tinyGPS.location.isUpdated()) // If the GPS data is vaild
{
if (logGPSData()) // Log the GPS data
{
SerialMonitor.println("GPS logged."); // Print a debug message
lastLog = millis(); // Update the lastLog variable
}
else // If we failed to log GPS
{ // Print an error, don't update lastLog
SerialMonitor.println("Failed to log new GPS data.");
}
}
else // If GPS data isn't valid
{
// Print a debug message. Maybe we don't have enough satellites yet.
SerialMonitor.print("No GPS data. Sats: ");
SerialMonitor.println(tinyGPS.satellites.value());
}
}
// If we're not logging, continue to "feed" the tinyGPS object:
while (gpsPort.available())
tinyGPS.encode(gpsPort.read());
}
}
byte logGPSData()
{
File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file
if (logFile)
{ // Print longitude, latitude, altitude (in feet), speed (in mph), course
// in (degrees), date, time, and number of satellites.
logFile.print(tinyGPS.location.lng(), 6);
logFile.print(',');
logFile.print(tinyGPS.location.lat(), 6);
logFile.print(',');
logFile.print(tinyGPS.altitude.feet(), 1);
logFile.print(',');
logFile.print(tinyGPS.speed.mph(), 1);
logFile.print(',');
logFile.print(tinyGPS.course.deg(), 1);
logFile.print(',');
logFile.print(tinyGPS.date.value());
logFile.print(',');
logFile.print(tinyGPS.time.value());
logFile.print(',');
logFile.print(tinyGPS.satellites.value());
logFile.print(AcX);
logFile.print(',');
logFile.print(AcY);
logFile.print(',');
logFile.print(AcZ);
logFile.print(',');
logFile.print(GyX);
logFile.print(',');
logFile.print(GyY);
logFile.print(',');
logFile.print(GyZ);
logFile.print(',');
logFile.print(Tmp);
logFile.println();
logFile.close();
return 1; // Return success
}
return 0; // If we failed to open the file, return fail
}
// printHeader() - prints our eight column names to the top of our log file
void printHeader()
{
File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file
if (logFile) // If the log file opened, print our column names to the file
{
int i = 0;
for (; i < LOG_COLUMN_COUNT; i++)
{
logFile.print(log_col_names[i]);
if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
logFile.print(','); // print a comma
else // If it's the last column
logFile.println(); // print a new line
}
logFile.close(); // close the file
}
}
// updateFileName() - Looks through the log files already present on a card,
// and creates a new file with an incremented file index.
void updateFileName()
{
int i = 0;
for (; i < MAX_LOG_FILES; i++)
{
memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
// Set logFileName to "gpslogXX.csv":
sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
if (!SD.exists(logFileName)) // If a file doesn't exist
{
break; // Break out of this loop. We found our index
}
else // Otherwise:
{
SerialMonitor.print(logFileName);
SerialMonitor.println(" exists"); // Print a debug statement
}
}
SerialMonitor.print("File name: ");
SerialMonitor.println(logFileName); // Debug print the file name
}
```
Then I started:
1. Studying how Arduino Memory works
2. Breaking the problem, focusing only to learn how to read and write on a SD the accelerometer information (the device is not connected to the PC)
The following code is my latest version:
```
void Read_Write()
// function that reads the MPU and writes the data to the SD.
{
// Local variables:
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // Variables read from MPU6050
// Read data:
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX = Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
GyX = Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
// Data preparation for file saving:
String dataString = ""; // string for assembling the data to log:
// Add time tag:
dataString += String(Time0); dataString += ",";
// Append the MPU6050 data to the string:
dataString += String(AcX); dataString += ",";
dataString += String(AcY); dataString += ",";
dataString += String(AcZ); dataString += ",";
dataString += String(GyX); dataString += ",";
dataString += String(GyY); dataString += ",";
dataString += String(GyZ);
// Open the file in append mode:
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// If the file is available, write to it:
if (dataFile)
{
dataFile.println(dataString);
dataFile.close();
if (Serial_plus_SD)
Serial.println(dataString);
}
// if the file does not open, pop up an error:
else
errorFW();
return;
}
```
I recived other suggestions such as ***"create a Buffer", but without a technical description and motivation I am having difficulties understand how to do it***.
(I don’t want to simply copy&paste the code as i have done intitially with the first version)
I have to use C Strings instead of C++ Strings?
I have a civil engineer background, so is my first time with coding.
***Thank you for your patience.*** | 2017/03/20 | [
"https://arduino.stackexchange.com/questions/36052",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/20786/"
] | A chat system I used to use "back in the day" used a fixed "stack" based string buffer.
Basically a single `char *` buffer of a fixed size was created at the beginning of the program and initialised to 0.
Then strings were appended to that buffer using whatever functions were appropriate at that time. A pointer was kept pointing to the start of the "free" space in the buffer. This is the pointer which was used for placing new text into that buffer.
The entire buffer was then printed to the output stream in one block, the first byte cleared, and the pointer reset to the start of the buffer.
This made a very efficient and simple string buffer which didn't fragment memory in any way and still allowed the use of standard C string functions such as `sprintf()`, `strcpy()`, etc.
For example:
```
char strbuf[128] = { 0 };
char *strptr = strbuf;
strcpy_P(strptr, (PGM_P)F("Temp = "));
strptr += strlen(strptr);
itoa(temperature, strptr, 10);
strptr += strlen(strptr);
Serial.println(strbuf);
strbuf[0] = 0;
strptr = strbuf;
``` | For fixed strings (which do not change), use e.g. F("Text") ... this will place the string in flash instead of heap space. Note that the Uno has 32 KB of flash and 2 KB of SRAM (which is used for heap space among others).
If you need variable sized strings but one or few at a time, make a dedicated buffer (of e.g. 64 bytes) and use that buffer for all string operations. It will take up 64 bytes all time, but will leave no heap gaps.
You can create it as a global variable (simple):
```
char string_buffer[64];
```
and use that string\_buffer for string operations.
Note that heap gaps are bad for all devices/operating systems, however since the Arduino has very little builtin SRAM, it is filledup quickly when using strings without thinking about memory management. |
59,219,485 | I have a full-width Bootstrap dropdown menu that is not working properly as it has a lot of space between the button and the menu.
So far I am only using CSS for this, no javascript. Here´s the code:
HTML:
```
<nav class="p-4 navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
<img src="http://lorempixel.com/30/30/abstract" width="30" height="30" class="d-inline-block align-top" alt="">
Shopstrap
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
<i class="fas fa-angle-up"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item dropdown catalog">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Catalog
<i class="fas fa-angle-up"></i>
</a>
<div class="dropdown-menu catalog-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</nav>
```
CSS:
```
.navbar-default .navbar-nav > li.dropdown:hover > a,
.navbar-default .navbar-nav > li.dropdown:hover > a:hover,
.navbar-default .navbar-nav > li.dropdown:hover > a:focus {
background-color: rgb(231, 231, 231);
color: rgb(85, 85, 85);
}
li.dropdown:hover > .dropdown-menu {
display: block;
}
.navbar .dropdown.catalog {
position: static;
float: none;
}
.navbar .dropdown .dropdown-menu.catalog-menu{
width: 100%;
}
```
Fiddle:
<https://jsfiddle.net/m4Lxugea/1/>
I hope any of you can help me with this. I was thinking in maybe I can´t do this purely CSS but I need to add javascript for the hovering.
Alejandro. | 2019/12/06 | [
"https://Stackoverflow.com/questions/59219485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6751870/"
] | One solution (works with your text input in your question, probably needs more input data to work-out quirks):
```
data = [
"get it as soon asdec. 5 - 9 when you choose expedited shipping at checkout.",
"get it as soon asdec. 10 - 13 when you choose standard shipping at checkout.",
"get it as soon as",
" order soon. get it as soon asnov. 21 - 26 when you choose standard shipping at checkout.",
"this item ships to canada. get it by thursday, nov. 21 - monday, dec. 2 choose this date at checkout.",
"want it friday, nov. 8?order within and choose two-day shipping at checkout.",
]
import re
for line in data:
m = re.findall(r'((?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\.)|(\d+)', line)
month_from, month_to, range_from, range_to = 'NULL', 'NULL', 'NULL', 'NULL'
if len(m) == 3:
month_from = m[0][0]
range_from = m[1][1]
range_to = m[2][1]
elif len(m) == 4:
month_from = m[0][0]
month_to = m[2][0]
range_from = m[1][1]
range_to = m[3][1]
elif len(m) == 2:
month_from = m[0][0]
range_from = m[1][1]
print('{:<10} {:<10} {:<10} {:<10}'.format(month_from, month_to, range_from, range_to))
```
Prints:
```
dec. NULL 5 9
dec. NULL 10 13
NULL NULL NULL NULL
nov. NULL 21 26
nov. dec. 21 2
nov. NULL 8 NULL
``` | You may use a pattern with a bit more precise patterns in between numbers and a couple of optional groups:
```
(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\W*(\d{1,2})(?:(?:.*?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec))?\W+(\d{1,2}))?
```
Or, add word boundaries to only match months as whole words:
```
\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\W*(\d{1,2})(?:(?:.*?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec))?\W+(\d{1,2}))?
```
See the [regex demo](https://regex101.com/r/aBGPmH/3)
**Details**
* `\b` - word boundary
* `(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)` - Group 1: abbreviated month names (when they are part of a longer pattern, it makes sense to make each alternative match at a different location in a string, thus, change it to `(j(?:an|u[nl])|feb|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec)`)
* `\W*` - 0 or more non-word chars
* `(\d{1,2})` - Group 2: one or two digits
* `(?:(?:.*?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec))?\W+(\d{1,2}))?` - an optional sequence of:
+ `(?:.*?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec))?` - an optional sequence of
- `.*?` - any 0+ chars other than line break chars as few as possible
- `(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)` - Group 3: abbreviated month names
+ `\W+` - 1 or more non-word chars
+ `(\d{1,2})` - Group 4: one or two digits
In Python, you may build the pattern dynamically to make it readable:
```
import re
months = r'(j(?:an|u[nl])|feb|ma[ry]|a(?:pr|ug)|sep|oct|nov|dec)'
pat = r'\b{0}\W*(\d{{1,2}})(?:(?:.*?{0})?\W+(\d{{1,2}}))?'.format(months)
re.findall(pat, text)
``` |
1,540,658 | I have been trying to solve this "Concurrent Programming" exam exercise (in C#):
>
> Knowing that `Stream` class contains `int Read(byte[] buffer, int offset, int size)` and `void Write(byte[] buffer, int offset, int size)` methods, implement in C# the `NetToFile` method that copies all data received from `NetworkStream net` instance to the `FileStream file` instance. To do the transfer, use asynchronous reads and synchronous writes, avoiding one thread to be blocked during read operations. The transfer ends when the `net` read operation returns value 0. To simplify, it is not necessary to support controlled cancel of the operation.
>
>
>
```
void NetToFile(NetworkStream net, FileStream file);
```
I've been trying to solve this exercise, but I'm struggling with a question related with the question itself. But first, here is my code:
```
public static void NetToFile(NetworkStream net, FileStream file) {
byte[] buffer = new byte[4096]; // buffer with 4 kB dimension
int offset = 0; // read/write offset
int nBytesRead = 0; // number of bytes read on each cycle
IAsyncResult ar;
do {
// read partial content of net (asynchronously)
ar = net.BeginRead(buffer,offset,buffer.Length,null,null);
// wait until read is completed
ar.AsyncWaitHandle.WaitOne();
// get number of bytes read on each cycle
nBytesRead = net.EndRead(ar);
// write partial content to file (synchronously)
fs.Write(buffer,offset,nBytesRead);
// update offset
offset += nBytesRead;
}
while( nBytesRead > 0);
}
```
The question I have is that, in the question statement, is said:
>
> To do the transfer, use asynchronous
> reads and synchronous writes, avoiding
> one thread to be blocked during read
> operations
>
>
>
I'm not really sure if my solution accomplishes what is wanted in this exercise, because I'm using `AsyncWaitHandle.WaitOne()` to wait until the asynchronous read completes.
On the other side, I'm not really figuring out what is meant to be a "non-blocking" solution in this scenario, as the `FileStream` write is meant to be made synchronously... and to do that, I have to wait until `NetworkStream` read completes to proceed with the `FileStream` writing, isn't it?
Can you, please, help me out with this?
---
[ EDIT 1 ] **Using *callback* solution**
Ok, if I understood what [Mitchel Sellers](https://stackoverflow.com/users/13279/mitchel-sellers) and [willvv](https://stackoverflow.com/users/84167/willvv) replied, I've been counseled to use a callback method to turn this into a "non-blocking" solution. Here is my code, then:
```
byte[] buffer; // buffer
public static void NetToFile(NetworkStream net, FileStream file) {
// buffer with same dimension as file stream data
buffer = new byte[file.Length];
//start asynchronous read
net.BeginRead(buffer,0,buffer.Length,OnEndRead,net);
}
//asynchronous callback
static void OnEndRead(IAsyncResult ar) {
//NetworkStream retrieve
NetworkStream net = (NetworkStream) ar.IAsyncState;
//get number of bytes read
int nBytesRead = net.EndRead(ar);
//write content to file
//... and now, how do I write to FileStream instance without
//having its reference??
//fs.Write(buffer,0,nBytesRead);
}
```
As you may have noticed, I'm stuck on the callback method, as I don't have a reference to the `FileStream` instance where I want to invoke the "Write(...)" method.
Additionally, this is not a thread-safe solution, as the `byte[]` field is exposed and may be shared among concurrent `NetToFile` invocations. I don't know how to solve this problem without exposing this `byte[]` field in the outer-scope... and I'm almost sure it may not be exposed this way.
I don't want to use a lambda or anonymous method solution, because that's not in the curriculum of "Concurrent Programing" course. | 2009/10/08 | [
"https://Stackoverflow.com/questions/1540658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76219/"
] | Even though it goes against the grain to help people with their homework, given that this is more than a year old, here's the proper way to accomplish this. All you need to **overlap** your read/write operations — no spawning of additional threads, or anything else is required.
```
public static class StreamExtensions
{
private const int DEFAULT_BUFFER_SIZE = short.MaxValue ; // +32767
public static void CopyTo( this Stream input , Stream output )
{
input.CopyTo( output , DEFAULT_BUFFER_SIZE ) ;
return ;
}
public static void CopyTo( this Stream input , Stream output , int bufferSize )
{
if ( !input.CanRead ) throw new InvalidOperationException( "input must be open for reading" );
if ( !output.CanWrite ) throw new InvalidOperationException( "output must be open for writing" );
byte[][] buf = { new byte[bufferSize] , new byte[bufferSize] } ;
int[] bufl = { 0 , 0 } ;
int bufno = 0 ;
IAsyncResult read = input.BeginRead( buf[bufno] , 0 , buf[bufno].Length , null , null ) ;
IAsyncResult write = null ;
while ( true )
{
// wait for the read operation to complete
read.AsyncWaitHandle.WaitOne() ;
bufl[bufno] = input.EndRead(read) ;
// if zero bytes read, the copy is complete
if ( bufl[bufno] == 0 )
{
break ;
}
// wait for the in-flight write operation, if one exists, to complete
// the only time one won't exist is after the very first read operation completes
if ( write != null )
{
write.AsyncWaitHandle.WaitOne() ;
output.EndWrite(write) ;
}
// start the new write operation
write = output.BeginWrite( buf[bufno] , 0 , bufl[bufno] , null , null ) ;
// toggle the current, in-use buffer
// and start the read operation on the new buffer.
//
// Changed to use XOR to toggle between 0 and 1.
// A little speedier than using a ternary expression.
bufno ^= 1 ; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.BeginRead( buf[bufno] , 0 , buf[bufno].Length , null , null ) ;
}
// wait for the final in-flight write operation, if one exists, to complete
// the only time one won't exist is if the input stream is empty.
if ( write != null )
{
write.AsyncWaitHandle.WaitOne() ;
output.EndWrite(write) ;
}
output.Flush() ;
// return to the caller ;
return ;
}
public static async Task CopyToAsync( this Stream input , Stream output )
{
await input.CopyToAsync( output , DEFAULT_BUFFER_SIZE ) ;
return;
}
public static async Task CopyToAsync( this Stream input , Stream output , int bufferSize )
{
if ( !input.CanRead ) throw new InvalidOperationException( "input must be open for reading" );
if ( !output.CanWrite ) throw new InvalidOperationException( "output must be open for writing" );
byte[][] buf = { new byte[bufferSize] , new byte[bufferSize] } ;
int[] bufl = { 0 , 0 } ;
int bufno = 0 ;
Task<int> read = input.ReadAsync( buf[bufno] , 0 , buf[bufno].Length ) ;
Task write = null ;
while ( true )
{
await read ;
bufl[bufno] = read.Result ;
// if zero bytes read, the copy is complete
if ( bufl[bufno] == 0 )
{
break;
}
// wait for the in-flight write operation, if one exists, to complete
// the only time one won't exist is after the very first read operation completes
if ( write != null )
{
await write ;
}
// start the new write operation
write = output.WriteAsync( buf[bufno] , 0 , bufl[bufno] ) ;
// toggle the current, in-use buffer
// and start the read operation on the new buffer.
//
// Changed to use XOR to toggle between 0 and 1.
// A little speedier than using a ternary expression.
bufno ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.ReadAsync( buf[bufno] , 0 , buf[bufno].Length );
}
// wait for the final in-flight write operation, if one exists, to complete
// the only time one won't exist is if the input stream is empty.
if ( write != null )
{
await write;
}
output.Flush();
// return to the caller ;
return;
}
}
```
Cheers. | It's strange that no one mentioned TPL.
[Here](http://blogs.msdn.com/b/pfxteam/archive/2009/06/30/9809774.aspx)'s very nice post by PFX team (Stephen Toub) about how to implement concurrent async stream copy. The post contains out-dated refenrece to samples so here's corrent one:
Get [Parallel Extensions Extras from code.msdn](http://code.msdn.microsoft.com/ParallelExtensionsExtras-2fdc7629) then
```
var task = sourceStream.CopyStreamToStreamAsync(destinationStream);
// do what you want with the task, for example wait when it finishes:
task.Wait();
```
Also consider using J.Richer's [AsyncEnumerator](http://msdn.microsoft.com/en-us/magazine/cc546608.aspx). |
44,989,393 | I have created dialog as component inside another component. Dialog opens without issue but after closing and trying reopen it id not visible.
Parent component
```js
import { Component,OnInit } from '@angular/core';
import { PostComponent } from './post/post.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
viewProviders: [PostComponent]
})
export class AppComponent implements OnInit {
display: boolean;
ngOnInit(): void {
}
openAdvancedSearch() {
this.display = true;
console.log("Display is set");
}
constructor() {
}
}
```
parent html
```html
<app-post [display]="display"></app-post>
<button type="button" class="btn btn-primary col"
(click)="openAdvancedSearch()" [style.width.px]="150">Advanced Search</button>
```
Dialog component
```js
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
@Input()
display: boolean = false;
publishedAfter: Date;
publishedBefore:Date;
constructor() { }
ngOnInit() {
}
}
```
Dialog html has a button clicking on which closes dialog
```html
<p-dialog header="Title" [(visible)]="display" [width]="500"
[contentStyle]="{'overflow':'visible'}">
<p-calendar [(ngModel)]="publishedAfter" [showIcon]="true"
[style.width.px]="150"></p-calendar>
<p-calendar [(ngModel)]="publishedBefore" [showIcon]="true"
[style.width.px]="150"></p-calendar>
<p-footer>
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<button (click)="display=false">Close</button>
</div>
</p-footer>
</p-dialog>
``` | 2017/07/08 | [
"https://Stackoverflow.com/questions/44989393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3063873/"
] | **Adding the code to solve the problem**
Child Component HTML
```
<p-dialog header="Reschedule Unassigned Task" [(visible)]="_display" modal="modal" width="700" [responsive]="true" [blockScroll]=true (onHide)="onHide($event)">
```
Child Component
```
@Input() get display(): string {
return this._display;
}
set display(value: string) {
console.log('set display ' + value)
this._display = value;
this.onDisplayChange.emit(this._display);
}
@Output() onDisplayChange: EventEmitter<string> = new EventEmitter<string>();
@Output() onClose: EventEmitter<string> = new EventEmitter<string>();
onHide(e: any) {
this.onClose.emit(this._display);
}
```
Parent Component calling child
```
<reschedule-dialog [(display)]="rescheduleDialogDisplay"
(onClose) = "onClose()"
[selectedItem]="selectedItemToReschedule
```
```
onClose() {
this.rescheduleDialogDisplay = null;
this.selectedItemToReschedule = null;
}
``` | I managed to solve this issue but there are some key points missed in all the answers.
When you click 'close' in the top right it runs close() in the child component.
It is here where you have to emit the change back to the parent:
```
export class child-comp implements OnInit {
@Input() showDialog: boolean;
@Output() closeDialog = new EventEmitter<any>();
close() {
console.log('calling on close');
this.closeDialog.emit();
}
}
```
Then in the parent component you need to receive this emit and have a function act on it which update the display state 'Only control the display state in the parent component' as previously suggested.
```
<child-comp [showDialog]="showDialog" (closeDialog)="updateDialog()"></child-comp>
updateDialog() {
this.showDialog = false;
console.log(this.showDialog);
}
```
Hope this is a help |
24,649,119 | I have a class with n data members as follows :
```
public class Input
{
int mode1 {get; set;}
int geom2 {get; set;}
int type3 {get; set;}
int spacing4 {get; set;}
int fluid5 {get; set;}
int spec6 {get; set;}
...
...
...
int data_n {get; set;}
}
```
and I have a filled list of n int items.
`List<int> dataList = new List<int>`
Now I want to fill an object of class Input from dataList through iteration or through any other direct method will be helpful. Thank you | 2014/07/09 | [
"https://Stackoverflow.com/questions/24649119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2149396/"
] | You could try something like this (*object initializer*):
```
Input input = new Input { mode1 = dataList[0],
geom2 = dataList[1],
type3 = dataList[2],
spacing4 = dataList[3],
fluid5 = dataList[4],
spec6 = dataList[5] };
``` | You can do this from reflection using `GetProperties` method as others said but why not use a simple way to do this?
```
Input i = new Input();
i.mode1 = dataList[0];
i.geom2 = dataList[1];
i.type3 = dataList[2];
i.spacing4 = dataList[3];
i.fluid5 = dataList[4];
i.spec6 = dataList[5];
``` |
9,833,009 | I'm looking for a javascript diff algorithm implementation or library, which has been tested on and works with arbitrary utf8 text files.
All of the ones I found so far (say for example, <http://ejohn.org/projects/javascript-diff-algorithm/>) fail on corner cases
(Try using a file which contains the string `'__proto__'` in my example library.) | 2012/03/23 | [
"https://Stackoverflow.com/questions/9833009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173773/"
] | I'm a fan of [google diff match patch](https://code.google.com/p/google-diff-match-patch/). You can try out an example [here](http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html).
There are different cleanup option to tweak the level of commonality between the diffs. I don't like the semantic cleanup option as I find it's too aggressive, but the efficiency cleanup with a value of 10 works well for me. | There is an diff algorithm implementation that I wrote with javascript in the following page.
<https://github.com/cubicdaiya/onp>
This runs with node.js. Forthermore there is a C++ addon version for node.js in following page.
<https://github.com/cubicdaiya/node-dtl>
You can install this with npm.
$ npm install -g dtl |
348,943 | I have a multipolygon containing a one large polygon, itself containing a number of smaller polygons, which constitute 'holes' in the largest polygon.
My goal is to simplify the multipolygon into one polygon that closely respects the existing perimeter but removes all the smaller polygons (holes)
I have been using a combination of `ST_ExteriorRing` and `ST_Dump` to get rid of the points and lines, however I can't make this work when there are multiple polygons.
The closest working solution I've found is to use `ST_ConcaveHull(geometry, 0.99)`, however this does not follow the perimeter of the shape closely enough (it smoothes over the recesses).
I've pasted the text representation of the multipolygon below
<https://gist.github.com/glennpjones/51acef849825470386f24a6c3259295d>
I'm using PostGIS 2.5.
How would you approach this? | 2020/01/29 | [
"https://gis.stackexchange.com/questions/348943",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/157261/"
] | According to the data provided
Try to go that way:
```
SELECT ST_MakePolygon(ST_ExteriorRing((ST_Dump(geom)).geom)) geom FROM data ORDER BY geom ASC LIMIT 2;
```
It's gotta work...
or
```
WITH
tbla AS (SELECT ST_MakePolygon(ST_ExteriorRing((ST_Dump(geom)).geom)) geom FROM data)
SELECT ST_Union(geom) geom FROM tbla;
```
If the system "swears" at the data, you can enhance it with the function ST\_MakeValid...
Success in knowing... | The "lines and points" in the geometry are actually very narrow/small holes. So it seems like you are looking to remove all the holes from a MultiPolygon. An approach for this is:
* "Explode" the MultiPolygon into separate Polygons using `ST_Dump`
* Remove the holes from each element Polygon using `ST_MakePolygon(ST_ExteriorRing(poly))`
* Combine the hole-free elements back using `ST_Collect`
A runnable SQL example showing this procedure:
```
WITH data AS (
SELECT 'MULTIPOLYGON (((90 240, 260 240, 260 100, 90 100, 90 240), (130 200, 200 200, 200 140, 130 140, 130 200)), ((290 240, 380 240, 380 170, 290 170, 290 240), (324 216, 360 216, 360 180, 324 180, 324 216)), ((310 140, 375 140, 375 91, 310 91, 310 140)))'::geometry AS geom
),
polys AS (
SELECT (ST_Dump( geom )).geom FROM data
),
polynoholes AS (
SELECT ST_Collect( ST_MakePolygon( ST_ExteriorRing( geom ))) FROM polys
)
SELECT * FROM polynoholes
``
``` |
20,512,141 | User.Identity can be accessed in a controller of course. But I don't want to have every controller have a copied method to grab user common attributes.
```
public class myClass
{
public void myMethod()
{ //assume user is authenticated for the purposes of this question
var currentUserId = User.Identity.GetUserId();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(currentUserId);
ViewBag.UserID = currentUser.Id;
ViewBag.favoriteColor = currentUser.favoriteColor;
}
}
```
What is a good way to do this so that it is accessible by all of my controllers? Where would I put it and how would I call it and what might I have to pass it to make it work, in a best practices sort of way? | 2013/12/11 | [
"https://Stackoverflow.com/questions/20512141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779772/"
] | You may want to use an absolute-positioned set of coloured divs within a relative-positioned container. See this:
<http://jsfiddle.net/aUsHh/13/>
CSS:
```
#slidercontainer {
display: block;
position: relative;
width: 100px;
height: 100px;
}
#slidercontainer div {
position: absolute;
display: block;
width: 100px;
height: 100px;
top: 0px;
left: 0px;
opacity: 0;
}
#blue {
background: blue;
}
#red {
background: red;
}
#green {
background: green;
}
}
```
JS:
```
var hash = "";
if(window.location.hash) {
if (hash != "")
$(hash).hide("slow");
hash = window.location.hash;
$(hash).show("slow");
}
$(window).on('hashchange', function() {
$(hash).animate({'opacity': 0, 'left': "200px"});
hash = window.location.hash;
$(hash).css("left","-100px");
$(hash).animate({'opacity': 1, 'left': "0px"});
});
``` | try js like this
```
if(window.location.hash) {
var hash = window.location.hash;
$('div').hide(1000);
$(hash).show(1000);
}
$(window).on('hashchange', function() {
var hash = window.location.hash;
$('div').hide(1000);
$(hash).show(1000);
});
```
you can use time in jquery hide and show functions. it is 1000=1 sec.
or
user a key word "slow" as default like this
```
$('div').hide('slow');
$(hash).show('slow');
``` |
43,709,004 | I'm working on app which shows the lyrics of song. And I have got an error: Method getText() must be called from the UI Thread. I was searching for answer, but no answer has helped solve the problem.
```
public class HomeActivity extends AppCompatActivity {
private EditText wykonawca;
private EditText tytul;
private Button pokazTekst;
private TextView tekst;
//String url = "http://www.tekstowo.pl/piosenka,";
String title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FindViews();
tekst.setMovementMethod(new ScrollingMovementMethod()); // mozliwosc scrolowania tekstu
pokazTekst.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SongText().execute();
}
});
}
public class SongText extends AsyncTask<Void, Void, Void>{
String url = "http://www.tekstowo.pl/piosenka,";
String author;
String song_name;
@Override
protected Void doInBackground(Void... params) {
try {
// here is error
author = wykonawca.getText().toString();
song_name = tytul.getText().toString();
url = url + author + "," + song_name + ".html";
Document doc = Jsoup.connect(url).get();
title = doc.select("div[class=song-text").text();
}
catch (IOException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
tekst.setText(title);
}
}
private void FindViews(){
// Edit text
wykonawca = (EditText) findViewById(R.id.wykonawca);
tytul = (EditText) findViewById(R.id.tytul);
// Buttons
pokazTekst = (Button) findViewById(R.id.pokazTekst);
// TextViews
tekst = (TextView) findViewById(R.id.tekst);
}
```
} | 2017/04/30 | [
"https://Stackoverflow.com/questions/43709004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7337397/"
] | In your parent constructor you need to bind the function properly.
This is what it could look like:
```
constructor(props) {
super(props);
this.updateState = this.updateState.bind(this);
this.state = { test: 0 };
}
``` | Corrected, working example based on answers above:
Parent:
```
export default class GameList extends Component {
constructor({ navigation }) {
super();
this.state = {
test: 0,
}
};
updateState() {
this.setState((prevState) => {
debugger;
return ({
test: prevState.test + 1,
});
});
}
render() {
return (
<View style={styles.background}>
<Header updateState={() => { this.updateState() }} />
</View >
)
}
}
```
Child:
```
class Header extends Component {
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Search..."
onChangeText={(text) => {
this.props.updateState();
}}
/>
</View>
);
}
}
export default Header;
``` |
38,883,921 | Every time I make a new Script in Unity, I always end up doing a bunch of checks for any components my script depends on, like:
```
SpriteRenderer sr = gameObject.GetComponent<SpriteRenderer>();
if(sr == null)
sr = gameObject.AddComponent<SpriteRenderer>() as SpriteRenderer;
```
So I decided to play around and make a generic method to do this with any Component, and I came up with the following code, which I simply added right to my own new Script.
```
T GetOrAddComponent<T>() where T : Component
{
T component = gameObject.GetComponent<T>();
if (component == null)
component = gameObject.AddComponent<T>() as T;
return component;
}
```
I've tried it and the function works well, but I'm wondering if there is any major downside to this approach, or if there is some other better way to complete the same task, possibly using a existing method I am unaware of or by creating the method in some other way. | 2016/08/10 | [
"https://Stackoverflow.com/questions/38883921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3476873/"
] | The GetComponent method is actually rather taxing on the system. If you are developing for mobile, too many of them can cause a noticeable lag in load times.
I personally use RequireComponent method. Then the script would automatically add the component the moment it's added to the GameObject. Then I would manually drag the name of the component to the field on the script object in the inspector.
Example:
```c#
using UnityEngine;
// PlayerScript requires the GameObject to have a RigidBody component
[RequireComponent (typeof (RigidBody))]
public class PlayerScript : MonoBehavior {
[SerializeField]
private RigidBody rb;
...
}
``` | In the new version of Unity (With C# 8.0 and above) you can simply do this in one line.
```
[SerializeField] private SpriteRenderer spriteRenderer;
public SpriteRenderer GetSpriteRenderer => spriteRenderer ??= GetComponent<SpriteRenderer>() ?? gameObject.AddComponent<SpriteRenderer>();
```
The code above does three things.
* Returns private local spriteRenderer component from the getter property if it's not null.
* If spriteRenderer is null, then it proceed to assign the value by calling GetComponent() before returning.
* If GetComponent() returns null, then the next operation will add sprite renderer component to the game object and assign to spriteRenderer before returning. |
57,766,662 | I am trying to retrieve images from Firebase Firestore. I am able to retrieve text in RecyclerView successfully however I'm not sure how to retrieve the images.
I had a look at similar questions unfortunately none helped.
**ListActivity :**
```
//initialize firestore
db = FirebaseFirestore.getInstance();
//initialize views
mRecyclerView = findViewById(R.id.resultRecycle);
//set recycler view properties
mRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
//show data in recycler view
showData();
}
private void showData() {
db.collection("Item")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
//called when data is retrieved
//show data
for(DocumentSnapshot doc: task.getResult()){
Model model = new
Model(doc.getString("id"),
doc.getString("Title"),
doc.getString("Location"),
//STUCK HERE
);
modelList.add(model);
}
//adapter
adapter = new CustomAdapter(ListActivity.this, modelList);
//set adapter to recycler view
mRecyclerView.setAdapter(adapter);
}
});
```
**CustomAdapter :**
```
public void onItemClick(View view, int position) {
//this will be called when user clicks an item
//show data on toast when clicking
String title = modelList.get(position).getTitle();
String location = modelList.get(position).getLocation();
String url = modelList.get(position).getUrl();
}
@Override
public void onItemLongClick(View view, int position) {
//this will be called when user clicks long item
}
});
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
//bind views /set data
holder.mTitle.setText(modelList.get(i).getTitle());
holder.mLocation.setText(modelList.get(i).getLocation());
Picasso.get().load(modelList.get(i).getUrl()).into(holder.mUrl);
}
```
Please see the image below link, thank you
[](https://i.stack.imgur.com/jD8va.png) | 2019/09/03 | [
"https://Stackoverflow.com/questions/57766662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827718/"
] | Here is the solution for this issue:
in my vue.config.js I made the following:
```
module.exports = {
chainWebpack: config => {
config.entry('theme') // you can add here as much themes as you want
.add('./src/theme.scss')
.end();
},
css: {
extract: {
filename: '[name].css', // to have a name related to a theme
chunkFilename: 'css/[name].css'
},
modules: false,
sourceMap: true
},
}
``` | I've typically not used file-loader in my CSS setup; instead I've always used a style-loader, css-loader with MiniCSSExtractPlugin:
<https://github.com/webpack-contrib/mini-css-extract-plugin#advanced-configuration-example>
Give that setup configuration for MiniCSSExtractPlugin a review.
MiniCSSExtractPlugin is a nice to have, so the most important thing to note is that you are missing the css-loader (which should be used instead of file-loader). |
49,101,461 | I would like to move my Player in "block" of 0.1 unity unit (or 1).
How to modify / configure Character controller to move with "fixed" step? | 2018/03/04 | [
"https://Stackoverflow.com/questions/49101461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/141579/"
] | Your reasoning is correct. There are 5 processes created from this code for a total of 6 processes including the original.
To verify, adding the following two lines after the above code:
```
printf("pid: %d, parent: %d\n", getpid(), getppid());
sleep(1);
```
Printed this on my machine (with comments added to match the pids with your tree:
```
pid: 2638, parent: 2498 // 1
pid: 2639, parent: 2638 // 2
pid: 2640, parent: 2638 // 4
pid: 2641, parent: 2639 // 3
pid: 2642, parent: 2639 // 5
pid: 2643, parent: 2641 // 6
``` | Yes it is correct. If you want to be sure print the pid (using getpid())for each parent-son and count the unique numbers printed. |
14,513,957 | so here is the code (I have tried many variations of this (with the div, without the div) and jquery itself is working, but not the dialog box) I can do an alert box, but if I put a dialog in, it never works. No popup, nothing. A basic dialog box does not work.
```
$('#link).click(function(){
$('#dialog).dialog();
}
<div id="dialog" title="Dialog Title" style="display:none"> Some text</div>
``` | 2013/01/25 | [
"https://Stackoverflow.com/questions/14513957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1839942/"
] | You missed a quote after the `#dialog` selector **and** the `#link` selector, try this:
```
$('#link').click(function(){
$('#dialog').dialog();
}
``` | Ok. So I figured out that in order to use the dialog box I had to include the jquery-ui declaration at the top of the page instead of just the jquery declaration.
```
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js" ></script>
``` |
984,419 | I just installed a gem but when I type
```
gem_name --help
```
It says:
```
'gem_name' is not recognized as an internal or external command
```
However, when I type
```
gem list --local
```
the gem shows up in the list so I know it's there - I just don't know how to see what it does.
Is there a different instruction to use to find out what commands this gem offers? | 2009/06/12 | [
"https://Stackoverflow.com/questions/984419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121636/"
] | Ruby gems can optionally install executable files. When you run `<gem_name> --help`, you're generally running the script, if any, installed by that gem, and passing it `--help` as a commandline parameter. By convention, most gems with executables support this parameter and output some useful information, but it's not a requirement - and, as mentioned, there are plenty of gems that don't install any executables at all.
In this case, it appears that the gem you installed doesn't provide any scripts (or, at the very least, doesn't provide any scripts with the same name as the gem). As others have suggested, looking at the rdoc for the gem might be a good way to start; you can use the `gem server` command to serve up all your local gems' rdoc content. Alternately, some gems host their rdoc at Rubyforge.
What is the gem in question? | Try this:
1- gem server
2- Point your browser to: <http://localhost:8808/> |
7,602,861 | Is there any way to clear the STDIN buffer in Perl? A part of my program has lengthy output (enough time for someone to enter a few characters) and after that output I ask for input, but if characters were entered during the output, they are "tacked on" to whatever is entered at the input part. Here is an example of my problem:
```
for(my $n = 0; $n < 70000; $n++){
print $n . "\n";
}
chomp(my $input = <STDIN>);
print $input . "\n";
```
The output would include any characters entered during the output from that for loop. How could I either disable STDIN or flush the STDIN buffer (or any other way to not allow extra characters to be inserted into STDIN before calling it)? | 2011/09/29 | [
"https://Stackoverflow.com/questions/7602861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689136/"
] | It looks like you can accomplish this with the [`Term::ReadKey`](http://search.cpan.org/perldoc?Term::ReadKey) module:
```
#!perl
use strict;
use warnings;
use 5.010;
use Term::ReadKey;
say "I'm starting to sleep...";
ReadMode 2;
sleep(10);
ReadMode 3;
my $key;
while( defined( $key = ReadKey(-1) ) ) {}
ReadMode 0;
say "Enter something:";
chomp( my $input = <STDIN> );
say "You entered '$input'";
```
Here's what happens:
* `ReadMode 2` means "put the input mode into regular mode but turn off echo". This means that any keyboard banging that the user does while you're in your computationally-expensive code won't get echoed to the screen. It still gets entered into `STDIN`'s buffer though, so...
* `ReadMode 3` turns `STDIN` into cbreak mode, meaning `STDIN` kind of gets flushed after every keypress. That's why...
* `while(defined($key = ReadKey(-1))) {}` happens. This is flushing out the characters that the user entered during the computationally-expensive code. Then...
* `ReadMode 0` resets `STDIN`, and you can read from `STDIN` as if the user hadn't banged on the keyboard.
When I run this code and bang on the keyboard during the `sleep(10)`, then enter some other text after the prompt, it only prints out the text I typed after the prompt appeared.
Strictly speaking the `ReadMode 2` isn't needed, but I put it there so the screen doesn't get cluttered up with text when the user bangs on the keyboard. | I had the same problem and solved it by just discarding anything in STDIN after the processing like this:
```
for(my $n = 0; $n < 70000; $n++){
print $n . "\n";
}
my $foo=<STDIN>;
print "would you like to continue [y/n]: ";
chomp(my $input = <STDIN>);
print $input . "\n";
``` |
27,546,971 | Lets say, I have a table, and I want to order by field with some string and size. When I use `ORDER BY size`, it gets something like this:
```
size 100
size 105
size 110
size 115
size 85
size 90
size 95
```
String can be different in each row, this is just example, when there is same string - `size`. I want to return this:
```
size 85
size 90
size 95
size 100
size 105
size 110
size 115
```
I know, that ordering by numeric string can be done with `ORDER BY CAST(size AS UNSIGNED)`, but how to do this, when its not numeric string, but the field is string with number? | 2014/12/18 | [
"https://Stackoverflow.com/questions/27546971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1631551/"
] | I simple way to do this is to use the length as a key:
```
order by length(size), size
```
Alternatively, use `substring_index()`:
```
order by substring_index(size, ' ', 1),
substring_index(size, ' ', -1) + 0
```
The `+ 0` does silent conversion to convert the second value to a number. | You are partially right. You could just fetch the number from your alpha numeric column
```
SELECT *
FROM MyTable
ORDER BY CAST(SUBSTRING(size, LOCATE(' ',size)+1) AS SIGNED)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.