qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
10,764,160 | How can I draw a simple BAR?
Like this:

Thank you. | 2012/05/26 | [
"https://Stackoverflow.com/questions/10764160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962508/"
] | $date = date('d/m/Y');
$date = strtotime($date); //in unix time stamp format | Basically american date format is `MM/DD/YYYY` and you are providing `DD/MM/YYYY` so thats why `startotime()` returns you a null values on this input; and i prefer you must follow standard date format of american `(MM/DD/YYYY)` because if you are using mentioned format of date that will create more problems as well in different places ..
if you check by this
```
echo date('Y-m-d', strtotime('05/26/2012') );
```
and it is working fine .. |
10,764,160 | How can I draw a simple BAR?
Like this:

Thank you. | 2012/05/26 | [
"https://Stackoverflow.com/questions/10764160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962508/"
] | Use MySQL's [`STR_TO_DATE()`](http://dev.mysql.com/doc/en/date-and-time-functions.html#function_str-to-date) function:
```
INSERT INTO my_table VALUES (STR_TO_DATE('26/5/12', '%e/%c/%y'))
``` | Try this:
```
$mysqldate = date("m/d/y g:i A", $datetime);
``` |
137,563 | What's the best way to place a page-sized figure including the correct caption numbering on the facing page of a chapter opening page?
Correct numbering means: if I put the figure before the chapter, the numbering of the previous chapter is continued and the list of figures shows it belonging to the previous chapter. But I want to have it labeled 6.1 if the new chapter will be chapter 6.
Now I was thinking: Is there a way to use a caption(command) that will only be defined later? Is there a package that does something like this already?
In essence, something like this:
```
\cleartoevenpage{\thispagestyle{empty}}
\begin{figure}[p]
\begin{sidecaption}{\theCaption} % TODO: how?
\includegraphics{image.jpg}
\end{sidecaption}
\end{figure}
\chapter{Chapter Title}
\defineTheCaption
```
Or, if that is not possible, how can I manually label the figure as if belonging to the next chapter, with the correct entry in the lof file?
PS: I am using memoir. The kind of opposite thing seems possible with \newfixedcaption: it allows to place a caption on a page preceding a figure. | 2013/10/12 | [
"https://tex.stackexchange.com/questions/137563",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/12493/"
] | You can (and should) define a command doing the work, rather than explicitly set all those commands for each chapter.
My idea is to define a `\chapterfigure` command that has one optional argument and two mandatory ones; the optional argument and the first mandatory one are used for `\includegraphics`, while the final argument contains the caption.
The command steps the `chapter` counter, so the number for the figure will be correct; after the figure the counter is stepped back, so when `\chapter` is processed, the chapter number will be right; then we patch `\memendofchapterhook` so that it steps the `figure` counter (that would have been reset to zero by `\chapter`) and redefines itself to its previous value (usually nothing, but one never knows). Similarly, we issue `\insertchapterspace`, then redefine it to simply redefine itself to its previous value, so when the command is called by `\chapter` it does nothing else than putting us back to the original situation.
For a chapter without a facing figure, just issue `\chapter` by itself. A label for `\chapterfigure` should be in a trailing optional argument, to reflect the syntax of `sidecaption`; so
```
\chapterfigure[<options for includegraphics>] % optional
{<graphic file name>} % mandatory
{<caption>} % mandatory
[<label>] % optional
```
Here's a complete example
```
\documentclass{memoir}
\usepackage{xparse}
\usepackage[demo]{graphicx}
\NewDocumentCommand{\chapterfigure}{O{} m m o}{%
\insertchapterspace
\cleartoevenpage{\thispagestyle{empty}}
\stepcounter{chapter}
\begin{figure}[p]
\IfNoValueTF{#4}
{\begin{sidecaption}{#3}}
{\begin{sidecaption}{#3}[#4]}
\includegraphics[#1]{#2}
\end{sidecaption}
\end{figure}
\addtocounter{chapter}{-1}
\let\keptmemendofchapterhook\memendofchapterhook
\renewcommand{\memendofchapterhook}{%
\stepcounter{figure}%
\keptmemendofchapterhook
\let\memendofchapterhook\keptmemendofchapterhook}%
\let\keptinsertchapterspace\insertchapterspace
\renewcommand\insertchapterspace{%
\let\insertchapterspace\keptinsertchapterspace}%
}
\begin{document}
\frontmatter
\tableofcontents
\listoffigures
\mainmatter
\chapterfigure[width=5cm,height=3cm]{somepic}
{A caption for this figure}
% Here's how to call it if there's a label
%\chapterfigure[width=5cm,height=3cm]{somepic}
% {A caption for this figure}[chapfig:one]
\chapter{A title for this chapter}
Some text
\begin{figure}[htp]
\centering
\includegraphics{xyz}
\caption{A caption to see it has the correct number}
\end{figure}
Some text
\end{document}
```
 | Here is a simple approach that I used (thanks to some hints here) to putting a landscape figure opposite a Chapter page, and numbering it as the first figure in that chapter:
