tyson0420/stack_llama_fil_ai
Text Generation
•
Updated
•
73
qid
int64 1
74.7M
| question
stringlengths 25
64.6k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 3
61.5k
|
---|---|---|---|---|---|
52,903,968 | I'm building an app that needs to make HTTP requests to an API. I want to handle the network connection status , so when the network is not reachable it presents a popup dialog and when the network is reachable again the popup dismisses.
Currently I am able to do that , THE PROBLEM is that when the popup is dismissed because the network is reachable again I do not know how to (or where to) make the HTTP requests again.
I have build a singleton's class to handle reachability:
```
import Foundation
import PopupDialog
import Alamofire
class Reachability {
private var currentViewController : UIViewController? = nil
private var popup : PopupDialog? = nil
let title = "Network connection error".localized
let message = "It seems you have problems with connection, please check your internet connection.".localized
let settingsButton = DefaultButton(title: "Settings".localized, action: {
if let url = URL(string:"App-Prefs:root=Settings&path=General") {
UIApplication.shared.open(url)
}
})
//shared instance
static let shared = Reachability()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
}
extension Reachability{
/**
Starts network observer and manages to listen on different kind of network
changes. Popup warning dialogs will be presented based on different kind of network status
such as network is not reachable and once network resorts back online defined popup dialog will
be dismissed automatically.
**/
public func startNetworkReachabilityObserver() {
if let status = reachabilityManager?.isReachable, status == false {
if self.currentViewController != nil{
}
self.presentReachabilityPopup()
return
}
reachabilityManager?.listener = { status in
switch status {
case .notReachable:
if self.currentViewController != nil {
self.presentReachabilityPopup()
}
break
case .unknown :
break
case .reachable(.ethernetOrWiFi), .reachable(.wwan):
if self.popup != nil ,self.currentViewController != nil {
self.popup?.dismiss()
}
break
}
}
reachabilityManager?.startListening()
}
public func stopNetworkReachabilityObserver() {
reachabilityManager?.stopListening()
}
// Configure current view controller as a network observer
public func currentViewController(_ vc: UIViewController?) {
self.currentViewController = vc
self.startNetworkReachabilityObserver() // Start network observer
}
// Presents an alert dialog box notifying the users concerning the network issues
private func presentReachabilityPopup() {
self.popup = PopupDialog(title: title, message: message )
self.popup?.addButton(settingsButton)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.5) {
if self.currentViewController != nil{
self.currentViewController?.present(self.popup!, animated: true, completion: nil)
}
}
}
}
```
And here is an example of a ViewController that needs to make the HTTP request when the network is reachable again:
```
import UIKit
import GoogleMaps
class ExploreViewController: UIViewController, GMSMapViewDelegate{
//MARK: Properties
var posts:[Post] = []
var followers:[User] = []
var images = [UIImage]()
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Explore".localized
// Configure reachability observer on this controller
Reachability.shared.currentViewController(self)
if Location.shared.requestAuth(){
self.fetchPosts()
self.setUpCameraPosition()
}
}
```
The function fetchPosts() contains the HTTP requests I need to perform. | 2018/10/20 | [
"https://Stackoverflow.com/questions/52903968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10532311/"
] | You can set a flag when the https api network connection is started for the first time.
```
var networkFlag = true
```
In that case your program would know that you actually started a network call.
Next, when you are in between the request and internet connectivity is not reachable, it would give a popup.
Solution to trigger https call again:
In code, where you check if network Reachability is true, put an if condition, and check the flag you set earlier if network connection was made.
```
//check for network reachability
if(reachable)
{
//check the flag set earlier which indicates network call was made
if(networkFlag)
{
//make an https call--your network call
//https:call put your method call here
}
```
Hope this helps :) | Screenshots:
![enter image description here](https://i.stack.imgur.com/nsE5d.jpg)
Internet connection OK
Reopening app. Internet connection: WRONG ( Airplane mode )
![enter image description here](https://i.stack.imgur.com/X7H0K.png)
![enter image description here](https://i.stack.imgur.com/e164U.jpg)
Internet connection OK again but not fetching
![enter image description here](https://i.stack.imgur.com/mgKpn.png)
Here is what I have modified:
```
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Explore".localized
// Configure reachability observer on this controller
Reachability.shared.currentViewController(self)
if Location.shared.requestAuth(){
if (Reachability.shared.reachabilityManager?.isReachable)!{
if self.networkFlag{
self.fetchPosts()
self.setUpCameraPosition()
}
}else{
self.networkFlag = false
}
}
}
``` |
1,569,507 | On a couple of projects now, I've used the SVN keywords to retrieve some information about the version of some core files. Something like this (PHP):
```
$revision = '$Revision: 1254 $'; // automatically updated each commit
$revision = preg_replace("/[^0-9]/", "");
echo "This file is at revision #" . $revision;
```
It occurred to me however, by inspecting the `$URL$` keyword output, I could tell if the current file was in a tag, branch or on the trunk and apply different logic to the program, eg, increase the cache times, etc.
```
$svnURL = '$URL: path/to/repo/tags/1.0.1/folder/file.txt $';
if (strpos($svnURL, "/tags/") !== false) {
echo "Tagged version!";
}
```
Is this veering sharply into WTF territory, or would you consider this practice to be acceptable? | 2009/10/14 | [
"https://Stackoverflow.com/questions/1569507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | Mm, that's veering into WTF world as far as I'm concerned.
Better off configuring those things as environment variables in a general place in your application. | In my opinion, using the SVN keywords to affect program logic is a little bit obscure. I don't feel it qualifies as pathological, but it would surely require some explanatory comments.
Also, in your example, you simply echo what amounts to version information. I take it from what you wrote that you intend actually to decrease the cache time for your tagged version. As that aids debugging and is specific to your internal practices, I can see why you might want to do this. |
1,569,507 | On a couple of projects now, I've used the SVN keywords to retrieve some information about the version of some core files. Something like this (PHP):
```
$revision = '$Revision: 1254 $'; // automatically updated each commit
$revision = preg_replace("/[^0-9]/", "");
echo "This file is at revision #" . $revision;
```
It occurred to me however, by inspecting the `$URL$` keyword output, I could tell if the current file was in a tag, branch or on the trunk and apply different logic to the program, eg, increase the cache times, etc.
```
$svnURL = '$URL: path/to/repo/tags/1.0.1/folder/file.txt $';
if (strpos($svnURL, "/tags/") !== false) {
echo "Tagged version!";
}
```
Is this veering sharply into WTF territory, or would you consider this practice to be acceptable? | 2009/10/14 | [
"https://Stackoverflow.com/questions/1569507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | Mm, that's veering into WTF world as far as I'm concerned.
Better off configuring those things as environment variables in a general place in your application. | This is a really bad idea, IMO. If you need configuration management, do it using configuration files and conditionals. Don't depend on your source code control system for configuration management. |
1,569,507 | On a couple of projects now, I've used the SVN keywords to retrieve some information about the version of some core files. Something like this (PHP):
```
$revision = '$Revision: 1254 $'; // automatically updated each commit
$revision = preg_replace("/[^0-9]/", "");
echo "This file is at revision #" . $revision;
```
It occurred to me however, by inspecting the `$URL$` keyword output, I could tell if the current file was in a tag, branch or on the trunk and apply different logic to the program, eg, increase the cache times, etc.
```
$svnURL = '$URL: path/to/repo/tags/1.0.1/folder/file.txt $';
if (strpos($svnURL, "/tags/") !== false) {
echo "Tagged version!";
}
```
Is this veering sharply into WTF territory, or would you consider this practice to be acceptable? | 2009/10/14 | [
"https://Stackoverflow.com/questions/1569507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | Mm, that's veering into WTF world as far as I'm concerned.
Better off configuring those things as environment variables in a general place in your application. | Not a good idea. A much better way to achieve this would be to assign the version/build number as part of of a continuous integration or build process. This can be done in .Net by changing the AssemblyInfo.cs file before building. |
1,569,507 | On a couple of projects now, I've used the SVN keywords to retrieve some information about the version of some core files. Something like this (PHP):
```
$revision = '$Revision: 1254 $'; // automatically updated each commit
$revision = preg_replace("/[^0-9]/", "");
echo "This file is at revision #" . $revision;
```
It occurred to me however, by inspecting the `$URL$` keyword output, I could tell if the current file was in a tag, branch or on the trunk and apply different logic to the program, eg, increase the cache times, etc.
```
$svnURL = '$URL: path/to/repo/tags/1.0.1/folder/file.txt $';
if (strpos($svnURL, "/tags/") !== false) {
echo "Tagged version!";
}
```
Is this veering sharply into WTF territory, or would you consider this practice to be acceptable? | 2009/10/14 | [
"https://Stackoverflow.com/questions/1569507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | Mm, that's veering into WTF world as far as I'm concerned.
Better off configuring those things as environment variables in a general place in your application. | I would consider this unacceptable, because you may at some point in the future migrate to a different source control system, whereupon this house of cards would come crashing down. It would come crashing down in a way that was (a) hard to detect, and (b) hard to fix. |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | You can add those to the setup script:
```
[Files]
Source: "vcredist_x86.exe"; DestDir: {tmp}; Flags: deleteafterinstall
[Run]
Filename: {tmp}\vcredist_x86.exe; \
Parameters: "/q /passive /Q:a /c:""msiexec /q /i vcredist.msi"""; \
StatusMsg: "Installing VC++ 2008 Redistributables..."
```
Note that the run parameters will change slightly, if you are using a different redistributable version from 2008. | I modified the above code as follows. Then I got it worked properly and the entire installation was pretty smooth and silent.
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/q /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;
```
Reference Links:
* <http://www.computerhope.com/cmd.htm>
* <https://web.archive.org/web/20150925001652/http://blogs.msdn.com/b/astebner/archive/2014/03/08/10078468.aspx> |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | I modified the above code as follows. Then I got it worked properly and the entire installation was pretty smooth and silent.
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/q /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;
```
Reference Links:
* <http://www.computerhope.com/cmd.htm>
* <https://web.archive.org/web/20150925001652/http://blogs.msdn.com/b/astebner/archive/2014/03/08/10078468.aspx> | Here is my solution:
```
Filename: "{tmp}\vc_redist.x86.exe"; Parameters: "/q /norestart"; \
Check: VCRedistNeedsInstall; StatusMsg: "Installing VC++ redistributables..."
``` |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | For a smooth install, check if it's necessary to install the redistributable. If the installed version is already up to date (quite likely), don't even unpack it.
```
[Files]
; VC++ redistributable runtime. Extracted by VC2017RedistNeedsInstall(), if needed.
Source: ".\Redist\VC_redist_2017.x64.exe"; DestDir: {tmp}; Flags: dontcopy
[Run]
Filename: "{tmp}\VC_redist_2017.x64.exe"; StatusMsg: "{cm:InstallingVC2017redist}"; \
Parameters: "/quiet"; Check: VC2017RedistNeedsInstall ; Flags: waituntilterminated
```
```pascal
[Code]
function VC2017RedistNeedsInstall: Boolean;
var
Version: String;
begin
if RegQueryStringValue(HKEY_LOCAL_MACHINE,
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', 'Version', Version) then
begin
// Is the installed version at least 14.14 ?
Log('VC Redist Version check : found ' + Version);
Result := (CompareStr(Version, 'v14.14.26429.03')<0);
end
else
begin
// Not even an old version installed
Result := True;
end;
if (Result) then
begin
ExtractTemporaryFile('VC_redist_2017.x64.exe');
end;
end;
```
Note that the 14.14 redistributable is also suitable for VS2015. | I modified the above code as follows. Then I got it worked properly and the entire installation was pretty smooth and silent.
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/q /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;
```
Reference Links:
* <http://www.computerhope.com/cmd.htm>
* <https://web.archive.org/web/20150925001652/http://blogs.msdn.com/b/astebner/archive/2014/03/08/10078468.aspx> |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | You can add those to the setup script:
```
[Files]
Source: "vcredist_x86.exe"; DestDir: {tmp}; Flags: deleteafterinstall
[Run]
Filename: {tmp}\vcredist_x86.exe; \
Parameters: "/q /passive /Q:a /c:""msiexec /q /i vcredist.msi"""; \
StatusMsg: "Installing VC++ 2008 Redistributables..."
```
Note that the run parameters will change slightly, if you are using a different redistributable version from 2008. | Here is my solution:
```
Filename: "{tmp}\vc_redist.x86.exe"; Parameters: "/q /norestart"; \
Check: VCRedistNeedsInstall; StatusMsg: "Installing VC++ redistributables..."
``` |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | For a smooth install, check if it's necessary to install the redistributable. If the installed version is already up to date (quite likely), don't even unpack it.
```
[Files]
; VC++ redistributable runtime. Extracted by VC2017RedistNeedsInstall(), if needed.
Source: ".\Redist\VC_redist_2017.x64.exe"; DestDir: {tmp}; Flags: dontcopy
[Run]
Filename: "{tmp}\VC_redist_2017.x64.exe"; StatusMsg: "{cm:InstallingVC2017redist}"; \
Parameters: "/quiet"; Check: VC2017RedistNeedsInstall ; Flags: waituntilterminated
```
```pascal
[Code]
function VC2017RedistNeedsInstall: Boolean;
var
Version: String;
begin
if RegQueryStringValue(HKEY_LOCAL_MACHINE,
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', 'Version', Version) then
begin
// Is the installed version at least 14.14 ?
Log('VC Redist Version check : found ' + Version);
Result := (CompareStr(Version, 'v14.14.26429.03')<0);
end
else
begin
// Not even an old version installed
Result := True;
end;
if (Result) then
begin
ExtractTemporaryFile('VC_redist_2017.x64.exe');
end;
end;
```
Note that the 14.14 redistributable is also suitable for VS2015. | You can add those to the setup script:
```
[Files]
Source: "vcredist_x86.exe"; DestDir: {tmp}; Flags: deleteafterinstall
[Run]
Filename: {tmp}\vcredist_x86.exe; \
Parameters: "/q /passive /Q:a /c:""msiexec /q /i vcredist.msi"""; \
StatusMsg: "Installing VC++ 2008 Redistributables..."
```
Note that the run parameters will change slightly, if you are using a different redistributable version from 2008. |
24,574,035 | How to install Microsoft VC++ redistributables silently in Inno Setup? I used the following code, most of the installation part is silent except the installation progress window.
Here is my `[Run]` section's code:-
```
[Run]
Filename: "{app}\bin\vcredist_x86.exe"; \
Parameters: "/passive /verysilent /norestart /q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; \
Check: VCRedistNeedsInstall; WorkingDir: {app}\bin;Flags: runminimized nowait; \
StatusMsg: Installing CRT...
``` | 2014/07/04 | [
"https://Stackoverflow.com/questions/24574035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355059/"
] | For a smooth install, check if it's necessary to install the redistributable. If the installed version is already up to date (quite likely), don't even unpack it.
```
[Files]
; VC++ redistributable runtime. Extracted by VC2017RedistNeedsInstall(), if needed.
Source: ".\Redist\VC_redist_2017.x64.exe"; DestDir: {tmp}; Flags: dontcopy
[Run]
Filename: "{tmp}\VC_redist_2017.x64.exe"; StatusMsg: "{cm:InstallingVC2017redist}"; \
Parameters: "/quiet"; Check: VC2017RedistNeedsInstall ; Flags: waituntilterminated
```
```pascal
[Code]
function VC2017RedistNeedsInstall: Boolean;
var
Version: String;
begin
if RegQueryStringValue(HKEY_LOCAL_MACHINE,
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', 'Version', Version) then
begin
// Is the installed version at least 14.14 ?
Log('VC Redist Version check : found ' + Version);
Result := (CompareStr(Version, 'v14.14.26429.03')<0);
end
else
begin
// Not even an old version installed
Result := True;
end;
if (Result) then
begin
ExtractTemporaryFile('VC_redist_2017.x64.exe');
end;
end;
```
Note that the 14.14 redistributable is also suitable for VS2015. | Here is my solution:
```
Filename: "{tmp}\vc_redist.x86.exe"; Parameters: "/q /norestart"; \
Check: VCRedistNeedsInstall; StatusMsg: "Installing VC++ redistributables..."
``` |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | Go into the menu on your external monitor. If there's an option that allows one device to toggle the power on the other via HDMI, make sure this is deselected (honestly, I don't think this will have an effect as your laptop is doing the driving, but for the sake of troubleshooting...).
I too use an MBP Retina with external monitor (via HDMI). If I shut off the external monitor while it has application windows in its desktop, the screen on my laptop refreshes and said windows are moved to my laptop's display. However, if I power the external monitor back on, these application windows "automagically" move back to where they were (same location and size) on the external' Desktop (as long as I haven't shut down the computer in the meantime). So, it seems one solution (if you're hard set against also using your laptop' display) is to leave the laptop open, but decrease the brightness of the screen to 0. I do this all the time when watching a movie on the big screen, and, truly, the laptop' profile is no less "bulky" than it would be if it was closed. An additional benefit to this method is that the laptop stays cooler (than it otherwise would by closing it). You can verify this with any free temperature-monitoring app.
If the above does not work or is otherwise intolerable, I would guess that a solution could be programmed, though I'm not sure where one would start with this. | I don't know if you can prevent it, but I use an app called [Stay](https://cordlessdog.com/stay/) by Cordless Dog ($15, free trial), which keeps windows in place between display configuration changes. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | Go into the menu on your external monitor. If there's an option that allows one device to toggle the power on the other via HDMI, make sure this is deselected (honestly, I don't think this will have an effect as your laptop is doing the driving, but for the sake of troubleshooting...).
I too use an MBP Retina with external monitor (via HDMI). If I shut off the external monitor while it has application windows in its desktop, the screen on my laptop refreshes and said windows are moved to my laptop's display. However, if I power the external monitor back on, these application windows "automagically" move back to where they were (same location and size) on the external' Desktop (as long as I haven't shut down the computer in the meantime). So, it seems one solution (if you're hard set against also using your laptop' display) is to leave the laptop open, but decrease the brightness of the screen to 0. I do this all the time when watching a movie on the big screen, and, truly, the laptop' profile is no less "bulky" than it would be if it was closed. An additional benefit to this method is that the laptop stays cooler (than it otherwise would by closing it). You can verify this with any free temperature-monitoring app.
If the above does not work or is otherwise intolerable, I would guess that a solution could be programmed, though I'm not sure where one would start with this. | The brightness issue was a bug which was fixed in 10.15.4; the resizing and placement issue of windows is an HDMI problem and how the Mac sees it.
If you have a DisplayPort, use that connection. It solved all the problems! |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | Go into the menu on your external monitor. If there's an option that allows one device to toggle the power on the other via HDMI, make sure this is deselected (honestly, I don't think this will have an effect as your laptop is doing the driving, but for the sake of troubleshooting...).
I too use an MBP Retina with external monitor (via HDMI). If I shut off the external monitor while it has application windows in its desktop, the screen on my laptop refreshes and said windows are moved to my laptop's display. However, if I power the external monitor back on, these application windows "automagically" move back to where they were (same location and size) on the external' Desktop (as long as I haven't shut down the computer in the meantime). So, it seems one solution (if you're hard set against also using your laptop' display) is to leave the laptop open, but decrease the brightness of the screen to 0. I do this all the time when watching a movie on the big screen, and, truly, the laptop' profile is no less "bulky" than it would be if it was closed. An additional benefit to this method is that the laptop stays cooler (than it otherwise would by closing it). You can verify this with any free temperature-monitoring app.
If the above does not work or is otherwise intolerable, I would guess that a solution could be programmed, though I'm not sure where one would start with this. | On recent versions of macOS set a user password to wake from sleep. The machine will then wake to a login screen and by the time you have entered the password, the external display will have been recognised and should then restore all the original window positions correctly. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | Go into the menu on your external monitor. If there's an option that allows one device to toggle the power on the other via HDMI, make sure this is deselected (honestly, I don't think this will have an effect as your laptop is doing the driving, but for the sake of troubleshooting...).
I too use an MBP Retina with external monitor (via HDMI). If I shut off the external monitor while it has application windows in its desktop, the screen on my laptop refreshes and said windows are moved to my laptop's display. However, if I power the external monitor back on, these application windows "automagically" move back to where they were (same location and size) on the external' Desktop (as long as I haven't shut down the computer in the meantime). So, it seems one solution (if you're hard set against also using your laptop' display) is to leave the laptop open, but decrease the brightness of the screen to 0. I do this all the time when watching a movie on the big screen, and, truly, the laptop' profile is no less "bulky" than it would be if it was closed. An additional benefit to this method is that the laptop stays cooler (than it otherwise would by closing it). You can verify this with any free temperature-monitoring app.
If the above does not work or is otherwise intolerable, I would guess that a solution could be programmed, though I'm not sure where one would start with this. | I had this problem for a while and tried lots of apps to fix it. Finally found a solution which was to use a HDMI to USB-C cable instead of HDMI-HDMI. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | I don't know if you can prevent it, but I use an app called [Stay](https://cordlessdog.com/stay/) by Cordless Dog ($15, free trial), which keeps windows in place between display configuration changes. | The brightness issue was a bug which was fixed in 10.15.4; the resizing and placement issue of windows is an HDMI problem and how the Mac sees it.
If you have a DisplayPort, use that connection. It solved all the problems! |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | I don't know if you can prevent it, but I use an app called [Stay](https://cordlessdog.com/stay/) by Cordless Dog ($15, free trial), which keeps windows in place between display configuration changes. | On recent versions of macOS set a user password to wake from sleep. The machine will then wake to a login screen and by the time you have entered the password, the external display will have been recognised and should then restore all the original window positions correctly. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | I don't know if you can prevent it, but I use an app called [Stay](https://cordlessdog.com/stay/) by Cordless Dog ($15, free trial), which keeps windows in place between display configuration changes. | I had this problem for a while and tried lots of apps to fix it. Finally found a solution which was to use a HDMI to USB-C cable instead of HDMI-HDMI. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | The brightness issue was a bug which was fixed in 10.15.4; the resizing and placement issue of windows is an HDMI problem and how the Mac sees it.
If you have a DisplayPort, use that connection. It solved all the problems! | I had this problem for a while and tried lots of apps to fix it. Finally found a solution which was to use a HDMI to USB-C cable instead of HDMI-HDMI. |
179,928 | I have my Retina Macbook Pro connected to a ASUS 2560x1440 display via the HDMI port. I keep the laptop lid closed so the monitor is the only display in use.
When I sleep my computer (via hot corners if it matters) and wake it back up, all the windows are resized and in the upper left hand corner. My assumption is that it is resizing and repositioning them for the built in display. Is there a way to prevent this from happening so I don't have to resize and move all my windows when I use the computer again? | 2015/04/07 | [
"https://apple.stackexchange.com/questions/179928",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/103560/"
] | On recent versions of macOS set a user password to wake from sleep. The machine will then wake to a login screen and by the time you have entered the password, the external display will have been recognised and should then restore all the original window positions correctly. | I had this problem for a while and tried lots of apps to fix it. Finally found a solution which was to use a HDMI to USB-C cable instead of HDMI-HDMI. |
10,441,077 | The company I'm working at is considering using RestKit. However, the JSON that our server returns is surrounded characters for security reasons. It's a pain. In another iPhone app, one that does not use RestKit and uses JSON only very little, I parse the string returned from the server, removing the characters preceding and trailing the JSON string. Once the the string is parsed, I call JSONValue on the string (we're using SBJSON) and get an NSDictionary.
I've heard that RestKit features a pluggable architecture. If that's the case is there somewhere I can intercept the strings coming back from the server prior to the point where RestKit does its parsing? | 2012/05/04 | [
"https://Stackoverflow.com/questions/10441077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258089/"
] | I wanted to find a fix that did not require me to change the RestKit codebase in any way and I found it. The answer was to create and register my own parser.
Parsers need to conform to the RKParser protocol. Basically what I needed to do was trim the server response and not parse the response into objects - there was already a parser that did that: RKJSONParserJSONKit. So I subclassed this class and registered my parser at start up:
```
[[RKParserRegistry sharedRegistry] setParserClass:[MyJSONParser class]
forMIMEType:@"application/json"];
``` | Just wanted to note that nowadays you can implement your own retrieve/map operation by subclassing the
* `RKHTTPRequestOperation` [(doc)](http://restkit.org/api/0.20.3/Classes/RKHTTPRequestOperation.html) — for retrieving file from server
* `RKObjectRequestOperation` [(doc)](http://restkit.org/api/0.20.3/Classes/RKObjectRequestOperation.html) — for mapping
* `RKManagedObjectRequestOperation` [(doc)](http://restkit.org/api/0.20.3/Classes/RKManagedObjectRequestOperation.html) — for mapping to core data objects
and registering them with `[RKObjectManager registerRequestOperationClass:]` [(doc)](http://restkit.org/api/0.20.3/Classes/RKObjectManager.html#//api/name/registerRequestOperationClass:) method. |
28,859,289 | I have two models: Sites and Regions. A Region has many Sites.
```
class Site(models.Model):
name = models.CharField(max_length=200, unique=True)
class Region(models.Model):
name = models.CharField(max_length=200, unique=True)
sites = models.ManyToManyField('Site')
```
i would like to loop through the queryset so as to get a dict (which will eventually become JSON) that looks like this:
```
regions = [
{
id: 1,
name: "Region 1",
sites: [
{
id: 1,
name: "Site 1"
},
{
id: 2,
name: "Site 2"
}
]
},{
id: 2,
name: "Region 2",
sites: [
{
id: 3,
name: "Site 3"
},
{
id: 4,
name: "Site 4"
}
]
},
]
```
The thing is, I would like to do it in one line. I feel like I'm on the right track with `{Region.name : {int(Site.id) : Site.name for Site in Region.sites.all()} for Region in Region.objects.all()}` but I'm having trouble nesting the loops. I feel like it should be something like the below, but this is not working:
```
{ 'id' : Region.id, 'name': Region.name, 'children' : { 'id': int(Site.id), 'name' : Site.name} for Site in Site.objects.all()} for Region in Region.objects.all()}
``` | 2015/03/04 | [
"https://Stackoverflow.com/questions/28859289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722798/"
] | Assign the result of `df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)` to a variable so you can perform boolean indexing and then use the index from this to call `isin` and filter your orig df:
```
In [366]:
users = df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)
users
Out[366]:
User_ID
189757330 False
222583401 False
287280509 False
329757763 False
414673119 True
624921653 False
Name: Datetime, dtype: bool
In [367]:
users[users]
Out[367]:
User_ID
414673119 True
Name: Datetime, dtype: bool
In [368]:
users[users].index
Out[368]:
Int64Index([414673119], dtype='int64')
In [361]:
df[df['User_ID'].isin(users[users].index)]
Out[361]:
User_ID Latitude Longitude Datetime
5 414673119 41.555014 2.096583 2014-02-24 20:15:30
6 414673119 41.555014 2.097583 2014-02-24 20:16:30
7 414673119 41.555014 2.098583 2014-02-24 20:17:30
```
You can then call `to_csv` on the above as normal | first, make sure you have no duplicate entries:
```
df = df.drop_duplicates()
```
then, figure out the counts for each:
```
counts = df.groupby('User_ID').Datetime.count()
```
finally, figure out where the indexes overlap:
```
df[df.User_ID.isin(counts[counts > 1].index)]
``` |
28,299,144 | I have been trying out Three.js lately and i used the exporter addon for Blender to test out making models in blender and exporting so i can use them in a three.js program.
I included the add-on to blender, and using just the basic cube model of blender, exported it to .json as the exporter says. Then i imported the model into my three.js using this as a [guide](http://blog.romanliutikov.com/post/58690562825/external-models-in-three-js)
but that gave me an error:
```
Uncaught TypeError: Cannot read property 'length' of undefined.
```
Ive already searched online and tried a few different approaches(like including a materials in the function call of the loader) but nothing seems to work.
I also checked stackoverflow for answers but so far nothing seems solved. If anyone would clarify what im doing wrong I would be very grateful.
The code for my `three.js` program:
```
var WIDTH = 1000,
HEIGHT = 1000;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var radius = 50,
segments = 16,
rings = 16;
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCCCCCC
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
var pointLight =
new THREE.PointLight(0x660000);
var $container = $('#container');
var renderer = new THREE.WebGLRenderer();
var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
var loader = new THREE.JSONLoader(); // init the loader util
scene.add(camera);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loader.load('test.json', function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var object = new THREE.Mesh(geometry, material);
scene.add(object);
});
(function animloop() {
requestAnimFrame(animloop);
renderer.render(scene, camera);
})();
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283490/"
] | In my experience so far with the exporter, you have to be very careful which boxes you tick!
This length error is usually because you are either not exporting the vertexes, or exporting the scene rather the object. | I have the same issue with the new exporter.
If select SCENE then I usually get "Cannot read property 'length' of undefined"
If I select only the object and the materials and vertices. It usually just seems to get stuck forever.
UPDATE
Check this response to this issue!
[Threejs blender exporter exports in wrong format](https://stackoverflow.com/questions/28078556/threejs-blender-exporter-exports-in-wrong-format) |
28,299,144 | I have been trying out Three.js lately and i used the exporter addon for Blender to test out making models in blender and exporting so i can use them in a three.js program.
I included the add-on to blender, and using just the basic cube model of blender, exported it to .json as the exporter says. Then i imported the model into my three.js using this as a [guide](http://blog.romanliutikov.com/post/58690562825/external-models-in-three-js)
but that gave me an error:
```
Uncaught TypeError: Cannot read property 'length' of undefined.
```
Ive already searched online and tried a few different approaches(like including a materials in the function call of the loader) but nothing seems to work.
I also checked stackoverflow for answers but so far nothing seems solved. If anyone would clarify what im doing wrong I would be very grateful.
The code for my `three.js` program:
```
var WIDTH = 1000,
HEIGHT = 1000;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var radius = 50,
segments = 16,
rings = 16;
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCCCCCC
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
var pointLight =
new THREE.PointLight(0x660000);
var $container = $('#container');
var renderer = new THREE.WebGLRenderer();
var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
var loader = new THREE.JSONLoader(); // init the loader util
scene.add(camera);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loader.load('test.json', function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var object = new THREE.Mesh(geometry, material);
scene.add(object);
});
(function animloop() {
requestAnimFrame(animloop);
renderer.render(scene, camera);
})();
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283490/"
] | In my experience so far with the exporter, you have to be very careful which boxes you tick!
This length error is usually because you are either not exporting the vertexes, or exporting the scene rather the object. | As roadkill stated earlier, exporting as Geometry instead of BufferedGeometry works.
Also note that loading JSON model loading is handled asyncronously (the callback is only called only when the operation is completed, the rest of your code keeps running). The model won't exist for the first frame or two, so check that your model exists before doing any operations with it inside the animation loop. |
28,299,144 | I have been trying out Three.js lately and i used the exporter addon for Blender to test out making models in blender and exporting so i can use them in a three.js program.
I included the add-on to blender, and using just the basic cube model of blender, exported it to .json as the exporter says. Then i imported the model into my three.js using this as a [guide](http://blog.romanliutikov.com/post/58690562825/external-models-in-three-js)
but that gave me an error:
```
Uncaught TypeError: Cannot read property 'length' of undefined.
```
Ive already searched online and tried a few different approaches(like including a materials in the function call of the loader) but nothing seems to work.
I also checked stackoverflow for answers but so far nothing seems solved. If anyone would clarify what im doing wrong I would be very grateful.
The code for my `three.js` program:
```
var WIDTH = 1000,
HEIGHT = 1000;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var radius = 50,
segments = 16,
rings = 16;
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCCCCCC
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
var pointLight =
new THREE.PointLight(0x660000);
var $container = $('#container');
var renderer = new THREE.WebGLRenderer();
var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
var loader = new THREE.JSONLoader(); // init the loader util
scene.add(camera);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loader.load('test.json', function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var object = new THREE.Mesh(geometry, material);
scene.add(object);
});
(function animloop() {
requestAnimFrame(animloop);
renderer.render(scene, camera);
})();
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283490/"
] | When you export, change the Type from buffergeometry to Geometry (Blender 2.76) | I have the same issue with the new exporter.
If select SCENE then I usually get "Cannot read property 'length' of undefined"
If I select only the object and the materials and vertices. It usually just seems to get stuck forever.
UPDATE
Check this response to this issue!
[Threejs blender exporter exports in wrong format](https://stackoverflow.com/questions/28078556/threejs-blender-exporter-exports-in-wrong-format) |
28,299,144 | I have been trying out Three.js lately and i used the exporter addon for Blender to test out making models in blender and exporting so i can use them in a three.js program.
I included the add-on to blender, and using just the basic cube model of blender, exported it to .json as the exporter says. Then i imported the model into my three.js using this as a [guide](http://blog.romanliutikov.com/post/58690562825/external-models-in-three-js)
but that gave me an error:
```
Uncaught TypeError: Cannot read property 'length' of undefined.
```
Ive already searched online and tried a few different approaches(like including a materials in the function call of the loader) but nothing seems to work.
I also checked stackoverflow for answers but so far nothing seems solved. If anyone would clarify what im doing wrong I would be very grateful.
The code for my `three.js` program:
```
var WIDTH = 1000,
HEIGHT = 1000;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var radius = 50,
segments = 16,
rings = 16;
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCCCCCC
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
var pointLight =
new THREE.PointLight(0x660000);
var $container = $('#container');
var renderer = new THREE.WebGLRenderer();
var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
var loader = new THREE.JSONLoader(); // init the loader util
scene.add(camera);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loader.load('test.json', function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var object = new THREE.Mesh(geometry, material);
scene.add(object);
});
(function animloop() {
requestAnimFrame(animloop);
renderer.render(scene, camera);
})();
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283490/"
] | When you export, change the Type from buffergeometry to Geometry (Blender 2.76) | As roadkill stated earlier, exporting as Geometry instead of BufferedGeometry works.
Also note that loading JSON model loading is handled asyncronously (the callback is only called only when the operation is completed, the rest of your code keeps running). The model won't exist for the first frame or two, so check that your model exists before doing any operations with it inside the animation loop. |
62,008,063 | ```py
Code object
Area_name object
Inner/_Outer_London object
NEET object
Score object
Noparents object
Familyoffwork float64
TeensPragnancy object
dtype: object
```
* I tried several ways of converting from object data type to numeric, but continue to get error.
```py
school_df2['foreign'] = school_df2.foreign.astype(float)
Output: AttributeError: 'NoneType' object has no attribute 'foreign'
df1['foreign'] = school_df2['foreign'].str.astype(float)
Output: TypeError: 'NoneType' object is not subscriptable
school_df2=pd.to_numeric(school_df2['foreign'], errors='coerce')
Output: TypeError: 'NoneType' object is not subscriptable
school_df2['foreign'] = pd.to_numeric(school_df2['foreign'],errors='coerce')
Output: TypeError: 'NoneType' object is not subscriptable
import numpy as np
np.array(['foreign','NEET','Score', 'Noparents', 'Familyoffwork','TeensPragnancy' ]).astype(np.float)
Output: ValueError: could not convert string to float: 'foreign'
```
* The beginning of my code is the following:
```
!wget -q -O 'london_data.csv' https://data.london.gov.uk/download/london-borough-profiles/c1693b82-68b1-44ee-beb2-3decf17dc1f8/london-borough-profiles.csv
print('Data downloaded!')
london_df = pd.read_csv('london_data.csv', encoding= 'unicode_escape')
london_df.head()
ldf=london_df.drop(['Turnout_at_2014_local_elections','Male_life_expectancy,_(2012-14)', 'Female_life_expectancy,_(2012-14)', 'Proportion_of_seats_won_by_Lib_Dems_in_2014_election', 'Proportion_of_seats_won_by_Labour_in_2014_election', 'Proportion_of_seats_won_by_Conservatives_in_2014_election', 'Political_control_in_council', 'Mortality_rate_from_causes_considered_preventable_2012/14', 'People_aged_17+_with_diabetes_(%)', 'Childhood_Obesity_Prevalance_(%)_2015/16', 'Ambulance_incidents_per_hundred_population_(2014)'], axis = 1)
ldf.head()
school_df = ldf [['Code', 'Area_name', 'Inner/_Outer_London','Proportion_of_16-18_year_olds_who_are_NEET_(%)_(2014)', 'Achievement_of_5_or_more_A*-_C_grades_at_GCSE_or_equivalent_including_English_and_Maths,_2013/14', 'Rates_of_Children_Looked_After_(2016)', '%_children_living_in_out-of-work_households_(2015)', 'Teenage_conception_rate_(2014)']]
school_df
school_df = school_df.rename(columns={'Proportion_of_16-18_year_olds_who_are_NEET_(%)_(2014)': 'NEET', 'Achievement_of_5_or_more_A*-_C_grades_at_GCSE_or_equivalent_including_English_and_Maths,_2013/14': 'Score','Rates_of_Children_Looked_After_(2016)': 'Noparents', '%_children_living_in_out-of-work_households_(2015)': 'Familyoffwork', 'Teenage_conception_rate_(2014)': 'TeensPragnancy'})
school_df
school_df1=school_df.drop(school_df.tail(5).index,inplace=True)
school_df1
school_df2=school_df.drop(school_df.head(1).index,inplace=True)
school_df2
school_df2.corr()
```
```
Familyoffwork
Familyoffwork 1.0
```
Can someone tell me why am I getting this error? | 2020/05/25 | [
"https://Stackoverflow.com/questions/62008063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13615020/"
] | I think I understand what you're trying to do. The following isnt very pretty code but it works. I grab all the permutations, and then check for sorted uniqueness against elements in a growing list to which I append new unique permutations:
```
from itertools import permutations
n = ['n1','n2','n3','n4','n5','n6']
# This will hold the collection of unique groupings
unique_groups = [[], [], []]
for x in permutations(n):
# divide into groups, and sort to be able to compare against unique_groups
sorted_groups = [sorted(x[0:2]), sorted(x[2:4]), sorted(x[4:6])]
u1, u2, u3 = unique_groups
s1, s2, s3 = sorted_groups
# check that all three groups are unique, and append if so
if (s1 not in u1) and (s2 not in u2) and (s3 not in u3):
u1.append(s1)
u2.append(s2)
u3.append(s3)
# Helper function to flatten the 3x3 output lists into 9x1 :
def flatten(l):
return [item for sublist in l for item in sublist]
result = [flatten(l) for l in zip(*(unique_groups))]
print(result)
``` | Reshape your arrays,
Sort them by pairs,
Convert to DataFrame,
and remove duplicates.
Assuming lol is your list of lists:
```
res=[]
for l in lol:
new_l = np.sort(np.reshape(l,(-1,2))).reshape(1,-1)[0]
res.append(new_l)
df=pd.DataFrame(res)
res = df.drop_duplicates().values.tolist()
```
example:
```
lol = [['n1','n2','n3','n4','n5','n6'],
['n2','n1','n3','n4','n5','n6'],
['n1','n3','n2','n4','n5','n6']]
res = [['n1', 'n2', 'n3', 'n4', 'n5', 'n6'],
['n1', 'n3', 'n2', 'n4', 'n5', 'n6']]
``` |
40,872,677 | I try to do the side menu that slides out from the left side.
I use a few guides, but my menu does not come out, but is immediately visible on the home screen.
The guides, when the side menu was at the center of the screen instead of the left side just added this line:
```
android:layout_gravity="start"
```
but in my application it does not work ...
My `activity_maps.xml`
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
tools:context="ru.marks.mygps1.MapsActivity"
android:layout_weight="1"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp">
<Button
android:text="but1"
android:id="@+id/B1"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</LinearLayout>
```
My `navigation_menu.xml`
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/button1"
android:title="Button 1" />
<item android:id="@+id/button2"
android:title="Button 2" />
<item android:id="@+id/button3"
android:title="Button 3" />
</menu>
```
I can not fix it, help.
```
edit:
```
[before adding the side menu](https://i.stack.imgur.com/5NRnr.png)
[after](https://i.stack.imgur.com/N8qIW.png)
I would like to make this menu was coming out of the left side
Code with my side:
```
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
``` | 2016/11/29 | [
"https://Stackoverflow.com/questions/40872677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7213272/"
] | It seems this is a duplicate of [THIS](https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row) issue. I believe the answer there will help you solve your problem. HINT: newline='' | I didn't dig into your code in much detail, but on first glance it looks like if you want to remove the extra line between each row of data, remove the newline character '\n' from the end of the reorder\_receipt.write() function call.
In other words, modify:
`reorder_receipt.write(GTIN+' '+product+ ... +str(re_stock)+'\n')`
to be:
`reorder_receipt.write(GTIN+' '+product+ ... +str(re_stock))` |
40,872,677 | I try to do the side menu that slides out from the left side.
I use a few guides, but my menu does not come out, but is immediately visible on the home screen.
The guides, when the side menu was at the center of the screen instead of the left side just added this line:
```
android:layout_gravity="start"
```
but in my application it does not work ...
My `activity_maps.xml`
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
tools:context="ru.marks.mygps1.MapsActivity"
android:layout_weight="1"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp">
<Button
android:text="but1"
android:id="@+id/B1"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</LinearLayout>
```
My `navigation_menu.xml`
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/button1"
android:title="Button 1" />
<item android:id="@+id/button2"
android:title="Button 2" />
<item android:id="@+id/button3"
android:title="Button 3" />
</menu>
```
I can not fix it, help.
```
edit:
```
[before adding the side menu](https://i.stack.imgur.com/5NRnr.png)
[after](https://i.stack.imgur.com/N8qIW.png)
I would like to make this menu was coming out of the left side
Code with my side:
```
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
``` | 2016/11/29 | [
"https://Stackoverflow.com/questions/40872677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7213272/"
] | It seems this is a duplicate of [THIS](https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row) issue. I believe the answer there will help you solve your problem. HINT: newline='' | I guess the problem is with the `target=row[4]`.
May be "target" string is getting an extra \n. So stripping it might solve the problem.
`target.strip()` |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | In addition to Cristian's answer:
```
function is_valid_google_ip($ip) {
$hostname = gethostbyaddr($ip); //"crawl-66-249-66-1.googlebot.com"
return preg_match('/\.googlebot|google\.com$/i', $hostname);
}
function is_valid_google_request($ip=null,$agent=null){
if(is_null($ip)){
$ip=$_SERVER['REMOTE_ADDR'];
}
if(is_null($agent)){
$agent=$_SERVER['HTTP_USER_AGENT'];
}
$is_valid_request=false;
if (strpos($agent, 'Google')!==false && is_valid_google_ip($ip)){
$is_valid_request=true;
}
return $is_valid_request;
}
```
**Note**
Sometimes when using `$_SERVER['HTTP_X_FORWARDED_FOR']` OR `$_SERVER['REMOTE_ADDR']` more than 1 IP address is returned, for example '155.240.132.261, 196.250.25.120'. When this string is passed as an argument for `gethostbyaddr()` PHP gives the following error:
>
> Warning: Address is not a valid IPv4 or IPv6 address in...
>
>
>
To work around this I use the following code to extract the first IP address from the string and discard the rest. (If you wish to use the other IPs they will be in the other elements of the $ips array).
```
if (strstr($remoteIP, ', ')) {
$ips = explode(', ', $remoteIP);
$remoteIP = $ips[0];
}
```
<https://www.php.net/manual/en/function.gethostbyaddr.php> | ```
//The function
function is_google() {
return strpos($_SERVER['HTTP_USER_AGENT'],"Googlebot");
}
``` |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | The recommended way by Google is to do a reverse dns lookup (gethostbyaddr) in order to get the associated host name AND then resolve that name to an IP (gethostbyname) and compare it to the remote\_addr (because reverse lookups can be faked, too).
But beware, end lokups take time and can severely slow down your webpage (maybe check for user agent first).
Google also publishes a machine readable file containing the IP addresses of their crawlers, see the link below.
See:
* <https://developers.google.com/search/docs/advanced/crawling/verifying-googlebot>
* <https://webmasters.googleblog.com/2006/09/how-to-verify-googlebot.html> | ```
//The function
function is_google() {
return strpos($_SERVER['HTTP_USER_AGENT'],"Googlebot");
}
``` |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | ```php
function detectSearchBot($ip, $agent, &$hostname)
{
$hostname = $ip;
// check HTTP_USER_AGENT what not to touch gethostbyaddr in vain
if (preg_match('/(?:google|yandex)bot/iu', $agent)) {
// success - return host, fail - return ip or false
$hostname = gethostbyaddr($ip);
// https://support.google.com/webmasters/answer/80553
if ($hostname !== false && $hostname != $ip) {
// detect google and yandex search bots
if (preg_match('/\.((?:google(?:bot)?|yandex)\.(?:com|ru))$/iu', $hostname)) {
// success - return ip, fail - return hostname
$ip = gethostbyname($hostname);
if ($ip != $hostname) {
return true;
}
}
}
}
return false;
}
```
In my project, I use this function to identify Google and Yandex search bots.
The result of the detectSearchBot function is caching.
The algorithm is based on Google’s recommendation - <https://support.google.com/webmasters/answer/80553> | ```
//The function
function is_google() {
return strpos($_SERVER['HTTP_USER_AGENT'],"Googlebot");
}
``` |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | In addition to Cristian's answer:
```
function is_valid_google_ip($ip) {
$hostname = gethostbyaddr($ip); //"crawl-66-249-66-1.googlebot.com"
return preg_match('/\.googlebot|google\.com$/i', $hostname);
}
function is_valid_google_request($ip=null,$agent=null){
if(is_null($ip)){
$ip=$_SERVER['REMOTE_ADDR'];
}
if(is_null($agent)){
$agent=$_SERVER['HTTP_USER_AGENT'];
}
$is_valid_request=false;
if (strpos($agent, 'Google')!==false && is_valid_google_ip($ip)){
$is_valid_request=true;
}
return $is_valid_request;
}
```
**Note**
Sometimes when using `$_SERVER['HTTP_X_FORWARDED_FOR']` OR `$_SERVER['REMOTE_ADDR']` more than 1 IP address is returned, for example '155.240.132.261, 196.250.25.120'. When this string is passed as an argument for `gethostbyaddr()` PHP gives the following error:
>
> Warning: Address is not a valid IPv4 or IPv6 address in...
>
>
>
To work around this I use the following code to extract the first IP address from the string and discard the rest. (If you wish to use the other IPs they will be in the other elements of the $ips array).
```
if (strstr($remoteIP, ', ')) {
$ips = explode(', ', $remoteIP);
$remoteIP = $ips[0];
}
```
<https://www.php.net/manual/en/function.gethostbyaddr.php> | [How to verify Googlebot](http://googlewebmastercentral.blogspot.com/2006/09/how-to-verify-googlebot.html). |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | The recommended way by Google is to do a reverse dns lookup (gethostbyaddr) in order to get the associated host name AND then resolve that name to an IP (gethostbyname) and compare it to the remote\_addr (because reverse lookups can be faked, too).
But beware, end lokups take time and can severely slow down your webpage (maybe check for user agent first).
Google also publishes a machine readable file containing the IP addresses of their crawlers, see the link below.
See:
* <https://developers.google.com/search/docs/advanced/crawling/verifying-googlebot>
* <https://webmasters.googleblog.com/2006/09/how-to-verify-googlebot.html> | [How to verify Googlebot](http://googlewebmastercentral.blogspot.com/2006/09/how-to-verify-googlebot.html). |
3,077,862 | I'm going to block all bots except the big search engines. One of my blocking methods will be to check for "language": Accept-Language: If it has no Accept-Language the bot's IP address will be blocked until 2037. Googlebot does not have Accept-Language, I want to verify it with DNS lookup
```
<?php
gethostbyaddr($_SERVER['REMOTE_ADDR']);
?>
```
Is it ok to use `gethostbyaddr`, can someone pass my "gethostbyaddr protection"? | 2010/06/20 | [
"https://Stackoverflow.com/questions/3077862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233286/"
] | ```php
function detectSearchBot($ip, $agent, &$hostname)
{
$hostname = $ip;
// check HTTP_USER_AGENT what not to touch gethostbyaddr in vain
if (preg_match('/(?:google|yandex)bot/iu', $agent)) {
// success - return host, fail - return ip or false
$hostname = gethostbyaddr($ip);
// https://support.google.com/webmasters/answer/80553
if ($hostname !== false && $hostname != $ip) {
// detect google and yandex search bots
if (preg_match('/\.((?:google(?:bot)?|yandex)\.(?:com|ru))$/iu', $hostname)) {
// success - return ip, fail - return hostname
$ip = gethostbyname($hostname);
if ($ip != $hostname) {
return true;
}
}
}
}
return false;
}
```
In my project, I use this function to identify Google and Yandex search bots.
The result of the detectSearchBot function is caching.
The algorithm is based on Google’s recommendation - <https://support.google.com/webmasters/answer/80553> | [How to verify Googlebot](http://googlewebmastercentral.blogspot.com/2006/09/how-to-verify-googlebot.html). |
23,747,958 | I'm trying to learn symfony PHP framework but unlike Ruby on Rails it is not really intuitive.
I'm rendering a form with newAction that looks like this
```
public function newAction()
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
```
it renders very simple form:
```
<form action="{{ path("AcmeStoreBundle_default_create") }}" method="post" {{ form_enctype(form) }} class="blogger">
{{ form_errors(form) }}
{{ form_row(form.price) }}
{{ form_row(form.name) }}
{{ form_row(form.description) }}
{{ form_rest(form) }}
<input type="submit" value="Submit" />
```
That points to the 'create' action:
```
public function createAction()
{
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect("/show/{$product->getId()}");
}
```
Right now this action only saves the same static values, but i would like it to access data from the form above. My question is very easy (i hope). How can i save this previously sent informations ie how can i get POST parameters inside createAction? | 2014/05/19 | [
"https://Stackoverflow.com/questions/23747958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902570/"
] | No need for two actions, you can add this in the same action newAction
```
public function newAction()
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
$em = $this->getDoctrine()->getManager();
$request = $this->getRequest();
if($request->getMethod() == 'POST'){
$form->bindRequest($request);/*or $form->handleRequest($request); depends on symfony version */
if ($form->isValid()) {
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('some_route'),array(params));
}
}
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
``` | If I correctly understood you:
```
// ...
use Symfony\Component\HttpFoundation\Request;
// ...
public function createAction(Request $request)
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect("/show/{$product->getId()}");
}
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
```
And here is the [link](http://symfony.com/doc/current/book/forms.html#handling-form-submissions) to doc page.
If you need directly get some request parameter you can use `$request->request->get('your_parameter_name');` for `POST` and `$request->query->get('your_parameter_name');` for `GET`.
Also you can get your form data like: `$form->get('your_parameter_name')->getData();`.
By the way, as mentioned above, you don't need two actions. |
23,747,958 | I'm trying to learn symfony PHP framework but unlike Ruby on Rails it is not really intuitive.
I'm rendering a form with newAction that looks like this
```
public function newAction()
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
```
it renders very simple form:
```
<form action="{{ path("AcmeStoreBundle_default_create") }}" method="post" {{ form_enctype(form) }} class="blogger">
{{ form_errors(form) }}
{{ form_row(form.price) }}
{{ form_row(form.name) }}
{{ form_row(form.description) }}
{{ form_rest(form) }}
<input type="submit" value="Submit" />
```
That points to the 'create' action:
```
public function createAction()
{
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect("/show/{$product->getId()}");
}
```
Right now this action only saves the same static values, but i would like it to access data from the form above. My question is very easy (i hope). How can i save this previously sent informations ie how can i get POST parameters inside createAction? | 2014/05/19 | [
"https://Stackoverflow.com/questions/23747958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902570/"
] | No need for two actions, you can add this in the same action newAction
```
public function newAction()
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
$em = $this->getDoctrine()->getManager();
$request = $this->getRequest();
if($request->getMethod() == 'POST'){
$form->bindRequest($request);/*or $form->handleRequest($request); depends on symfony version */
if ($form->isValid()) {
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('some_route'),array(params));
}
}
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
``` | Something that can help you :
<http://www.leaseweblabs.com/2013/04/symfony2-crud-generator/>
Very useful short videos that explain how to use CRUD generator command lines. And then if you use CRUD generator which is in Symfony2 by default, you will have your action newAction self created and you'll be able to read code generated (best practice code with your symfony version) and try to understand it. |
23,747,958 | I'm trying to learn symfony PHP framework but unlike Ruby on Rails it is not really intuitive.
I'm rendering a form with newAction that looks like this
```
public function newAction()
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
```
it renders very simple form:
```
<form action="{{ path("AcmeStoreBundle_default_create") }}" method="post" {{ form_enctype(form) }} class="blogger">
{{ form_errors(form) }}
{{ form_row(form.price) }}
{{ form_row(form.name) }}
{{ form_row(form.description) }}
{{ form_rest(form) }}
<input type="submit" value="Submit" />
```
That points to the 'create' action:
```
public function createAction()
{
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect("/show/{$product->getId()}");
}
```
Right now this action only saves the same static values, but i would like it to access data from the form above. My question is very easy (i hope). How can i save this previously sent informations ie how can i get POST parameters inside createAction? | 2014/05/19 | [
"https://Stackoverflow.com/questions/23747958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902570/"
] | Something that can help you :
<http://www.leaseweblabs.com/2013/04/symfony2-crud-generator/>
Very useful short videos that explain how to use CRUD generator command lines. And then if you use CRUD generator which is in Symfony2 by default, you will have your action newAction self created and you'll be able to read code generated (best practice code with your symfony version) and try to understand it. | If I correctly understood you:
```
// ...
use Symfony\Component\HttpFoundation\Request;
// ...
public function createAction(Request $request)
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect("/show/{$product->getId()}");
}
return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
'form' => $form->createView()
));
}
```
And here is the [link](http://symfony.com/doc/current/book/forms.html#handling-form-submissions) to doc page.
If you need directly get some request parameter you can use `$request->request->get('your_parameter_name');` for `POST` and `$request->query->get('your_parameter_name');` for `GET`.
Also you can get your form data like: `$form->get('your_parameter_name')->getData();`.
By the way, as mentioned above, you don't need two actions. |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | USB 3.0 often has blue lining inside the port.
If you want to know specifically for your macbook air, go to apple support page <http://support.apple.com/specs/> - Click on "Browse by Product" and enter your Macbook Air serial number. It will show you the Tech Spec specifically for your Macbook Air series, and the tech spec will tell you what USB you have. | You were looking in the right place, it does tell you there. Take a look at the highlighted part in my screenshot below.
![enter image description here](https://i.stack.imgur.com/qEtPk.png)
A USB Hi-Speed bus is USB 2.0, A USB 'SuperSpeed' or USB '3.0 Hi-Speed' bus are both USB3. |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | USB 3.0 often has blue lining inside the port.
If you want to know specifically for your macbook air, go to apple support page <http://support.apple.com/specs/> - Click on "Browse by Product" and enter your Macbook Air serial number. It will show you the Tech Spec specifically for your Macbook Air series, and the tech spec will tell you what USB you have. | Tap the black apple, then choose "About this Mac, followed by Support, then Specifications. Lots of info there, including number and type of USB port |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | USB 3.0 often has blue lining inside the port.
If you want to know specifically for your macbook air, go to apple support page <http://support.apple.com/specs/> - Click on "Browse by Product" and enter your Macbook Air serial number. It will show you the Tech Spec specifically for your Macbook Air series, and the tech spec will tell you what USB you have. | (just updating an old question)
To cover all Mac's and the technology in general, USB 3.0 adds 5 pins and unique interfaces. Where the shape hasn't changed (like with type "A", the flat plain rectangle), just look for the extra 5 pads or contacts.
This should produce a positive ID across computers more reliably than manufacturer labeling, color preferences, or document accuracy.
[This page](http://www.moddiy.com/pages/USB-2.0-%7B47%7D-3.0-Connectors-%26-Pinouts.html) has a nice set of comparison images. There are also a few singles down the right side of the [Wikipedia USB 3.0 article](https://en.wikipedia.org/wiki/USB_3.0). |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | USB 3.0 often has blue lining inside the port.
If you want to know specifically for your macbook air, go to apple support page <http://support.apple.com/specs/> - Click on "Browse by Product" and enter your Macbook Air serial number. It will show you the Tech Spec specifically for your Macbook Air series, and the tech spec will tell you what USB you have. | Another approach, there are 3 things that confirm that you have only USB2:
1. USB High-Speed Bus
2. Driver: EHCI
3. Speed: 480Mb/s
>
>
> ```
> USB 1.0 Low Speed (1.5 Mbit/s), Full Speed (12 Mbit/s)
> USB 2.0 High Speed (480 Mbit/s)
> USB 3.0 SuperSpeed (5 Gbit/s)
> USB 3.1 SuperSpeed+ (10 Gbit/s)
>
> ```
>
>
**Reference:** <https://en.wikipedia.org/wiki/USB>
>
> ### Open Host Controller Interface
>
>
> The OHCI standard for USB is similar to the **OHCI** standard for
> FireWire, but supports USB 1.1 (full and low speeds) only.
>
>
> ### Universal Host Controller Interface
>
>
> Universal Host Controller Interface (**UHCI**) is a proprietary
> interface created by Intel for USB 1.x (full and low speeds).
>
>
> ### Enhanced Host Controller Interface
>
>
> Enhanced Host Controller Interface (**EHCI**-SPECIFICATION) is a
> high-speed controller standard applicable to USB 2.0.
>
>
> ### Extensible Host Controller Interface
>
>
> Extensible Host Controller Interface (**XHCI**) is the newest host
> controller standard that improves speed, power efficiency and
> virtualization over its predecessors The goal was also to define a USB
> host controller to replace UHCI/OHCI/EHCI. It supports all USB device
> speeds (USB 3.1 SuperSpeed+, USB 3.0 SuperSpeed, USB 2.0 Low-, Full-,
> and High-speed, USB 1.1 Low- and Full-speed).
>
>
>
**Reference:** <https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire)> |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | You were looking in the right place, it does tell you there. Take a look at the highlighted part in my screenshot below.
![enter image description here](https://i.stack.imgur.com/qEtPk.png)
A USB Hi-Speed bus is USB 2.0, A USB 'SuperSpeed' or USB '3.0 Hi-Speed' bus are both USB3. | Tap the black apple, then choose "About this Mac, followed by Support, then Specifications. Lots of info there, including number and type of USB port |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | You were looking in the right place, it does tell you there. Take a look at the highlighted part in my screenshot below.
![enter image description here](https://i.stack.imgur.com/qEtPk.png)
A USB Hi-Speed bus is USB 2.0, A USB 'SuperSpeed' or USB '3.0 Hi-Speed' bus are both USB3. | (just updating an old question)
To cover all Mac's and the technology in general, USB 3.0 adds 5 pins and unique interfaces. Where the shape hasn't changed (like with type "A", the flat plain rectangle), just look for the extra 5 pads or contacts.
This should produce a positive ID across computers more reliably than manufacturer labeling, color preferences, or document accuracy.
[This page](http://www.moddiy.com/pages/USB-2.0-%7B47%7D-3.0-Connectors-%26-Pinouts.html) has a nice set of comparison images. There are also a few singles down the right side of the [Wikipedia USB 3.0 article](https://en.wikipedia.org/wiki/USB_3.0). |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | You were looking in the right place, it does tell you there. Take a look at the highlighted part in my screenshot below.
![enter image description here](https://i.stack.imgur.com/qEtPk.png)
A USB Hi-Speed bus is USB 2.0, A USB 'SuperSpeed' or USB '3.0 Hi-Speed' bus are both USB3. | Another approach, there are 3 things that confirm that you have only USB2:
1. USB High-Speed Bus
2. Driver: EHCI
3. Speed: 480Mb/s
>
>
> ```
> USB 1.0 Low Speed (1.5 Mbit/s), Full Speed (12 Mbit/s)
> USB 2.0 High Speed (480 Mbit/s)
> USB 3.0 SuperSpeed (5 Gbit/s)
> USB 3.1 SuperSpeed+ (10 Gbit/s)
>
> ```
>
>
**Reference:** <https://en.wikipedia.org/wiki/USB>
>
> ### Open Host Controller Interface
>
>
> The OHCI standard for USB is similar to the **OHCI** standard for
> FireWire, but supports USB 1.1 (full and low speeds) only.
>
>
> ### Universal Host Controller Interface
>
>
> Universal Host Controller Interface (**UHCI**) is a proprietary
> interface created by Intel for USB 1.x (full and low speeds).
>
>
> ### Enhanced Host Controller Interface
>
>
> Enhanced Host Controller Interface (**EHCI**-SPECIFICATION) is a
> high-speed controller standard applicable to USB 2.0.
>
>
> ### Extensible Host Controller Interface
>
>
> Extensible Host Controller Interface (**XHCI**) is the newest host
> controller standard that improves speed, power efficiency and
> virtualization over its predecessors The goal was also to define a USB
> host controller to replace UHCI/OHCI/EHCI. It supports all USB device
> speeds (USB 3.1 SuperSpeed+, USB 3.0 SuperSpeed, USB 2.0 Low-, Full-,
> and High-speed, USB 1.1 Low- and Full-speed).
>
>
>
**Reference:** <https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire)> |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | Tap the black apple, then choose "About this Mac, followed by Support, then Specifications. Lots of info there, including number and type of USB port | Another approach, there are 3 things that confirm that you have only USB2:
1. USB High-Speed Bus
2. Driver: EHCI
3. Speed: 480Mb/s
>
>
> ```
> USB 1.0 Low Speed (1.5 Mbit/s), Full Speed (12 Mbit/s)
> USB 2.0 High Speed (480 Mbit/s)
> USB 3.0 SuperSpeed (5 Gbit/s)
> USB 3.1 SuperSpeed+ (10 Gbit/s)
>
> ```
>
>
**Reference:** <https://en.wikipedia.org/wiki/USB>
>
> ### Open Host Controller Interface
>
>
> The OHCI standard for USB is similar to the **OHCI** standard for
> FireWire, but supports USB 1.1 (full and low speeds) only.
>
>
> ### Universal Host Controller Interface
>
>
> Universal Host Controller Interface (**UHCI**) is a proprietary
> interface created by Intel for USB 1.x (full and low speeds).
>
>
> ### Enhanced Host Controller Interface
>
>
> Enhanced Host Controller Interface (**EHCI**-SPECIFICATION) is a
> high-speed controller standard applicable to USB 2.0.
>
>
> ### Extensible Host Controller Interface
>
>
> Extensible Host Controller Interface (**XHCI**) is the newest host
> controller standard that improves speed, power efficiency and
> virtualization over its predecessors The goal was also to define a USB
> host controller to replace UHCI/OHCI/EHCI. It supports all USB device
> speeds (USB 3.1 SuperSpeed+, USB 3.0 SuperSpeed, USB 2.0 Low-, Full-,
> and High-speed, USB 1.1 Low- and Full-speed).
>
>
>
**Reference:** <https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire)> |
652,700 | How do I tell if my MacBook Air supports USB 3.0. I found
**About This Mac** → **More Info...** → **System Report...** → **Hardware** → **USB**
But nothing there clearly states version 2.0 or 3.0. How can I know for sure? In particular, I want to know if I can use an external hard drive that requires a "USB 3.0-ready laptop".
![enter image description here](https://i.stack.imgur.com/6s7ya.png) | 2013/10/01 | [
"https://superuser.com/questions/652700",
"https://superuser.com",
"https://superuser.com/users/207377/"
] | (just updating an old question)
To cover all Mac's and the technology in general, USB 3.0 adds 5 pins and unique interfaces. Where the shape hasn't changed (like with type "A", the flat plain rectangle), just look for the extra 5 pads or contacts.
This should produce a positive ID across computers more reliably than manufacturer labeling, color preferences, or document accuracy.
[This page](http://www.moddiy.com/pages/USB-2.0-%7B47%7D-3.0-Connectors-%26-Pinouts.html) has a nice set of comparison images. There are also a few singles down the right side of the [Wikipedia USB 3.0 article](https://en.wikipedia.org/wiki/USB_3.0). | Another approach, there are 3 things that confirm that you have only USB2:
1. USB High-Speed Bus
2. Driver: EHCI
3. Speed: 480Mb/s
>
>
> ```
> USB 1.0 Low Speed (1.5 Mbit/s), Full Speed (12 Mbit/s)
> USB 2.0 High Speed (480 Mbit/s)
> USB 3.0 SuperSpeed (5 Gbit/s)
> USB 3.1 SuperSpeed+ (10 Gbit/s)
>
> ```
>
>
**Reference:** <https://en.wikipedia.org/wiki/USB>
>
> ### Open Host Controller Interface
>
>
> The OHCI standard for USB is similar to the **OHCI** standard for
> FireWire, but supports USB 1.1 (full and low speeds) only.
>
>
> ### Universal Host Controller Interface
>
>
> Universal Host Controller Interface (**UHCI**) is a proprietary
> interface created by Intel for USB 1.x (full and low speeds).
>
>
> ### Enhanced Host Controller Interface
>
>
> Enhanced Host Controller Interface (**EHCI**-SPECIFICATION) is a
> high-speed controller standard applicable to USB 2.0.
>
>
> ### Extensible Host Controller Interface
>
>
> Extensible Host Controller Interface (**XHCI**) is the newest host
> controller standard that improves speed, power efficiency and
> virtualization over its predecessors The goal was also to define a USB
> host controller to replace UHCI/OHCI/EHCI. It supports all USB device
> speeds (USB 3.1 SuperSpeed+, USB 3.0 SuperSpeed, USB 2.0 Low-, Full-,
> and High-speed, USB 1.1 Low- and Full-speed).
>
>
>
**Reference:** <https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire)> |
36,951,231 | The Architecture of my software is,
WPF (Windows desktop application on users' computers) - WCF web role(Windows Communication Foundation) on Azure Cloud Service (Here, the connectionstring to Azure SQL database exists)- Azure SQL Server(Azure SQL database).
According to my knowledge, new feature like 'database.secure.windows.net' can be included recently in connectionstring to Azure SQL database..
So, I've changed the connectionstring of my application as included the 'secure' in connectionstring as above and through this I can access to Azure SQL database successfully without any problem as before.
If we configure our connectionstring with 'secure.windows.net', is there no need to worry about connectionstring to be exposured?
If still, I need to encrypt my connectionstring to Azure SQL database, then how can I implement this?
How can I encrypt(maybe, RSA ?) ?
In the way of trying to encrypt, I've learned about RSA encryption little bit but not quite enough.
And the most important thing I want know is, if I've encrypted with RSA container or makecert.exe (certificate), how can I export the RSA container or the certificate to Azure SQL database(Azure SQL server) so that Azure SQL database(Azure SQL server) can decrypt the encrypted connectionstring to allow accesses from client applications?
P.S) According to Microsoft Azure's official document, DPAPI and RSA are not supported with Azure and we have to use another protected configuration provider like PKCS12 ProtectedConfigurationProvider.
Because my major is not related to software but bio-chemistry, an explanation in detail will be greatly appreciated !
Thank you so much ! | 2016/04/30 | [
"https://Stackoverflow.com/questions/36951231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5541055/"
] | I guess this line is giving issues
```
<li> ${results.testID + ""} </li>
```
I'm wondering what is the purpose of that. Why are you trying to concatenate an Integer with an empty String?
Concatenation in `el` is not achieved with the `+` operator. You just have to place to el expressions close to each other.
The following should work
```
<li> ${results.testID} ${""}</li>
```
and this would do the same, but make more sense
```
<li> ${results.testID}</li>
```
Edit:
As JB Nizet as pointed out on his comment to the question the problem is caused by a bad choice when naming the variable that refers to the current item.
Quoting him:
>
> Not sure if that has something to do with the exception, but naming
> the current item results(in var="results") is a bad idea: it's the
> same name as the collection itself. Name it result, and change
> ${results.testID} to ${result.testID}.
>
>
> | Most probably you defined Result.testID to be Integer (in Result class).
But in your database the testID column is String. Most data are numeric, so `result.setTestID(rs.getString("testID"));` does not usually fail, but you have some cases where database data in testID column is not numeric. Thus the "Cannot convert testID of type class java.lang.String to class java.lang.Integer" error |
32,214,676 | I have a pulsing rectangle animated with animateWithDuration and `setAnimationRepeatCount()`.
I'm trying to add a sound effect in the animations block witch is "clicking" synchronously. But the sound effect is only playing once. I can't find any hint on this anywhere.
```
UIView.animateWithDuration(0.5,
delay: 0,
options: UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.Repeat,
animations: {
UIView.setAnimationRepeatCount(4)
self.audioPlayer.play()
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
```
The sound effect should play four times but doesn't.
Audio Implementation:
```
//global:
var metronomClickSample = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("metronomeClick", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: metronomClickSample, error: nil)
audioPlayer.prepareToPlay()
....
}
@IBAction func act_toggleStartTapped(sender: AnyObject) {
....
UIView.animateWithDuration(....
animations: {
UIView.setAnimationRepeatCount(4)
self.audioPlayer.play()
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
}
``` | 2015/08/25 | [
"https://Stackoverflow.com/questions/32214676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5265864/"
] | Providing the `UIViewAnimationOptions.Repeat` option does **NOT** cause the animation block to be called repeatedly. The animation is repeated on a `CoreAnimation` level. If you place a breakpoint in the animation block, you'll notice that it is only executed once.
If you want the animation to execute in a loop alongside the sound, create a repeating `NSTimer` and call the animation / sound from there. Keep in mind that the timer will retain the target, so don't forget to invalidate the timer to prevent retain cycle.
**EDIT:** Added implementation below
First, we'll need to create the timer, assuming we have an instance variable called `timer`. This can be done in `viewDidLoad:` or `init` method of a view. Once initialized, we schedule for execution with the run loop, otherwise it will not fire repeatedly.
```
self.timesFired = 0
self.timer = NSTimer(timeInterval: 0.5, target: self, selector:"timerDidFire:", userInfo: nil, repeats: true)
if let timer = self.timer {
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
```
The following is the method fired by the timer every interval (in this case 0.5 seconds). Here, you can run your animations and audio playback. Note that `UIViewAnimationOptions.Repeat` option has been removed since the timer is now responsible for handling the repeating animation and audio. If you only the timer to fire a specific number of times, you can add an instance variable to keep track of times fired and invalidate the timer if the count is above the threshold.
```
func timerDidFire(timer: NSTimer) {
/*
* If limited number of repeats is required
* and assuming there's an instance variable
* called `timesFired`
*/
if self.timesFired > 5 {
if let timer = self.timer {
timer.invalidate()
}
self.timer = nil
return
}
++self.timesFired
self.audioPlayer.play()
var options = UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut;
UIView.animateWithDuration(0.5, delay: 0, options: options, animations: {
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
}
``` | Without seeing the implementation of the audio player some things I can think of include:
* The audio file is too long and perhaps has silence on the end of it so it is not playing the first part of the file which has the sound in it
* the audio file needs to be set to the beginning of the file every time (it could just be playing the end of the file the other 3 times leading to no audio output)
* The animation is happening to quickly and the audio doesn't have time to buffer
Hopefully these suggestions help you narrow down the problem but without seeing the implementation of the player, it is really hard to say what the actual problem is. |
260,212 | I have written a SOQL query that selects a look up field from a custom object.
My problem is it returns the uuid ( e.g. 1017800012NQqABAFD) and not the name (e.g.Joe Soap).
---
```
Select Name, Surname from Account
```
My result:
```
NAME
1545154151541SADDEEFF
SURNAME
1655466464648SDEDEFE
```
Why do I get the data in this way? How can I get the data I am looking for instead? | 2019/04/26 | [
"https://salesforce.stackexchange.com/questions/260212",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/56658/"
] | Relationship fields (lookup, master-detail) in the Salesforce UI display the `Name` field of the related record, but that's only due to UI magic.
In the backing data store, lookup fields are actually record Ids (as you are seeing).
If you want to get the name of a related record, you'll need to query for it.
```
List<Opportunity> oppsList = [SELECT Id, AccountId, Account.Name FROM Opportunity LIMIT 5];
for(Opportunity opp :oppsList){
system.debug(opp.AccountId); // Will print something like "001000000000123AAA"
system.debug(opp.Account.Name); // Will print something like "Phil's Chairsmithery"
}
``` | The return of the Id for the Name is usually caused by creating the object without specifying a Name field value - Salesforce ensures that a name is always set, using the Id allocated when needed. |
27,380,316 | I have an svg image made by path elements and the path elements are inside g tags which transform and apply the fill to the path elements. The fill I used was a pattern which was predefined in the defs tag. The pattern element contains image tags which link to oth
Now the problem: when i put the svg code directly into the html, it worked fine; but the image needs to flexible for resizing so it has to be in img tags. Unfortunately when I link the svg externally, the fill on the path elements become transparent.I think the problem is that the image is not rendered because when I replace the fill with a simple hex color it works fine.
Here is the svg:
```
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="232" height="158">
<defs>
<filter id="contrast">
<feComponentTransfer>
<feFuncR type="linear" slope="25" intercept="-(0.5 * 25) + 0.5"></feFuncR>
<feFuncG type="linear" slope="25" intercept="-(0.5 * 25) + 0.5"></feFuncG>
<feFuncB type="linear" slope="100" intercept="-(0.5 * 100) + 0.5"></feFuncB>
</feComponentTransfer>
</filter>
<pattern id="bg1" patternUnits="userSpaceOnUse" width="1000" height="3000">
<image xlink:href="svg_bg.png" x="0" y="-25" width="2200" height="1800" style="filter: url(#contrast);"></image>
</pattern>
</defs>
<g transform="scale(0.5,0.5)" stroke="none" fill="url(#bg1)">
<path d="M150 0 L75 200 L225 200 Z" />
</g>
</svg>
``` | 2014/12/09 | [
"https://Stackoverflow.com/questions/27380316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123852/"
] | When used in an image context, i.e. via an `<img>` tag or css background image SVG files must be complete in a single file to protect user's privacy.
You need to embed the svg\_bg.png file into the SVG file as a data url to get this to work. | You should check the numbers in coordinates `x` and `y` everywhere and `href` to the `svb_bg.png`.
Demo for you code: <http://jsbin.com/diwoduheze/1/> |
26,643,911 | I have two tables, Location and Job
When I want to create a new job, I can select the location from a drop down list which is populated from the location table.
My create view:
```
public ActionResult Create(CreateJobViewModel model)
{
model.Locations = repository.GetAllLocations()
.Select(x => new SelectListItem { Text = x.State, Value = x.LocationId.ToString() })
.ToList();
return View(model);
}
```
and my view model:
```
public class CreateJobViewModel
{
public Job Job { get; set; }
public IList<SelectListItem> Locations { get; set; }
public int SelectLocationId { get; set; }
}
```
This all works fine, but how do i get the selected value from the drop down box and then save that value in the foreign key field of the Job table?
My post action looks like this:
```
[HttpPost]
[Authorize(Roles = "Employer")]
[ValidateAntiForgeryToken]
public ActionResult Create(Job job)
{
repository.AddJob(job);
return RedirectToAction("Create");
}
```
The post action uses Job entity and the get action uses CreateJobViewModel, during my previous projects, I only either do create or I display, I never come into a situation like this.
I am thinking something of passing the model between views???
and in my create view, I don't know which model i should use, the view model "CreateJobViewModel" or "Job" entity?
```
@model foo.CreateJobViewModel
```
or
```
@model foo.Job
```
How can I link the two models??? | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610857/"
] | You should use view model in the create and then use custom mapping logic to make Job entity and send to your business or data layer.
You can use Auto mapper for mapping between the entities. | You are thinking about this wrong. Why do you have a Job view model and a Job business object?
Your view should only know about the view model, your controller should (how you have this setup) knows about both the view model and business model, and the repository only knows about the business model.
Have the Post action return a Job View Model. Then convert the View Model to a model in the controller and pass to the repository.
There are several ways you could do this, doing this by hand in the controller, doing this in the constructor of the business object, or utilizing an automapper.
My preference is to create a new constructor for the business object that accepts a view model and copy the properties over that I need (and I do it from model to view model as well). |
26,643,911 | I have two tables, Location and Job
When I want to create a new job, I can select the location from a drop down list which is populated from the location table.
My create view:
```
public ActionResult Create(CreateJobViewModel model)
{
model.Locations = repository.GetAllLocations()
.Select(x => new SelectListItem { Text = x.State, Value = x.LocationId.ToString() })
.ToList();
return View(model);
}
```
and my view model:
```
public class CreateJobViewModel
{
public Job Job { get; set; }
public IList<SelectListItem> Locations { get; set; }
public int SelectLocationId { get; set; }
}
```
This all works fine, but how do i get the selected value from the drop down box and then save that value in the foreign key field of the Job table?
My post action looks like this:
```
[HttpPost]
[Authorize(Roles = "Employer")]
[ValidateAntiForgeryToken]
public ActionResult Create(Job job)
{
repository.AddJob(job);
return RedirectToAction("Create");
}
```
The post action uses Job entity and the get action uses CreateJobViewModel, during my previous projects, I only either do create or I display, I never come into a situation like this.
I am thinking something of passing the model between views???
and in my create view, I don't know which model i should use, the view model "CreateJobViewModel" or "Job" entity?
```
@model foo.CreateJobViewModel
```
or
```
@model foo.Job
```
How can I link the two models??? | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610857/"
] | Here is some code of mine, similar to your problem, you can modify it by your requirements. Hope it helps.
Controller:
```
public ActionResult Create()
{
string selected = (from cat in dc.Category
join sub in dc.SubCategory on cat.Id equals sub.SubCategoryId
select cat.Name).First();
ViewBag.Category = new SelectList(dc.Category, "Id", "Name", selected);
var model = new SubCategory();
return View(model);
}
```
View:
```
<div> Category:</div>
<div>
@Html.DropDownListFor(model => model.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Category,
new { @class = "form-control" })
</div>
``` | You are thinking about this wrong. Why do you have a Job view model and a Job business object?
Your view should only know about the view model, your controller should (how you have this setup) knows about both the view model and business model, and the repository only knows about the business model.
Have the Post action return a Job View Model. Then convert the View Model to a model in the controller and pass to the repository.
There are several ways you could do this, doing this by hand in the controller, doing this in the constructor of the business object, or utilizing an automapper.
My preference is to create a new constructor for the business object that accepts a view model and copy the properties over that I need (and I do it from model to view model as well). |
1,323,556 | The site I am working on wants to generate its own shortened URLs rather than rely on a third party like tinyurl or bit.ly.
Obviously I could keep a running count new URLs as they are added to the site and use that to generate the short URLs. But I am trying to avoid that if possible since it seems like a lot of work just to make this one thing work.
As the things that need short URLs are all real physical files on the webserver my current solution is to use their inode numbers as those are already generated for me ready to use and guaranteed to be unique.
```
function short_name($file) {
$ino = @fileinode($file);
$s = base_convert($ino, 10, 36);
return $s;
}
```
This seems to work. Question is, what can I do to make the short URL even shorter?
On the system where this is being used, the inodes for newly added files are in a range that makes the function above return a string 7 characters long.
Can I safely throw away some (half?) of the bits of the inode? And if so, should it be the high bits or the low bits?
I thought of using the crc32 of the filename, but that actually makes my short names longer than using the inode.
Would something like this have any risk of collisions? I've been able to get down to single digits by picking the right value of "$referencefile".
```
function short_name($file) {
$ino = @fileinode($file);
// arbitrarily selected pre-existing file,
// as all newer files will have higher inodes
$ino = $ino - @fileinode($referencefile);
$s = base_convert($ino, 10, 36);
return $s;
}
``` | 2009/08/24 | [
"https://Stackoverflow.com/questions/1323556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113331/"
] | Not sure this is a good idea : if you have to change server, or change disk / reformat it, the inodes numbers of your files will most probably change... And all your short URL will be broken / lost !
Same thing if, for any reason, you need to move your files to another partition of your disk, btw.
Another idea might be to calculate some crc/md5/whatever of the file's name, like you suggested, and use some algorithm to "shorten" it.
Here are a couple articles about that :
* [Create short IDs with PHP - Like Youtube or TinyURL](http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/)
* [Using Php and MySQL to create a short url service!](http://www.follor.com/2009/01/using-php-and-mysql-to-create-a-short-url-service/)
* [Building a URL Shortener](http://snook.ca/archives/php/url-shortener) | Check out [Lessn](http://www.shauninman.com/archive/2009/08/17/less_n) by Sean Inman; Haven't played with it yet, but it's a self-hosted roll your own URL solution. |
1,323,556 | The site I am working on wants to generate its own shortened URLs rather than rely on a third party like tinyurl or bit.ly.
Obviously I could keep a running count new URLs as they are added to the site and use that to generate the short URLs. But I am trying to avoid that if possible since it seems like a lot of work just to make this one thing work.
As the things that need short URLs are all real physical files on the webserver my current solution is to use their inode numbers as those are already generated for me ready to use and guaranteed to be unique.
```
function short_name($file) {
$ino = @fileinode($file);
$s = base_convert($ino, 10, 36);
return $s;
}
```
This seems to work. Question is, what can I do to make the short URL even shorter?
On the system where this is being used, the inodes for newly added files are in a range that makes the function above return a string 7 characters long.
Can I safely throw away some (half?) of the bits of the inode? And if so, should it be the high bits or the low bits?
I thought of using the crc32 of the filename, but that actually makes my short names longer than using the inode.
Would something like this have any risk of collisions? I've been able to get down to single digits by picking the right value of "$referencefile".
```
function short_name($file) {
$ino = @fileinode($file);
// arbitrarily selected pre-existing file,
// as all newer files will have higher inodes
$ino = $ino - @fileinode($referencefile);
$s = base_convert($ino, 10, 36);
return $s;
}
``` | 2009/08/24 | [
"https://Stackoverflow.com/questions/1323556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113331/"
] | Not sure this is a good idea : if you have to change server, or change disk / reformat it, the inodes numbers of your files will most probably change... And all your short URL will be broken / lost !
Same thing if, for any reason, you need to move your files to another partition of your disk, btw.
Another idea might be to calculate some crc/md5/whatever of the file's name, like you suggested, and use some algorithm to "shorten" it.
Here are a couple articles about that :
* [Create short IDs with PHP - Like Youtube or TinyURL](http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/)
* [Using Php and MySQL to create a short url service!](http://www.follor.com/2009/01/using-php-and-mysql-to-create-a-short-url-service/)
* [Building a URL Shortener](http://snook.ca/archives/php/url-shortener) | Rather clever use of the filesystem there. If you are guaranteed that inode ids are unique its a quick way of generating the unique numbers. I wonder if this could work consistently over NFS, because obviously different machines will have different inode numbers. You'd then just serialize the link info in the file you create there.
To shorten the urls a bit, you might take case sensitivity into account, and do one of the safe encodings (you'll get about base62 out of it - 10 [0-9] + 26 (a-z) + 26 (A-Z), or less if you remove some of the 'conflict' letters like `I` vs `l` vs `1`... there are plenty of examples/libraries out there).
You'll also want to 'home' your ids with an offset, like you said. You will also need to figure out how to keep temp file/log file, etc creation from eating up your keyspace. |
1,323,556 | The site I am working on wants to generate its own shortened URLs rather than rely on a third party like tinyurl or bit.ly.
Obviously I could keep a running count new URLs as they are added to the site and use that to generate the short URLs. But I am trying to avoid that if possible since it seems like a lot of work just to make this one thing work.
As the things that need short URLs are all real physical files on the webserver my current solution is to use their inode numbers as those are already generated for me ready to use and guaranteed to be unique.
```
function short_name($file) {
$ino = @fileinode($file);
$s = base_convert($ino, 10, 36);
return $s;
}
```
This seems to work. Question is, what can I do to make the short URL even shorter?
On the system where this is being used, the inodes for newly added files are in a range that makes the function above return a string 7 characters long.
Can I safely throw away some (half?) of the bits of the inode? And if so, should it be the high bits or the low bits?
I thought of using the crc32 of the filename, but that actually makes my short names longer than using the inode.
Would something like this have any risk of collisions? I've been able to get down to single digits by picking the right value of "$referencefile".
```
function short_name($file) {
$ino = @fileinode($file);
// arbitrarily selected pre-existing file,
// as all newer files will have higher inodes
$ino = $ino - @fileinode($referencefile);
$s = base_convert($ino, 10, 36);
return $s;
}
``` | 2009/08/24 | [
"https://Stackoverflow.com/questions/1323556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113331/"
] | Rather clever use of the filesystem there. If you are guaranteed that inode ids are unique its a quick way of generating the unique numbers. I wonder if this could work consistently over NFS, because obviously different machines will have different inode numbers. You'd then just serialize the link info in the file you create there.
To shorten the urls a bit, you might take case sensitivity into account, and do one of the safe encodings (you'll get about base62 out of it - 10 [0-9] + 26 (a-z) + 26 (A-Z), or less if you remove some of the 'conflict' letters like `I` vs `l` vs `1`... there are plenty of examples/libraries out there).
You'll also want to 'home' your ids with an offset, like you said. You will also need to figure out how to keep temp file/log file, etc creation from eating up your keyspace. | Check out [Lessn](http://www.shauninman.com/archive/2009/08/17/less_n) by Sean Inman; Haven't played with it yet, but it's a self-hosted roll your own URL solution. |
38,501,570 | I am trying to send a message from addon (webextension) to a html page which is in the addon. The webextension API is using the chrome interface which is compatible with Chrome browser. I am using Firefox 48 beta.
This is the background script (the "initiate-page" message is important):
```
chrome.runtime.onMessage.addListener(
function(package, sender
){
switch (package.message){
case "open":
if (package.subject == "tab")
{
win = myNamespace.tabs[package.module];
result = win ? false : true;
if (result)
chrome.tabs.create(
{"url": package.url },
function(tab) {
if (chrome.extension.lastError )
console.log(chrome.extension.lastError);
else
myNamespace.tabs[package.module] = tab.id;
chrome.tabs.onRemoved.addListener(
function( tabId, removeInfo )
{
for (var k in myNamespace.tabs )
{
if (tabId === myNamespace.tabs[k])
{
myNamespace.tabs[k] = null;
break;
}
}
}
);
}
);
}
break;
case "initiate-page":
if (package.subject == "html-add-listeners")
{
switch(package.module){
case "easy_options":
case "advanced_options":
case "images_options":
chrome.tabs.sendMessage(
package.sender.id,
{ message:"initiate-page-response",
subject:"accept-namespace",
recepient: {id: package.sender.id },
module: package.module,
namespace: myNamespace,
info: "response to tab exists message"
}
)
break;
}
}
break;
}
}
)
```
So, when the addon receives a message from the module "easy\_options", it means that easy\_options.html needs some data to load to its document. Therefore I send a message with namespace which contains the data.
Now the addons page easy\_options.js (again, the second part is important where chrome.runtime.onMessage listener is added):
```
chrome.tabs.query(
{ active: true, currentWindow: true},
function(tabs) {
browser.runtime.sendMessage(
{ message:"initiate-page",
subject: "html-add-listeners",
module: "easy_options",
sender:{id:tabs[0].id}
}
)
}
);
chrome.runtime.onMessage.addListener(
function(package, sender
){
switch (package.message){
case "initiate-page-response":
if (package.subject == "accept-namespace")
{
switch(package.module){
case "easy_options":
document.addEventListener('DOMContentLoaded', myNamespace.easy.restore);
document.getElementById("easy_form_save").addEventListener("submit", myNamespace.easy.save);
document.getElementById("easy_form_restore").addEventListener("submit", myNamespace.easy.restore);
document.getElementById("easy_form_remove_item").addEventListener("submit", myNamespace.easy.remove_profiles);
document.getElementById("easy_form_remove_profiles").addEventListener("submit", myNamespace.easy.remove_profiles);
document.getElementById("list").addEventListener("change", myNamespace.easy.restoreDefault);
break;
}
}
break;
}
}
)
```
What happens is:
1. I send message (A) to background listener and it accepts the message
2. background listener sends message (B)
3. addons options script receives the first message (A) in the runtime.OnMessage listener (I do not want to process this message)
What should happen
1. I send message (A) to background listener and it accepts the message
2. background listener sends message (B)
3. addons options script receives the first message (A) in the runtime.OnMessage listener (I do not want to process this message)
4. addons options script should receive the second message (B) in the runtime.OnMessage listener and I should process it
Question:
Why does the fourth step not happen? Why is the message (B alias "initiate-page-response") not received?
Maybe Chrome addon programmers can help too, I think the things should work similarly. | 2016/07/21 | [
"https://Stackoverflow.com/questions/38501570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141649/"
] | Since it's an extension page, and not a content script, `chrome.tabs.sendMessage` is not going to reach it.
You need to broadcast your message with `chrome.runtime.sendMessage` to reach `chrome-extension://` pages such as an options page.
If you don't like the broadcast nature of `runtime.sendMessage`, you should use `sendResponse` callback argument to pass a response back to sender (probably preferable), or establish a long-lived port with `runtime.connect`. | Thanks to Xan's explanation, I have found this works like charm
background script:
```
chrome.runtime.onMessage.addListener(
function(package, sender, sendResponse
){
switch (package.message){
case "open":
if (package.subject == "tab")
{
win = myNamespace.tabs[package.module];
result = win ? false : true;
if (result)
chrome.tabs.create(
{"url": package.url },
function(tab) {
if (chrome.extension.lastError )
console.log(chrome.extension.lastError);
else
myNamespace.tabs[package.module] = tab.id;
chrome.tabs.onRemoved.addListener(
function( tabId, removeInfo )
{
for (var k in myNamespace.tabs )
{
if (tabId === myNamespace.tabs[k])
{
myNamespace.tabs[k] = null;
break;
}
}
}
);
}
);
}
break;
case "initiate-page":
if (package.subject == "html-add-listeners")
{
switch(package.module){
case "easy_options":
case "advanced_options":
case "images_options":
sendResponse(
{ message:"initiate-page-response",
subject:"accept-namespace",
recepient: {id: package.sender.id },
module: package.module,
namespace: myNamespace,
info: "response to initiate-page message"
}
)
break;
}
}
break;
}
}
)
```
Addon's option page script:
```
chrome.tabs.query(
{ active: true, currentWindow: true},
function(tabs) {
browser.runtime.sendMessage(
{ message:"initiate-page",
subject: "html-add-listeners",
module: "easy_options",
sender:{id:tabs[0].id}
},
function response(message){
console.log("RESPONSE:");
console.log(message);
return true;
}
)
}
);
``` |
44,795 | A similar story goes for two different cities.
Baijnath and Gokarna.
Which one is the correct one?
If both of them are true, did Ravana carry Shivlinga twice? | 2021/02/16 | [
"https://hinduism.stackexchange.com/questions/44795",
"https://hinduism.stackexchange.com",
"https://hinduism.stackexchange.com/users/21873/"
] | Karkati is one such example. She takes boon from Brahma and realizes later to become good and becomes Jivan muktha.
Her story is mentioned in [Part 3 - The Story of Karkaṭī](https://www.wisdomlib.org/hinduism/book/laghu-yoga-vasistha/d/doc209654.html) in `Utpatti-prakaraṇa` of Yoga-Vasistha
Initially, she performs an intensive tapas and asks Brahma for a boon as follows
>
> After she had passed thus a painful Tapas for
> 1,000 years, the Lotus-seated Brahmā appeared visibly before her. Are
> there any objects which cannot be acquired in this world even by the
> vicious through the performance of rare Tapas? With the arrival of
> Brahmā before her, she made obeisance to him mentally without stir
> ring from her spot and reflected thus: “**In order to assuage my
> ever-increasing fire, if I transform myself into the form of an
> iron-like Jīva-Sūcikā (living needle). I can enter into the bodies of
> all in the world and consume as much food as I require**.” Whilst these
> thoughts were revolving in her mind, Brahmā asked her the object of
> her wish. Karkaṭī replied thus “Oh Lord that favorest those, thy
> devotees who contemplate upon and praise thee. thy servant wishes to
> be come a Jīva-Sūcikā.”
>
>
>
After obtaining boon from Brahma, she utilizes her boon and harms others. But, afterwards, she realizes about evil in her and performs tapas again for Brahma with pure mind and finally gets liberation.
>
> So saying Brahmā vanished from view, whereupon this mountain-sized
> personage reduced herself to the size of a Jīva-Sūcikā and entered
> into the minds of the ferocious as well as the timid in order to make
> them perish. Having entered in the form of Vāyu within all Jīvas in
> earth and in Ākāśa, she fed upon all their lives in the form of Jīva
> Sūcikā and Vāyu-Sūcikā. Surfeited with such an enjoyment, she
> exclaimed “Whirling and making me despondent, my desires do make even
> the needle to wear away and making me giddy, do destroy me. Away with
> these desires of mine ! With a cruel heart. I have afflicted many
> lives in vain. **Therefore, I shall divest myself of all desires and
> perform Tapas in the Himalayas “So saying, she gave up all fluctuation
> of mind, devoid of any longing- for objects. Thus a thousand years
> passed, purifying her of the two-fold Karmas, (virtuous and sinful).**
> While thus, she was engaged in spiritual contemplation with an
> illuminated mind, free from all the pains of love and hatred and
> slighting this universe, the all-full Jñāna dawned in her mind and
> therefore Brahmā came voluntarily to her and imparted to her the
> following truths: (< Thou hast attained the Jīvanmukti state. Thy
> mind has been quite illumined; yet thou shalt be in thy old form of a
> Rākṣasa lady and sup port thyself on earth in the bodies of persons
> without Jñāna as well as the cruel and the base. Happiness thou shalt
> en joy thus.” With these blessings, Brahmā disappeared.
>
>
> | Vibhishana is an example. He asked for a boon that he should always be righteous and also obtain the light of divine knowledge from Brahma
<http://www.sacred-texts.com/hin/m03/m03273.htm>
>
> Brahma then addressed Vibhishana, 'O my son, I am much pleased with thee! Ask any boon thou pleasest!' Thereupon, Vibhishana replied, '**Even in great danger, may I never swerve from the path of righteousness, and though ignorant, may I, O adorable Sire, be illumined with the light of divine knowledge**!'
>
>
>
Brahma was so pleased by him that he even bestowed upon him immortality.
>
> And Brahma replied, 'O scourge of thy enemies, as thy soul inclines not to unrighteousness although born in the Rakshasa race, **I grant thee immortality!'**
>
>
> |
15,635,640 | I have a problem to remove duplicate object in 2 list
```
public class Pump
{
public int PumpID { get; set; }
public string PumpName { get; set; }
public string LogicalNumber { get; set; }
}
public void LoadPump()
{
var pumps = _pumpRepository.GetAll(); // 2 Pump
var pumpsActive = _pumpRepository.GetAllActive(); // 1 Pump Active (Pump 1)
//i try like this
List<Pump> pumpsNonActive = pumps.Except(pumpsActive).ToList(); // Result 2
//if like this
List<Pump> pumpsNonActive = pumpsActive.Except(pumps).ToList(); // Result 1 (Pump 1)
}
```
I want to get only 1 result in pumpsNonActive (Result = Pump 2). Anyone can help me :/ | 2013/03/26 | [
"https://Stackoverflow.com/questions/15635640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802473/"
] | Implement [`.Equals(object)`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) and [`.GetHashCode()`](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx).
```
public class Pump
{
public int PumpID { get; set; }
public string PumpName { get; set; }
public string LogicalNumber { get; set; }
public override bool Equals(object o)
{
var casted = o as Pump;
if (casted == null)
return false;
return PumpID == o.PumpID;
}
public override int GetHashCode()
{
return PumpID.GetHashCode();
}
}
``` | Imeplement
```
public class Pump: IEquatable<Pump>
{
public bool Equals(Pump other)
{
...
}
}
``` |
15,635,640 | I have a problem to remove duplicate object in 2 list
```
public class Pump
{
public int PumpID { get; set; }
public string PumpName { get; set; }
public string LogicalNumber { get; set; }
}
public void LoadPump()
{
var pumps = _pumpRepository.GetAll(); // 2 Pump
var pumpsActive = _pumpRepository.GetAllActive(); // 1 Pump Active (Pump 1)
//i try like this
List<Pump> pumpsNonActive = pumps.Except(pumpsActive).ToList(); // Result 2
//if like this
List<Pump> pumpsNonActive = pumpsActive.Except(pumps).ToList(); // Result 1 (Pump 1)
}
```
I want to get only 1 result in pumpsNonActive (Result = Pump 2). Anyone can help me :/ | 2013/03/26 | [
"https://Stackoverflow.com/questions/15635640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802473/"
] | You could override `Equals` or you can try the following:
```
List<Pump> pumpsNonActive = pumps.Where(r => !pumpsActive
.Any(t => t.PumpID == r.PumpID))
.ToList();
```
This worked for the following dataset:
```
List<Pump> pumps = new List<Pump>()
{
new Pump() { PumpID = 1, LogicalNumber = "SomeName", PumpName="PumpName1"},
new Pump() {PumpID = 2, LogicalNumber = "Number", PumpName = "PumpName2"},
new Pump(){PumpID = 3, LogicalNumber = "Number", PumpName = "PumpName3"},
};
List<Pump> pumpsActive= new List<Pump>()
{
new Pump() { PumpID = 1, LogicalNumber = "2", PumpName="3"},
};
``` | Imeplement
```
public class Pump: IEquatable<Pump>
{
public bool Equals(Pump other)
{
...
}
}
``` |
15,635,640 | I have a problem to remove duplicate object in 2 list
```
public class Pump
{
public int PumpID { get; set; }
public string PumpName { get; set; }
public string LogicalNumber { get; set; }
}
public void LoadPump()
{
var pumps = _pumpRepository.GetAll(); // 2 Pump
var pumpsActive = _pumpRepository.GetAllActive(); // 1 Pump Active (Pump 1)
//i try like this
List<Pump> pumpsNonActive = pumps.Except(pumpsActive).ToList(); // Result 2
//if like this
List<Pump> pumpsNonActive = pumpsActive.Except(pumps).ToList(); // Result 1 (Pump 1)
}
```
I want to get only 1 result in pumpsNonActive (Result = Pump 2). Anyone can help me :/ | 2013/03/26 | [
"https://Stackoverflow.com/questions/15635640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802473/"
] | You could override `Equals` or you can try the following:
```
List<Pump> pumpsNonActive = pumps.Where(r => !pumpsActive
.Any(t => t.PumpID == r.PumpID))
.ToList();
```
This worked for the following dataset:
```
List<Pump> pumps = new List<Pump>()
{
new Pump() { PumpID = 1, LogicalNumber = "SomeName", PumpName="PumpName1"},
new Pump() {PumpID = 2, LogicalNumber = "Number", PumpName = "PumpName2"},
new Pump(){PumpID = 3, LogicalNumber = "Number", PumpName = "PumpName3"},
};
List<Pump> pumpsActive= new List<Pump>()
{
new Pump() { PumpID = 1, LogicalNumber = "2", PumpName="3"},
};
``` | Implement [`.Equals(object)`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) and [`.GetHashCode()`](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx).
```
public class Pump
{
public int PumpID { get; set; }
public string PumpName { get; set; }
public string LogicalNumber { get; set; }
public override bool Equals(object o)
{
var casted = o as Pump;
if (casted == null)
return false;
return PumpID == o.PumpID;
}
public override int GetHashCode()
{
return PumpID.GetHashCode();
}
}
``` |
33,439,810 | I am trying to print the binary tree using networkx library in python.
But, I am unable to preserve the left and right childs. Is there a way to tell the Graph to print left child first and then the right child?
```
import networkx as nx
G = nx.Graph()
G.add_edges_from([(10,20), (11,20)])
nx.draw_networkx(G)
```
[![enter image description here](https://i.stack.imgur.com/KlNua.jpg)](https://i.stack.imgur.com/KlNua.jpg)

EDIT 1: On using the pygraphwiz, it results in a directed graph atleast. So, I have better picture of the root node.
Below is the code I am using:
```
import pygraphviz as pgv
G = pgv.AGraph()
G.add_node('20')
G.add_node('10')
G.add_node('11')
G.add_edge('20','10')
G.add_edge('20','11')
G.add_edge('10','7')
G.add_edge('10','12')
G.layout()
G.draw('file1.png')
from IPython.display import Image
Image('file1.png')
```
But, this is still far from a structured format. I will post on what I find out next. The new graph looks like below (atleast we know the root):
[![Root to Leaf Binary tree](https://i.stack.imgur.com/czjFJ.png)](https://i.stack.imgur.com/czjFJ.png)
EDIT 2: For those who are facing issues with installation, please [refer to this post.](https://stackoverflow.com/questions/22698227/python-installation-issues-with-pygraphviz-and-graphviz) [The answer to this](https://stackoverflow.com/a/28832992/4160889) - its very helpful if you want to install pygraphviz on windows 64 bit. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33439810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160889/"
] | I believe Networkx is not suited to binary trees but you can set the node positions yourself. I have wrote the following algorithm to setup node positions but it works fine for full or complete binary trees where key nodes are ordered [0,1,...].
```
def full_tree_pos(G):
n = G.number_of_nodes()
if n == 0 : return {}
# Set position of root
pos = {0:(0.5,0.9)}
if n == 1:
return pos
# Calculate height of tree
i = 1
while(True):
if n >= 2**i and n<2**(i+1):
height = i
break
i+=1
# compute positions for children in a breadth first manner
p_key = 0
p_y = 0.9
p_x = 0.5
l_child = True # To indicate the next child to be drawn is a left one, if false it is the right child
for i in xrange(height):
for j in xrange(2**(i+1)):
if 2**(i+1)+j-1 < n:
print 2**(i+1)+j-1
if l_child == True:
pos[2**(i+1)+j-1] = (p_x - 0.2/(i*i+1) ,p_y - 0.1)
G.add_edge(2**(i+1)+j-1,p_key)
l_child = False
else:
pos[2**(i+1)+j-1] = (p_x + 0.2/(i*i+1) ,p_y - 0.1)
l_child = True
G.add_edge(2**(i+1)+j-1,p_key)
p_key += 1
(p_x,p_y) = pos[p_key]
return pos
G = nx.Graph()
G.add_nodes_from(xrange(25))
pos = full_tree_pos(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
```
which gave the following graph. [![enter image description here](https://i.stack.imgur.com/Kdysx.png)](https://i.stack.imgur.com/Kdysx.png) | **Note** If you use networkx version 1.11 or earlier, see the note at the end.
The following assumes that each node has an attribute assigned to it telling whether it is the left or right child of its parent. So you'll have to assign this - by default a graph does not have any concept of this. Perhaps it might be possible to convince the networkx people to make a new class of graph which is a binary tree and stores this information automatically, but at present, it's not there. I don't know whether there would be enough interest to justify this.
```
import networkx as nx
def binary_tree_layout(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5,
pos = None, parent = None):
'''If there is a cycle that is reachable from root, then this will see infinite recursion.
G: the graph
root: the root node of current branch
width: horizontal space allocated for this branch - avoids overlap with other branches
vert_gap: gap between levels of hierarchy
vert_loc: vertical location of root
xcenter: horizontal location of root
pos: a dict saying where all nodes go if they have been assigned
parent: parent of this branch.
each node has an attribute "left: or "right"'''
if pos == None:
pos = {root:(xcenter,vert_loc)}
else:
pos[root] = (xcenter, vert_loc)
neighbors = list(G.neighbors(root))
if parent != None:
neighbors.remove(parent)
if len(neighbors)!=0:
dx = width/2.
leftx = xcenter - dx/2
rightx = xcenter + dx/2
for neighbor in neighbors:
if G.nodes[neighbor]['child_status'] == 'left':
pos = binary_tree_layout(G,neighbor, width = dx, vert_gap = vert_gap,
vert_loc = vert_loc-vert_gap, xcenter=leftx, pos=pos,
parent = root)
elif G.nodes[neighbor]['child_status'] == 'right':
pos = binary_tree_layout(G,neighbor, width = dx, vert_gap = vert_gap,
vert_loc = vert_loc-vert_gap, xcenter=rightx, pos=pos,
parent = root)
return pos
```
Here is a sample call where I made **even** nodes into left children.
```
G= nx.Graph()
G.add_edges_from([(0,1),(0,2), (1,3), (1,4), (2,5), (2,6), (3,7)])
for node in G.nodes():
if node%2==0:
G.nodes[node]['child_status'] = 'left' #assign even to be left
else:
G.nodes[node]['child_status'] = 'right' #and odd to be right
pos = binary_tree_layout(G,0)
nx.draw(G, pos=pos, with_labels = True)
```
[![enter image description here](https://i.stack.imgur.com/5fV37.png)](https://i.stack.imgur.com/5fV37.png)
---
**edit notes** An earlier version of this answer worked for networkx version 1.11 and earlier. If you need it, please open the edit history and use the 2nd version of this answer. |
25,815,449 | I'm chasing my tail here. All I'm looking to do is return a string from the $scope.getPlacesTextRaw function.
```
$scope.getPlacesTextRaw = function(selectedPlace){
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
return metadata.description.replace(/ /g,"_");
});
};
```
Another attempt:
```
$scope.getPlacesTextRaw = function(selectedPlace){
var deferred = $q.defer();
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
deferred.resolve('@' + metadata.description.replace(/ /g,"_"));
});
deferred.promise.then(function(string){
return string;
});
};
```
I'm calling getPlacesTextRaw from within a directive:
```
<mentio-menu
mentio-for="'hashtag'"
mentio-trigger-char="'@'"
mentio-items="places"
mentio-template-url="/places-mentions.tpl"
mentio-search="searchPlaces(term)"
mentio-select="getPlacesTextRaw(item);">
</mentio-menu>
``` | 2014/09/12 | [
"https://Stackoverflow.com/questions/25815449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438846/"
] | In both cases, a constant string of characters `"hello\0"` is allocated in a read-only section of the executable image.
In the case of `char* s="hello"`, the variable `s` is set to point to the location of that string in memory every time the function is called, so it can be used for read operations (`c = s[i]`), but not for write operations (`s[i] = c`).
In the case of `char s[]="hello"`, the array `s` is allocated on the stack and filled with the contents of that string every time the function is called, so it can be used for read operations (`c = s[i]`) and for write operations (`s[i] = c`). | One is a pointer the other is an array.
An array defines data that stays in the current scope stack space.
A pointer defines a memory address that is in the current scope stack space, but which references memory from the heap. |
25,815,449 | I'm chasing my tail here. All I'm looking to do is return a string from the $scope.getPlacesTextRaw function.
```
$scope.getPlacesTextRaw = function(selectedPlace){
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
return metadata.description.replace(/ /g,"_");
});
};
```
Another attempt:
```
$scope.getPlacesTextRaw = function(selectedPlace){
var deferred = $q.defer();
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
deferred.resolve('@' + metadata.description.replace(/ /g,"_"));
});
deferred.promise.then(function(string){
return string;
});
};
```
I'm calling getPlacesTextRaw from within a directive:
```
<mentio-menu
mentio-for="'hashtag'"
mentio-trigger-char="'@'"
mentio-items="places"
mentio-template-url="/places-mentions.tpl"
mentio-search="searchPlaces(term)"
mentio-select="getPlacesTextRaw(item);">
</mentio-menu>
``` | 2014/09/12 | [
"https://Stackoverflow.com/questions/25815449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438846/"
] | When using `char s[] = "hello";`, the char array is created in the scope of the current function, hence the memory is allocated on the stack when entering the function.
When using `char *s = "hello";`, `s` is a pointer to a constant string which the compiler saves in a block of memory of the program which is blocked for write-access, hence the segmentation fault. | One is a pointer the other is an array.
An array defines data that stays in the current scope stack space.
A pointer defines a memory address that is in the current scope stack space, but which references memory from the heap. |
25,815,449 | I'm chasing my tail here. All I'm looking to do is return a string from the $scope.getPlacesTextRaw function.
```
$scope.getPlacesTextRaw = function(selectedPlace){
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
return metadata.description.replace(/ /g,"_");
});
};
```
Another attempt:
```
$scope.getPlacesTextRaw = function(selectedPlace){
var deferred = $q.defer();
mentionsFactory.getPlaceMetaData(selectedPlace).then(function(metadata) {
console.log("here is our metadata", metadata);
deferred.resolve('@' + metadata.description.replace(/ /g,"_"));
});
deferred.promise.then(function(string){
return string;
});
};
```
I'm calling getPlacesTextRaw from within a directive:
```
<mentio-menu
mentio-for="'hashtag'"
mentio-trigger-char="'@'"
mentio-items="places"
mentio-template-url="/places-mentions.tpl"
mentio-search="searchPlaces(term)"
mentio-select="getPlacesTextRaw(item);">
</mentio-menu>
``` | 2014/09/12 | [
"https://Stackoverflow.com/questions/25815449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438846/"
] | When using `char s[] = "hello";`, the char array is created in the scope of the current function, hence the memory is allocated on the stack when entering the function.
When using `char *s = "hello";`, `s` is a pointer to a constant string which the compiler saves in a block of memory of the program which is blocked for write-access, hence the segmentation fault. | In both cases, a constant string of characters `"hello\0"` is allocated in a read-only section of the executable image.
In the case of `char* s="hello"`, the variable `s` is set to point to the location of that string in memory every time the function is called, so it can be used for read operations (`c = s[i]`), but not for write operations (`s[i] = c`).
In the case of `char s[]="hello"`, the array `s` is allocated on the stack and filled with the contents of that string every time the function is called, so it can be used for read operations (`c = s[i]`) and for write operations (`s[i] = c`). |
70,926,877 | I currently have a bool mask vector generated in Eigen. I would like to use this binary mask similar as in Python `numpy`, where depending on the `True` value, i get a sub-matrix or a sub-vector, where i can further do some calculations on these.
To achieve this in Eigen, i currently "convert" the mask vector into another vector containing the indices by simply iterating over the mask:
```
Eigen::Array<bool, Eigen::Dynamic, 1> mask = ... // E.G.: [0, 1, 1, 1, 0, 1];
Eigen::Array<uint32_t, Eigen::Dynamic, 1> mask_idcs(mask.count(), 1);
int z_idx = 0;
for (int z = 0; z < mask.rows(); z++) {
if (mask(z)) {
mask_idcs(z_idx++) = z;
}
}
// do further calculations on vector(mask_idcs)
// E.G.: vector(mask_idcs)*3 + another_vector
```
However, i want to further optimize this and am wondering if Eigen3 provides a more elegant solution for this, something like `vector(from_bin_mask(mask))`, which may benefit from the libraries optimization.
There are already some questions here in SO, but none seems to answer this simple use-case
([1](https://stackoverflow.com/questions/16253415/eigen-boolean-array-slicing), [2](https://stackoverflow.com/questions/24654840/eigen-mask-an-array)). Some refer to the `select`-function, which returns an equally sized vector/matrix/array, but i want to discard elements via a mask and only work further with a smaller vector/matrix/array.
Is there a way to do this in a more elegant way? Can this be optimized otherwise?
(I am using the `Eigen::Array`-type since most of the calculations are element-wise in my use-case) | 2022/01/31 | [
"https://Stackoverflow.com/questions/70926877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10840396/"
] | As far as I'm aware, there is no "out of the shelf" solution using Eigen's methods. However it is interesting to notice that (at least for Eigen versions greater or equal than `3.4.0`), you can using a `std::vector<int>` for indexing (see [this section](https://eigen.tuxfamily.org/dox/group__TutorialSlicingIndexing.html)). Therefore the code you've written could simplified to
```
Eigen::Array<bool, Eigen::Dynamic, 1> mask = ... // E.G.: [0, 1, 1, 1, 0, 1];
std::vector<int> mask_idcs;
for (int z = 0; z < mask.rows(); z++) {
if (mask(z)) {
mask_idcs.push_back(z);
}
}
// do further calculations on vector(mask_idcs)
// E.G.: vector(mask_idcs)*3 + another_vector
```
If you're using `c++20`, you could use an alternative implementation using `std::ranges` without using raw for-loops:
```
int const N = mask.size();
auto c = iota(0, N) | filter([&mask](auto const& i) { return mask[i]; });
auto masked_indices = std::vector(begin(c), end(c));
// ... Use it as vector(masked_indices) ...
```
I've implemented some minimal examples in [compiler explorer](https://godbolt.org/z/9oTW7PfM6) in case you'd like to check out. I honestly wished there was a simpler way to initialize the `std::vector` from the raw range, but it's currently [not so simple](https://timur.audio/how-to-make-a-container-from-a-c20-range). Therefore I'd suggest you to wrap the code into a helper function, for example
```
auto filtered_indices(auto const& mask) // or as you've suggested from_bin_mask(auto const& mask)
{
using std::ranges::begin;
using std::ranges::end;
using std::views::filter;
using std::views::iota;
int const N = mask.size();
auto c = iota(0, N) | filter([&mask](auto const& i) { return mask[i]; });
return std::vector(begin(c), end(c));
}
```
and then use it as, for example,
```
Eigen::ArrayXd F(5);
F << 0.0, 1.1548, 0.0, 0.0, 2.333;
auto mask = (F > 1e-15).eval();
auto D = (F(filtered_indices(mask)) + 3).eval();
```
It's not as clean as in `numpy`, but it's something :) | I have found another way, which seems to be more elegant then comparing each element if it equals to `0`:
```
Eigen::SparseMatrix<bool> mask_sparse = mask.matrix().sparseView();
for (uint32_t k = 0; k<mask.outerSize(); ++k) {
for (Eigen::SparseMatrix<bool>::InnerIterator it(mask_sparse, k); it; ++it) {
std::cout << it.row() << std::endl; // row index
std::cout << it.col() << std::endl; // col index
// Do Stuff or built up an array
}
}
```
Here we can at least build up a vector (or multiple vectors, if we have more dimensions) and then later use it to "mask" a vector or matrix. (This is taken from the [documentation](https://eigen.tuxfamily.org/dox/group__TutorialSparse.html)).
So applied to this specific usecase, we simply do:
```
Eigen::Array<uint32_t, Eigen::Dynamic, 1> mask_idcs(mask.count(), 1);
Eigen::SparseVector<bool> mask_sparse = mask.matrix().sparseView();
int z_idx = 0;
for (Eigen::SparseVector<bool>::InnerIterator it(mask_sparse); it; ++it) {
mask_idcs(z_idx++) = it.index()
}
// do Stuff like vector(mask_idcs)*3 + another_vector
```
However, i do not know which version is faster for large masks containing thousands of elements. |
37,569,973 | I have a kendo grid on Cordova app. Here on the grid, the scrolling is jagged due to the css rule 'k-grid tr:hover' in kendo css. If I disable this rule from developer tools, scrolling is smooth. Is there any way to disable this hover rule?
I don't want to override hover behaviour. I want to disable it.
Edit: The problem is due to hover the scrolling is not smooth on the grid. The scroll starts after touchend of the swipe but instead it should move with touchmove. This causes the scrolling to be jagged. Removing the hover rule solves this and makes scroll smooth.
Do ask for further clarification if necessary. | 2016/06/01 | [
"https://Stackoverflow.com/questions/37569973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6409808/"
] | You can use pointer-events: none property on the DOM element.
<https://developer.mozilla.org/en/docs/Web/CSS/pointer-events>
```
.k-grid tr {
pointer-events: none;
}
```
With this property, the hover event on that element will be completely ignored. | I took hint from Gabriel's answer but I applied pointer events none to the td elements inside .k-grid tr. But this is just a temporary fix as this removes the possibility of adding pointer events to those td elements. I am still looking for a better alternative. |
37,569,973 | I have a kendo grid on Cordova app. Here on the grid, the scrolling is jagged due to the css rule 'k-grid tr:hover' in kendo css. If I disable this rule from developer tools, scrolling is smooth. Is there any way to disable this hover rule?
I don't want to override hover behaviour. I want to disable it.
Edit: The problem is due to hover the scrolling is not smooth on the grid. The scroll starts after touchend of the swipe but instead it should move with touchmove. This causes the scrolling to be jagged. Removing the hover rule solves this and makes scroll smooth.
Do ask for further clarification if necessary. | 2016/06/01 | [
"https://Stackoverflow.com/questions/37569973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6409808/"
] | I've "solved" it by disabling the hover and then replicating the tr even background color:
```
.k-grid tr:hover {
background: none;
}
.k-grid tr.k-alt:hover {
background: none;
}
.k-grid tr.k-alt:nth-child(even) {
background-color: #f5f5f5;
}
```
of course you can play with the colors | I took hint from Gabriel's answer but I applied pointer events none to the td elements inside .k-grid tr. But this is just a temporary fix as this removes the possibility of adding pointer events to those td elements. I am still looking for a better alternative. |
58,373,282 | The below query doesn't list out all records that contain `null` value in `WFD_DETECTION_EPA` when we pass in some value in `S1_WFD_OPERATION_CODE` variable. Only records with `WFD_DETECTION_EPA` is not `null` appear in the result.
How to enhance this query?
```
AND UPPER (FD.WFD_DETECTION_EPA) LIKE
'%'
|| CASE
WHEN LENGTH (S0_WFD_DETECTION_EPA) > 0
THEN
UPPER (S0_WFD_DETECTION_EPA)
ELSE
'%'
END
|| '%'
AND UPPER (FD.WFD_OPERATION_CODE) LIKE
'%'
|| CASE
WHEN LENGTH (S1_WFD_OPERATION_CODE) > 0
THEN
UPPER (S1_WFD_OPERATION_CODE)
ELSE
'%'
END
|| '%'
``` | 2019/10/14 | [
"https://Stackoverflow.com/questions/58373282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4877272/"
] | TS 4.2
------
allows [leading/middle rest elements](https://devblogs.microsoft.com/typescript/announcing-typescript-4-2/#non-trailing-rests) in tuple types. You can now write:
```
type WithLastQux = [...Bar[], Qux]
```
To allow an *optional* last `Qux` (thanks @last-child):
```
type WithLastQux = [...Bar[], Qux] | Bar[]
```
Test:
```
// ok
const t11: WithLastQux = ["qux"]
const t12: WithLastQux = ["bar", "qux"]
const t13: WithLastQux = ["bar", "bar", "bar", "qux"]
const t14: WithLastQux = ["bar"]
const t15: WithLastQux = []
// error
const t16: WithLastQux = ["qux", "qux"]
const t17: WithLastQux = ["qux", "bar"]
```
As extension, define a generic function helper to keep narrow, fixed-sized tuple types:
```
function foo<T extends WithLastQux>(t: T): T { return t }
foo(["bar", "qux"])
// type: function foo<["bar", "qux"]>(t: ["bar", "qux"]): ["bar", "qux"]
```
Note, that an *optional* last `Qux` element via `[...Bar[], Qux?]` is not directly possible:
>
> The only restriction is that a rest element can be placed anywhere in a tuple, so long as it’s not followed by another optional element or rest element. ([docs](https://devblogs.microsoft.com/typescript/announcing-typescript-4-2/#non-trailing-rests))
>
>
>
[Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQghgJygXigIgEaLQbgFCiRQCKArgB4roCOFaB40A6gJbAAWAMnAM7BmVUAbQB0Y+AiEBdADQkKUqAB9YiaXjwB6TVAD2AazwBjXQDs+UYAEYrALiisO3PgKpC0tcminGzF6wBM9o5cvPwUbpjYch50PibmwJZWAMzBbKEuEcJRCGgxWHkF0TRxvonJACzpTmGuOYXe5f5WAKw1meGCUOpaOhAICLoIzUnWAGwdzl2RnvmlXoqjyQDsU3XZPbFexXk+fVAAggA2wAOmcMAsAG4Q9kYIEJfQAOYQpgMsRlAJfAhwLFMZwAJlAAGakUxGK5mKAHYC6KBgR48Aa3cEscgQYEAWh4LAAXtBgKQwMcIHJgWYAORJADuLGB70siMQ-xAeAhUJhpnBul0AB4ACpQCDkM6mYE8BwZaYCAB8AApgPYhQBKVVQADeUEeJIQvKSAF8NNo9IYwfzFdI1Zyre5GlJbZbdNbtt5nfbcvN3U67a6HSVvbsfXM-X0BkMRi63XMQ36Y+44wsPUA)
---
TS 4.0
------
In JS, [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) always need to be the last function parameter. TS 4.0 comes with a feature called [variadic tuple types](https://github.com/microsoft/TypeScript/pull/39094), which you can think of here as "rest parameters for types".
The neat thing is: variadic tuple types [can be placed anywhere](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/#variadic-tuple-types) in function parameters, not just at the end. We now can define an arbitrary amount of `bar` items with an optional last element `qux`.
Example: `[bar, bar, <and arbitrary more>, qux]` can be interpreted as variadic tuple `[...T, qux]`, where `T` stands for all the `bar` items.
### Solution 1: Separate `Assert` type
```
type Assert<T extends readonly (Bar | Qux)[]> =
T extends readonly [] ? T :
T extends readonly [...infer I, infer U] ?
I extends [] ? T :
I extends Bar[] ? T : readonly [...{ [K in keyof I]: Bar }, U] :
never
function assert<T extends readonly (Bar | Qux)[] | readonly [Bar | Qux]>(
a: Assert<T>): T { return a as T }
// OK
const ok1 = assert([])
const ok2 = assert(["bar"])
const ok3 = assert(["qux"])
const ok4 = assert(["bar", "qux"])
const ok5 = assert(["bar", "bar", "bar"])
const ok6 = assert(["bar", "bar", "bar", "qux"])
// errors
const err1 = assert(["qux", "qux"])
const err2 = assert(["qux", "bar"])
const err3 = assert(["bar", "bar", "qux", "bar"])
const err4 = assert(["bar", "bar", "qux", "qux"])
```
You might substitute the `assert` helper function with some kind of "sentinel" type:
```
type Sentinel<T, U extends T> = U
const arr1 = ["bar", "bar"] as const
const arr2 = ["qux", "bar"] as const
type Arr1Type = Sentinel<Assert<typeof arr1>, typeof arr1> // OK
type Arr2Type = Sentinel<Assert<typeof arr2>, typeof arr2> // error
```
[Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQghgJygXigIgEaLQKFJKARQFcAPFdARzNxwHo6oEI4ATAewDsAbEKYgM4RWUABYRmUAJacoAYzhCocKMGJhu0KQKhhFQkQDcpKgAaL5XAcFN5w0AIIChCYAB4AKlAilgETqw6zGxcvFAAFPBIAD5EZACUANoAugB8KDhQWVBePn4BQSwcPHwpUAD8OVAAXJnZub7%20gUxFoaUAdJ0yAGYSUACSADTSnL1IAKrJFXVZ-d6NBVBllV612QPz%20c1Ry1XVLSElS53tAN5LANIjUADWECDs3QPJ%201FQAL7DkzUzUJwQhgkODsBA8AAYKE4XO4UqkQdAPABGSHOCQwzDYNLwnIAJhR0LciTQ1FIaCx%20ARAGZ8WjCRiEGhhsSaOT7DkACw01x0rAMpm8xnoAWs0EAVi56IF-Ow0r5VBZcPojAAShAALZwMCqdSaKDGFSJE7nYLFMKJK4yW73R7PV6ID5fKbddhIDAQYB%20JASBAuqCsbQaOAgbFIgD6AFEEEhUFDaUSSYLmaSRQicRGoxK6QnZWS4RScpT09GoLHuUSpUKZfLSTmUxyi5ny1X6Yns9Xc8CGAdTaU3rESKQnS65BAdB4AMqqdgjMbajSj4aWhRKB7EP1cADkwH4SnMOjkVhsOG6xE4cmAUi4ylR3IaW0KhzCkXt-YSZViJraSz7cUHqXCcD7KW7geKk8T7F4py-MwagILIKgWB4ODvJ2jAAPIXDgB6cNYUDsDcyKoPoaLhCk8RYYeeE3HiRE3sApEtsk5HYbh%20HUrR0IMQmTEUTh274ZyHEkU2cpJmSzGUfh4pCa4DEVi2tYSXxVEAGwUMRskiYm8nydx5FKt4UYugIvG4d6hHXpx8Y0Eyemmdu3o0ZZwliYp9mGQg7HOZpCmVqJbaMUpZlRoJ3n0VpOa2TZ7Y8di47%20Be-zcJ4XybE0Y7pKg4zuYgCAWRFflktelh8TlUZOdZNaFVMFgscA2IOFGiIeGyqDxZwiUQMlwFuBSNq5YiqTDH1TwDXmbKNQgOItQQbUJTIXVuD1I3KOVQ2qPY-VrUAA)
### Solution 2: Function overloading
```
type Bar = "bar"
type Qux = "qux"
function assert<T extends Bar[] = []>(
arg: (Qux | Bar)[] extends [...T, Qux] ? never : [...T, Qux]): [...T, Qux]
function assert<T extends Bar[] = []>(arg: [...T]): [...T]
function assert<T extends Bar[] = []>(arg: [...T, Qux?]) { return arg }
```
[Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQghgJygXigIgEaLQKFJKARQFcAPFdARzNxwDNiA7AY2AEsB7RqOAZ14gJgAHgAqUCKWARGAE16xEAbQC6FVQD4AFDih6eCAOYAuKFpLkAPooQBKVRKkz5UJQDoPogDREyagPxQjBAAboJQpu6ePhYqtpEebt6+pCr0TKyc3HwCQmKO0nIK8AgOqJpaiCauiaJxCZ5pDCzsXDz8giLikoUuJWWuKtpVDUkxZP5xUADeUAgQwMQI2UZQAL44OAD0W1AA8gDSOMxcvMBQHADWAIwUOZ1aqrbHp+dXAEx3HUKPmNhxL0YZwulwAzF9csBftRSGgAScgW9LgAWCEPJR-BBoHxoGFw54I4FXACsaJ+GKwWJxlOx6Bp8NeIIAbGSoRTsNSOXSubiaADtrtBAgOAheIDgULbqh7uTebCcXiGYiJAgEJ9pd82XLaZj8eLzkLwRrIb8aZyqVQaOa9YSDarUcb0brrQqrZbYXEgA)
---
TS 3.9 and older
----------------
If you really need rest parameters followed by a last element (the specification only allows them to be last, see @Nit's answer), here is an alternative:
### Assumptions
* A concrete array value is present and typed (e.g. `as const`)
* array size up to 256 elements (`StringToNumber` hardcoded size limit)
* You don't want to declare the `Bar`/`Qux` asserting type in a [recursive manner](https://github.com/microsoft/TypeScript/issues/26223): while technically possible, recursive types are not officially supported [till version 4.1](https://github.com/microsoft/TypeScript/pull/40002) (*Note: updated*).
### Code
```
type Bar = { bar: string };
type Qux = { qux: number };
// asserts Qux for the last index of T, other elements have to be Bar
type AssertQuxIsLast<T extends readonly any[]> = {
[K in keyof T]: StringToNumber[Extract<K, string>] extends LastIndex<T>
? T[K] extends Qux
? Qux
: never
: T[K] extends Bar
? Bar
: never;
};
// = calculates T array length minus 1
type LastIndex<T extends readonly any[]> = ((...t: T) => void) extends ((
x: any,
...u: infer U
) => void)
? U["length"]
: never;
// TS doesn't support string to number type conversions ,
// so we support (index) numbers up to 256
export type StringToNumber = {
[k: string]: number;
0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 37: 37, 38: 38, 39: 39, 40: 40, 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 47: 47, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 58: 58, 59: 59, 60: 60, 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 97: 97, 98: 98, 99: 99, 100: 100, 101: 101, 102: 102, 103: 103, 104: 104, 105: 105, 106: 106, 107: 107, 108: 108, 109: 109, 110: 110, 111: 111, 112: 112, 113: 113, 114: 114, 115: 115, 116: 116, 117: 117, 118: 118, 119: 119, 120: 120, 121: 121, 122: 122, 123: 123, 124: 124, 125: 125, 126: 126, 127: 127, 128: 128, 129: 129, 130: 130, 131: 131, 132: 132, 133: 133, 134: 134, 135: 135, 136: 136, 137: 137, 138: 138, 139: 139, 140: 140, 141: 141, 142: 142, 143: 143, 144: 144, 145: 145, 146: 146, 147: 147, 148: 148, 149: 149, 150: 150, 151: 151, 152: 152, 153: 153, 154: 154, 155: 155, 156: 156, 157: 157, 158: 158, 159: 159, 160: 160, 161: 161, 162: 162, 163: 163, 164: 164, 165: 165, 166: 166, 167: 167, 168: 168, 169: 169, 170: 170, 171: 171, 172: 172, 173: 173, 174: 174, 175: 175, 176: 176, 177: 177, 178: 178, 179: 179, 180: 180, 181: 181, 182: 182, 183: 183, 184: 184, 185: 185, 186: 186, 187: 187, 188: 188, 189: 189, 190: 190, 191: 191, 192: 192, 193: 193, 194: 194, 195: 195, 196: 196, 197: 197, 198: 198, 199: 199, 200: 200, 201: 201, 202: 202, 203: 203, 204: 204, 205: 205, 206: 206, 207: 207, 208: 208, 209: 209, 210: 210, 211: 211, 212: 212, 213: 213, 214: 214, 215: 215, 216: 216, 217: 217, 218: 218, 219: 219, 220: 220, 221: 221, 222: 222, 223: 223, 224: 224, 225: 225, 226: 226, 227: 227, 228: 228, 229: 229, 230: 230, 231: 231, 232: 232, 233: 233, 234: 234, 235: 235, 236: 236, 237: 237, 238: 238, 239: 239, 240: 240, 241: 241, 242: 242, 243: 243, 244: 244, 245: 245, 246: 246, 247: 247, 248: 248, 249: 249, 250: 250, 251: 251, 252: 252, 253: 253, 254: 254, 255: 255
};
```
### Tests
```
const arr1 = [{ bar: "bar1" }, { bar: "foo1" }, { qux: 42 }] as const
const arr2 = [{ bar: "bar2" }, { bar: "foo2" }] as const
const arr3 = [{ qux: 42 }] as const
const typedArr1: AssertQuxIsLast<typeof arr1> = arr1
const typedArr2: AssertQuxIsLast<typeof arr2> = arr2 // error (OK)
const typedArr3: AssertQuxIsLast<typeof arr3> = arr3
```
### Explanations
`AssertQuxIsLast` is a [mapped tuple type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#mapped-types-on-tuples-and-arrays). Each key `K` in `T` is an index of the form `"0"`,`"1"`,`"2"`, etc. . But this type is a `string`, not a `number`!
In order to assert `Qux` for the last index, we need to convert `K` back to `number` in order to compare it with `T['length']`, which returns the array length `number`. As the compiler doesn't support a dynamic [string to number conversion](https://github.com/microsoft/TypeScript/issues/26223) yet, we have created our own converter with `StringToNumber`.
[Playground](https://www.typescriptlang.org/play/#code/C4TwDgpgBAQghgJygXigbygI0QLigZ2AQEsA7AcygF8BuAWAChRIoBFAVwA8V0oBHLnlLsAtpghJajRgHoZUOPnwTg+NlygAzAPZJgAC2gAbRcChkAJhG7bNUACoAaKNoMSoEIxBERSqqPpwAG7QwNpY0PAIjMzQAIJKKhycAJL4ADKmADz2HpzAvhZqCBBwFtqkRiAKpCAA2gC6AHw8aIxQUHUA0uakUADWECC2Dg14AMpEZOT22gByouIIdQCi+QhwAMbAWV3OhCQUTQ15BaRFUJmEKefWOU3tHVAA-A7dJ9ZnF8mPTy-qnF+TyEEBC0QYfzw9nep0KaiiQNeCIhwKgpFBEnoDCkDFk8lQmzgRk27BMBTUuUQG2qXgoBigIjI7DUAEYYuBoFdgDcrJwcrDzsVSuVKtU4LVGi1UAAKaUAOgVwChAEoUC0gtpiBZVZ84VBZY9OHhxSBHI8FXL2HgyJp3ABVRiq5DqzXax6vO11ABEtPIBi9DUeILBWLxDnGUHKEHwpAA5GZ8OwwGBdAmphQoGE0Yt3LEoJsKmD8MQKmpALwbgFI9s0MOQEcIAd2gieTqf1lmsquEYgkaiTmfCACYAKwANkY1hTCDMecmhxm8xzSFQbRRdX6eAO0zG2e7CCxHQADHgD84WXgWc4B3gB84AMx4W-OAAseCfziHeCHzhHeBHzgA7Hg-7OAAHHgIHOAAnHgkGnkeUAsieCFnshp5XghN4IfeWGni+CFvghH6EaeP4IX+CGARRp5gQhEEIdB9GXvBA5IQOKFsZe6EDphA7Ybxl54QOBHDteX5QAOpESZelEDsB4k0QOdEDgxyl3vBt5IbeKFaXe6G3pht7YYZd54beBG3kRFl3qRt7kbelH2XeNG3nRt4MW5z7wU+SFPihvnPuhT6YU+2Ehc+eFPgRT5EdFz6kU+5FPpRSXPjRT50U+DGZe+8FDkhQ4oQV77oUOmFDth5XvnhQ4EUORF1e+pGju+lFDnJQ40R174MUOsFQCO8EDd+KEjhe-XoSOmEjth03fnhI4ESORFLd+pEjuRI6UZt340SOdEjgxB0AfB-5If+KHnQB6H-ph-7YXdAF4f+BH-kRr0AaR-7kf+lE-QBNH-nR-4McDoHwSBSEgShUOgehIGYSB2GI6BeEgQRIFERjoGkSB5EgZR+OgTRIF0SBDFk1B8GQUhkEobTUHoZBmGQdhLNQXhkEEZBRHc1BpGQeRkGUULUE0ZBdGQQxktwfBiFIYhKEK3B6GIZhiHYercF4YhBGIURetwaRiHkYhlGm3BNGIXRiEMTbp6IeeiH24rLJja7KssmrLIa979vayyussvrQf20bLImyyZuR-blsstbLK2wnaGyyxaGKxxGEq9xaEa-xGHa0JaH68OaFG1JGFm7JaGW4paG26pWGyxpp5aeeOlYSr+ktxrxlYdrZkt-rVlYUbtkt2bjlYZbLkt7bHn4bL3m4Yr-n4SrQW4RrYX4drkW4frsX4UbCW4WbKX4Zb6W4bb2WEbLeWngV55FYRKulY-GuVYR2s1Y-+sNYRI2zVCJmzao-S2XVCK216iRWWQ0yKK1GiRFWk0SIa1mmRbWC0SL6xWmRI260SJm22mRS2e0SK2yOhRWWp1TznXPJdCiKsbp0I1g9Ci2tnp0P1u9CiRsvp0LNn9CiltAZ0NtqDWissIbUUVjDWiKt4bUQ1sjWi2s0bUX1ljWiRtcbUTNoTWilsSbUVthTeistqanlpueem9EVZM2sRrNm9Ftac2sfrXm9EjYC2sWbEW9FLbi2sbbaW4kDzMQiUxdiB4xosS4geHiB4+LJKYoJA8wkDxERYmJFikkDzkRYjJA8ckWIKQPEpA8KkqmXgduJJ29T2Ku1qVxT2tS+K+3qYJAOtTskh3qZJcOtSZLR3qQpOOtSVJJ3Eixa8qcZnsQztxLi2cZl8TztxQShcZnZJLjMyS5duIySrjMhStcZkqQbrxZizdxKtzuXE-S14u53L4r3XigkB53OycPXikkx53JkpPXiCkZ53JUvPISzEl7iV8teVeQkuIb1hXxbeQlBJ71hdkw+QlJIn1hTJc+QkFJX1hSpW+w5mIP3Ek-GlcTSqiR4uVUSj4aWCV-jS7JdVGA4kYAWUghAFAIAQCyHgdQMDYAQHgL0kqWRemoM4CVuAoBeh0NoOVCreACCNFAIK1ATiKHzKWYAfLjVCoQAOMVSqpUqslQOeVVBFVYGVaq7Q2h7X6oUGoflhBTUCrMFSW8Vr+CCF1ZaqgBrvXGukAwH104OQWDiMKlCCRlBTmSGkLkWRYgjCpCyKU5q2SxrNbERNwr0KpqSFwTN2Qc12CpAOAtDaoC1gkAgXQ+oADyXRlR+sFaWpNCBsKVvTdWjItaOS5uFbeJt07GBAA) | Since in Javascript the [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) are only allowed as the last parameter, the same approach was historically adopted for types in Typescript.
There are longstanding tickets to remove this limitation for types, see [here](https://github.com/microsoft/TypeScript/issues/25717) and [here](https://github.com/microsoft/TypeScript/issues/1360), however at the moment, it's still not supported.
Given you [can't strictly define specific-followed-by-rest tuples](https://stackoverflow.com/a/44402762/1470607) in Typescript, there doesn't seem to be a straightforward way to implement this until the functionality is added to Typescript itself.
Alternatively, you can manually generate a comfortable number of valid type lists in a separate build step, but at that point I doubt the gained value is worth it. |