```
% For viewing in Adobe Reader, don’t forget to set View> Page Display > Show Cover Page in Two-Page View
\documentclass[draft,12pt,letterpaper,dvipsnames,svgnames,table,openright,twoside]{book}
\usepackage{pdflscape} % Has landscape environment
\usepackage{graphicx}
\graphicspath{{./images/}}
\usepackage{caption}
\usepackage{lettrine}
\usepackage{calligra}
\usepackage[nopar]{lipsum}
%
\begin{document}
\renewcommand{\LettrineFontHook}{\calligra}
% PREFACE
\chapter*{Preface}
\lipsum[2-4]
% CHAPT 1
% \section[shortish TOC entry]{formatted chapter title} \sectionmark{short title for running headers}
\chapter{Dummy Chapter}
\lipsum[2-4]
%
% CHAPT 2
\makeatletter\@openrightfalse %%%%
\newpage
\cleardoublepage\part[~STONE AGE]{STONE AGE}
%
% The following page is rotated 90-degrees clockwise in the pdf.
% In the book it appears on the LHS, opposite the section “Chapter 16”
\stepcounter{chapter}
\begin{landscape}
\begin{figure}
\captionsetup{width=1.20\textwidth}
%\vspace{12pt} % To move picture further away from binding (odd page)
\vspace{-36pt} % To move picture further away from binding (even page)
\centering
\includegraphics[width=6in]{US_Frequency_Allocations_Jan_2016_a.png}
\caption[U.S. Electromagnetic Spectrum Frequency Allocations, October 2003]{U.S. Electromagnetic Spectrum usage from DC to 300 GHz}
\scriptsize{\emph{Photo Credit: U.S. Government, Department of Commerce}}
\label{figure:FCC_EM_Radio_Spectrum}
\end{figure}
\end{landscape}
\addtocounter{chapter}{-1}
\newpage
% \section[shortish TOC entry]{formatted chapter title} \sectionmark{short title for running headers}
\chapter{2001: Welcome to Space \& Beyond!}
\label{section:DC2Daylight}
\@openrighttrue\makeatother
% Body Text:
\lettrine[lines=3,lhang=0.33,lraise=0.0,loversize=0.30,slope=-16pt,findent=2.3em,nindent=-0.4em]{U}{\textbf{nknown Origins}} \lipsum[1-5]
%
\end{document}
\endinput
``` |
21,840,504 | My confusion is not new here or arround the web, yet, i have some questions for which i did not find answers anywhere:
The first question is:
>
> Why is Inherits necessary on CodeFile and not on CodeBehind?
>
>
>
I read: <http://msdn.microsoft.com/en-us/library/vstudio/ms178138(v=vs.100).aspx> and some more pages, and i understand that CodeFile is for source code and for compilation on the fly while the other is for an assembly. This raised me another question:
>
> Why do everyone say that CodeBehind must be an assembly if i find
> File.aspx.cs everywhere including in a test project i have and it
> works like a charm? Is this a compiled assembly?
>
>
>
But, as of the first question, and based on the url i supplied, i might understand, why the Inherits is necessary. I assume the compiler must know what is the name of the partial class to compile later. Makes sense. Yet, shouldn't it be necessary on CodeBehind as well? If we are going to merge the partial classes, i suppose i should give the name of the one i want to merge. I even tried adding another partial class to the .cs file and it compiled/ran well.
Am I missing something here?
I also read that CodeBehind is not used anymore and it's CodeFile, the new one.
Any .NET guru to help me?
Thank you all in advance.
**UPDATED:**
I tried to implement events using no Inherits on CodeBehind. It didn't work. This makes more sense. But, it doesn't complain on compilation, while CodeFile does. Is there any reason for this? | 2014/02/17 | [
"https://Stackoverflow.com/questions/21840504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1646155/"
] | Not sure about rows, the rest can be found via the [Information Schema](http://technet.microsoft.com/en-us/library/ms186778.aspx)
```
select Table_Name, COUNT(Column_Name) As NumberOfColumns
from INFORMATION_SCHEMA.COLUMNS
where table_catalog = @DBName
group by Table_Name
``` | i think you are asking about number of rows in a table
look at this
```
$dbhost = 'localhost';
$dbname = 'modify this';
$dbuser = 'and this';
$dbpass = 'and this';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die('can not connect to sql');
mysql_select_db($dbname) or die('can not select db');
$res=mysql_query("SELECT * FROM table");
$rows=mysql_num_rows($res);
echo $rows;//outputs a number (the number of rows in a table)
``` |
21,840,504 | My confusion is not new here or arround the web, yet, i have some questions for which i did not find answers anywhere:
The first question is:
>
> Why is Inherits necessary on CodeFile and not on CodeBehind?
>
>
>
I read: <http://msdn.microsoft.com/en-us/library/vstudio/ms178138(v=vs.100).aspx> and some more pages, and i understand that CodeFile is for source code and for compilation on the fly while the other is for an assembly. This raised me another question:
>
> Why do everyone say that CodeBehind must be an assembly if i find
> File.aspx.cs everywhere including in a test project i have and it
> works like a charm? Is this a compiled assembly?
>
>
>
But, as of the first question, and based on the url i supplied, i might understand, why the Inherits is necessary. I assume the compiler must know what is the name of the partial class to compile later. Makes sense. Yet, shouldn't it be necessary on CodeBehind as well? If we are going to merge the partial classes, i suppose i should give the name of the one i want to merge. I even tried adding another partial class to the .cs file and it compiled/ran well.
Am I missing something here?
I also read that CodeBehind is not used anymore and it's CodeFile, the new one.
Any .NET guru to help me?
Thank you all in advance.
**UPDATED:**
I tried to implement events using no Inherits on CodeBehind. It didn't work. This makes more sense. But, it doesn't complain on compilation, while CodeFile does. Is there any reason for this? | 2014/02/17 | [
"https://Stackoverflow.com/questions/21840504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1646155/"
] | This one gets the rows but won't show the column count:
```
sp_MSforeachtable @command1="select count(*) from ?"
```
(from here <http://www.sqlservercentral.com/Forums/Topic271576-5-1.aspx>) | i think you are asking about number of rows in a table
look at this
```
$dbhost = 'localhost';
$dbname = 'modify this';
$dbuser = 'and this';
$dbpass = 'and this';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die('can not connect to sql');
mysql_select_db($dbname) or die('can not select db');
$res=mysql_query("SELECT * FROM table");
$rows=mysql_num_rows($res);
echo $rows;//outputs a number (the number of rows in a table)
``` |
4,769,973 | There are number of REST frameworks around for ASP.NET MVC. Which one is the most mature in your opinion? Following are few I briefly looked at, but I couldn't decide.
1. [Snooze](http://www.assembla.com/wiki/show/snooze)
2. [BistroMVC](http://bistroframework.org/index.php?title=Bistro_Framework_Home)
3. [Restful Service with WCF](http://msdn.microsoft.com/en-us/netframework/cc950529)
4. [OpenRasta](http://openrasta.org)
5. [Siesta](http://kohari.org/2009/08/10/siesta-painless-rest-via-asp-net-mvc/)
6. [REST support build in ASP.Net MVC SDK](http://weblogs.asp.net/cibrax/archive/2009/04/17/developing-restful-services-with-json-and-pox-support-in-the-asp-net-mvc.aspx)
.... there are few more. | 2011/01/22 | [
"https://Stackoverflow.com/questions/4769973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282566/"
] | Personally I would go with the default ASP.NET routing engine which is built and supported by Microsoft. This will ensure that you won't find yourself one day into the position of having to migrate some code which has become obsolete because the authors simply decided to abandon the project. Of course if there is something specific that you want to implement which isn't supported out of the box you could search for alternatives. But as far as exposing a RESTful API is concerned the routing engine should work just fine. | I completely agree with Darin.
But if you're looking for something closer to what WCF offers (Web service, versus a typical Web site), I've been extremely happy with WCF REST.
There's a WCF REST Service Template available via Visual Studio's Extension Manager that will get you up and running fairly quickly. |
4,769,973 | There are number of REST frameworks around for ASP.NET MVC. Which one is the most mature in your opinion? Following are few I briefly looked at, but I couldn't decide.
1. [Snooze](http://www.assembla.com/wiki/show/snooze)
2. [BistroMVC](http://bistroframework.org/index.php?title=Bistro_Framework_Home)
3. [Restful Service with WCF](http://msdn.microsoft.com/en-us/netframework/cc950529)
4. [OpenRasta](http://openrasta.org)
5. [Siesta](http://kohari.org/2009/08/10/siesta-painless-rest-via-asp-net-mvc/)
6. [REST support build in ASP.Net MVC SDK](http://weblogs.asp.net/cibrax/archive/2009/04/17/developing-restful-services-with-json-and-pox-support-in-the-asp-net-mvc.aspx)
.... there are few more. | 2011/01/22 | [
"https://Stackoverflow.com/questions/4769973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282566/"
] | Personally I would go with the default ASP.NET routing engine which is built and supported by Microsoft. This will ensure that you won't find yourself one day into the position of having to migrate some code which has become obsolete because the authors simply decided to abandon the project. Of course if there is something specific that you want to implement which isn't supported out of the box you could search for alternatives. But as far as exposing a RESTful API is concerned the routing engine should work just fine. | OpenRasta
Have been implementing RESTFul service using OR, only one word to describe it => "Pure Awesomeness" ....actually it's 2 words.
For me the simplicity is a plus, the framework is easy to use and adopt to. Some of it's conventions in my opinion really help me to understand Resful. Many integration points in the framework, very easy to extend its functionalists.
watching video recordings of seb's talk is very entertaining as well :) very opinionated (in a good way IMO) |
4,769,973 | There are number of REST frameworks around for ASP.NET MVC. Which one is the most mature in your opinion? Following are few I briefly looked at, but I couldn't decide.
1. [Snooze](http://www.assembla.com/wiki/show/snooze)
2. [BistroMVC](http://bistroframework.org/index.php?title=Bistro_Framework_Home)
3. [Restful Service with WCF](http://msdn.microsoft.com/en-us/netframework/cc950529)
4. [OpenRasta](http://openrasta.org)
5. [Siesta](http://kohari.org/2009/08/10/siesta-painless-rest-via-asp-net-mvc/)
6. [REST support build in ASP.Net MVC SDK](http://weblogs.asp.net/cibrax/archive/2009/04/17/developing-restful-services-with-json-and-pox-support-in-the-asp-net-mvc.aspx)
.... there are few more. | 2011/01/22 | [
"https://Stackoverflow.com/questions/4769973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282566/"
] | Personally I would go with the default ASP.NET routing engine which is built and supported by Microsoft. This will ensure that you won't find yourself one day into the position of having to migrate some code which has become obsolete because the authors simply decided to abandon the project. Of course if there is something specific that you want to implement which isn't supported out of the box you could search for alternatives. But as far as exposing a RESTful API is concerned the routing engine should work just fine. | I agree with Darin. Personally, I think [Apache Thrift](http://thrift.apache.org/) is also an option for doing client and server communication. |
47,663,333 | I want to go through my ArrayList of ArrayLists and remove all the ones that are empty. Is there a fast and efficient way to do this, other then I guess a for loop?
Example Ouput:
>
> [ [alec, joe, ray], [], [eric, jacob], [] ]
>
>
>
Would then look like this:
>
> [ [alec, joe, ray], [eric, jacob] ]
>
>
> | 2017/12/05 | [
"https://Stackoverflow.com/questions/47663333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6950859/"
] | something like this should suffice.
```
nestedArrayList = nestedArrayList.stream()
.filter(e -> !e.isEmpty())
.collect(Collectors.toCollection(ArrayList::new));
```
or as Zabuza has suggested, you could use `removeIf`:
```
nestedArrayList.removeIf(ArrayList::isEmpty);
```
IMHO I'd go with the second approach for a couple of reasons but most importantly reading it like *"nestedArrayList remove if ArrayList is empty"* provides better intent of the code and easier to understand. | Lambdas above as posted by Aomine or iterator like this:
```
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> lista = new ArrayList<>(){{
add(new ArrayList<>(Arrays.asList(1,2,3)));
add(new ArrayList<>());
}};
Iterator<ArrayList<Integer>> iter = lista.iterator();
while(iter.hasNext()){
if (iter.next().isEmpty())
iter.remove();
}
System.out.println(lista);
}
}
``` |
43,412 | I want to accomplish network shown in image. 
1.Local can access servers
2.internet can access servers with limited ports and cannot connect to local network
3.I have only 1 public static ip so i cannot place firewall between router and isp
4. My firewall is small so I couldn't able to use firewall as my main network gateway
The question is firewall's traffic will be same as gateway or the small firewall can handle it as shown in image?
Is there other good solution?
Can i do it with only router? | 2017/08/20 | [
"https://networkengineering.stackexchange.com/questions/43412",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/30186/"
] | Your stack switches should be connected to both routers. That way, you will have redundancy if a router fails. If possible, your servers should also be dual-homed to both routers. VRRP will do you no good unless you are connected to both routers.
Unless you intend to apply access lists to restrict data flows between user groups, creating lots of VLANs doesn't buy you much. There's no hard and fast rule here -- just don't make it more complicated than necessary.
You don't mention what your load balancer will be used for, so it's hard to say where it belongs. | ATT usually hands off their network as a private address. You may be able to use layer 3 switches in place of the routers and do a combined core and distribution at those switches if the network isn't very big. It can save money, you can stack most with a modules or special cables, you get fast routing, less chance of bottle necks than "router on a stick" and give you more ports. Just be sure you don't need complex routing and they meet your routing needs. Normally, your distribution layer would connect to two routers if your doing a first hop redundancy protocol like hsrp, vrrp or glbp. But, if you do the combined core/distribution design you will connect your access layer switched to both layer three switches but since they are stacked you wouldn't necessarily need vrrp. You could create your gateways at the vlan interface (svis) and put the vlan s on the uplink ports (one on each switch). Again, this depends on the size of network and your routing needs. I have set up many networks this way. |
43,412 | I want to accomplish network shown in image. 
1.Local can access servers
2.internet can access servers with limited ports and cannot connect to local network
3.I have only 1 public static ip so i cannot place firewall between router and isp
4. My firewall is small so I couldn't able to use firewall as my main network gateway
The question is firewall's traffic will be same as gateway or the small firewall can handle it as shown in image?
Is there other good solution?
Can i do it with only router? | 2017/08/20 | [
"https://networkengineering.stackexchange.com/questions/43412",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/30186/"
] | Your stack switches should be connected to both routers. That way, you will have redundancy if a router fails. If possible, your servers should also be dual-homed to both routers. VRRP will do you no good unless you are connected to both routers.
Unless you intend to apply access lists to restrict data flows between user groups, creating lots of VLANs doesn't buy you much. There's no hard and fast rule here -- just don't make it more complicated than necessary.
You don't mention what your load balancer will be used for, so it's hard to say where it belongs. | "Also, I want to install Load Balancer but I don't know where should I put it, behind routers/switches or Firewall?"
As Ron Trunk mentioned, you didn't specify what you want to do with the load balancer. If you are using it for a combination of traffic and redundancy, then in-line behind the firewall would allow traffic to flow smoothly and offer alternative routes in the event of an outage.
The VLAN setup you've shown will do some balancing on it's own, but I do wonder if the perceived benefit of that many VLANs is balanced by the setup and maintenance for them. You don't mention how many geo-locations are shown here, but that is another way to think of segmenting your network.
You can get more information from the documentation pages at f5.com, or Cisco's docwiki.cisco.com, perhaps thinking up some options will lead you to the best fit. |
39,648 | When I'm opening .avi files, I want to open them with VLC Media player, when right clicking the item, I see this:

As you can see QuickTime is the default player, I want to change it to VLC, so I change it:

After changing it, every .avi I open gets opened by VLC, however, when I reboot my Mac, the default goes back to QuickTime... how do I prevent this and keep VLC as the default. | 2012/02/07 | [
"https://apple.stackexchange.com/questions/39648",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/2677/"
] | I was doing it the wrong way like you try to for a long time and also have retreated to using RCDefaultApp in the past... but there's actually a way to do that natively which works.
Do the following:
```
1) right click your file
2) choose "Get Info"
3) in the popup find the "Open with" strip (this is by default closed) and open it
4) from the drop down choose the program you want to open that type of file
5) click "Change all..."
```
And that's the correct way to do it | There's a great preference pane [RCDefaultApp](http://www.rubicode.com/Software/RCDefaultApp/). It should do what you want.
>
> RCDefaultApp is a Mac OS X 10.2 or higher preference pane that allows a user to set the default application used for various URL schemes, file extensions, file types, MIME types, and Uniform Type Identifiers (or UTIs; MacOS 10.4 only). MacOS X uses the extension and file type settings to choose the application when opening a file in Finder, while Safari and other applications use the URL and MIME type settings at other times for content not related to a file (such as an unknown URL protocol, or a media stream).
>
>
> |
39,648 | When I'm opening .avi files, I want to open them with VLC Media player, when right clicking the item, I see this:

As you can see QuickTime is the default player, I want to change it to VLC, so I change it:

After changing it, every .avi I open gets opened by VLC, however, when I reboot my Mac, the default goes back to QuickTime... how do I prevent this and keep VLC as the default. | 2012/02/07 | [
"https://apple.stackexchange.com/questions/39648",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/2677/"
] | There's a great preference pane [RCDefaultApp](http://www.rubicode.com/Software/RCDefaultApp/). It should do what you want.
>
> RCDefaultApp is a Mac OS X 10.2 or higher preference pane that allows a user to set the default application used for various URL schemes, file extensions, file types, MIME types, and Uniform Type Identifiers (or UTIs; MacOS 10.4 only). MacOS X uses the extension and file type settings to choose the application when opening a file in Finder, while Safari and other applications use the URL and MIME type settings at other times for content not related to a file (such as an unknown URL protocol, or a media stream).
>
>
> | For anyone Googling for the same issue: as the venerable RCDefaultApp is now broken under 10.12 and later, there's a open-source equivalent [SwiftDefaultApp](https://github.com/Lord-Kamina/SwiftDefaultApps)
>
> This Preference pane is chiefly intended to be a modern replacement for the amazing RCDefaultApp developed way back when by Carl Lindberg, which stopped working in 10.12 due to deprecation of ObjC Garbage collection
>
>
> ...
>
>
> This Preference pane will let you view and change default application
> associations for basically any URI Scheme and/or filetype in macOS.
>
>
>
The UI is practically identical to RCDefaultApps, exception that "Extensions" (i.e. file extensions) is now rolled into "Uniform Type Identifiers", and it can be a little harder to find a specific extension. However, it works beautifully, both as a solution to the issue and as a replacement for RCDefaultApp. |
39,648 | When I'm opening .avi files, I want to open them with VLC Media player, when right clicking the item, I see this:

As you can see QuickTime is the default player, I want to change it to VLC, so I change it:

After changing it, every .avi I open gets opened by VLC, however, when I reboot my Mac, the default goes back to QuickTime... how do I prevent this and keep VLC as the default. | 2012/02/07 | [
"https://apple.stackexchange.com/questions/39648",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/2677/"
] | I was doing it the wrong way like you try to for a long time and also have retreated to using RCDefaultApp in the past... but there's actually a way to do that natively which works.
Do the following:
```
1) right click your file
2) choose "Get Info"
3) in the popup find the "Open with" strip (this is by default closed) and open it
4) from the drop down choose the program you want to open that type of file
5) click "Change all..."
```
And that's the correct way to do it | For anyone Googling for the same issue: as the venerable RCDefaultApp is now broken under 10.12 and later, there's a open-source equivalent [SwiftDefaultApp](https://github.com/Lord-Kamina/SwiftDefaultApps)
>
> This Preference pane is chiefly intended to be a modern replacement for the amazing RCDefaultApp developed way back when by Carl Lindberg, which stopped working in 10.12 due to deprecation of ObjC Garbage collection
>
>
> ...
>
>
> This Preference pane will let you view and change default application
> associations for basically any URI Scheme and/or filetype in macOS.
>
>
>
The UI is practically identical to RCDefaultApps, exception that "Extensions" (i.e. file extensions) is now rolled into "Uniform Type Identifiers", and it can be a little harder to find a specific extension. However, it works beautifully, both as a solution to the issue and as a replacement for RCDefaultApp. |
65,084,907 | ```
if(edatevalue=="") // **checking if edatevalue is blank**
{
edatevalue = now; // **set edatevalue to now time**
}
else
{
edate = edatevalue; // **assign edatevalue to edate variable**
}
if(sdatevalue=="") // **check if sdatevalue is blank**
{
sdatevalue=0; // **assign 0 to sdatevalue**
}
else
{
sdate = sdatevalue; // **assign sdatevalue to sdate variable**
}
var partmsg=""; // **create variable partmsg as blank**
if(sdate==0) // **check if sdate is = 0**
{
partmsg = "where timestamp between " + sdate " and " + edate; // **create string in variable partmsg**
}
var query = "";
if(topic=="submit")
{
query = "select * from energymonitoring limit 10 ";
query = query+partmsg;
}
var msg1 = {topic:query};
return msg1;
```
i am trying to troubleshoot the **"missing ; before statement"** on line `"partmsg = "where timestamp between " + sdate " and " + edate;"`
Edit: I have since then amended accordingly to @Ken Lee's example. | 2020/12/01 | [
"https://Stackoverflow.com/questions/65084907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14519443/"
] | The reason why you are not able to remove all the elements is that when you are removing an element from the array the `j` value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
```py
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
```
Output
```
3
5
[4,6]
```
As you can see in this output `print(j)` does not print all the elements, it only prints `3` and `5`. So only `3` and `5` are removed.
**How to solve it?**
So you can either use `clear()`, like this
```
lis.clear()
```
Or if you want to use iteration you can do it with `pop()` like this
```
for i in range(len(lis)):
lis.pop(i)
```
Or you can create a shallow copy of the list and `remove()` the elements one by one like this
```
for i in list(lis):
lis.remove(i)
```
Or you can use `:` to return the whole slice of the array (copy of the array)
```
for i in x[:]:
x.remove(i)
``` | use clear to clear all the element of the list
```
lis =[3,4,5,6]
lis.clear()
print(lis)
```
Output:
```
[]
``` |
65,084,907 | ```
if(edatevalue=="") // **checking if edatevalue is blank**
{
edatevalue = now; // **set edatevalue to now time**
}
else
{
edate = edatevalue; // **assign edatevalue to edate variable**
}
if(sdatevalue=="") // **check if sdatevalue is blank**
{
sdatevalue=0; // **assign 0 to sdatevalue**
}
else
{
sdate = sdatevalue; // **assign sdatevalue to sdate variable**
}
var partmsg=""; // **create variable partmsg as blank**
if(sdate==0) // **check if sdate is = 0**
{
partmsg = "where timestamp between " + sdate " and " + edate; // **create string in variable partmsg**
}
var query = "";
if(topic=="submit")
{
query = "select * from energymonitoring limit 10 ";
query = query+partmsg;
}
var msg1 = {topic:query};
return msg1;
```
i am trying to troubleshoot the **"missing ; before statement"** on line `"partmsg = "where timestamp between " + sdate " and " + edate;"`
Edit: I have since then amended accordingly to @Ken Lee's example. | 2020/12/01 | [
"https://Stackoverflow.com/questions/65084907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14519443/"
] | The reason why you are not able to remove all the elements is that when you are removing an element from the array the `j` value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
```py
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
```
Output
```
3
5
[4,6]
```
As you can see in this output `print(j)` does not print all the elements, it only prints `3` and `5`. So only `3` and `5` are removed.
**How to solve it?**
So you can either use `clear()`, like this
```
lis.clear()
```
Or if you want to use iteration you can do it with `pop()` like this
```
for i in range(len(lis)):
lis.pop(i)
```
Or you can create a shallow copy of the list and `remove()` the elements one by one like this
```
for i in list(lis):
lis.remove(i)
```
Or you can use `:` to return the whole slice of the array (copy of the array)
```
for i in x[:]:
x.remove(i)
``` | A correct solution will be to create a shallow copy with the help of `list()` function.
```
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
```
Output
```
[]
``` |
12,744,483 | Our control system has a lot of data files that have specific versions. The data files are "append only", so a higher version will always contain a superset of the definitions in the earlier versions.
In order to avoid "magic numbers" in our code, we have created a code generator that take a piece of data and turns it into a C# class file. I have a pretty large class library containing pretty much only such files. This results in much more readable code and some additional compiler checks because type previously risky type casting can now be part of the generated code, so that users of the library consume their correct subtypes directly.
However, the question comes up what data file version was used in the latest version of the class library. I would like every class file to "contribute" to a global list. If static constructors were automatically run, this is what I would do:
```
// GlobalConstants.cs (not generated)
public static partial class GlobalConstants
{
public static List<string> Lst = new List<string>();
static void AddVersionInfo(string mod)
{
Lst.Add(mod);
}
}
// Motor.cs
public static partial class GlobalConstants
{
// Generated from Motor metadata
public class MotorUtil
{
public const int SomeConst1 = 2;
static MotorUtil()
{
AddVersionInfo("<Motor version info>");
}
}
}
// Tank.cs
public static partial class GlobalConstants
{
// Generated from Tank metadata
public class TankUtil
{
public const int SomeConst1 = 2;
public const int SomeConst2 = 3;
public const int SomeConst3 = 5;
static TankUtil()
{
AddVersionInfo("<Tank version info>");
}
}
}
```
If static constructors where run automatically, this would result in every generated file (tank.cs, motor.cs, boiler.cs etc) being added to the list, which could be inspected by a tool.
A compile time MEF, if you like.
Unfortunately. If I print out contents of "Lst", then it's always an empty list because the static constructors haven't run.
These .cs files come from different parties and the author of GlobalConstants.cs should not be required to know about them.
My question is: Is there a way in which I can generate this code so that one can add generated .cs files at will and they will appear in the "Lst" list? | 2012/10/05 | [
"https://Stackoverflow.com/questions/12744483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80577/"
] | The static constructors for each of your nested classes won't run until those nested classes are referenced for the first time. That hasn't happened in your above code, hence the list is empty.
One way I could imagine you might be able to do this would be for a static initializer in the `GlobalConstants` class to use reflection to find the nested classes.
Or maybe you could add a static field in each partial class file that references the nested class, forcing its static constructor to run:
```
public static partial class GlobalConstants
{
// Generated from Tank metadata
private static TankUtil _unusedTankUtilField = new TankUtil();
public class TankUtil
{
public const int SomeConst1 = 2;
public const int SomeConst2 = 3;
public const int SomeConst3 = 5;
static TankUtil()
{
AddVersionInfo("<Tank version info>");
}
}
}
```
Also I don't believe the order of execution of static initializers across partial class files is strictly defined (presumably corresponds to the order they are processed by the compiler). So I'd suggest you make your "AddVersionInfo" method responsible for initializing the list:
```
public static partial class GlobalConstants
{
public static List<string> Lst;
static void AddVersionInfo(string mod)
{
if (Lst == null) Lst = new List<string>();
Lst.Add(mod);
}
}
``` | For a somewhat simpler syntax, you could do it using attributes instead of static classes.
If you define an attribute;
```
public class UtilVersionAttribute : Attribute
{
private readonly string _versionInfo;
public UtilVersionAttribute(string versionInfo) { _versionInfo = versionInfo; }
public string VersionInfo { get { return _versionInfo; } }
}
```
...you can just attribute the classes instead...
```
public static partial class GlobalConstants
{
[UtilVersion("<Motor version info>")]
public class MotorUtil
{
public const int SomeConst1 = 2;
}
}
```
...and update it when the program first starts using...
```
static void UpdateVersionInfo(Assembly assembly)
{
foreach (Type type in assembly.GetTypes())
{
var attribute =
type.GetCustomAttributes(typeof (UtilVersionAttribute), true)
.FirstOrDefault();
if(attribute != null)
GlobalConstants.Lst.Add((attribute as UtilVersionAttribute).VersionInfo);
}
}
static void Main(string[] args)
{
var assembly = Assembly.GetExecutingAssembly();
UpdateVersionInfo(assembly);
GlobalConstants.Lst.ForEach(Console.WriteLine);
}
```
...for a complete list of your versions.
MEF may help here too, you may want to consider using it instead of implementing a "light version". Even your static constructor registrations are runtime registrations, not compile time, so I'm not sure of your reasons for staying away from it. |
28,671,753 | I'm trying to create mocks for my login procedure. I use POST method with a couple of fields and login object (with login, password, etc.)
For that I'm using JsonPath. Code below:
```
{
"request": {
"method": "POST",
"url": "/login",
"bodyPatterns" : [
{"matchesJsonPath" : "$.method"},
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
{"matchesJsonPath" : "$.params.login"},
{"matchesJsonPath" : "$.params.password"}
]
},
"response": {
"status": 200,
"bodyFileName": "login.json"
}
}
```
I'm checking the clientVersion because it's similar to the examples.
My problem is, that with te given POST JSON:
```
{
"method": "login",
"params": {
"clientVersion": "1",
"login": "test@test.com",
"password": "681819535da188b6ef2"
}
}
```
I receive 404.
However, when I change
```
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
```
to normal
```
{"matchesJsonPath" : "$.params.clientVersion"},
```
everything works just fine.
So - how to check inside wiremock, using matchesJsonPath if given field equals some value?
How to apply it to the root field like method in my case?
And while we're at it - I had similar problems with checking if the value is not null. I tried to apply regular expressions and such - no luck. | 2015/02/23 | [
"https://Stackoverflow.com/questions/28671753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812056/"
] | Following worked for me.
`"matchesJsonPath" : "$.rootItem.itemA[0].item..[?(@.fieldName=='file')]"`
Json :
```
{
"rootItem" : {
"itemA" : [
{
"item" : {
"fieldName" : "file",
"name" : "test"
}
}
]
}
}
```
Wiremock
```
{
"request" : {
"urlPattern" : "/testjsonpath",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$.rootItem.itemA[0].item..[?(@.fieldName=='file')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"result\": \"success\"}",
"headers" : {
"Content-Type" : "application/json"
}
}
}
``` | try with double dots operator (recursive)
```
$..params[?(@.clientVersion == "1")]
``` |
28,671,753 | I'm trying to create mocks for my login procedure. I use POST method with a couple of fields and login object (with login, password, etc.)
For that I'm using JsonPath. Code below:
```
{
"request": {
"method": "POST",
"url": "/login",
"bodyPatterns" : [
{"matchesJsonPath" : "$.method"},
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
{"matchesJsonPath" : "$.params.login"},
{"matchesJsonPath" : "$.params.password"}
]
},
"response": {
"status": 200,
"bodyFileName": "login.json"
}
}
```
I'm checking the clientVersion because it's similar to the examples.
My problem is, that with te given POST JSON:
```
{
"method": "login",
"params": {
"clientVersion": "1",
"login": "test@test.com",
"password": "681819535da188b6ef2"
}
}
```
I receive 404.
However, when I change
```
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
```
to normal
```
{"matchesJsonPath" : "$.params.clientVersion"},
```
everything works just fine.
So - how to check inside wiremock, using matchesJsonPath if given field equals some value?
How to apply it to the root field like method in my case?
And while we're at it - I had similar problems with checking if the value is not null. I tried to apply regular expressions and such - no luck. | 2015/02/23 | [
"https://Stackoverflow.com/questions/28671753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812056/"
] | **Update Wiremock**. It should work with newer versions >= 2.0.0-beta. Its [JsonPath](https://github.com/jayway/JsonPath) dependency was very outdated ([GitHub #261](https://github.com/tomakehurst/wiremock/issues/261)).
Using the double dots operator is semantically not the same, as the filter will also match for elements with the same name deeper down the tree. | try with double dots operator (recursive)
```
$..params[?(@.clientVersion == "1")]
``` |
28,671,753 | I'm trying to create mocks for my login procedure. I use POST method with a couple of fields and login object (with login, password, etc.)
For that I'm using JsonPath. Code below:
```
{
"request": {
"method": "POST",
"url": "/login",
"bodyPatterns" : [
{"matchesJsonPath" : "$.method"},
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
{"matchesJsonPath" : "$.params.login"},
{"matchesJsonPath" : "$.params.password"}
]
},
"response": {
"status": 200,
"bodyFileName": "login.json"
}
}
```
I'm checking the clientVersion because it's similar to the examples.
My problem is, that with te given POST JSON:
```
{
"method": "login",
"params": {
"clientVersion": "1",
"login": "test@test.com",
"password": "681819535da188b6ef2"
}
}
```
I receive 404.
However, when I change
```
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
```
to normal
```
{"matchesJsonPath" : "$.params.clientVersion"},
```
everything works just fine.
So - how to check inside wiremock, using matchesJsonPath if given field equals some value?
How to apply it to the root field like method in my case?
And while we're at it - I had similar problems with checking if the value is not null. I tried to apply regular expressions and such - no luck. | 2015/02/23 | [
"https://Stackoverflow.com/questions/28671753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812056/"
] | It's working in my case :
wiremock:
```
"request": {
"urlPathPattern": "/api/authins-portail-rs/authins/inscription/infosperso",
"bodyPatterns" : [
{"matchesJsonPath" : "$[?(@.nir == '123456789')]"},
{"matchesJsonPath" : "$[?(@.nomPatronyme == 'aubert')]"},
{"matchesJsonPath" : "$[?(@.prenoms == 'christian')]"},
{"matchesJsonPath" : "$[?(@.dateNaissance == '01/09/1952')]"}
],
"method": "POST"
```
}
Json:
```
{
"nir": "123456789",
"nomPatronyme": "aubert",
"prenoms": "christian",
"dateNaissance": "01/09/1952"
}
``` | try with double dots operator (recursive)
```
$..params[?(@.clientVersion == "1")]
``` |
28,671,753 | I'm trying to create mocks for my login procedure. I use POST method with a couple of fields and login object (with login, password, etc.)
For that I'm using JsonPath. Code below:
```
{
"request": {
"method": "POST",
"url": "/login",
"bodyPatterns" : [
{"matchesJsonPath" : "$.method"},
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
{"matchesJsonPath" : "$.params.login"},
{"matchesJsonPath" : "$.params.password"}
]
},
"response": {
"status": 200,
"bodyFileName": "login.json"
}
}
```
I'm checking the clientVersion because it's similar to the examples.
My problem is, that with te given POST JSON:
```
{
"method": "login",
"params": {
"clientVersion": "1",
"login": "test@test.com",
"password": "681819535da188b6ef2"
}
}
```
I receive 404.
However, when I change
```
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
```
to normal
```
{"matchesJsonPath" : "$.params.clientVersion"},
```
everything works just fine.
So - how to check inside wiremock, using matchesJsonPath if given field equals some value?
How to apply it to the root field like method in my case?
And while we're at it - I had similar problems with checking if the value is not null. I tried to apply regular expressions and such - no luck. | 2015/02/23 | [
"https://Stackoverflow.com/questions/28671753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812056/"
] | It's working in my case :
wiremock:
```
"request": {
"urlPathPattern": "/api/authins-portail-rs/authins/inscription/infosperso",
"bodyPatterns" : [
{"matchesJsonPath" : "$[?(@.nir == '123456789')]"},
{"matchesJsonPath" : "$[?(@.nomPatronyme == 'aubert')]"},
{"matchesJsonPath" : "$[?(@.prenoms == 'christian')]"},
{"matchesJsonPath" : "$[?(@.dateNaissance == '01/09/1952')]"}
],
"method": "POST"
```
}
Json:
```
{
"nir": "123456789",
"nomPatronyme": "aubert",
"prenoms": "christian",
"dateNaissance": "01/09/1952"
}
``` | Following worked for me.
`"matchesJsonPath" : "$.rootItem.itemA[0].item..[?(@.fieldName=='file')]"`
Json :
```
{
"rootItem" : {
"itemA" : [
{
"item" : {
"fieldName" : "file",
"name" : "test"
}
}
]
}
}
```
Wiremock
```
{
"request" : {
"urlPattern" : "/testjsonpath",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$.rootItem.itemA[0].item..[?(@.fieldName=='file')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"result\": \"success\"}",
"headers" : {
"Content-Type" : "application/json"
}
}
}
``` |
28,671,753 | I'm trying to create mocks for my login procedure. I use POST method with a couple of fields and login object (with login, password, etc.)
For that I'm using JsonPath. Code below:
```
{
"request": {
"method": "POST",
"url": "/login",
"bodyPatterns" : [
{"matchesJsonPath" : "$.method"},
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
{"matchesJsonPath" : "$.params.login"},
{"matchesJsonPath" : "$.params.password"}
]
},
"response": {
"status": 200,
"bodyFileName": "login.json"
}
}
```
I'm checking the clientVersion because it's similar to the examples.
My problem is, that with te given POST JSON:
```
{
"method": "login",
"params": {
"clientVersion": "1",
"login": "test@test.com",
"password": "681819535da188b6ef2"
}
}
```
I receive 404.
However, when I change
```
{"matchesJsonPath" : "$.params[?(@.clientVersion == "1")]"},
```
to normal
```
{"matchesJsonPath" : "$.params.clientVersion"},
```
everything works just fine.
So - how to check inside wiremock, using matchesJsonPath if given field equals some value?
How to apply it to the root field like method in my case?
And while we're at it - I had similar problems with checking if the value is not null. I tried to apply regular expressions and such - no luck. | 2015/02/23 | [
"https://Stackoverflow.com/questions/28671753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812056/"
] | It's working in my case :
wiremock:
```
"request": {
"urlPathPattern": "/api/authins-portail-rs/authins/inscription/infosperso",
"bodyPatterns" : [
{"matchesJsonPath" : "$[?(@.nir == '123456789')]"},
{"matchesJsonPath" : "$[?(@.nomPatronyme == 'aubert')]"},
{"matchesJsonPath" : "$[?(@.prenoms == 'christian')]"},
{"matchesJsonPath" : "$[?(@.dateNaissance == '01/09/1952')]"}
],
"method": "POST"
```
}
Json:
```
{
"nir": "123456789",
"nomPatronyme": "aubert",
"prenoms": "christian",
"dateNaissance": "01/09/1952"
}
``` | **Update Wiremock**. It should work with newer versions >= 2.0.0-beta. Its [JsonPath](https://github.com/jayway/JsonPath) dependency was very outdated ([GitHub #261](https://github.com/tomakehurst/wiremock/issues/261)).
Using the double dots operator is semantically not the same, as the filter will also match for elements with the same name deeper down the tree. |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | In [k8s networkpolicy docs](https://kubernetes.io/docs/concepts/services-networking/network-policies/#isolated-and-non-isolated-pods) you read:
>
> By default, pods are non-isolated; they accept traffic from any
> source.
>
>
> Pods become isolated by having a NetworkPolicy that selects them. Once
> there is any NetworkPolicy in a namespace selecting a particular pod,
> that pod will reject any connections that are not allowed by any
> NetworkPolicy. (Other pods in the namespace that are not selected by
> any NetworkPolicy will continue to accept all traffic.)
>
>
> Network policies do not conflict; they are additive. If any policy or
> policies select a pod, the pod is restricted to what is allowed by the
> union of those policies' ingress/egress rules. Thus, order of
> evaluation does not affect the policy result
>
>
>
This means that once you assign(select) a pod with network policy you never set deny rules because everyting is denied by default. You only specify allow rules.
This beeing explained lets go back to k8s docs where you can read the following:
>
> There are four kinds of selectors that can be specified in an ingress
> from section or egress to section:
>
>
> **podSelector**: This selects particular Pods in the same namespace as the
> NetworkPolicy which should be allowed as ingress sources or egress
> destinations.
>
>
> **namespaceSelector**: This selects particular namespaces for which all
> Pods should be allowed as ingress sources or egress destinations.
>
>
> **namespaceSelector** and **podSelector**: A single to/from entry that
> specifies both namespaceSelector and podSelector selects particular
> Pods within particular namespaces
> [...]
>
>
>
I am not going to paste all docs here, check the rest [here](https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors).
---
Now to answer you question: `"I need to know if i can do it without adding a labels to namspace and pod or not ?"`
What you should notice in the docs metioned above is that you can only target namespace and pods using labels.
And when you don't use namespace label selector, the selector dafaults to the namespace where networkpolicy is deployed.
So, yes, you can do it without adding a labels to a namespace as long as you deploy network policy in the namespace you want to target. And you can also do it without adding labels to a pod as long as this is the only pod in the namespace. | From the question, i am not getting ... completely confused.
statement 1 --> on same namespace, the pod can communicate with port 80
statement 2 --> does not allow access to Pods not listening on port 80
So, could someone clarify here ?
what exactly they are asking ? do we need to provide the 80 access to pod or not ? |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | In [k8s networkpolicy docs](https://kubernetes.io/docs/concepts/services-networking/network-policies/#isolated-and-non-isolated-pods) you read:
>
> By default, pods are non-isolated; they accept traffic from any
> source.
>
>
> Pods become isolated by having a NetworkPolicy that selects them. Once
> there is any NetworkPolicy in a namespace selecting a particular pod,
> that pod will reject any connections that are not allowed by any
> NetworkPolicy. (Other pods in the namespace that are not selected by
> any NetworkPolicy will continue to accept all traffic.)
>
>
> Network policies do not conflict; they are additive. If any policy or
> policies select a pod, the pod is restricted to what is allowed by the
> union of those policies' ingress/egress rules. Thus, order of
> evaluation does not affect the policy result
>
>
>
This means that once you assign(select) a pod with network policy you never set deny rules because everyting is denied by default. You only specify allow rules.
This beeing explained lets go back to k8s docs where you can read the following:
>
> There are four kinds of selectors that can be specified in an ingress
> from section or egress to section:
>
>
> **podSelector**: This selects particular Pods in the same namespace as the
> NetworkPolicy which should be allowed as ingress sources or egress
> destinations.
>
>
> **namespaceSelector**: This selects particular namespaces for which all
> Pods should be allowed as ingress sources or egress destinations.
>
>
> **namespaceSelector** and **podSelector**: A single to/from entry that
> specifies both namespaceSelector and podSelector selects particular
> Pods within particular namespaces
> [...]
>
>
>
I am not going to paste all docs here, check the rest [here](https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors).
---
Now to answer you question: `"I need to know if i can do it without adding a labels to namspace and pod or not ?"`
What you should notice in the docs metioned above is that you can only target namespace and pods using labels.
And when you don't use namespace label selector, the selector dafaults to the namespace where networkpolicy is deployed.
So, yes, you can do it without adding a labels to a namespace as long as you deploy network policy in the namespace you want to target. And you can also do it without adding labels to a pod as long as this is the only pod in the namespace. | Below yaml will help you to solve your problem, It did work for me.
the point is mainly to use only the port section of ingress array.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: network-policy
spec:
podSelector: {} #selects all the pods in the namespace deployed
policyTypes:
- Ingress
ingress:
- ports: #in input traffic allowed only through 80 port only
- protocol: TCP
port: 80
``` |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | In [k8s networkpolicy docs](https://kubernetes.io/docs/concepts/services-networking/network-policies/#isolated-and-non-isolated-pods) you read:
>
> By default, pods are non-isolated; they accept traffic from any
> source.
>
>
> Pods become isolated by having a NetworkPolicy that selects them. Once
> there is any NetworkPolicy in a namespace selecting a particular pod,
> that pod will reject any connections that are not allowed by any
> NetworkPolicy. (Other pods in the namespace that are not selected by
> any NetworkPolicy will continue to accept all traffic.)
>
>
> Network policies do not conflict; they are additive. If any policy or
> policies select a pod, the pod is restricted to what is allowed by the
> union of those policies' ingress/egress rules. Thus, order of
> evaluation does not affect the policy result
>
>
>
This means that once you assign(select) a pod with network policy you never set deny rules because everyting is denied by default. You only specify allow rules.
This beeing explained lets go back to k8s docs where you can read the following:
>
> There are four kinds of selectors that can be specified in an ingress
> from section or egress to section:
>
>
> **podSelector**: This selects particular Pods in the same namespace as the
> NetworkPolicy which should be allowed as ingress sources or egress
> destinations.
>
>
> **namespaceSelector**: This selects particular namespaces for which all
> Pods should be allowed as ingress sources or egress destinations.
>
>
> **namespaceSelector** and **podSelector**: A single to/from entry that
> specifies both namespaceSelector and podSelector selects particular
> Pods within particular namespaces
> [...]
>
>
>
I am not going to paste all docs here, check the rest [here](https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors).
---
Now to answer you question: `"I need to know if i can do it without adding a labels to namspace and pod or not ?"`
What you should notice in the docs metioned above is that you can only target namespace and pods using labels.
And when you don't use namespace label selector, the selector dafaults to the namespace where networkpolicy is deployed.
So, yes, you can do it without adding a labels to a namespace as long as you deploy network policy in the namespace you want to target. And you can also do it without adding labels to a pod as long as this is the only pod in the namespace. | statement 2 --> does not allow access to Pods not listening on port 80
How to not allow when a pod not listening this a TCP state of a server .. You can also have pods not listening on port 80 on same namespace . I don't think this is solved in your above yaml . |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | In [k8s networkpolicy docs](https://kubernetes.io/docs/concepts/services-networking/network-policies/#isolated-and-non-isolated-pods) you read:
>
> By default, pods are non-isolated; they accept traffic from any
> source.
>
>
> Pods become isolated by having a NetworkPolicy that selects them. Once
> there is any NetworkPolicy in a namespace selecting a particular pod,
> that pod will reject any connections that are not allowed by any
> NetworkPolicy. (Other pods in the namespace that are not selected by
> any NetworkPolicy will continue to accept all traffic.)
>
>
> Network policies do not conflict; they are additive. If any policy or
> policies select a pod, the pod is restricted to what is allowed by the
> union of those policies' ingress/egress rules. Thus, order of
> evaluation does not affect the policy result
>
>
>
This means that once you assign(select) a pod with network policy you never set deny rules because everyting is denied by default. You only specify allow rules.
This beeing explained lets go back to k8s docs where you can read the following:
>
> There are four kinds of selectors that can be specified in an ingress
> from section or egress to section:
>
>
> **podSelector**: This selects particular Pods in the same namespace as the
> NetworkPolicy which should be allowed as ingress sources or egress
> destinations.
>
>
> **namespaceSelector**: This selects particular namespaces for which all
> Pods should be allowed as ingress sources or egress destinations.
>
>
> **namespaceSelector** and **podSelector**: A single to/from entry that
> specifies both namespaceSelector and podSelector selects particular
> Pods within particular namespaces
> [...]
>
>
>
I am not going to paste all docs here, check the rest [here](https://kubernetes.io/docs/concepts/services-networking/network-policies/#behavior-of-to-and-from-selectors).
---
Now to answer you question: `"I need to know if i can do it without adding a labels to namspace and pod or not ?"`
What you should notice in the docs metioned above is that you can only target namespace and pods using labels.
And when you don't use namespace label selector, the selector dafaults to the namespace where networkpolicy is deployed.
So, yes, you can do it without adding a labels to a namespace as long as you deploy network policy in the namespace you want to target. And you can also do it without adding labels to a pod as long as this is the only pod in the namespace. | 1. You need to label the namespace first
For e.g **kubectl label ns namespace-name env: testing**
2.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-port-from-namespace
namespace: staging
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
env: staging
ports:
- protocol: TCP
port: 80
``` |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | 1. You need to label the namespace first
For e.g **kubectl label ns namespace-name env: testing**
2.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-port-from-namespace
namespace: staging
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
env: staging
ports:
- protocol: TCP
port: 80
``` | From the question, i am not getting ... completely confused.
statement 1 --> on same namespace, the pod can communicate with port 80
statement 2 --> does not allow access to Pods not listening on port 80
So, could someone clarify here ?
what exactly they are asking ? do we need to provide the 80 access to pod or not ? |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | 1. You need to label the namespace first
For e.g **kubectl label ns namespace-name env: testing**
2.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-port-from-namespace
namespace: staging
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
env: staging
ports:
- protocol: TCP
port: 80
``` | Below yaml will help you to solve your problem, It did work for me.
the point is mainly to use only the port section of ingress array.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: network-policy
spec:
podSelector: {} #selects all the pods in the namespace deployed
policyTypes:
- Ingress
ingress:
- ports: #in input traffic allowed only through 80 port only
- protocol: TCP
port: 80
``` |
64,153,049 | kubernetes V19
Create a new NetworkPolicy named allow-port-from-namespace that allows Pods in the existing namespace internal to connect to port 80 of other Pods in the same namespace.
Ensure that the new NetworkPolicy:
does not allow access to Pods not listening on port 80
does not allow access from Pods not in namespace internal
i need to know if i can do it without adding a labels to namspace and pod or not ? | 2020/10/01 | [
"https://Stackoverflow.com/questions/64153049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584773/"
] | 1. You need to label the namespace first
For e.g **kubectl label ns namespace-name env: testing**
2.
```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-port-from-namespace
namespace: staging
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
env: staging
ports:
- protocol: TCP
port: 80
``` | statement 2 --> does not allow access to Pods not listening on port 80
How to not allow when a pod not listening this a TCP state of a server .. You can also have pods not listening on port 80 on same namespace . I don't think this is solved in your above yaml . |
41,508,796 | I've searching the [moment.js docs](http://momentjs.com/docs/) and [stackoverflow](https://stackoverflow.com/) for a way to use the `fromNow()` function but returning everything in hours.
What I mean is:
```
moment([2017, 01, 05]).fromNow(); // a day ago
```
should be
```
moment([2017, 01, 05]).fromNow(); // 24 hours ago
```
I know it's possible to do this using `.diff` and probably other similar functions and then adding the text, but is it possible to use `.fromNow()` to do this? | 2017/01/06 | [
"https://Stackoverflow.com/questions/41508796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4453976/"
] | You can use [`relativeTimeThreshold`](http://momentjs.com/docs/#/customization/relative-time-threshold/) to customize thresholds for moment relative time.
As the docs says:
>
> `duration.humanize` has thresholds which define when a unit is considered a minute, an hour and so on. For example, by default more than 45 seconds is considered a minute, more than 22 hours is considered a day and so on. To change those cutoffs use `moment.relativeTimeThreshold(unit, limit)` where unit is one of `s`, `m`, `h`, `d`, `M`.
>
>
>
In your case, you can increase hour thresholds to get relative days as hours. Here a working example showing time as hours from 1 hour to 26 days:
```js
var m1 = moment().subtract(5, 'h');
var m2 = moment().subtract(55, 'h');
var m3 = moment().subtract(1, 'd');
// Default results
console.log(m1.fromNow());
console.log(m2.fromNow());
console.log(m3.fromNow());
// Change relativeTimeThreshold
moment.relativeTimeThreshold('m', 60);
moment.relativeTimeThreshold('h', 24*26);
// Results in hours
console.log(m1.fromNow());
console.log(m2.fromNow());
console.log(m3.fromNow());
```
```html
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
```
Note that, if you need, moment lets you customize relative time further with [`relativeTime`](http://momentjs.com/docs/#/customization/relative-time/) ([here](https://stackoverflow.com/a/38385371/4131048) one of my examples) and [`relativeTimeRounding`](http://momentjs.com/docs/#/customization/relative-time-rounding/) method. | If you definitely want to use `fromNow()`, I don't see any way other than overriding moment's built-in function. For example, you can override it to return the difference in hours as follows:
```
moment.fn.fromNow = function (a) {
var duration = moment().diff(this, 'hours');
return duration;
}
```
Then you can check that `fromNow()` returns the value in hours:
```
console.log(moment([2017,0,6]).fromNow());
```
which returns:
```
19
```
Note: Tried at 19:00 :) |
23,604,020 | First of all, excuse me if the code below does not contain an array but a list. I am new to VBA so I don't know all the basics yet. The code below retrieves an array (or a list) of all Excel files in a certain folder. The code is used to retrieve data from each file and is pasted in a master file.
Okay, here is my MWE:
```
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, wbCount As Integer
FolderName = "C:\Users\Robin\Desktop\Test"
wbCount = 0
wbName = Dir(FolderName & "\" & "*.xlsm")
While wbName <> ""
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
wbList(wbCount) = wbName
wbName = Dir
Wend
If wbCount = 0 Then Exit Sub
End Sub
```
Now here is the problem: The array contains a template file, and the name of the file contains the word *TEMPLATE*. How do I filter out (or exclude) the file which file name contains the string "TEMPLATE"?
Any help would be much appreciated! Thanks in advance! | 2014/05/12 | [
"https://Stackoverflow.com/questions/23604020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851837/"
] | The variable `wbName` contains the filenames from the `Dir` command. Check to see if the string contains what you want to exlude.
Extend the line
```
While wbName <> ""
```
into
```
While wbName <> "" And InStr(1, UCase(wbName), "TEMPLATE") = 0
```
to exlude any filenames that contain `TEMPLATE`, regardless of case.
**EDIT**
The logic in my suggestion above was wrong, it stopped when it encountered the first filename containing "TEMPLATE". Try the following instead:
```
While wbName <> ""
'***** Only add to wbCount if wbName does not contain TEMPLATE
If InStr(1, UCase(wbName), "TEMPLATE") = 0 Then
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
wbList(wbCount) = wbName
End If
wbName = Dir
Wend
```
**EDIT 2**
Some general tips on finding errors:
* Always use `Option Explicit` at the top of your modules. It will force you to declare your variables, minimizing the risk of typos etc introducing bugs.
* Step through your code using `F8` to identify errors and checking vaules of variables and functions
* If possible, remove code to simplify it, only keeping the logic like `While` loops and `If` statements to make sure the basics work. Then add the details back.
Finally, the key to my solution is finding the files that contain "TEMPLATE" in the name. The statement `InStr(1, UCase(wbName), "TEMPLATE") = 0` will be `False` for all files containing the string "TEMPLATE" anywhere, regardless of case, and `True` otherwise. (The `Ucase` part is what makes the statement case insensitive.)
Try to add it to your logic. | ```
Dim fNameList As Variant
Dim storFName As String
Dim i As Integer
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, wbCount As Integer
FolderName = "C:\Users\Robin\Desktop\Test"
wbCount = 0
wbName = Dir(FolderName & "\" & "*.xlsm")
While wbName <> ""
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
fNameList = Split(wbName, ".")
For i = 0 To UBound(fNameList) '<- Here i is being use
If (UCase(InStr(fNameList(i), "TEMPLATE"))) Then
UCase(storFName) = fNameList (i)
End If
Next i '<- Here i is being increase
If storFName <> "TEMPLATE" Then
wbList(wbCount) = wbName
wbName = Dir
End If
Wend
If wbCount = 0 Then Exit Sub
End Sub
```
Will it work for you? |
23,604,020 | First of all, excuse me if the code below does not contain an array but a list. I am new to VBA so I don't know all the basics yet. The code below retrieves an array (or a list) of all Excel files in a certain folder. The code is used to retrieve data from each file and is pasted in a master file.
Okay, here is my MWE:
```
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, wbCount As Integer
FolderName = "C:\Users\Robin\Desktop\Test"
wbCount = 0
wbName = Dir(FolderName & "\" & "*.xlsm")
While wbName <> ""
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
wbList(wbCount) = wbName
wbName = Dir
Wend
If wbCount = 0 Then Exit Sub
End Sub
```
Now here is the problem: The array contains a template file, and the name of the file contains the word *TEMPLATE*. How do I filter out (or exclude) the file which file name contains the string "TEMPLATE"?
Any help would be much appreciated! Thanks in advance! | 2014/05/12 | [
"https://Stackoverflow.com/questions/23604020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851837/"
] | The variable `wbName` contains the filenames from the `Dir` command. Check to see if the string contains what you want to exlude.
Extend the line
```
While wbName <> ""
```
into
```
While wbName <> "" And InStr(1, UCase(wbName), "TEMPLATE") = 0
```
to exlude any filenames that contain `TEMPLATE`, regardless of case.
**EDIT**
The logic in my suggestion above was wrong, it stopped when it encountered the first filename containing "TEMPLATE". Try the following instead:
```
While wbName <> ""
'***** Only add to wbCount if wbName does not contain TEMPLATE
If InStr(1, UCase(wbName), "TEMPLATE") = 0 Then
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
wbList(wbCount) = wbName
End If
wbName = Dir
Wend
```
**EDIT 2**
Some general tips on finding errors:
* Always use `Option Explicit` at the top of your modules. It will force you to declare your variables, minimizing the risk of typos etc introducing bugs.
* Step through your code using `F8` to identify errors and checking vaules of variables and functions
* If possible, remove code to simplify it, only keeping the logic like `While` loops and `If` statements to make sure the basics work. Then add the details back.
Finally, the key to my solution is finding the files that contain "TEMPLATE" in the name. The statement `InStr(1, UCase(wbName), "TEMPLATE") = 0` will be `False` for all files containing the string "TEMPLATE" anywhere, regardless of case, and `True` otherwise. (The `Ucase` part is what makes the statement case insensitive.)
Try to add it to your logic. | ```
Sub test()
Dim x() As String, i As Integer
x = ReadDataFromAllWorkbooksInFolder("C:\Users\Robin\Desktop\Test")
For i = 0 To UBound(x)
Debug.Print x(i)
Next i
End Sub
Private Function ReadDataFromAllWorkbooksInFolder(FolderName As String) As Variant
Dim wbName As String
Dim wbCount As Integer
Dim wbList() As String
wbCount = 0
ReDim wbList(0)
wbName = Dir(FolderName & "\*.xlsm")
While wbName <> vbNullString
If Not (UCase(wbName) Like "*TEMPLATE*") Then
ReDim Preserve wbList(wbCount)
wbList(wbCount) = wbName
wbCount = wbCount + 1
End If
wbName = Dir
Wend
ReadDataFromAllWorkbooksInFolder = wbList
End Function
```
Once you get comfortable with VBA you'll probably switch to Scripting.FileSystemObject and Scripting.Dictionary... |
23,604,020 | First of all, excuse me if the code below does not contain an array but a list. I am new to VBA so I don't know all the basics yet. The code below retrieves an array (or a list) of all Excel files in a certain folder. The code is used to retrieve data from each file and is pasted in a master file.
Okay, here is my MWE:
```
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, wbCount As Integer
FolderName = "C:\Users\Robin\Desktop\Test"
wbCount = 0
wbName = Dir(FolderName & "\" & "*.xlsm")
While wbName <> ""
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
wbList(wbCount) = wbName
wbName = Dir
Wend
If wbCount = 0 Then Exit Sub
End Sub
```
Now here is the problem: The array contains a template file, and the name of the file contains the word *TEMPLATE*. How do I filter out (or exclude) the file which file name contains the string "TEMPLATE"?
Any help would be much appreciated! Thanks in advance! | 2014/05/12 | [
"https://Stackoverflow.com/questions/23604020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851837/"
] | ```
Dim fNameList As Variant
Dim storFName As String
Dim i As Integer
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, wbCount As Integer
FolderName = "C:\Users\Robin\Desktop\Test"
wbCount = 0
wbName = Dir(FolderName & "\" & "*.xlsm")
While wbName <> ""
wbCount = wbCount + 1
ReDim Preserve wbList(1 To wbCount)
fNameList = Split(wbName, ".")
For i = 0 To UBound(fNameList) '<- Here i is being use
If (UCase(InStr(fNameList(i), "TEMPLATE"))) Then
UCase(storFName) = fNameList (i)
End If
Next i '<- Here i is being increase
If storFName <> "TEMPLATE" Then
wbList(wbCount) = wbName
wbName = Dir
End If
Wend
If wbCount = 0 Then Exit Sub
End Sub
```
Will it work for you? | ```
Sub test()
Dim x() As String, i As Integer
x = ReadDataFromAllWorkbooksInFolder("C:\Users\Robin\Desktop\Test")
For i = 0 To UBound(x)
Debug.Print x(i)
Next i
End Sub
Private Function ReadDataFromAllWorkbooksInFolder(FolderName As String) As Variant
Dim wbName As String
Dim wbCount As Integer
Dim wbList() As String
wbCount = 0
ReDim wbList(0)
wbName = Dir(FolderName & "\*.xlsm")
While wbName <> vbNullString
If Not (UCase(wbName) Like "*TEMPLATE*") Then
ReDim Preserve wbList(wbCount)
wbList(wbCount) = wbName
wbCount = wbCount + 1
End If
wbName = Dir
Wend
ReadDataFromAllWorkbooksInFolder = wbList
End Function
```
Once you get comfortable with VBA you'll probably switch to Scripting.FileSystemObject and Scripting.Dictionary... |
32,510,319 | I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
```
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}
```
The shortened html is:
```
<p><img id="leftArrow"><span id="completeList"><img style="float: right" id="rightArrow"></p>
```
The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322719/"
] | Docker generates a `config.json` file in `~/.docker/`
It looks like:
```
{
"auths": {
"index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "email@company.com"
}
}
}
```
what you actually want is:
```
{"https://index.docker.io/v1/": {"auth": "XXXXXXXXXXXXXX", "email": "email@company.com"}}
```
note 3 things:
* 1) there is no `auths` wrapping
* 2) there is `https://` in front of the
URL
* 3) it's **one line**
then you **base64** encode that and use as data for the `.dockercfg` name
```
apiVersion: v1
kind: Secret
metadata:
name: registry
data:
.dockercfg: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==
type: kubernetes.io/dockercfg
```
Note again the `.dockercfg` line is **one line** (base64 tends to generate a multi-line string) | I've been experiencing the same problem. What I did notice is that in the example (<https://kubernetes.io/docs/user-guide/images/#specifying-imagepullsecrets-on-a-pod>) .dockercfg has the following format:
```
{
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "jdoe@example.com"
}
}
```
While the one generated by docker in my machine looks something like this:
```
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "email@company.com"
}
}
}
```
By checking at the source code, I found that there is actually a test for this use case (<https://github.com/kubernetes/kubernetes/blob/6def707f9c8c6ead44d82ac8293f0115f0e47262/pkg/kubelet/dockertools/docker_test.go#L280>)
I confirm you that if you just take and encode "auths", as in the example, it will work for you.
Probably the documentation should be updated. I will raise a ticket on github. |
32,510,319 | I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
```
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}
```
The shortened html is:
```
<p><img id="leftArrow"><span id="completeList"><img style="float: right" id="rightArrow"></p>
```
The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322719/"
] | Another possible reason why you might see "image not found" is if the namespace of your secret doesn't match the namespace of the container.
For example, if your Deployment yaml looks like
```
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: mydeployment
namespace: kube-system
```
Then you must make sure the Secret yaml uses a matching namespace:
```
apiVersion: v1
kind: Secret
metadata:
name: mysecret
namespace: kube-system
data:
.dockerconfigjson: ****
type: kubernetes.io/dockerconfigjson
```
If you don't specify a namespace for your secret, it will end up in the default namespace and won't get used. There is no warning message. I just spent hours on this issue so I thought I'd share it here in the hope I can save somebody else the time. | I've been experiencing the same problem. What I did notice is that in the example (<https://kubernetes.io/docs/user-guide/images/#specifying-imagepullsecrets-on-a-pod>) .dockercfg has the following format:
```
{
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "jdoe@example.com"
}
}
```
While the one generated by docker in my machine looks something like this:
```
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "email@company.com"
}
}
}
```
By checking at the source code, I found that there is actually a test for this use case (<https://github.com/kubernetes/kubernetes/blob/6def707f9c8c6ead44d82ac8293f0115f0e47262/pkg/kubelet/dockertools/docker_test.go#L280>)
I confirm you that if you just take and encode "auths", as in the example, it will work for you.
Probably the documentation should be updated. I will raise a ticket on github. |
32,510,319 | I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
```
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}
```
The shortened html is:
```
<p><img id="leftArrow"><span id="completeList"><img style="float: right" id="rightArrow"></p>
```
The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322719/"
] | Another reason you might see this error is due to using a kubectl version different than the cluster version (e.g. using kubectl 1.9.x against a 1.8.x cluster).
The format of the secret generated by the *kubectl create secret docker-registry* command has changed between versions.
A 1.8.x cluster expect a secret with the format:
```
{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
```
But the secret generated by the 1.9.x kubectl has this format:
```
{
"auths":{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
}
```
So, double check the value of the .dockercfg data of your secret and verify that it matches the format expected by your kubernetes cluster version. | I've been experiencing the same problem. What I did notice is that in the example (<https://kubernetes.io/docs/user-guide/images/#specifying-imagepullsecrets-on-a-pod>) .dockercfg has the following format:
```
{
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "jdoe@example.com"
}
}
```
While the one generated by docker in my machine looks something like this:
```
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "email@company.com"
}
}
}
```
By checking at the source code, I found that there is actually a test for this use case (<https://github.com/kubernetes/kubernetes/blob/6def707f9c8c6ead44d82ac8293f0115f0e47262/pkg/kubelet/dockertools/docker_test.go#L280>)
I confirm you that if you just take and encode "auths", as in the example, it will work for you.
Probably the documentation should be updated. I will raise a ticket on github. |
32,510,319 | I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
```
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}
```
The shortened html is:
```
<p><img id="leftArrow"><span id="completeList"><img style="float: right" id="rightArrow"></p>
```
The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322719/"
] | Docker generates a `config.json` file in `~/.docker/`
It looks like:
```
{
"auths": {
"index.docker.io/v1/": {
"auth": "ZmFrZXBhc3N3b3JkMTIK",
"email": "email@company.com"
}
}
}
```
what you actually want is:
```
{"https://index.docker.io/v1/": {"auth": "XXXXXXXXXXXXXX", "email": "email@company.com"}}
```
note 3 things:
* 1) there is no `auths` wrapping
* 2) there is `https://` in front of the
URL
* 3) it's **one line**
then you **base64** encode that and use as data for the `.dockercfg` name
```
apiVersion: v1
kind: Secret
metadata:
name: registry
data:
.dockercfg: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==
type: kubernetes.io/dockercfg
```
Note again the `.dockercfg` line is **one line** (base64 tends to generate a multi-line string) | Another reason you might see this error is due to using a kubectl version different than the cluster version (e.g. using kubectl 1.9.x against a 1.8.x cluster).
The format of the secret generated by the *kubectl create secret docker-registry* command has changed between versions.
A 1.8.x cluster expect a secret with the format:
```
{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
```
But the secret generated by the 1.9.x kubectl has this format:
```
{
"auths":{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
}
```
So, double check the value of the .dockercfg data of your secret and verify that it matches the format expected by your kubernetes cluster version. |
32,510,319 | I have a right arrow that when clicked shows the hidden left arrow. There is text centered between the two arrows so the margin changes on the centered text when both arrows are visible so I removed the css styling on #completeList and am trying to add the css with JQuery. Here is the code that I am trying:
```
$('#completeList').css('margin-left', '44%');
if ($('#leftArrow').is(':visible')) {
$('#completeList').css('margin-left', '32%');
}
```
The shortened html is:
```
<p><img id="leftArrow"><span id="completeList"><img style="float: right" id="rightArrow"></p>
```
The problem I am having is the 44% margin-left is not changing to the 32% margin-left when $('#leftArrow') is visible.
Is the jQuery i used a viable solution or should I be looking for another way? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32510319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5322719/"
] | Another possible reason why you might see "image not found" is if the namespace of your secret doesn't match the namespace of the container.
For example, if your Deployment yaml looks like
```
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: mydeployment
namespace: kube-system
```
Then you must make sure the Secret yaml uses a matching namespace:
```
apiVersion: v1
kind: Secret
metadata:
name: mysecret
namespace: kube-system
data:
.dockerconfigjson: ****
type: kubernetes.io/dockerconfigjson
```
If you don't specify a namespace for your secret, it will end up in the default namespace and won't get used. There is no warning message. I just spent hours on this issue so I thought I'd share it here in the hope I can save somebody else the time. | Another reason you might see this error is due to using a kubectl version different than the cluster version (e.g. using kubectl 1.9.x against a 1.8.x cluster).
The format of the secret generated by the *kubectl create secret docker-registry* command has changed between versions.
A 1.8.x cluster expect a secret with the format:
```
{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
```
But the secret generated by the 1.9.x kubectl has this format:
```
{
"auths":{
"https://registry.gitlab.com":{
"username":"...",
"password":"...",
"email":"...",
"auth":"..."
}
}
}
```
So, double check the value of the .dockercfg data of your secret and verify that it matches the format expected by your kubernetes cluster version. |
30,737,897 | I am using a UITextView that displays different text depending on the course of user actions. Some text includes hyperlinks and some does not, so I would like to retain the UITextView's default setting to detect links. However, once I switch back to text that does not have a hyperlink, the entire text field is converted into a hyperlink for some link from the previous text. It is entirely blue, and if the user clicks on it, the app opens Safari to go to the link that's no longer there. I've tried setting the text to nil before replacing with real replacement text, but this hasn't worked:
```
infoLabel.text = nil;
```
Neither has this
```
infoLabel.text = @"";
```
Also I have tried explicitly setting the dataDetector type property on UILabel when I change the text, but then the text color is black even though I have set it to another color. So if I do this I have to reset the text color every time I reset the data detector type property. Quite frustrating. This feels like a bug. What am I missing? | 2015/06/09 | [
"https://Stackoverflow.com/questions/30737897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678042/"
] | I have also experienced this exact issue.
Attempted different things to remedy the problem, but nothing worked.
Reported the issue to the Google AppEngine issue tracker:
<https://code.google.com/p/googleappengine/issues/detail?id=12105> | I'm not sure why the annotation processor is somehow injecting `this$0` as a path parameter. Does your API really need to have the `members` and `session` in part of the path? Or, can/should these both be query parameters instead (see the auto-generated code and how it has injected them there)? Try removing the `@Named` annotation for both of these, which should make them query parameters automatically. |
30,737,897 | I am using a UITextView that displays different text depending on the course of user actions. Some text includes hyperlinks and some does not, so I would like to retain the UITextView's default setting to detect links. However, once I switch back to text that does not have a hyperlink, the entire text field is converted into a hyperlink for some link from the previous text. It is entirely blue, and if the user clicks on it, the app opens Safari to go to the link that's no longer there. I've tried setting the text to nil before replacing with real replacement text, but this hasn't worked:
```
infoLabel.text = nil;
```
Neither has this
```
infoLabel.text = @"";
```
Also I have tried explicitly setting the dataDetector type property on UILabel when I change the text, but then the text color is black even though I have set it to another color. So if I do this I have to reset the text color every time I reset the data detector type property. Quite frustrating. This feels like a bug. What am I missing? | 2015/06/09 | [
"https://Stackoverflow.com/questions/30737897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4678042/"
] | I have also experienced this exact issue.
Attempted different things to remedy the problem, but nothing worked.
Reported the issue to the Google AppEngine issue tracker:
<https://code.google.com/p/googleappengine/issues/detail?id=12105> | Given that this method is doing modification, it should be a POST. I would recommend not using @Named here. I would create an `AddGroupRequest` class that contains both parameters. This way they are passed in as a JSON body rather than as URL parameters. As mentioned, this is a bug, and you can file an issue at the App Engine [public tracker](https://code.google.com/p/googleappengine/issues/list) if you need a List to work in URL parameters. But I suggest going with my solution instead, unless you have good reason to use such a URL. |
50,747,747 | Instead of using physics bodies to detect collisions I am simply using enumerateChildNodes to check if SKSpriteNodes intersect. Its works great for me when the SKSpriteNodes are both children of the scene but it doesn't work when one of the SKSpriteNodes is a grandchild. I have tried using // and / before the name of the SKSpriteNode to search through all of the tree but it doesn't help. Here is my code:
```
override func didMove(to view: SKView) {
let red = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(10,10))
red.name = "red"
self.addChild(red)
let blue = SKSpriteNode(color: UIColor.blueColor(), size: CGSizeMake(10,10))
blue.name = "blue"
self.addChild(blue)
let green = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(10,10))
green.name = "green"
blue.addChild(green)
}
override func update(_ currentTime: TimeInterval) {
enumerateChildNodes(withName:"red") {node, _ in
let red = node as! SKSpriteNode
if red.frame.intersects((self.childNode(withName:"//blue/green")?.frame)!)
{
red.removeFromParent()
}
}
``` | 2018/06/07 | [
"https://Stackoverflow.com/questions/50747747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9426356/"
] | Ana, I have watched your questions change over the past several iterations, and it is clear you know what pieces you need to put together, but you are somewhat making it more difficult on yourself than it needs to be by how you are trying to fit them together.
The purpose for dynamically allocating your structures or data are (1) handle larger amounts of data than will fit within your program stack (not an issue here), (2) to allow you to grow or shrink the amount of storage you are using as your data needs fluctuate over the course of your program (also not an issue here), or (3) to allow you to tailor your storage needs based on data in use in your program. This last part seems to be what you are attempting, but by allocating a fixed size for your character arrays -- you completely lose the benefit of tailoring your allocation to the size of your data.
In order to allocate storage for each of the strings contained in your data, you need to get the length of each string, and then allocate `length + 1` characters for storage (the +1 for the *nul-terminating* character). While you can use `malloc` and then `strcpy` to accomplish the allocation and copy to the new block of memory, if you have `strdup`, that can do both for you in one function call.
The quandary you are faced with is "*Where do I store the data before I get the lengths and allocate an copy?*" You can handle this in a number of ways. You can declare a jumble of different variables, and parse the data into individual variables to begin with (somewhat messy), you can allocate one struct with the fixed values to initially store the values (a good option, but calling `malloc` for `30` or `50` chars doesn't make a lot of sense when a fixed array will do), or you can declare a separate temporary struct with fixed array sizes to use (that way to collect the jumble of separate variables into a struct that can then easily be passed to your allocate function) Consider each, and use the one that works best for you.
Your function return types do not make a whole lot of sense as they are. You need to choose a meaningful return type that will allow the function to indicate whether it succeeded or failed, and then return a value (or pointer to a value) that provides useful information to the remainder of your program. Gauging success/failure of a function is particularly important with functions that allocate memory or handle input or output.
In addition to the return type you choose, you need to think through the parameters you are passing to each function. You need to think about what variables need to be available where in your function. Take your `FILE*` parameter. You never user the file outside of your `store()` function - so why do you have it declared in `main()` which causes you to have to worry about returning the open stream through a pointer -- that you don't use.
With that in mind we can look at putting the pieces of your program together in a slightly manner.
First, do not use *magic numbers* sprinkled throughout your code. (e.g. `9, 10, 20, 30, 50, etc..`) Instead,
```
#define MAXN 9 /* if you need constants, define one (or more) */
#define MAXC 30
#define MAXL 50
```
(or you can use an `enum` for the same purpose)
For the purpose of the example, you can use a struct that you will dynamically allocate for efficient storage of your data, and a temporary struct to aid in parsing values from your line of data. For example:
```
typedef struct { /* struct to hold dynamically allocated data */
long date; /* sized to exact number of chars required. */
int home_score,
away_score;
char *h_team,
*a_team,
*reason,
*city,
*country,
*neutral_field;
} data_t;
typedef struct { /* temp struct to parse data from line */
long date; /* sized to hold largest anticipated data */
int home_score,
away_score;
char h_team[MAXC],
a_team[MAXC],
reason[MAXC],
city[MAXC],
country[MAXC],
neutral_field[MAXN];
} data_tmp_t;
```
Next, the entire purpose of your `open_output` function is to open a file for writing. It should return the open file stream on success or NULL otherwise, e.g.
```
/* pass filename to open, returns open file stream pointer on
* success, NULL otherwise.
*/
FILE *open_output (const char *string)
{
FILE *output = NULL;
if ((output = fopen (string, "w")) == NULL)
fprintf (stderr, "file open failed. '%s'.\n", string);
return output;
}
```
Your `alloc_data` function is allocating a data struct and filling its values. It should return a pointer to the fully allocated and filled struct on success, or NULL on failure, e.g.
```
/* pass temporary struct containing data, dynamic struct allocated,
* each member allocated to hold exact number of chars (+ terminating
* character). pointer to allocated struct returned on success,
* NULL otherwise.
*/
data_t *alloc_data (data_tmp_t *tmp)
{
data_t *d = malloc (sizeof *d); /* allocate structure */
if (d == NULL)
return NULL;
d->date = tmp->date;
/* allocate each string member with strdup. if not available,
* simply use malloc (strlen(str) + 1), and then strcpy.
*/
if ((d->h_team = strdup (tmp->h_team)) == NULL)
return NULL;
if ((d->a_team = strdup (tmp->a_team)) == NULL)
return NULL;
d->home_score = tmp->home_score;
d->away_score = tmp->away_score;
if ((d->reason = strdup (tmp->reason)) == NULL)
return NULL;
if ((d->city = strdup (tmp->city)) == NULL)
return NULL;
if ((d->country = strdup (tmp->country)) == NULL)
return NULL;
if ((d->neutral_field = strdup (tmp->neutral_field)) == NULL)
return NULL;
return d; /* return pointer to allocated struct */
}
```
Any time you are allocating multiple values that are nested within a struct (or nested structs), get in the habit of writing a `free_data` function to `free` the memory you allocate in `alloc_data`. It is far better to write one free function to properly handle a complex structure you have allocated compared to sprinkling individual `free` calls around your code. There is no return to check when freeing a variable, so you can use a `void` function here:
```
/* frees each allocated member of d, and then d itself */
void free_data (data_t *d)
{
free (d->h_team);
free (d->a_team);
free (d->reason);
free (d->city);
free (d->country);
free (d->neutral_field);
free (d);
}
```
Your `store()` function is where most of the decisions and validation checks take place. The purpose of your code is to parse and then store a `string` in a `filename`. That should get you thinking about what parameters are required. The remainder of the file handling can all be internal to `store()` since the `FILE` is not used further in the calling function. Now, depending on how many writes you are doing, it may make perfect sense to declare and open the `FILE` once in `main()` and then pass an open (and validated) `FILE*` parameter, which would then require only a single `fopen` call and a final `close` in `main()`. For purposes here, all will be handled in `store` so you can check for any stream error after each write by checking the return of `fclose`.
Since you are allocating and storing a struct which may be needed for further use in the calling function, choosing to return a pointer to the caller (or `NULL` on failure) makes for a good choice of return type for `store()`. You could do something like:
```
/* parses data in string into separate values and stores data in string
* to filename (note: use mode "a" to append instead of "w" which
* truncates). returns pointer to fully-allocated struct on success,
* NULL otherwise.
*/
data_t *store (const char *string, const char *filename)
{
data_tmp_t tmp = { .date = 0 };
data_t *d = NULL;
FILE *output = open_output (filename); /* no need to pass in */
/* not used later in main */
if (output == NULL) { /* validate file open for writing */
return NULL;
}
/* parse csv values with sscanf - avoids later need to convert values
* validate all values successfully converted.
*/
if (sscanf (string, "%ld,%29[^,],%29[^,],%d,%d,%29[^,],%29[^,],"
"%29[^,],%8[^\n]",
&tmp.date, tmp.h_team, tmp.a_team, &tmp.home_score,
&tmp.away_score, tmp.reason, tmp.city, tmp.country,
tmp.neutral_field) != 9) {
fprintf (stderr, "error: failed to parse string.\n");
return NULL;
}
d = alloc_data (&tmp); /* allocate d and deep-copy tmp to d */
if (d == NULL) { /* validate allocation/copy succeeded */
perror ("malloc-alloc_data");
return NULL;
}
/* output values to file */
fprintf (output, "%ld,%s,%s,%d,%d,%s,%s,%s,%s\n", d->date, d->h_team,
d->a_team, d->home_score, d->away_score, d->reason, d->city,
d->country, d->neutral_field );
if (fclose (output) == EOF) /* always validate close-after-write */
perror ("stream error-output");
return d; /* return fully allocated/populated struct */
}
```
Your `main()` can then handle nothing more than your string that needs to be parsed, the filename to write the data to, and a pointer to the fully allocated struct resulting from the parse so it is available for further use. (it also takes the file to write to as the 1st argument to the program -- or it will write to `"saida.txt"` by default if no argument is provided, e.g.
```
int main (int argc, char *argv[])
{
char *string = "18820218,Northern Ireland,England,0,13,Friendly,"
"Belfast,Ireland,FALSE";
/* filename set to 1st argument (or "saida.txt" by default) */
char *filename = argc > 1 ? argv[1] : "saida.txt";
data_t *d = NULL;
d = store (string, filename); /* store string in filename */
if (d == NULL) { /* validate struct returned */
fprintf (stderr, "error: failed to store string.\n");
return 1;
}
/* output struct values as confirmation of what was stored in file */
printf ("stored: %ld,%s,%s,%d,%d,%s,%s,%s,%s\n", d->date, d->h_team,
d->a_team, d->home_score, d->away_score, d->reason, d->city,
d->country, d->neutral_field );
free_data (d); /* free all memory when done */
return 0;
}
```
While not mandated by the C Standard, the "standard" coding style for C avoids the use of `camelCase` or `MixedCase` variable names in favor of all *lower-case* while reserving *upper-case* names for use with macros and constants. It is a matter of style -- so it is completely up to you, but failing to follow it can lead to the wrong first impression in some circles.
Putting it altogether, you could do something like the following:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 9 /* if you need constants, define one (or more) */
#define MAXC 30
#define MAXL 50
typedef struct { /* struct to hold dynamically allocated data */
long date; /* sized to exact number of chars required. */
int home_score,
away_score;
char *h_team,
*a_team,
*reason,
*city,
*country,
*neutral_field;
} data_t;
typedef struct { /* temp struct to parse data from line */
long date; /* sized to hold largest anticipated data */
int home_score,
away_score;
char h_team[MAXC],
a_team[MAXC],
reason[MAXC],
city[MAXC],
country[MAXC],
neutral_field[MAXN];
} data_tmp_t;
/* pass filename to open, returns open file stream pointer on
* success, NULL otherwise.
*/
FILE *open_output (const char *string)
{
FILE *output = NULL;
if ((output = fopen (string, "w")) == NULL)
fprintf (stderr, "file open failed. '%s'.\n", string);
return output;
}
/* pass temporary struct containing data, dynamic struct allocated,
* each member allocated to hold exact number of chars (+ terminating
* character). pointer to allocated struct returned on success,
* NULL otherwise.
*/
data_t *alloc_data (data_tmp_t *tmp)
{
data_t *d = malloc (sizeof *d); /* allocate structure */
if (d == NULL)
return NULL;
d->date = tmp->date;
/* allocate each string member with strdup. if not available,
* simply use malloc (strlen(str) + 1), and then strcpy.
*/
if ((d->h_team = strdup (tmp->h_team)) == NULL)
return NULL;
if ((d->a_team = strdup (tmp->a_team)) == NULL)
return NULL;
d->home_score = tmp->home_score;
d->away_score = tmp->away_score;
if ((d->reason = strdup (tmp->reason)) == NULL)
return NULL;
if ((d->city = strdup (tmp->city)) == NULL)
return NULL;
if ((d->country = strdup (tmp->country)) == NULL)
return NULL;
if ((d->neutral_field = strdup (tmp->neutral_field)) == NULL)
return NULL;
return d; /* return pointer to allocated struct */
}
/* frees each allocated member of d, and then d itself */
void free_data (data_t *d)
{
free (d->h_team);
free (d->a_team);
free (d->reason);
free (d->city);
free (d->country);
free (d->neutral_field);
free (d);
}
/* parses data in string into separate values and stores data in string
* to filename (note: use mode "a" to append instead of "w" which
* truncates). returns pointer to fully-allocated struct on success,
* NULL otherwise.
*/
data_t *store (const char *string, const char *filename)
{
data_tmp_t tmp = { .date = 0 };
data_t *d = NULL;
FILE *output = open_output (filename); /* no need to pass in */
/* not used later in main */
if (output == NULL) { /* validate file open for writing */
return NULL;
}
/* parse csv values with sscanf - avoids later need to convert values
* validate all values successfully converted.
*/
if (sscanf (string, "%ld,%29[^,],%29[^,],%d,%d,%29[^,],%29[^,],"
"%29[^,],%8[^\n]",
&tmp.date, tmp.h_team, tmp.a_team, &tmp.home_score,
&tmp.away_score, tmp.reason, tmp.city, tmp.country,
tmp.neutral_field) != 9) {
fprintf (stderr, "error: failed to parse string.\n");
return NULL;
}
d = alloc_data (&tmp); /* allocate d and deep-copy tmp to d */
if (d == NULL) { /* validate allocation/copy succeeded */
perror ("malloc-alloc_data");
return NULL;
}
/* output values to file */
fprintf (output, "%ld,%s,%s,%d,%d,%s,%s,%s,%s\n", d->date, d->h_team,
d->a_team, d->home_score, d->away_score, d->reason, d->city,
d->country, d->neutral_field );
if (fclose (output) == EOF) /* always validate close-after-write */
perror ("stream error-output");
return d; /* return fully allocated/populated struct */
}
int main (int argc, char *argv[])
{
char *string = "18820218,Northern Ireland,England,0,13,Friendly,"
"Belfast,Ireland,FALSE";
/* filename set to 1st argument (or "saida.txt" by default) */
char *filename = argc > 1 ? argv[1] : "saida.txt";
data_t *d = NULL;
d = store (string, filename); /* store string in filename */
if (d == NULL) { /* validate struct returned */
fprintf (stderr, "error: failed to store string.\n");
return 1;
}
/* output struct values as confirmation of what was stored in file */
printf ("stored: %ld,%s,%s,%d,%d,%s,%s,%s,%s\n", d->date, d->h_team,
d->a_team, d->home_score, d->away_score, d->reason, d->city,
d->country, d->neutral_field );
free_data (d); /* free all memory when done */
return 0;
}
```
**Example Use/Output**
```
$ ./bin/store_teams dat/saida.txt
stored: 18820218,Northern Ireland,England,0,13,Friendly,Belfast,Ireland,FALSE
```
**Verify Output File**
```
$ cat dat/saida.txt
18820218,Northern Ireland,England,0,13,Friendly,Belfast,Ireland,FALSE
```
**Memory Use/Error Check**
There is no need to cast the return of `malloc`, it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714)
In any code you write that dynamically allocates memory, you have 2 *responsibilities* regarding any block of memory allocated: (1) *always preserve a pointer to the starting address* for the block of memory so, (2) it can be *freed* when it is no longer needed.
It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux `valgrind` is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
```
$ valgrind ./bin/store_teams dat/saida.txt
==16038== Memcheck, a memory error detector
==16038== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==16038== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==16038== Command: ./bin/store_teams dat/saida.txt
==16038==
stored: 18820218,Northern Ireland,England,0,13,Friendly,Belfast,Ireland,FALSE
==16038==
==16038== HEAP SUMMARY:
==16038== in use at exit: 0 bytes in 0 blocks
==16038== total heap usage: 8 allocs, 8 frees, 672 bytes allocated
==16038==
==16038== All heap blocks were freed -- no leaks are possible
==16038==
==16038== For counts of detected and suppressed errors, rerun with: -v
==16038== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```
Always confirm that you have freed all memory you have allocated and that there are no memory errors.
Hopefully this helps you understand how better to approach putting the puzzle pieces together in a less jumbled way and how to focus on what parameters are needed by each function, and how to think about choosing a meaningful type return for each of your functions. Look things over and let me know if you have further questions. | Code as shown will not compile-build for the following reasons:
* The member`d->line1` does not exist in struct.
* The function `void alloc_Data(Data *d, int size)` has two arguments,
but the call: `alloc_Data(d);` has only 1 argument.
Also, since definition for the function `open_output(string, &output);` is not provided, the code cannot be run by anyone attempting to help. (assumptions are made beyond this point)
Beyond that...
This:
```
token = strtok(NULL, ",");
d->h_team = token;
```
is effectively *changing the address* of a previously malloc'ed pointer, resulting in a memory leak. (This is because any subsequent calls to `free(d->h_team);` will be made to an address location that was never malloc'ed).
This:
```
token = strtok(NULL, ",");
strcpy(d->h_team,token);
```
results in assigning the contents residing at the address of `token` to the address located at `d->h_team`, meaning that you can still call `free(d->h_team);` when done using it. (avoiding a memory leak)
To get past the failure you are seeing, this might help:
```
char *string = "18820218,Northern Ireland,England,0,13,Friendly,Belfast,Ireland,FALSE";
char *workingbuf = '\0'
workingbuf = strdup(string);
token = strtok(string, ",");
...
```
One last thought, it is a good idea to check the output of `strtok()` before assuming `token` contains anything:
```
token = strtok(NULL, ",");
if(token)
{
d->h_team = token;
...
```
***Edit***
After implementing the changes I suggested above, including your addition of `open_output`, your code ran. |
11,680,877 | I used to utilize the following:
```
public event EventHandler OnComplete = delegate { };
```
I'm not sure, how this is called, is this an "event default initializer"??
But the problem appeared to be when I derived from EventArgs, created my own EventHandler and decided to use the same approach. Please, see:
```
public class MyEventArgs : EventArgs
{
int result;
public int Result
{
get
{
if (exceptionObject == null)
return result;
else
throw new InvalidOperationException();
}
internal set { result = value; }
}
Exception exceptionObject;
public Exception ExceptionObject
{
get { return exceptionObject; }
internal set { exceptionObject = value; }
}
}
public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);
public class MyOperation
{
public event MyEventHandler OnOperationComplete = delegate { };
}
```
So, the line
```
public event MyEventHandler OnOperationComplete = delegate { };
```
causes the problem.
How can I make the proper default initialization for "my" events? | 2012/07/27 | [
"https://Stackoverflow.com/questions/11680877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467858/"
] | ```
public event MyEventHandler OnOperationComplete = (sender, args) => { return null; };
```
I also think you meant to say:
```
public delegate void MyEventHandler(object sender, MyEventArgs e);
```
not
```
public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);
``` | ```
public event Action OnDied = delegate { };
```
The easiest method |
402,352 | Alright, I'm trying to create I guess an LED matrix display(?) so that I can make essentially a text display using 8x5 LEDs per letter, to make 11 letters in total. I'm definitely willing to learn a lot and NEED to learn a lot as I have little experience with something like this. My goal is to be able to display individual letters to make the display show like "Hey there" using 5x8 LEDs for each letter.
I'm looking to use possibly an arduino device, but as they have limited inputs, and I need about 440 inputs.. how would I make this work? I've researched a bit and it seems I could do something related to this <https://www.circuitspecialists.com/blog/build-8x8-led-matrix> . Would this be my best bet maybe? How would I extend this from 64 to 440 in terms of delivering it to the arduino device?
Also I would like to ask what arduino device might be best for this, and what accessories I might need that aren't mentioned in that page, if the provided link is a good idea.
Edit: Sorry for being somewhat vague. I'd be using 5mm Red LEDs and I only need to be able to turn on and off each individual LED. <https://www.circuitspecialists.com/bag-red5mm.html> | 2018/10/21 | [
"https://electronics.stackexchange.com/questions/402352",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/193539/"
] | Common logic voltage levels are 3.3 V and 5 V, and many batteries have 4.2 V or 4.1 V. So the brown-out levels are obviously designed to be 0.7 V below these supply voltages.
In general, power supplies are assumed to have tolerances of ± 10 % (this is why the datasheet often says "4.5 V – 5.5 V"). And when your power supply outputs 4.5 V, you want to have some additional safety factor so that your microcontroller does not reset at the slightest dip, but only when the voltage is so low that the power supply is (apparently) completely toast. (The decoupling capacitors buffer the voltage, so a dip of 0.7 V indicates that the actual power supply is already lower, and that the decoupling capacitors are already partially discharged.)
In other words: 2.6 V is the correct brown-out level to use for a nominal 3.3 V supply. | Actually when you use battery, your voltage drops gradually. and you dont want your system to stop working while voltage drops just a little bit. and as you can see in the diagram if your clock is 8mhz you can work with supply voltage as low as 2.7 and lower than that is unsafe or unstable. so you'd want brown out detection to detect when your supply voltage is low enough to make the system unstable or unsafe. 2.6v is a good value when your using 8Mhz clock. if you decide to use a higher clock rate then obviously it's good practice to make brown out threshold higher. you can also make the threshold lower if you'd use lower frequencies or want to extend battery life and you'd risk performance in non critical applications. |
402,352 | Alright, I'm trying to create I guess an LED matrix display(?) so that I can make essentially a text display using 8x5 LEDs per letter, to make 11 letters in total. I'm definitely willing to learn a lot and NEED to learn a lot as I have little experience with something like this. My goal is to be able to display individual letters to make the display show like "Hey there" using 5x8 LEDs for each letter.
I'm looking to use possibly an arduino device, but as they have limited inputs, and I need about 440 inputs.. how would I make this work? I've researched a bit and it seems I could do something related to this <https://www.circuitspecialists.com/blog/build-8x8-led-matrix> . Would this be my best bet maybe? How would I extend this from 64 to 440 in terms of delivering it to the arduino device?
Also I would like to ask what arduino device might be best for this, and what accessories I might need that aren't mentioned in that page, if the provided link is a good idea.
Edit: Sorry for being somewhat vague. I'd be using 5mm Red LEDs and I only need to be able to turn on and off each individual LED. <https://www.circuitspecialists.com/bag-red5mm.html> | 2018/10/21 | [
"https://electronics.stackexchange.com/questions/402352",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/193539/"
] | You need to look at the **tolerance** of the brownout voltage threshold as well as the nominal value.
[](https://i.stack.imgur.com/58bWd.png)
The 2.6V setting (and really, any of the settings) is **useless** for a 3.3V nominal supply at any clock frequency. It *might* work, but is that good enough for you? It isn't for me.
If you need a reliable BOD reset you'll have to supply it externally or use different chip.
Perhaps they committed to the settings before they characterized the chip and figured out that it will not operate reliably at (say) 1.8V. | Actually when you use battery, your voltage drops gradually. and you dont want your system to stop working while voltage drops just a little bit. and as you can see in the diagram if your clock is 8mhz you can work with supply voltage as low as 2.7 and lower than that is unsafe or unstable. so you'd want brown out detection to detect when your supply voltage is low enough to make the system unstable or unsafe. 2.6v is a good value when your using 8Mhz clock. if you decide to use a higher clock rate then obviously it's good practice to make brown out threshold higher. you can also make the threshold lower if you'd use lower frequencies or want to extend battery life and you'd risk performance in non critical applications. |
3,000,921 | I'm trying to prove the following statement.
"Let $A$ be a (finite dimensional?) algebra over some field $K$. Then $Ae$ is indecomposable if and only if the idempotent $e$ is primitive."
It is clear to me that if $e=e\_1+e\_2$ for some orthogonal idempotents, then this will yield $Ae=Ae\_1\oplus Ae\_2$. I am however, unsure about the other direction.
I assume that $Ae=P\_1\oplus P\_2$, so that $e=e\_1+e\_2$ for some uniquely determined $e\_1\in P\_1, e\_2\in P\_2$. I can't seem to derive the orthogonality or idempotency of $e\_1, e\_2$. | 2018/11/16 | [
"https://math.stackexchange.com/questions/3000921",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/416046/"
] | **Hint:** It is clear that $\ker T^k\subset\ker T^{k+1}$. So, you have an increasing sequence of subspaces of a $n$-dimensional space. | $N(T^{k}) \subset N(T^{k+1})$. If equality does not hold then the dimension of $N(T^{k})$ must be smaller than that of $N(T^{k+1})$. If the assertion is not true you will get a strictly decreasing sequence of positive integers all less than or equal to the dimension of the space. This is a contradiction. |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.
```
var function_itself = function() {
alert('in function itself');
}
function_itself.PRE_PROCESS = function() {
alert('in pre_process');
}
function_itself.POST_PROCESS = function() {
alert('in post_process');
}
var function_processor = function(func) {
if (func.PRE_PROCESS) {
func.PRE_PROCESS.call();
}
func.call();
if (func.POST_PROCESS) {
func.POST_PROCESS.call();
}
}
``` | I don't know if this will be useful. You do need to modify the original function but only once and you don't need to keep editing it for firing hooks
<https://github.com/rcorp/hooker> |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.
```
var function_itself = function() {
alert('in function itself');
}
function_itself.PRE_PROCESS = function() {
alert('in pre_process');
}
function_itself.POST_PROCESS = function() {
alert('in post_process');
}
var function_processor = function(func) {
if (func.PRE_PROCESS) {
func.PRE_PROCESS.call();
}
func.call();
if (func.POST_PROCESS) {
func.POST_PROCESS.call();
}
}
``` | The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.
```
// usage:
/*
function test(x) {
alert(x);
}
var htest = hookable(test);
htest.addHook("before", function (x) {
alert("Before " + x);
})
htest.addHook("after", function (x) {
alert("After " + x);
})
htest("test") // => Before test ... test ... After test
*/
function hookable(fn) {
var ifn = fn,
hooks = {
before : [],
after : []
};
function hookableFunction() {
var args = [].slice.call(arguments, 0),
i = 0,
fn;
for (i = 0; !!hooks.before[i]; i += 1) {
fn = hooks.before[i];
fn.apply(this, args);
}
ifn.apply(this, arguments);
for (i = 0; !!hooks.after[i]; i++) {
fn = hooks.after[i];
fn.apply(this, args);
}
}
hookableFunction.addHook = function (type, fn) {
if (hooks[type] instanceof Array) {
hooks[type].push(fn);
} else {
throw (function () {
var e = new Error("Invalid hook type");
e.expected = Object.keys(hooks);
e.got = type;
return e;
}());
}
};
return hookableFunction;
}
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Might not be pretty but it seems to work...
```
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
``` | The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.
```
// usage:
/*
function test(x) {
alert(x);
}
var htest = hookable(test);
htest.addHook("before", function (x) {
alert("Before " + x);
})
htest.addHook("after", function (x) {
alert("After " + x);
})
htest("test") // => Before test ... test ... After test
*/
function hookable(fn) {
var ifn = fn,
hooks = {
before : [],
after : []
};
function hookableFunction() {
var args = [].slice.call(arguments, 0),
i = 0,
fn;
for (i = 0; !!hooks.before[i]; i += 1) {
fn = hooks.before[i];
fn.apply(this, args);
}
ifn.apply(this, arguments);
for (i = 0; !!hooks.after[i]; i++) {
fn = hooks.after[i];
fn.apply(this, args);
}
}
hookableFunction.addHook = function (type, fn) {
if (hooks[type] instanceof Array) {
hooks[type].push(fn);
} else {
throw (function () {
var e = new Error("Invalid hook type");
e.expected = Object.keys(hooks);
e.got = type;
return e;
}());
}
};
return hookableFunction;
}
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Take a look at [jQuery's AOP plugin](http://plugins.jquery.com/project/AOP). In general, google "javascript aspect oriented programming". | Here's what I did, might be useful in other applications like this:
```
//Setup a hooking object
a={
hook:function(name,f){
aion.hooks[name]=f;
}
}a.hooks={
//default hooks (also sets the object)
};
//Add a hook
a.hook('test',function(){
alert('test');
});
//Apply each Hook (can be done with for)
$.each(a.hooks,function(index,f){
f();
});
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.
```
// usage:
/*
function test(x) {
alert(x);
}
var htest = hookable(test);
htest.addHook("before", function (x) {
alert("Before " + x);
})
htest.addHook("after", function (x) {
alert("After " + x);
})
htest("test") // => Before test ... test ... After test
*/
function hookable(fn) {
var ifn = fn,
hooks = {
before : [],
after : []
};
function hookableFunction() {
var args = [].slice.call(arguments, 0),
i = 0,
fn;
for (i = 0; !!hooks.before[i]; i += 1) {
fn = hooks.before[i];
fn.apply(this, args);
}
ifn.apply(this, arguments);
for (i = 0; !!hooks.after[i]; i++) {
fn = hooks.after[i];
fn.apply(this, args);
}
}
hookableFunction.addHook = function (type, fn) {
if (hooks[type] instanceof Array) {
hooks[type].push(fn);
} else {
throw (function () {
var e = new Error("Invalid hook type");
e.expected = Object.keys(hooks);
e.got = type;
return e;
}());
}
};
return hookableFunction;
}
``` | Here's what I did, might be useful in other applications like this:
```
//Setup a hooking object
a={
hook:function(name,f){
aion.hooks[name]=f;
}
}a.hooks={
//default hooks (also sets the object)
};
//Add a hook
a.hook('test',function(){
alert('test');
});
//Apply each Hook (can be done with for)
$.each(a.hooks,function(index,f){
f();
});
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Very simple answer:
```
function someFunction() { alert("Bar!") }
var placeholder=someFunction;
someFunction=function() {
alert("Foo?");
placeholder();
}
``` | The following function will give you before and after hooks that can be stacked. So if you have a number of potential functions that need to run before the given function or after the given function then this would be a working solution. This solution does not require jQuery and uses native array methods (no shims required). It should also be context sensitive so if you are calling the original function with a context if should run each before and after function likewise.
```
// usage:
/*
function test(x) {
alert(x);
}
var htest = hookable(test);
htest.addHook("before", function (x) {
alert("Before " + x);
})
htest.addHook("after", function (x) {
alert("After " + x);
})
htest("test") // => Before test ... test ... After test
*/
function hookable(fn) {
var ifn = fn,
hooks = {
before : [],
after : []
};
function hookableFunction() {
var args = [].slice.call(arguments, 0),
i = 0,
fn;
for (i = 0; !!hooks.before[i]; i += 1) {
fn = hooks.before[i];
fn.apply(this, args);
}
ifn.apply(this, arguments);
for (i = 0; !!hooks.after[i]; i++) {
fn = hooks.after[i];
fn.apply(this, args);
}
}
hookableFunction.addHook = function (type, fn) {
if (hooks[type] instanceof Array) {
hooks[type].push(fn);
} else {
throw (function () {
var e = new Error("Invalid hook type");
e.expected = Object.keys(hooks);
e.got = type;
return e;
}());
}
};
return hookableFunction;
}
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Might not be pretty but it seems to work...
```
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
``` | This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.
```
var function_itself = function() {
alert('in function itself');
}
function_itself.PRE_PROCESS = function() {
alert('in pre_process');
}
function_itself.POST_PROCESS = function() {
alert('in post_process');
}
var function_processor = function(func) {
if (func.PRE_PROCESS) {
func.PRE_PROCESS.call();
}
func.call();
if (func.POST_PROCESS) {
func.POST_PROCESS.call();
}
}
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Take a look at [jQuery's AOP plugin](http://plugins.jquery.com/project/AOP). In general, google "javascript aspect oriented programming". | Very simple answer:
```
function someFunction() { alert("Bar!") }
var placeholder=someFunction;
someFunction=function() {
alert("Foo?");
placeholder();
}
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Might not be pretty but it seems to work...
```
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
``` | Here's what I did, might be useful in other applications like this:
```
//Setup a hooking object
a={
hook:function(name,f){
aion.hooks[name]=f;
}
}a.hooks={
//default hooks (also sets the object)
};
//Add a hook
a.hook('test',function(){
alert('test');
});
//Apply each Hook (can be done with for)
$.each(a.hooks,function(index,f){
f();
});
``` |
789,630 | EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | 2009/04/25 | [
"https://Stackoverflow.com/questions/789630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96039/"
] | Might not be pretty but it seems to work...
```
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
``` | Very simple answer:
```
function someFunction() { alert("Bar!") }
var placeholder=someFunction;
someFunction=function() {
alert("Foo?");
placeholder();
}
``` |
33,601,182 | I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
```
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
```
Order Class(nevermind the name Paraggelia I gave it)
```
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
```
Product Class:
```
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
``` | 2015/11/09 | [
"https://Stackoverflow.com/questions/33601182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3976788/"
] | In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
`unset();` for all the session variables `unset($_SESSION['login_user']);` for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session\_start(); should be at very first line in your php file if I am correct, or it throws error. | instead of : **header('Location: index.php');**
try to do it with javascript :
**echo '< script> document.location.href="index.php"< /script>';** |
46,087,971 | i want adding and subtracting this type of data: $12,587.30.which returns answer in same format.how can do this ?
Here is my code example:
```
print(int(col_ammount2.lstrip('$'))-int(col_ammount.lstrip('$')))
```
I removed $ sign and convert it to int but it gives me base 10 error. | 2017/09/07 | [
"https://Stackoverflow.com/questions/46087971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368131/"
] | You mentioned you want to do arithmetic operations to the numbers (addition/subtraction) so you probably want them in `float` instead. The difference between an integer (`int`) and `float` is that integers do not carry decimal points.
Additionally, as @officialaimm mentioned you need to remove the commas too, for example
```
float('$3,333.33'.replace('$', '').replace(',', ''))
```
will give you
```
3333.33
```
So putting it into your code
```
print(float(col_ammount2.lstrip('$').replace(',', ''))
- float(col_ammount.lstrip('$').replace(',', '')))
```
An additional note for when you parse a floating point number (same applies to integers too), you may want to watch out for empty values, i.e.
```
float('')
```
is bad. One of the things u can do in case `col_amount` and `col_amount2` may be empty at some point is default them to `0` if that happens
```
float(col_amount.lstrip(...).replace(...) or 0)
```
You also want to read this to know about workaround to problems you may face with floating point arithmetic <https://docs.python.org/3/tutorial/floatingpoint.html> | There are two things you are missing here. Firstly python `int(...)` cannot parse numbers with commas so you will need to remove commas as well by using `.replace(',','')`. Secondly `int()` cannot parse floating point values you will have to use `float(...)` first and after that maybe typecast it to int using `int` or `math.ceil`, `math.floor` appropriately as per your choice and needs.
Maybe something like this will solve your problem:
```
col_ammount2='$1,587.30'
col_ammount = '$2,567.67'
print(int(float(col_ammount2.lstrip('$').replace(',','')))-int(float(col_ammount.lstrip('$').replace(',',''))))
```
If you are doing these sorts of things quite often in your code, making a function as such might be handy:
```
integerify_currency = lambda x:int(float(x.lstrip('$').replace(',','')))
``` |
18,524,290 | Okay so I need to check if an ip\_adress is already in my database if it is i need to update row 'visit' and add 1. if it doesnt exit then add the ip\_adress to my database in row 'ip\_adress' here is my code:
```
<?php include'connect.php';
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$ip = ip2long($ip);
$result = mysqli_query($con,"SELECT ip_adress FROM ip_visits");
while($row = mysqli_fetch_array($result))
{
$ip_adress = $row['ip_adress'];
if($ip_adress === $ip){
mysqli_query($con,"UPDATE ip_visits SET ip_adress = ip_adress + 1");
}else{
mysqli_query($con,"INSERT INTO ip_visits (ip_adress) VALUES ('$ip')");
}
```
}
```
mysqli_close($con);
?>
``` | 2013/08/30 | [
"https://Stackoverflow.com/questions/18524290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2658101/"
] | You can do it like this
```
SELECT MIN(user_id) user_id,
MIN(friend_id) friend_id
FROM Table1
GROUP BY LEAST(user_id, friend_id),
GREATEST(user_id, friend_id)
HAVING COUNT(*) = 1
```
Given sample data
```
| USER_ID | FRIEND_ID |
|---------|-----------|
| 1 | 2 |
| 2 | 1 |
| 1 | 3 |
| 2 | 4 |
| 5 | 6 |
| 6 | 5 |
```
Output of the query
```
| USER_ID | FRIEND_ID |
|---------|-----------|
| 1 | 3 |
| 2 | 4 |
```
Here is **[SQLFiddle](http://sqlfiddle.com/#!2/84195/1)** demo | You can do this with the `not exists` clause:
```
select f.B as A, f.A as B
from friends f
where not exists (select 1
from friends f2
where f2.A = f.B and f2.B = f.A
);
```
The `select` clause gives you the ones that are missing. Personally, I would just do `select f.*` to get the unmatched friends. |
18,815,691 | I have a form that I'm doing a few simple calculations on. I can't get the calculation to run after I unhide the elements. I have proven that the calculations work outside this form but I'm trying to add it to a form that uses other libraries. I just can't figure out what I need to do to get the calculation to bind to the id's after they are shown. Here's a link to the a partial form with just the needed inputs to keep it simple. [testform](http://ericrohloff.com/test/log/log/test1.html) If you click on "Yes" the elements show that I'm working with. Thanks for any guidance.
Here's the calculation script that I made.
```
<script>
function pottopot() {
if ($('#item78_number_1').val()>0 && $('#item76_number_1').val()>0){
totalpotgals = parseInt($('#item76_number_1').val(),10)
* parseInt($('#item78_number_1').val(),10)
/ parseInt($('#item47_number_1').val(),10);
$('#item48_number_1').val(totalpotgals.toFixed(2));
}
}
</script>
``` | 2013/09/15 | [
"https://Stackoverflow.com/questions/18815691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043630/"
] | You need to bind events after DOM ready. If I understood it correctly you need to put your code in document.ready event. Try:
```
$(document).ready(function(){
//put your jquery code here
});
```
As you are already using jQuery use `.keyup` and `.on` to bind events on DOM elements like:
```
$("input.<YOUR_DOM_CLASS>").on("keyup",function(){
//do something here
});
``` | Try this.
```
$(document).ready(function(){
$("input[name=pottopot]").change(function(){
//call your method that does the calculation.
pottopot();
});
});
```
Try to define all your variable. Avoid any console error.
JavaScript will stop executing if there is an error in the page like, variable not defines etc.
To know the error details open the developer tool **CTRL + SHIFT + I** in chrome. |
19,242,690 | **HTML Code:**
```
<ul id="menu-controls">
<li><a target="_self" onclick="return displaySubMenu(0);" id="menu-controls-0" href="" class=""><span>Home</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(1);" id="menu-controls-1" href="" class=""><span>Oleg Test</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(2);" id="menu-controls-2" href="" class="act"><span>Products</span></a></li>
<li><a class="active" onclick="return displaySubMenu(3);"target="_self" ><span>About Us</span></a> </li>
<li><a class="" onclick="return displaySubMenu(4);"><span>Contact Us</span></a></li>
<li><a class="" onclick="return displaySubMenu(5);" class=""><span>Login / Register</span></a></li>
</ul>
```
How we identify that "previous active class is left or right" when displaySubMenu call on click link?
Need to check "active" class is left or right in display menu function? | 2013/10/08 | [
"https://Stackoverflow.com/questions/19242690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2738734/"
] | You can use `.index()` to determine position of your `a.active` :
```
$("#menu-controls li a").click(function () {
var myActive = $("a.active").parent().index();
var myClicked = $(this).parent().index()
if (myActive < myClicked) {
alert("Previous active was left")
} else if (myActive > myClicked) {
alert("Previous active was right")
} else if (myActive == myClicked) {
alert("Previous active is this clicked one")
}
$("a.active").removeClass("active");
$(this).addClass("active")
})
```
Check the [**Fiddle**](http://jsfiddle.net/7BmD2/) | Don't know if I've understood your question correctly but if I'm right, try this.. Give a generic class(for eg. "items") to each of the anchor tags.. Now in the displaySubMenu function use this->
```
var flag = 0;
var th = $(this);
$(th).parent().find('.items').each(function(){
$(this).removeClass('left');
$(this).removeClass('right');
if(flag == 1){
$(this).addClass('right');
} else
if($(this) == $(th) {
flag = 1;
} else {
$(this).addClass('left');
});
if($(th).parent().find('.active').hasClass('left')){
console.log("Left"); // Write your code here for the case where previously active is left
$(this).removeClass('active');
} else if($(th).parent().find('.active').hasClass('right')){
console.log("Right"); // Write your code here for the case where previously active is right
$(this).removeClass('active');
}
$(th).addClass('active');
```
In this code, I'm simply traversing the anchor tags one by one and all the tags before the currently clicked element are given the class left and those after it are given the class right by using a flag (As those tags written before the currently clicked tag shall be in it's left and vice-versa). Now it is checked if the previously active class has the class left or right and then we add the class active to the currently clicked tag after removing it from the previous tag.. |
19,242,690 | **HTML Code:**
```
<ul id="menu-controls">
<li><a target="_self" onclick="return displaySubMenu(0);" id="menu-controls-0" href="" class=""><span>Home</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(1);" id="menu-controls-1" href="" class=""><span>Oleg Test</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(2);" id="menu-controls-2" href="" class="act"><span>Products</span></a></li>
<li><a class="active" onclick="return displaySubMenu(3);"target="_self" ><span>About Us</span></a> </li>
<li><a class="" onclick="return displaySubMenu(4);"><span>Contact Us</span></a></li>
<li><a class="" onclick="return displaySubMenu(5);" class=""><span>Login / Register</span></a></li>
</ul>
```
How we identify that "previous active class is left or right" when displaySubMenu call on click link?
Need to check "active" class is left or right in display menu function? | 2013/10/08 | [
"https://Stackoverflow.com/questions/19242690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2738734/"
] | You can use `.index()` to determine position of your `a.active` :
```
$("#menu-controls li a").click(function () {
var myActive = $("a.active").parent().index();
var myClicked = $(this).parent().index()
if (myActive < myClicked) {
alert("Previous active was left")
} else if (myActive > myClicked) {
alert("Previous active was right")
} else if (myActive == myClicked) {
alert("Previous active is this clicked one")
}
$("a.active").removeClass("active");
$(this).addClass("active")
})
```
Check the [**Fiddle**](http://jsfiddle.net/7BmD2/) | Here a [FIDDLE](http://jsfiddle.net/cgd6w/) that log if the active element is before or after the clicked one.
Change on HTML : new param in the function 'this'
```
<ul id="menu-controls">
<li><a target="_self" onclick="return displaySubMenu(0, this);" id="menu-controls-0" href="" class=""><span>Home</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(1, this);" id="menu-controls-1" href="" class=""><span>Oleg Test</span></a></li>
<li><a target="_self" onclick="return displaySubMenu(2, this);" id="menu-controls-2" href="" class="act"><span>Products</span></a></li>
<li><a class="" onclick="return displaySubMenu(3, this);"target="_self" ><span>About Us</span></a> </li>
<li><a class="active" onclick="return displaySubMenu(4, this);"><span>Contact Us</span></a></li>
<li><a class="" onclick="return displaySubMenu(5, this);" class=""><span>Login / Register</span></a></li>
</ul>
```
the JQUERY :
```
function displaySubMenu(number, element){
var lastActive = $('.active').parents('li');
var currentClick = $(element).parents('li');
console.log(lastActive);console.log(currentClick);
if($(currentClick).next(lastActive).length){
var lastPosition = 'right';
} else {
var lastPosition = 'left';
}
console.log(lastPosition);
}
``` |
7,753 | Before building up a new frame, it's crucially important to ream/face the headtube and crown race seat (and the bottom bracket, if using press-fit cups). You should also ideally chase the threads of the BB and the derailleur hanger.
But why don't manufacturers (e.g., [Surly](http://surlybikes.com/info_hole/spew/spew_care_and_feeding_of_your_steel_frame)) do this before they leave the factory? Surly in particular mentions that they *do* in fact face their head tubes, but they do so before painting the frame, requiring new frame owners to re-face them.
Why wouldn't they just do this before shipping the frame out? It seems like a no-brainer. | 2012/01/18 | [
"https://bicycles.stackexchange.com/questions/7753",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/1442/"
] | **First** thing that comes to my mind is labour costs.
**Second** thing that comes to mind is that once you break that paint seal by reaming/facing you are allowing contact with the air and elements. As a good practice you should coat the threads with a little grease before assembly, meaning that when you get that new frame, you tap out the mounting holes and then screw in the mounting bolt with grease that will re-seal the exposed metal.
**Third**..tradition. New frames never came faced in the old days as it was expected that the professional bike mechanic would be doing all that as it was their job. | It is important to note that most manufacturer's of quality frames do face and ream their frames before they assemble or ship. They often do it before paint because they do it with machinery to build/assemble their frames, which allow a level of precision which wasn't possible with a locally produced hand built frame. So facing to raw metal isn't necessary anymore.
In addition, the components installed on a modern bicycle often require a level of precision in frame specifications which can be destroyed by hand reaming or facing a frame after purchase. Campagnolo Ultra Torque cranks in particular, when installed, require a very specific shell width for the bottom bracket to be installed and function correctly. The tolerance range is less than .5 millimeters.
So it is not always automatically a good idea to face your frame in a shop or on your own. |
6,766 | The title pretty much sums up my question: is it more beneficial to take a hot (warm) shower after a workout or a cold one?
I've noticed that I tend to feel more relaxed while taking a warmer shower and my muscles loosen up, but when you see professional athletes, they seem to quickly ice themselves down.
So I was just wondering if one is more beneficial than the other. | 2012/06/12 | [
"https://fitness.stackexchange.com/questions/6766",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/3654/"
] | As athletes after a substantial workout ice baths (54 degrees Fahrenheit / 12 degrees Celsius and below) is good for the body to halt the excessive blood flow which you have induced through stress training. This allows for faster recovery and allows the body to recharge the nervous system for the subsequent day; in an extremely minimal fashion though.
Hot tubbing (or hot showers) increases blood flow and allows specifically the joints and small muscles to warm up for your upcoming level of stress which you put your body under. The circulation welcomes more fluid distribution in your joints and acts as a cushion for the stress (say in running, jumping, Olympic lifting, etc...). These are best done BEFORE you work out.
I have found from experience that the trick is being consistent in ice bathing after each workout and even on your off days to ice bath to speed recovery. The less inflamed a muscle is the greater the opportunity you have to work it out again. Hence people prescribe 48-72 hours of rest before the next same muscle group stimulation.
There is always the option of doing transition showers. These are hot and cold showers which *shock* the body. You can time your transition showers by doing 1 minute hot and 3 minutes cold/cool.
Honestly take a mildly warm shower after you workout. The extra sweat releases the toxins your body built up for the workout. See it as doing an extended cool down with stretching in a warm room. The muscles relax and the toxins of stress are released from the body. The cold shower won't make a substantial difference in your recovery unless you stand there for 20 minutes straight in freezing cold water.
As George Constanza put it so eloquently "Cold Showers? They're for psychotics". | Cold showers/icing help reduce swelling and inflammation.
I view it the same way as treating acute injuries: you ice the first 24-48 hrs, *then* heat.
OTOH, I dislike cold showers, so my view, and my actions, aren't always in alignment. |
6,766 | The title pretty much sums up my question: is it more beneficial to take a hot (warm) shower after a workout or a cold one?
I've noticed that I tend to feel more relaxed while taking a warmer shower and my muscles loosen up, but when you see professional athletes, they seem to quickly ice themselves down.
So I was just wondering if one is more beneficial than the other. | 2012/06/12 | [
"https://fitness.stackexchange.com/questions/6766",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/3654/"
] | Cold showers/icing help reduce swelling and inflammation.
I view it the same way as treating acute injuries: you ice the first 24-48 hrs, *then* heat.
OTOH, I dislike cold showers, so my view, and my actions, aren't always in alignment. | Just to add some research evidence to back up the two other answers:
A Cochrane systematic review: Leeder, Jonathan, Conor Gissane, Ken van Someren, Warren Gregson, and Glyn Howatson. "Cold water immersion and recovery from strenuous exercise: a meta-analysis." British journal of sports medicine (2011): bjsports-2011. <https://scholar.google.com/scholar?cluster=17487784705795906396&hl=en&as_sdt=0,22> ; <http://onlinelibrary.wiley.com/doi/10.1002/14651858.CD008262.pub2/full>
>
> There was some evidence that cold-water immersion reduces delayed onset muscle soreness after exercise compared with passive interventions involving rest or no intervention. There was insufficient evidence to conclude on other outcomes or for other comparisons. The majority of trials did not undertake active surveillance of pre-defined adverse events. High quality, well reported research in this area is required.
>
>
>
A more detailed abstract:
>
> Delayed onset muscle soreness commonly results after sports and
> exercise activity. Cold-water immersion (CWI), which involves people
> immersing themselves in water at temperatures of less than 15°C, is
> sometimes used to manage muscle soreness after exercise and to speed
> up recovery time.
>
>
> Our review included 17 small trials, involving a total of 366
> participants. Study quality was low. Fourteen trials compared
> cold-water immersion applied after exercise with 'passive' treatment
> involving rest or no treatment. The temperature, duration and
> frequency of cold-water immersion varied between the different trials
> as did the exercises and settings. There was some evidence that
> cold-water immersion reduces muscle soreness at 24, 48, 72 and even at
> 96 hours after exercise compared with 'passive' treatment. Limited
> evidence from four trials indicated that participants considered that
> cold-water immersion improved recovery/reduced fatigue immediately
> afterwards. Most of the trials did not consider complications relating
> to cold-water immersion and so we cannot say whether these are a
> problem. There were only limited data available for other comparisons
> of cold-water immersion versus warm or contrasting (alternative
> warm/cold) water immersion, light jogging, and compression stockings.
> None of these showed important differences between the interventions
> being compared.
>
>
> While the evidence shows that cold-water immersion reduces delayed
> onset muscle soreness after exercise, the optimum method of cold-water
> immersion and its safety are not clear.
>
>
>
A few other systematic reviews:
* Ranalli, Gregory F., Julianne K. DeMartini, Douglas J. Casa, Brendon P. McDermott, Lawrence E. Armstrong, and Carl M. Maresh. "Effect of body cooling on subsequent aerobic and anaerobic exercise performance: a systematic review." The Journal of Strength & Conditioning Research 24, no. 12 (2010): 3488-3496. <https://scholar.google.com/scholar?cluster=8065838624919032849&hl=en&as_sdt=0,22>
* Torres, Rui, Fernando Ribeiro, José Alberto Duarte, and Jan MH Cabri. "Evidence of the physiotherapeutic interventions used currently after exercise-induced muscle damage: systematic review and meta-analysis." Physical Therapy in Sport 13, no. 2 (2012): 101-114. <https://scholar.google.com/scholar?cluster=3409581060760059325&hl=en&as_sdt=0,22> |
6,766 | The title pretty much sums up my question: is it more beneficial to take a hot (warm) shower after a workout or a cold one?
I've noticed that I tend to feel more relaxed while taking a warmer shower and my muscles loosen up, but when you see professional athletes, they seem to quickly ice themselves down.
So I was just wondering if one is more beneficial than the other. | 2012/06/12 | [
"https://fitness.stackexchange.com/questions/6766",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/3654/"
] | As athletes after a substantial workout ice baths (54 degrees Fahrenheit / 12 degrees Celsius and below) is good for the body to halt the excessive blood flow which you have induced through stress training. This allows for faster recovery and allows the body to recharge the nervous system for the subsequent day; in an extremely minimal fashion though.
Hot tubbing (or hot showers) increases blood flow and allows specifically the joints and small muscles to warm up for your upcoming level of stress which you put your body under. The circulation welcomes more fluid distribution in your joints and acts as a cushion for the stress (say in running, jumping, Olympic lifting, etc...). These are best done BEFORE you work out.
I have found from experience that the trick is being consistent in ice bathing after each workout and even on your off days to ice bath to speed recovery. The less inflamed a muscle is the greater the opportunity you have to work it out again. Hence people prescribe 48-72 hours of rest before the next same muscle group stimulation.
There is always the option of doing transition showers. These are hot and cold showers which *shock* the body. You can time your transition showers by doing 1 minute hot and 3 minutes cold/cool.
Honestly take a mildly warm shower after you workout. The extra sweat releases the toxins your body built up for the workout. See it as doing an extended cool down with stretching in a warm room. The muscles relax and the toxins of stress are released from the body. The cold shower won't make a substantial difference in your recovery unless you stand there for 20 minutes straight in freezing cold water.
As George Constanza put it so eloquently "Cold Showers? They're for psychotics". | Just to add some research evidence to back up the two other answers:
A Cochrane systematic review: Leeder, Jonathan, Conor Gissane, Ken van Someren, Warren Gregson, and Glyn Howatson. "Cold water immersion and recovery from strenuous exercise: a meta-analysis." British journal of sports medicine (2011): bjsports-2011. <https://scholar.google.com/scholar?cluster=17487784705795906396&hl=en&as_sdt=0,22> ; <http://onlinelibrary.wiley.com/doi/10.1002/14651858.CD008262.pub2/full>
>
> There was some evidence that cold-water immersion reduces delayed onset muscle soreness after exercise compared with passive interventions involving rest or no intervention. There was insufficient evidence to conclude on other outcomes or for other comparisons. The majority of trials did not undertake active surveillance of pre-defined adverse events. High quality, well reported research in this area is required.
>
>
>
A more detailed abstract:
>
> Delayed onset muscle soreness commonly results after sports and
> exercise activity. Cold-water immersion (CWI), which involves people
> immersing themselves in water at temperatures of less than 15°C, is
> sometimes used to manage muscle soreness after exercise and to speed
> up recovery time.
>
>
> Our review included 17 small trials, involving a total of 366
> participants. Study quality was low. Fourteen trials compared
> cold-water immersion applied after exercise with 'passive' treatment
> involving rest or no treatment. The temperature, duration and
> frequency of cold-water immersion varied between the different trials
> as did the exercises and settings. There was some evidence that
> cold-water immersion reduces muscle soreness at 24, 48, 72 and even at
> 96 hours after exercise compared with 'passive' treatment. Limited
> evidence from four trials indicated that participants considered that
> cold-water immersion improved recovery/reduced fatigue immediately
> afterwards. Most of the trials did not consider complications relating
> to cold-water immersion and so we cannot say whether these are a
> problem. There were only limited data available for other comparisons
> of cold-water immersion versus warm or contrasting (alternative
> warm/cold) water immersion, light jogging, and compression stockings.
> None of these showed important differences between the interventions
> being compared.
>
>
> While the evidence shows that cold-water immersion reduces delayed
> onset muscle soreness after exercise, the optimum method of cold-water
> immersion and its safety are not clear.
>
>
>
A few other systematic reviews:
* Ranalli, Gregory F., Julianne K. DeMartini, Douglas J. Casa, Brendon P. McDermott, Lawrence E. Armstrong, and Carl M. Maresh. "Effect of body cooling on subsequent aerobic and anaerobic exercise performance: a systematic review." The Journal of Strength & Conditioning Research 24, no. 12 (2010): 3488-3496. <https://scholar.google.com/scholar?cluster=8065838624919032849&hl=en&as_sdt=0,22>
* Torres, Rui, Fernando Ribeiro, José Alberto Duarte, and Jan MH Cabri. "Evidence of the physiotherapeutic interventions used currently after exercise-induced muscle damage: systematic review and meta-analysis." Physical Therapy in Sport 13, no. 2 (2012): 101-114. <https://scholar.google.com/scholar?cluster=3409581060760059325&hl=en&as_sdt=0,22> |
60,204,201 | I have 3 sections. Each section has their height. JSFiddle at the end of the question.
**GOAL**: I want an img (rocket picture) to follow the user as he scrolls and **change positions (slide) from right to left** when he scrolls pass a section.
I've managed to make the rocket follow me as I scroll down. Now I want the rocket to slide over to the left when I pass the first section, then slide back right when I pass the second section.
The rocket rotates when the user scrolls pass a section. That works great! But when I want it to slide
over to a different side, **it only works on the left. I can't get it to go right** Here is the jQuery part for moving the rocket :
```
$(document).scroll(function() {
var scrollIs = $(window).scrollTop();
console.log("I've scrolled: ", scrollIs);
if($(window).scrollTop() >= topOfSecondSection - 230){ //passed first section
$(".rocket").css('transform', 'rotate(50deg)'); //turn rocket WORKS
//$(".rocket").css('left', '10px'); //JUMP CUTS THE ROCKET TO LEFT SIDE, DOESN'T SLIDE/MOVE IT
$(".rocket").stop().animate({ "left": "10px"}, 100); //ISN'T INSTANT-SMOOTH
$("#first-section").css("background","red");
$("#second-section").css("background","blue");
$("#third-section").css("background","orange");
}
if($(window).scrollTop() >= topOfThirdSection - 150){ //passed second section
$(".rocket").css('transform', 'rotate(1deg)'); //turns rocket back to look straight WORKS
//$(".rocket").css('right', '10px'); //move rocket right DOESNT'T MOVE
$(".rocket").stop().animate({ "right": "10px"}, 100); //DOESN'T MOVE
$("#first-section").css("background","purple");
$("#second-section").css("background","yellow");
$("#third-section").css("background","brown");
}
//DEFAULT
if($(window).scrollTop() < s1Height){
//return to normal
$(".rocket").css('transform', 'rotate(1deg)'); //WORKS
//$(".rocket").css('right', '10px'); //DOESN'T MOVE
$(".rocket").stop().animate({ "right": "10px"}, 100); //DOESN'T MOVE
$("#first-section").css("background","green");
$("#second-section").css("background","grey");
}
});
```
---
Here is the JSFiddle: **<https://jsfiddle.net/prozik/d7g3wtye/101/>**
[](https://i.stack.imgur.com/kReCV.png)
EDIT:
When I create in CSS:
```
.moveLeft {
left: 10px;
}
.moveRight {
right: 10px;
}
```
And then in jQuery I do:
```
$(".rocket").removeClass("moveLeft");
$(".rocket").addClass("moveRight");
```
It works. It moves the element right / left. But it blinks the rocket in the position. I need it to slide over to a different slide.
JSFiddlle: <https://jsfiddle.net/prozik/d7g3wtye/113/> | 2020/02/13 | [
"https://Stackoverflow.com/questions/60204201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7232826/"
] | Don't use raw types (look at the diamond operator at the end of the declaration) and favor constructor over setter when you can :
```
final List<Student> studentList = new ArrayList<>();
studentList.add(new Student(value));
```
If the list is designed to be immutable, with Java 9 it would be just :
```
final List<Student> studentList = List.of(new Student(value)) ;
``` | ```
List<Student> list = Stream.of(new Student("name"))
.collect(Collectors.toList());
```
The name of the student would be passed in constructor instead of a setter.
Or via `Arrays` **(exists since JDK 1.5)**
```
List<Student> list = Arrays.asList(new Student("name"));
```
`Arrays.asList()` method can take as many objects (student) as you want to. Check its [Javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)). |
344,906 | For one dimensional non-relativistic quantum mechanics, the solutions to $\hat H\psi=E\psi$ seems not requiring the energy $E\_n$ to contain the "$n$" term without specific boundary conditions.
Does the quantization come from that the wave function $\psi$ should vanish at infinity?
That is the boundary condition:
$$\psi\to0 \ \ \text{as} \ \ x\to\infty.$$
---
Sorry if the question is already asked. | 2017/07/10 | [
"https://physics.stackexchange.com/questions/344906",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/158306/"
] | I have no idea what you mean by "requiring a common n term" but it is very convenenient to think of quantization as resulting from imposing boundary conditions to solutions of the Schrodinger equation. This perspective is often found in elementary texts that present quantization by analogy to the appearance of (discrete) normal modes on a string or in a tube resulting from forcing a node or an antinode at one end (or both ends) of the physical system.
Specifically, it is not hard to find solutions of the Schrodinger equation for arbitrary potentials, but it is a lot more delicate to find solutions *that satisfy the boundary conditions* for this potential. This last requirement very severely restricts the possible choices of the eigenvalues: you can try increasing by a tiny amount the energy $E\_n$ of the $n$'th eigenstate of the simple harmonic oscillator and the wave function will eventually diverge.
In the case of exactly solvable potentials, like the harmonic oscillator or the hydrogen atom, the boundary conditions at $\infty$ dictate the asymptotic behavior of $\psi(x)$ or $\psi(r)$. This asymptotic behavior is found as a first step and then included in an ansatz function that interpolates from $\infty$ back to finite values and must satisfy some differential equation for finite values of $x$ or $r$. Quantization "occurs" when one must select those interpolating functions that do not "undo" the asymptotic behavior already found.
If you can access it, [this older paper](http://www.tandfonline.com/doi/abs/10.1080/00107516408203103?journalCode=tcph20) by Sir Nevill Mott contains an excellent summary of the relation between quantization and boundary conditions.
(I see @tparker has already adressed the issue of compact support.) | You are correct that typically only bound states (corresponding to the boundary condition that your wrote down) have discrete energy levels.
But you used the term "compact support" the wrong way. "Compact support" doesn't mean the boundary condition that you wrote down; it means that the wavefunction is *identically* zero outside of some finite maximum radius $R$ from the origin, not just that it approaches zero. It is very rare for energy eigenstates to have compact support. |
214,017 | I have an ASP.NET MVC 4 solution that I'm putting together, leveraging IoC and the repository pattern using Entity Framework 5. I have a new requirement to be able to pull data from a second database (from another internal application) which I don't have control over.
There is no API available unfortunately for the second application and the general pattern at my place of work is to go direct to the database.
I want to maintain a consistent approach to modeling the domain and use entity framework to pull the data out, so thus far I have used Entity Framework's database first approach to generate a domain model and database context over the top of this.
However, I've become a little stuck on how to include the second domain model in the application.
I have a generic repository which I've now moved out to a common DataAccess project, but short of creating two distinct wrappers for the generic repository (so each can identify with a specific database context), I'm struggling to see how I can elegantly include multiple models? | 2013/10/10 | [
"https://softwareengineering.stackexchange.com/questions/214017",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/104543/"
] | When talking to an external system you are building an integration. When you integrate with someone, this someone does not become part of your domain model.
As you mentioned, you have no control of that other database. If one day they change something in their tables, your whole application will become unusable and there will be very little you can do except changing your application.
What integration normally assumes and you mentined that too is an API. If you have no API you have build your own. Create a separate service that will read from that database and give it to your main application via an API. Every communication that occurs between your system an external system can be divided to messages (one or two way) and on-demand data requests. For messages you can use a bus like MassTransit or NServiceBus and you build your own module, in vase of NServiceBus it would be a satellite, to transfer messages to and from the external database. If this is on-demand data requests, you can build your own web service that will read from that external database and provide it to your external system for reading via web service calls.
How you work with external database within the adapter is your own choice. You can use EF if you like. If they change their table you will just change your adapter.
Plus, this adapter approach (in fact this is a design pattern) you can easily switch when they come up with a proper API one day or may be any other method like exchanging XML files or similar.
And one last comment - the fact that you created a model in EF designer by clicking "read from database" button or how it called does not mean you got a domain model. You just got some classes that mapped to some tables. Some call it "domain model" but believe me, it is not. | I think at some point you are going to have to write two adapters. Interfaces are a great way to tie things together, but each model needs to access its own data.
I think you are on the rigjt path by seperating out the data access. If you have both models interact through an interface, adding more models in the future will be easier.
What objects knows the context on the information being saved? I can see where you could have a couple of objects som type of SQL statement object to write to the database. Even then you still need to translate to/from the domain models.
Good luck. |
214,017 | I have an ASP.NET MVC 4 solution that I'm putting together, leveraging IoC and the repository pattern using Entity Framework 5. I have a new requirement to be able to pull data from a second database (from another internal application) which I don't have control over.
There is no API available unfortunately for the second application and the general pattern at my place of work is to go direct to the database.
I want to maintain a consistent approach to modeling the domain and use entity framework to pull the data out, so thus far I have used Entity Framework's database first approach to generate a domain model and database context over the top of this.
However, I've become a little stuck on how to include the second domain model in the application.
I have a generic repository which I've now moved out to a common DataAccess project, but short of creating two distinct wrappers for the generic repository (so each can identify with a specific database context), I'm struggling to see how I can elegantly include multiple models? | 2013/10/10 | [
"https://softwareengineering.stackexchange.com/questions/214017",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/104543/"
] | When talking to an external system you are building an integration. When you integrate with someone, this someone does not become part of your domain model.
As you mentioned, you have no control of that other database. If one day they change something in their tables, your whole application will become unusable and there will be very little you can do except changing your application.
What integration normally assumes and you mentined that too is an API. If you have no API you have build your own. Create a separate service that will read from that database and give it to your main application via an API. Every communication that occurs between your system an external system can be divided to messages (one or two way) and on-demand data requests. For messages you can use a bus like MassTransit or NServiceBus and you build your own module, in vase of NServiceBus it would be a satellite, to transfer messages to and from the external database. If this is on-demand data requests, you can build your own web service that will read from that external database and provide it to your external system for reading via web service calls.
How you work with external database within the adapter is your own choice. You can use EF if you like. If they change their table you will just change your adapter.
Plus, this adapter approach (in fact this is a design pattern) you can easily switch when they come up with a proper API one day or may be any other method like exchanging XML files or similar.
And one last comment - the fact that you created a model in EF designer by clicking "read from database" button or how it called does not mean you got a domain model. You just got some classes that mapped to some tables. Some call it "domain model" but believe me, it is not. | Taking a step back from your actual question, you could be in for a whole world of pain if the rug is pulled from under you by the other project changing it's schema.
You acknowledge the other system does not have an API for you to use. I would push for this to be created.
The other project may not be be in an active workstream, have budget etc, so maybe your project will have to pay for it in some fashion, and maybe even you have to do the work. |
58,760,818 | I want to replace last 2 values of one of the column with zero. I understand for NaN values, I am able to use .fillna(0), but I would like to replace row 6 value of the last column as well.
```
Weight Name Age d_id_max
0 45 Sam 14 2
1 88 Andrea 25 1
2 56 Alex 55 1
3 15 Robin 8 3
4 71 Kia 21 3
5 44 Sia 43 2
6 54 Ryan 45 1
7 34 Dimi 65 NaN
```
df.drop(df.tail(2).index,inplace=True)
```
Weight Name Age d_id_max
0 45 Sam 14 2
1 88 Andrea 25 1
2 56 Alex 55 1
3 15 Robin 8 3
4 71 Kia 21 3
5 44 Sia 43 2
6 54 Ryan 45 0
7 34 Dimi 65 0
``` | 2019/11/08 | [
"https://Stackoverflow.com/questions/58760818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11079456/"
] | Before pandas 0.20.0 (long time) it was job for `ix`, but [now it is deprecated](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#ix-indexer-is-deprecated). So you can use:
[`DataFrame.iloc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) for get last rows and also [`Index.get_loc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html) for positions of column `d_id_max`:
```
df.iloc[-2:, df.columns.get_loc('d_id_max')] = 0
print (df)
Weight Name Age d_id_max
0 45 Sam 14 2.0
1 88 Andrea 25 1.0
2 56 Alex 55 1.0
3 15 Robin 8 3.0
4 71 Kia 21 3.0
5 44 Sia 43 2.0
6 54 Ryan 45 0.0
7 34 Dimi 65 0.0
```
Or [`DataFrame.loc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) with indexing index values:
```
df.loc[df.index[-2:], 'd_id_max'] = 0
``` | Try `.iloc` and `get_loc`
```
df.iloc[[-1,-2], df.columns.get_loc('d_id_max')] = 0
Out[232]:
Weight Name Age d_id_max
0 45 Sam 14 2.0
1 88 Andrea 25 1.0
2 56 Alex 55 1.0
3 15 Robin 8 3.0
4 71 Kia 21 3.0
5 44 Sia 43 2.0
6 54 Ryan 45 0.0
7 34 Dimi 65 0.0
``` |
58,760,818 | I want to replace last 2 values of one of the column with zero. I understand for NaN values, I am able to use .fillna(0), but I would like to replace row 6 value of the last column as well.
```
Weight Name Age d_id_max
0 45 Sam 14 2
1 88 Andrea 25 1
2 56 Alex 55 1
3 15 Robin 8 3
4 71 Kia 21 3
5 44 Sia 43 2
6 54 Ryan 45 1
7 34 Dimi 65 NaN
```
df.drop(df.tail(2).index,inplace=True)
```
Weight Name Age d_id_max
0 45 Sam 14 2
1 88 Andrea 25 1
2 56 Alex 55 1
3 15 Robin 8 3
4 71 Kia 21 3
5 44 Sia 43 2
6 54 Ryan 45 0
7 34 Dimi 65 0
``` | 2019/11/08 | [
"https://Stackoverflow.com/questions/58760818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11079456/"
] | Before pandas 0.20.0 (long time) it was job for `ix`, but [now it is deprecated](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#ix-indexer-is-deprecated). So you can use:
[`DataFrame.iloc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) for get last rows and also [`Index.get_loc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html) for positions of column `d_id_max`:
```
df.iloc[-2:, df.columns.get_loc('d_id_max')] = 0
print (df)
Weight Name Age d_id_max
0 45 Sam 14 2.0
1 88 Andrea 25 1.0
2 56 Alex 55 1.0
3 15 Robin 8 3.0
4 71 Kia 21 3.0
5 44 Sia 43 2.0
6 54 Ryan 45 0.0
7 34 Dimi 65 0.0
```
Or [`DataFrame.loc`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) with indexing index values:
```
df.loc[df.index[-2:], 'd_id_max'] = 0
``` | You can use:
```
df['d_id_max'].iloc[-2:] = 0
Weight Name Age d_id_max
0 45 Sam 14 2.0
1 88 Andrea 25 1.0
2 56 Alex 55 1.0
3 15 Robin 8 3.0
4 71 Kia 21 3.0
5 44 Sia 43 2.0
6 54 Ryan 45 0.0
7 34 Dimi 65 0.0
``` |
12,744,613 | I am new to web service. I have given a task to write a client code which will call a authentication web service which is exposed on https. I need to pass username and password from client code to check for valid user. I also have keystore and trustore file. I don't know how to use these files. Can anyone please guide me and provide a sample client code?
I am using Axis to generate client stub from wsdl.
Regards,
Vishal | 2012/10/05 | [
"https://Stackoverflow.com/questions/12744613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1357784/"
] | thats because you're sending JSON
standard php $\_POST is build from key-value pairs
so you should post key1=value1&key2=value2
or you should read from
```
$HTTP_RAW_POST_DATA
```
or
```
<?php $postdata = file_get_contents("php://input"); ?>
```
and use
```
json_decode( $postdata );
```
PHP will not automatically decode json for you
you can also use another approach and POST your json like data=YourJsonCode
and then decode it using json\_decode( $\_POST['data'] ); | Try sending url encoded name/value pairs. You can also use `EntityUtils` to convert the response to a `String` for you.
```
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
``` |
12,744,613 | I am new to web service. I have given a task to write a client code which will call a authentication web service which is exposed on https. I need to pass username and password from client code to check for valid user. I also have keystore and trustore file. I don't know how to use these files. Can anyone please guide me and provide a sample client code?
I am using Axis to generate client stub from wsdl.
Regards,
Vishal | 2012/10/05 | [
"https://Stackoverflow.com/questions/12744613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1357784/"
] | Problem solved. There was a htaccess file that redirected all non www pages. | Try sending url encoded name/value pairs. You can also use `EntityUtils` to convert the response to a `String` for you.
```
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
``` |
63,037,501 | I have some data with the following features: `id, group, sex, datebirth, date1, date2, date3, ctrl1, ctrl2, ctrl3, ab4v1, ab4v2, ab4v3`.
What I want is to transform this dataframe onto another one with the following columns in long format: `id, group, sex, datebirth, version, date, ctrl, ab4`.
(NOTE: `version` will get values 1, 2 or 3).
Usually, I would use reshape function in R, but I have to use `pivot_longer`. How could I do this transformation?
I tried things like:
```
df %>% pivot_longer(cols = -c("id","group","sex","datebirth"),
names_to = c("version",".value"),
names_pattern = "([A-Za-z]+)(\\d+)")
```
But I get nothing... Any ideas?
Thank you in advance.
This is what I have:
```
id group sex datebirth date1 date2 date3 ctrl1 ctrl2 ctrl3 ab4v1 ab4v2 ab4v3
1 1 A Male 1975-01-08 2010-10-10 2011-11-12 2011-12-12 183 835 139 745 584 817
2 2 B Male 1998-05-12 2010-10-10 2011-11-12 2011-12-12 172 727 214 793 653 499
3 3 A Male 2005-12-28 2010-10-10 2011-11-23 2011-12-23 157 667 222 664 505 924
4 4 C Female 1957-07-01 2010-10-10 2011-11-25 2011-12-25 186 123 344 584 582 653
```
This is what I want:
```
id group sex datebirth version date ctrl ab4
1 1 A Male 1975-01-08 1 2010-10-10 183 745
2 2 B Male 1998-05-12 1 2010-10-10 172 793
3 3 A Male 2005-12-28 1 2010-10-10 157 664
4 4 C Female 1957-07-01 1 2010-10-10 186 584
.........
``` | 2020/07/22 | [
"https://Stackoverflow.com/questions/63037501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13976843/"
] | We need the change the order of `names_to`. We could either use `names_sep` or `names_pattern`. The only difference is that `names_sep` directs to a delimiter. Here the delimiter is the boundary between a letter (`(?<=[A-Za-z])`) and a digit (`(?=[0-9]$)`). Here, it means check for the boundary that succeeds a letter and precedes a digit. With the `names_pattern`, we are capturing specific sets of characters in a group (`(...)`). The OP's post used that `"([A-Za-z]+)(\\d+)"` i.e. one or more letters as the first group and digits as the second group.
```
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = date1:ab4v3, names_to = c(".value", "version"),
names_sep = "(?<=[A-Za-z])(?=[0-9]$)")
# A tibble: 12 x 8
# id group sex datebirth version date ctrl ab4v
# <int> <chr> <chr> <chr> <chr> <chr> <int> <int>
# 1 1 A Male 1975-01-08 1 2010-10-10 183 745
# 2 1 A Male 1975-01-08 2 2011-11-12 835 584
# 3 1 A Male 1975-01-08 3 2011-12-12 139 817
# 4 2 B Male 1998-05-12 1 2010-10-10 172 793
# 5 2 B Male 1998-05-12 2 2011-11-12 727 653
# 6 2 B Male 1998-05-12 3 2011-12-12 214 499
# 7 3 A Male 2005-12-28 1 2010-10-10 157 664
# 8 3 A Male 2005-12-28 2 2011-11-23 667 505
# 9 3 A Male 2005-12-28 3 2011-12-23 222 924
#10 4 C Female 1957-07-01 1 2010-10-10 186 584
#11 4 C Female 1957-07-01 2 2011-11-25 123 582
#12 4 C Female 1957-07-01 3 2011-12-25 344 653
```
### data
```
df <- structure(list(id = 1:4, group = c("A", "B", "A", "C"), sex = c("Male",
"Male", "Male", "Female"), datebirth = c("1975-01-08", "1998-05-12",
"2005-12-28", "1957-07-01"), date1 = c("2010-10-10", "2010-10-10",
"2010-10-10", "2010-10-10"), date2 = c("2011-11-12", "2011-11-12",
"2011-11-23", "2011-11-25"), date3 = c("2011-12-12", "2011-12-12",
"2011-12-23", "2011-12-25"), ctrl1 = c(183L, 172L, 157L, 186L
), ctrl2 = c(835L, 727L, 667L, 123L), ctrl3 = c(139L, 214L, 222L,
344L), ab4v1 = c(745L, 793L, 664L, 584L), ab4v2 = c(584L, 653L,
505L, 582L), ab4v3 = c(817L, 499L, 924L, 653L)), class = "data.frame",
row.names = c("1",
"2", "3", "4"))
``` | The following is ugly but I believe it might work. It's a sequence of `pivot_longer` statements, taking care of one variable in wide format at a time.
```
library(dplyr)
library(tidyr)
fun <- function(X, Var){
Vard <- paste0(Var, "\\d")
X %>%
select(1:4, matches( {{ Vard }} )) %>%
pivot_longer(
cols = matches( {{ Vard }} ),
names_to = "version",
values_to = Var
) %>%
mutate(version = sub(Var, "", version))
}
vars <- c("date", "ctrl", "ab4v")
Reduce(function(x, y) merge(x, y), lapply(vars, function(v) fun(df1, v)))
# id group sex datebirth version date ctrl ab4v
#1 1 A Male 1975-01-08 1 2010-10-10 183 745
#2 1 A Male 1975-01-08 2 2011-11-12 835 584
#3 1 A Male 1975-01-08 3 2011-12-12 139 817
#4 2 B Male 1998-05-12 1 2010-10-10 172 793
#5 2 B Male 1998-05-12 2 2011-11-12 727 653
#6 2 B Male 1998-05-12 3 2011-12-12 214 499
#7 3 A Male 2005-12-28 1 2010-10-10 157 664
#8 3 A Male 2005-12-28 2 2011-11-23 667 505
#9 3 A Male 2005-12-28 3 2011-12-23 222 924
#10 4 C Female 1957-07-01 1 2010-10-10 186 584
#11 4 C Female 1957-07-01 2 2011-11-25 123 582
#12 4 C Female 1957-07-01 3 2011-12-25 344 653
``` |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | You would typically just write to the pipe, or use select or poll. If you need a handshake mechanism you can do that out of band various ways or come up with and in-band protocol.
I don't know if there is a built-in way to know if a reader on the other end is blocking. Why do you need to know this? |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I don't think that's true: For example, *right before* calling read() on the reader side, the pipe would have a reader that isn't actually reading. | If I recall correctly, you can not have a pipe with no reader which means that you have either a read(2) or a select(2) syscal pending at all time. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That sounds as if you were trying to supervise dpkg where occasionally some post-inst script queries the admin whether it may override some config file.
Anyway, you may want to look at how strace works:
```
strace -f -etrace=read your.program
```
Of course you need to keep track of which fds are the pipes you write about, but you probably need only stdin, anyway. | You would typically just write to the pipe, or use select or poll. If you need a handshake mechanism you can do that out of band various ways or come up with and in-band protocol.
I don't know if there is a built-in way to know if a reader on the other end is blocking. Why do you need to know this? |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That sounds as if you were trying to supervise dpkg where occasionally some post-inst script queries the admin whether it may override some config file.
Anyway, you may want to look at how strace works:
```
strace -f -etrace=read your.program
```
Of course you need to keep track of which fds are the pipes you write about, but you probably need only stdin, anyway. | If I recall correctly, you can not have a pipe with no reader which means that you have either a read(2) or a select(2) syscal pending at all time. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That sounds as if you were trying to supervise dpkg where occasionally some post-inst script queries the admin whether it may override some config file.
Anyway, you may want to look at how strace works:
```
strace -f -etrace=read your.program
```
Of course you need to keep track of which fds are the pipes you write about, but you probably need only stdin, anyway. | I don't think that's true: For example, *right before* calling read() on the reader side, the pipe would have a reader that isn't actually reading. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You would typically just write to the pipe, or use select or poll. If you need a handshake mechanism you can do that out of band various ways or come up with and in-band protocol.
I don't know if there is a built-in way to know if a reader on the other end is blocking. Why do you need to know this? | If I recall correctly, you can not have a pipe with no reader which means that you have either a read(2) or a select(2) syscal pending at all time. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have these options:
* if you know that the child will need certain input (such as shell that will read a command), just write to a pipe
* if you assume the child won't read anything usually, but may do it sometimes, you probably need something like job control in the shell (use a terminal for communication with the child, use process groups and TIOCSPGRP ioctl on the terminal to get the child to the background; the child will get SIGTTIN when it tries to read from the terminal, and you can wait() for that). This is how bash handles things like "`(sleep 10; read a;)&`"
* if you don't know what to write, or you have more possibilities, you will have to parse the output | If I recall correctly, you can not have a pipe with no reader which means that you have either a read(2) or a select(2) syscal pending at all time. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have these options:
* if you know that the child will need certain input (such as shell that will read a command), just write to a pipe
* if you assume the child won't read anything usually, but may do it sometimes, you probably need something like job control in the shell (use a terminal for communication with the child, use process groups and TIOCSPGRP ioctl on the terminal to get the child to the background; the child will get SIGTTIN when it tries to read from the terminal, and you can wait() for that). This is how bash handles things like "`(sleep 10; read a;)&`"
* if you don't know what to write, or you have more possibilities, you will have to parse the output | I don't think that's true: For example, *right before* calling read() on the reader side, the pipe would have a reader that isn't actually reading. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | I don't think that's true: For example, *right before* calling read() on the reader side, the pipe would have a reader that isn't actually reading. |
450,106 | I'm trying to find out if a child process is waiting for user input (without parsing its output). Is it possible, in C on Unix, to determine if a pipe's read end currently has a read() call blocking?
The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | 2009/01/16 | [
"https://Stackoverflow.com/questions/450106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The thing is, I have no control over the programs exec'd in the child processes. They print all kinds of verbose garbage which I would usually want to redirect to /dev/null. Occasionally though one will prompt the user for something. (With the prompt having no reliable format.) So my idea was:
* In a loop:
+ Drain child's stdout, append it to a temporary buffer.
+ Check (no idea how) if the child is asking for user input, in which case the buffer is printed to stdout.
* When the child exits, throw away the buffer. | If I recall correctly, you can not have a pipe with no reader which means that you have either a read(2) or a select(2) syscal pending at all time. |
9,121,854 | Is it possible to use an LdapConnection from System.DirectoryServices.Protocols to query Active Directory?
I'm having issues instantiating a PrincipalContext. Here's my code, in case anyone can spot the issue:
```
private LdapConnection getLdapConnection(string username, string password, string ldapServer, bool secured)
{
int port = secured ? 636 : 389;
LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer, port, false, false));
if (secured)
{
connection.SessionOptions.ProtocolVersion = 3;
connection.SessionOptions.SecureSocketLayer = true;
}
connection.Credential = new NetworkCredential(username, password);
connection.AuthType = AuthType.Basic;
connection.SessionOptions.VerifyServerCertificate += (conn, cert) => { return true; };
connection.Bind();
return connection;
}
```
When trying to instantiate the Principal Context I am using
```
PrincipalContext context = new PrincipalContext(
ContextType.Domain,
ldapServer,
null,
useSsl ? ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind : ContextOptions.SimpleBind,
username,
password);
```
I am passing the same values in, for the sake of completeness username is in the format of `domain\user` and the ldapServer is in the format of `server.domain.com` with ldapServer having :636 appended when creating the Principal Context.
The server I am connecting to has certificate issues which I guess could be preventing this as the LdapConnection is set to return true for verification. This isn't an issue as it's trusted. I don't have access to the server and as such cannot change this. | 2012/02/02 | [
"https://Stackoverflow.com/questions/9121854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366038/"
] | As far as I understant the container parameter can't be `null` when you target a domain. Can you just try this constructor :
```
PrincipalContext domainContextMonou = new PrincipalContext(ContextType.Domain,
"server.domain.com :389",
"dc=domain,dc=com",
username,
password);
```
And then this one :
```
PrincipalContext domainContextMonou = new PrincipalContext(ContextType.Domain,
"server.domain.com :636",
"dc=domain,dc=com",
useSsl ? ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind : ContextOptions.SimpleBind,
username,
password);
``` | I suspect part of your problem with the LDAP code is that you're using `AuthType.Basic`. Try `Negotiate` instead. |
3,719,626 | Provide an example of an infinity of dense subsets of a space $(X,d)$ such that the intersection of all of them is not a dense subset.
I have tried taking $(\mathbb{Q}, d\_{usual})$ and as dense subsets the intervals $(0,1), (1,2), (2,3), ...$
But it seems to me that it does not work, since the lock of each one of the subsets is not the $\mathbb{Q}$ and with this it would not be true that they are dense. | 2020/06/14 | [
"https://math.stackexchange.com/questions/3719626",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/700522/"
] | For every $x\in\mathbb{Q}$, take $A\_x=\mathbb{Q}-\{x\}$. | Take $X= (0,\infty)$ with the usual metric. For $p$ a prime, define $D\_p$ be the set of quotients $n/p^k,$ where $n\in \mathbb N$ and $p$ are relatively prime, and $k\in\mathbb N.$ Then each $D\_p$ is dense in $X$ and the collection $\{D\_p\}$ is pairwise disjoint. |
55,102,552 | I have this class:
```
public class FooFileRepo {
@Override
public File getDirectory(String directoryPath) {
...
File directory = new File(directoryPath);
...
return directory;
}
@Override
public void mkdirs(File f) {
...
f.getParentFile().mkdirs();
}
public void writeFile(String path, String content) throws FileNotFoundException, UnsupportedEncodingException{
...
try (PrintWriter writer = new PrintWriter(path, "UTF-8");) {
writer.println(content);
}
}
```
}
How can I mock filesystem operation, for writing unit tests for this class?
Thanks. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55102552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453712/"
] | As a note, you'll never get this to function as perfectly as you may think. There are utilities for cleaning up garbage and unloading assets but even if you follow all best practices, you still might not get Unity to clean up all the garbage (it does a lot in the background that'll retain allocated memory and there's not much you can do about it). If you're curious about why this is, I'd suggest their writeup on [Heap Fragmentation](https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html?_ga=2.235425601.1547097256.1552318017-1747974858.1545148988) as well as their [Memory Optimization Guide](https://unity3d.com/learn/tutorials/topics/performance-optimization/optimizing-garbage-collection-unity-games).
---
As far as what you're doing with your specific project, there are at least some improvements you can make:
1) Avoid using the `WWW` class at all costs. It creates a lot more garbage than it's worth, doesn't always clean up well, and is obsolete in newest versions of Unity. Use [UnityWebRequest](https://docs.unity3d.com/Manual/UnityWebRequest-DownloadingAssetBundle.html) to download bundles instead.
2) Don't get in the habit of loading a bundle just to load a single asset and then unloading that bundle. If you have lots of loads occurring at runtime, this will cause thrashing and is a fairly inefficient way of managing your bundles. I noticed you're calling `bundle.Unload(false)` which means the *bundle* is being unloaded but the *loaded prefab asset* isn't. I'd suggest restructuring this in a way that you can:
1. load the bundle you need
2. load the assets you need from that bundle
3. wait for the lifetime of *all* those assets to end
4. call `bundle.Unload(true)`
3) Be careful with your call to `StopCoroutine(loadBundleRef);` (if `loadBundleRef` is a `Coroutine` object that is running your web request and bundle loading logic). Interrupting these async operations could lead to memory issues. You should have something in place that ensures web requests and bundle loads either finish completely or, on failure, throw and let your game recover. Don't allow something like `StopCoroutine` to interrupt them.
4) `System.GC.Collect();` is slow and garbage collection happens periodically anyway. Use it sparingly and you might also want to call [`Resources.UnloadUnusedAssets`](https://docs.unity3d.com/ScriptReference/Resources.UnloadUnusedAssets.html) before calling it. | *Please consider the @Foggzie Answer too for some best practices (I used some of them)!*
There was two issue with my code or testing procedeure.
1. Don't Use WWW.LoadFromCacheOrDownload
----------------------------------------
Unity Built-in WWW.LoadFromCacheOrDownload is crap! Seriously! Why ? [Ben Vinson](https://blog.kongregate.com/unity-webgl-memory-optimization-part-deux/) and [unity](https://blogs.unity3d.com/2016/09/20/understanding-memory-in-unity-webgl/) also explain in their blogs:
>
> Another source of memory-related problems is the IndexedDB filesystem
> used by Unity. Any time you cache an asset bundle or use any
> filesystem-related methods, they are stored in a virtual filesystem
> backed by IndexedDB.
>
>
> What you might not realize is that this virtual filesystem is loaded
> into and persisted in memory as soon as your Unity application starts.
> This means that if you are using the default Unity caching mechanism
> for Asset Bundles, you are adding the size of all of those bundles to
> the memory requirements for your game, **even if they are not being
> loaded**.
>
>
>
And Unity Clearly mentioned in [his blog](https://blogs.unity3d.com/2016/09/20/understanding-memory-in-unity-webgl/) to use UnityWebRequest instead LoadFromCacheOrDownload:
>
> A longer term solution to minimize asset bundle caching memory overhead is to use WWW Constructor instead of LoadFromCacheOrDownload() or use UnityWebRequest.GetAssetBundle() with no hash/version parameter if you are using the new UnityWebRequest API.
>
>
> Then use an alternative caching mechanism at the XMLHttpRequest-level,
> that stores the downloaded file directly into indexedDB, bypassing the
> memory file system. This is exactly what we have developed recently
> and it is available on the asset store. Feel free to use it in your
> projects and customize it if you need to.
>
>
>
2. Don't Measure Memory when Chrome Dev Tools are Open
------------------------------------------------------
The memory increment on page reload problem seems related to FireFox internal mechanism. But It was occurring in chrome due to the dev tools which were open when I was checking the memory.
Once I was measuring my tab memory in chrome the dev tools was open so it increment the memory with each page refresh. This reason defined by one of the [Unity official at forum](https://forum.unity.com/threads/webgl-excessive-memory-consumption-1-5gb.622720/#post-4363831)
>
> One point to note is that when profiling memory usage on page reloads
> in Firefox, make sure to have the Firefox web console (and debugger)
> window closed. Firefox has a behavior that if web console is open, it
> keeps the Firefox JS debugger alive, which pins all visited pages to
> be cached in memory, never reclaiming them. Closing the Firefox web
> page console allows freeing the old pages from memory.
>
>
> I do not know if Chrome might have similar behavior, but for good
> measure, it is good to have its web console closed to ensure it is not
> keeping pages alive.
>
>
> If someone has a public test case available that they can post, that
> would be helpful in pinpointing the source.
>
>
>
But actually [my test suggest](https://forum.unity.com/threads/webgl-excessive-memory-consumption-1-5gb.622720/#post-4364326) that this problem still persist in fireFox while resolve for Google Chrome.
*Remember, I got this answer after a long struggle.*
Update: I found that when you reload the page in firefox it get double the memory of page. So it is firefox issue, not related to unity webgl. |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You got it reversed. Do this: <http://www.sqlfiddle.com/#!2/09239/3>
```
SELECT Brand
FROM
(
-- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
) x
where Brand not in (select BrandName from account)
```
Sample Account data:
```
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
```
Output:
```
| BRAND |
-----------
| HYUNDAI |
```
---
Better yet, materialized the brands to a table:
```
select *
from Brand
where BrandName not in (select BrandName from account)
```
Output:
```
| BRANDNAME |
-------------
| HYUNDAI |
```
Sample data and live test: <http://www.sqlfiddle.com/#!2/09239/1>
```
CREATE TABLE Brand
(`BrandName` varchar(7));
INSERT INTO Brand
(`BrandName`)
VALUES
('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW');
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
``` | You should use [Except](http://technet.microsoft.com/en-us/library/ms188055.aspx): EXCEPT returns any distinct values from the left query that are not also found on the right query.
```
WITH SomeRows(datacol) --It will look for missing stuff here
AS( SELECT *
FROM ( VALUES ('FORD'),
('TOYOTA'),
('BMW')
) AS F (datacol)),
AllRows (datacol) --This has everthing
AS( SELECT *
FROM ( VALUES ('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW')
) AS F (datacol))
SELECT datacol
FROM AllRows
EXCEPT
SELECT datacol
FROM SomeRows
``` |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You should use [Except](http://technet.microsoft.com/en-us/library/ms188055.aspx): EXCEPT returns any distinct values from the left query that are not also found on the right query.
```
WITH SomeRows(datacol) --It will look for missing stuff here
AS( SELECT *
FROM ( VALUES ('FORD'),
('TOYOTA'),
('BMW')
) AS F (datacol)),
AllRows (datacol) --This has everthing
AS( SELECT *
FROM ( VALUES ('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW')
) AS F (datacol))
SELECT datacol
FROM AllRows
EXCEPT
SELECT datacol
FROM SomeRows
``` | Contributing Excel code to make the typing of the answer easier:
Say column A has the values (Ford, Hyundai,...).
In column B, put this in every cell:
```
select 'x' as brand from dual union
```
In column C, write this formula, and copy it down.
`=REPLACE(A2,9,1,A1)`
All of the `select`/`union` statements should appear in column C. |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You got it reversed. Do this: <http://www.sqlfiddle.com/#!2/09239/3>
```
SELECT Brand
FROM
(
-- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
) x
where Brand not in (select BrandName from account)
```
Sample Account data:
```
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
```
Output:
```
| BRAND |
-----------
| HYUNDAI |
```
---
Better yet, materialized the brands to a table:
```
select *
from Brand
where BrandName not in (select BrandName from account)
```
Output:
```
| BRANDNAME |
-------------
| HYUNDAI |
```
Sample data and live test: <http://www.sqlfiddle.com/#!2/09239/1>
```
CREATE TABLE Brand
(`BrandName` varchar(7));
INSERT INTO Brand
(`BrandName`)
VALUES
('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW');
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
``` | You can do:
```
SELECT a.val
FROM
(
SELECT 'FORD' val UNION ALL
SELECT 'HYUNDAI' UNION ALL
SELECT 'TOYOTA' UNION ALL
SELECT 'BMW' UNION ALL
etc...
etc...
) a
LEFT JOIN account b ON a.val = b.name
WHERE b.name IS NULL
``` |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You got it reversed. Do this: <http://www.sqlfiddle.com/#!2/09239/3>
```
SELECT Brand
FROM
(
-- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
) x
where Brand not in (select BrandName from account)
```
Sample Account data:
```
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
```
Output:
```
| BRAND |
-----------
| HYUNDAI |
```
---
Better yet, materialized the brands to a table:
```
select *
from Brand
where BrandName not in (select BrandName from account)
```
Output:
```
| BRANDNAME |
-------------
| HYUNDAI |
```
Sample data and live test: <http://www.sqlfiddle.com/#!2/09239/1>
```
CREATE TABLE Brand
(`BrandName` varchar(7));
INSERT INTO Brand
(`BrandName`)
VALUES
('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW');
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
``` | This worked perfectly, thanks Michael.
```
SELECT Brand
FROM
( -- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
)
where Brand not in (select BrandName from account)
```
Luxspes and Zane thank you for your inputs |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You got it reversed. Do this: <http://www.sqlfiddle.com/#!2/09239/3>
```
SELECT Brand
FROM
(
-- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
) x
where Brand not in (select BrandName from account)
```
Sample Account data:
```
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
```
Output:
```
| BRAND |
-----------
| HYUNDAI |
```
---
Better yet, materialized the brands to a table:
```
select *
from Brand
where BrandName not in (select BrandName from account)
```
Output:
```
| BRANDNAME |
-------------
| HYUNDAI |
```
Sample data and live test: <http://www.sqlfiddle.com/#!2/09239/1>
```
CREATE TABLE Brand
(`BrandName` varchar(7));
INSERT INTO Brand
(`BrandName`)
VALUES
('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW');
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
``` | Contributing Excel code to make the typing of the answer easier:
Say column A has the values (Ford, Hyundai,...).
In column B, put this in every cell:
```
select 'x' as brand from dual union
```
In column C, write this formula, and copy it down.
`=REPLACE(A2,9,1,A1)`
All of the `select`/`union` statements should appear in column C. |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | You can do:
```
SELECT a.val
FROM
(
SELECT 'FORD' val UNION ALL
SELECT 'HYUNDAI' UNION ALL
SELECT 'TOYOTA' UNION ALL
SELECT 'BMW' UNION ALL
etc...
etc...
) a
LEFT JOIN account b ON a.val = b.name
WHERE b.name IS NULL
``` | Contributing Excel code to make the typing of the answer easier:
Say column A has the values (Ford, Hyundai,...).
In column B, put this in every cell:
```
select 'x' as brand from dual union
```
In column C, write this formula, and copy it down.
`=REPLACE(A2,9,1,A1)`
All of the `select`/`union` statements should appear in column C. |
11,464,543 | How can I find a missing values from a set of values, using SQL (Oracle DB)
e.g.
```
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
```
(The "IN" clause may contain hundreds of values)
If 'HYUNDAI' is missing in the ACCOUNT table, I need to get the result as "HYUNDAI".
Currently I use the result of the above query to do a Vlookup against the original set of values to find the missing values, I want to directly get the missing values without doing the Vlookup.
Thanks
Kiran, | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522572/"
] | This worked perfectly, thanks Michael.
```
SELECT Brand
FROM
( -- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
)
where Brand not in (select BrandName from account)
```
Luxspes and Zane thank you for your inputs | Contributing Excel code to make the typing of the answer easier:
Say column A has the values (Ford, Hyundai,...).
In column B, put this in every cell:
```
select 'x' as brand from dual union
```
In column C, write this formula, and copy it down.
`=REPLACE(A2,9,1,A1)`
All of the `select`/`union` statements should appear in column C. |
8,591,802 | I've been struggling for a long time with basic controls that Windows Forms offers to developers, but... right now, I am developing an application that requires more advanced control than normal "TextBox".
Since, at this time, my application is about memory management, I have to show in the form, the process memory in bytes (or other type of data) to the user, giving it the ability to modify it as he wants.
The problem comes here, because... if I show the data in a TextBox, it only allow me to display the data in read-only text because if I let the user modify the textbox directly, it will be very messy and unaesthetic.
I was reviewing some projects on SourceForge about C# and the handling of hexadecimal data, and i found a good project, called [Be.HexEditor](http://sourceforge.net/projects/hexbox/), which has a control developed and designed by its creators, but in GDI+.
The control is called HexBox, and that's just what I need to get.
Do any of you know how to develop a control like this?... I would greatly facilitate things. What kind of manuals/books should I read to learn this kind of development? I ask this because I ignore everything about GDI+.
Or... is there other way for do it? | 2011/12/21 | [
"https://Stackoverflow.com/questions/8591802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907489/"
] | Using pure batch you could do this:
```
:LOOP
yourprogram.exe
ping 127.0.0.1 -n 61 >NUL
goto :LOOP
```
This means you don't have to install any other programs or create more scripts. It might not be pretty but it works! I have pinged 61 times as pinging the loopback seems to create a delayed second. | Download [unixutils for win32](http://unxutils.sourceforge.net/). In here, you will find **sleep.exe**. Put it somewhere in your path. (frex, in c:\windows)
Then, you can build a batch file similar to this
```
echo off
:here
sleep 60s
echo Exec app
rem your app goes here
goto here
``` |
28,295,013 | I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker.
*I'm using the Date Picker as a Count Down Timer*
So this is kind of all, except some usual outlets and vars:
```
override func viewDidLoad() {
super.viewDidLoad()
// tfName.delegate = self
// tfDescription.delegate = self
//
datePicker.countDownDuration = 60
// pickerValueChanged(self)
}
@IBAction func pickerValueChanged(sender: AnyObject) {
seconds = Int(datePicker.countDownDuration)
hours = seconds / 3600
if hours == 0{
minutes = seconds / 60
} else{
minutes = seconds % 3600 / 60
}
labelDuration.text = "\(hours) hours \(minutes) minutes"
}
```
The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing.
I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin..
Thank you for your time!
**Update: Added pictures**
After the first spin, pickerValueChanged does not get called:

From the second spin and beyond, the event gets called and the label is updated:

**Tried:**
Executing:
`datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()`
solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute.
This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again.
So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this?
**Solution:**
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28295013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069967/"
] | I came up the following solution to initialize the datePicker component (in countdown timer mode) with 0 hours and 1 minute and it responds directly at the first spin. Since this appears to be a bug and is very frustrating if you want a textlabel to update its value when the datePicker is changed and it does not at the first go:
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
```
The timeZone component is not really needed for this to work for my implementation. | None of these solutions work, when you use the DatePicker as an inputView for a textfield.
I have attached my code below. I am still searching for a good solution for this, because none of the above fixes the problem in my scenario.
```
self.durationDatePicker.datePickerMode = .countDownTimer
self.durationDatePicker.preferredDatePickerStyle = .wheels
self.durationDatePicker.minuteInterval = 5
self.durationDatePicker.addTarget(self, action: #selector(CreateEventDetailsViewController.datePickerValueChanged(picker:)), for: .valueChanged)
self.durationTextField.inputView = self.durationDatePicker
``` |
28,295,013 | I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker.
*I'm using the Date Picker as a Count Down Timer*
So this is kind of all, except some usual outlets and vars:
```
override func viewDidLoad() {
super.viewDidLoad()
// tfName.delegate = self
// tfDescription.delegate = self
//
datePicker.countDownDuration = 60
// pickerValueChanged(self)
}
@IBAction func pickerValueChanged(sender: AnyObject) {
seconds = Int(datePicker.countDownDuration)
hours = seconds / 3600
if hours == 0{
minutes = seconds / 60
} else{
minutes = seconds % 3600 / 60
}
labelDuration.text = "\(hours) hours \(minutes) minutes"
}
```
The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing.
I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin..
Thank you for your time!
**Update: Added pictures**
After the first spin, pickerValueChanged does not get called:

From the second spin and beyond, the event gets called and the label is updated:

**Tried:**
Executing:
`datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()`
solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute.
This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again.
So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this?
**Solution:**
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28295013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069967/"
] | I came up the following solution to initialize the datePicker component (in countdown timer mode) with 0 hours and 1 minute and it responds directly at the first spin. Since this appears to be a bug and is very frustrating if you want a textlabel to update its value when the datePicker is changed and it does not at the first go:
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
```
The timeZone component is not really needed for this to work for my implementation. | I don't know if I got your problem, but Date picker works using the target-action pattern and it triggers this mechanism when you change a value.
So if the problem is the very first value shown, you should initialize your variable taking it as the "default" value. |
28,295,013 | I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker.
*I'm using the Date Picker as a Count Down Timer*
So this is kind of all, except some usual outlets and vars:
```
override func viewDidLoad() {
super.viewDidLoad()
// tfName.delegate = self
// tfDescription.delegate = self
//
datePicker.countDownDuration = 60
// pickerValueChanged(self)
}
@IBAction func pickerValueChanged(sender: AnyObject) {
seconds = Int(datePicker.countDownDuration)
hours = seconds / 3600
if hours == 0{
minutes = seconds / 60
} else{
minutes = seconds % 3600 / 60
}
labelDuration.text = "\(hours) hours \(minutes) minutes"
}
```
The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing.
I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin..
Thank you for your time!
**Update: Added pictures**
After the first spin, pickerValueChanged does not get called:

From the second spin and beyond, the event gets called and the label is updated:

**Tried:**
Executing:
`datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()`
solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute.
This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again.
So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this?
**Solution:**
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28295013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069967/"
] | I came up the following solution to initialize the datePicker component (in countdown timer mode) with 0 hours and 1 minute and it responds directly at the first spin. Since this appears to be a bug and is very frustrating if you want a textlabel to update its value when the datePicker is changed and it does not at the first go:
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
```
The timeZone component is not really needed for this to work for my implementation. | Actually, all you need is to **not** set `datePicker.countDownDuration` in `viewDidLoad` but add it to `viewDidAppear`, or later. |
28,295,013 | I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker.
*I'm using the Date Picker as a Count Down Timer*
So this is kind of all, except some usual outlets and vars:
```
override func viewDidLoad() {
super.viewDidLoad()
// tfName.delegate = self
// tfDescription.delegate = self
//
datePicker.countDownDuration = 60
// pickerValueChanged(self)
}
@IBAction func pickerValueChanged(sender: AnyObject) {
seconds = Int(datePicker.countDownDuration)
hours = seconds / 3600
if hours == 0{
minutes = seconds / 60
} else{
minutes = seconds % 3600 / 60
}
labelDuration.text = "\(hours) hours \(minutes) minutes"
}
```
The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing.
I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin..
Thank you for your time!
**Update: Added pictures**
After the first spin, pickerValueChanged does not get called:

From the second spin and beyond, the event gets called and the label is updated:

**Tried:**
Executing:
`datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()`
solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute.
This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again.
So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this?
**Solution:**
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28295013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069967/"
] | Time ago I found another problem that somehow resembles this one. It was about presenting a view controller from within the `tableView:didSelectRowAtIndexPath:` and the problem was that it was taking lots of time for the new controller to actually show up. One of the workarounds turned out to be using `dispatch_async` on the main queue. The same worked for me in this case.
In my `viewDidLoad`, I asynchronously dispatched the picker setup code on the main queue and, in my case, it started to respond to the `valueChanged` event even on the first pick:
```
DispatchQueue.main.async {
self.pickerView.datePickerMode = .countDownTimer
self.pickerView.minuteInterval = 5
self.pickerView.countDownDuration = 15
}
``` | I don't know if I got your problem, but Date picker works using the target-action pattern and it triggers this mechanism when you change a value.
So if the problem is the very first value shown, you should initialize your variable taking it as the "default" value. |
28,295,013 | I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker.
*I'm using the Date Picker as a Count Down Timer*
So this is kind of all, except some usual outlets and vars:
```
override func viewDidLoad() {
super.viewDidLoad()
// tfName.delegate = self
// tfDescription.delegate = self
//
datePicker.countDownDuration = 60
// pickerValueChanged(self)
}
@IBAction func pickerValueChanged(sender: AnyObject) {
seconds = Int(datePicker.countDownDuration)
hours = seconds / 3600
if hours == 0{
minutes = seconds / 60
} else{
minutes = seconds % 3600 / 60
}
labelDuration.text = "\(hours) hours \(minutes) minutes"
}
```
The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing.
I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin..
Thank you for your time!
**Update: Added pictures**
After the first spin, pickerValueChanged does not get called:

From the second spin and beyond, the event gets called and the label is updated:

**Tried:**
Executing:
`datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()`
solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute.
This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again.
So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this?
**Solution:**
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28295013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069967/"
] | I came up the following solution to initialize the datePicker component (in countdown timer mode) with 0 hours and 1 minute and it responds directly at the first spin. Since this appears to be a bug and is very frustrating if you want a textlabel to update its value when the datePicker is changed and it does not at the first go:
```
var dateComp : NSDateComponents = NSDateComponents()
dateComp.hour = 0
dateComp.minute = 1
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var date : NSDate = calendar.dateFromComponents(dateComp)!
datePicker.setDate(date, animated: true)
```
The timeZone component is not really needed for this to work for my implementation. | I think you should try implement this delegate instead
```
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.