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
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
You can find explanations about timers and how to use (declare) it in the help system of your IDE. For example, in the [CODESYS](https://en.wikipedia.org/wiki/CODESYS) help you can read about timers of the standard library. In general, you can declare timer-delay (TON) as: ``` VAR MY_TON: TON; END_VAR (* standard.library should be added to the project *) ``` Then you can use it: ``` MY_TON(IN:= IN_VALUE,PT:= TIME_SET); (*IN_VALUE - is BOOL variable that activates your timer TIME_SET - is TIME variable*) SOME_OUTPUT := MY_TON.Q; (*Q - is the timer's output, and it can be used as BOOL variable. *) ``` You can also use constants to set up your timer: ``` MY_TON(IN:= True, PT:= t#5s); ``` As a BOOL variable, the timer's output can be used in IF and WHILE statements: ``` IF MY_TON.Q THEN (*Some statements...*) END_IF WHILE MY_TON.Q DO (*Some statements...*) END_WHILE ``` All examples are run in CODESYS v3.5 SP5 and v2.3. For other IDEs there might be nuances.
I solved it like this in Gx-Works(Mitsubishi / FXCPU): ``` TON_1(IN:= Enable_Timer,PT:= PresetTime ,Q:= Output,ET:= TimeLeft); ``` Remember to declare TON\_1 :)
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
The timer works so that `TON.Q` goes high only if `TON.IN` is continuously high for at least the duration of `TON.PT`. This makes sure that `TON.Q` only goes high if `TON.IN` is in a stable high state. This could be useful for instance to ensure that the output is only enabled if a button is pressed for at least a duration of `TON.PT`.
I have done this with an OMRON PLC which supports the ST language. There's a timer interrupt in the PLC, and we used it to build our own timer in ST, and then we could skip out of the PLC limitations. When the PLC power on, the code inside the interrupt task is executed every interruption, and you can write "A=A+1" inside the interrupt handler. When you start to use the timer, just record the current data of A. Let's say A1; the interval is: ``` Interval= Current_Data_Of_A-A1 ``` Then compare `Interval` to the time you want. If `Interval` is bigger than the time you want, then execute the next code.
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
You can find explanations about timers and how to use (declare) it in the help system of your IDE. For example, in the [CODESYS](https://en.wikipedia.org/wiki/CODESYS) help you can read about timers of the standard library. In general, you can declare timer-delay (TON) as: ``` VAR MY_TON: TON; END_VAR (* standard.library should be added to the project *) ``` Then you can use it: ``` MY_TON(IN:= IN_VALUE,PT:= TIME_SET); (*IN_VALUE - is BOOL variable that activates your timer TIME_SET - is TIME variable*) SOME_OUTPUT := MY_TON.Q; (*Q - is the timer's output, and it can be used as BOOL variable. *) ``` You can also use constants to set up your timer: ``` MY_TON(IN:= True, PT:= t#5s); ``` As a BOOL variable, the timer's output can be used in IF and WHILE statements: ``` IF MY_TON.Q THEN (*Some statements...*) END_IF WHILE MY_TON.Q DO (*Some statements...*) END_WHILE ``` All examples are run in CODESYS v3.5 SP5 and v2.3. For other IDEs there might be nuances.
I have done this with an OMRON PLC which supports the ST language. There's a timer interrupt in the PLC, and we used it to build our own timer in ST, and then we could skip out of the PLC limitations. When the PLC power on, the code inside the interrupt task is executed every interruption, and you can write "A=A+1" inside the interrupt handler. When you start to use the timer, just record the current data of A. Let's say A1; the interval is: ``` Interval= Current_Data_Of_A-A1 ``` Then compare `Interval` to the time you want. If `Interval` is bigger than the time you want, then execute the next code.
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
You can find explanations about timers and how to use (declare) it in the help system of your IDE. For example, in the [CODESYS](https://en.wikipedia.org/wiki/CODESYS) help you can read about timers of the standard library. In general, you can declare timer-delay (TON) as: ``` VAR MY_TON: TON; END_VAR (* standard.library should be added to the project *) ``` Then you can use it: ``` MY_TON(IN:= IN_VALUE,PT:= TIME_SET); (*IN_VALUE - is BOOL variable that activates your timer TIME_SET - is TIME variable*) SOME_OUTPUT := MY_TON.Q; (*Q - is the timer's output, and it can be used as BOOL variable. *) ``` You can also use constants to set up your timer: ``` MY_TON(IN:= True, PT:= t#5s); ``` As a BOOL variable, the timer's output can be used in IF and WHILE statements: ``` IF MY_TON.Q THEN (*Some statements...*) END_IF WHILE MY_TON.Q DO (*Some statements...*) END_WHILE ``` All examples are run in CODESYS v3.5 SP5 and v2.3. For other IDEs there might be nuances.
Typically, you set a preset time and enable the timer. When it elapses, there will be done sort of done bit set true. When you reset the enable, the time will reset as well.
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
You can find explanations about timers and how to use (declare) it in the help system of your IDE. For example, in the [CODESYS](https://en.wikipedia.org/wiki/CODESYS) help you can read about timers of the standard library. In general, you can declare timer-delay (TON) as: ``` VAR MY_TON: TON; END_VAR (* standard.library should be added to the project *) ``` Then you can use it: ``` MY_TON(IN:= IN_VALUE,PT:= TIME_SET); (*IN_VALUE - is BOOL variable that activates your timer TIME_SET - is TIME variable*) SOME_OUTPUT := MY_TON.Q; (*Q - is the timer's output, and it can be used as BOOL variable. *) ``` You can also use constants to set up your timer: ``` MY_TON(IN:= True, PT:= t#5s); ``` As a BOOL variable, the timer's output can be used in IF and WHILE statements: ``` IF MY_TON.Q THEN (*Some statements...*) END_IF WHILE MY_TON.Q DO (*Some statements...*) END_WHILE ``` All examples are run in CODESYS v3.5 SP5 and v2.3. For other IDEs there might be nuances.
We also have built our own timer structure with using milliseconds counter provided by PLC, so we could make arrays of timer (Schneider Electric) when we need and exceed PLC limitation. ``` TTIMER Count: UINT timclock :INT OUT :BOOL IN: BOOL END_STRUCT; TIM_SOD=ARRAY[0..1] OF TTIMER; (*This part runs every cycle of PLC*) FOR I:=0 TO 1 DO IF TIM_SOD[I].IN (*timer on*) THEN IF (TIM_SOD[I].Count)>0 (*number of seconds left*) THEN IF ABS_INT(IN:=timclock-TIM_SOD[I].CLK)>=100 (*timclock -mSec counter*) THEN aTIM_SOD[I].Count:=TIM_SOD[I].Count-1; TIM_SOD[I].CLK:=TIM_SOD[I].CLK+100; END_IF; ELSE TIM_SOD[I].IN:=0; (*timer off*) TIM_SOD[I].Out:=1; (*Timer have run out*) END_IF; END_IF; END_FOR; (*-------------------------------------------------*) (*This part runs once when we need start timer*) TIM_SOD[0].COUNT:=H690; (*delay in seconds*) TIM_SOD[0].CLK:=TIMCLOCK; (*current value of mSec counter*) TIM_SOD[0].IN:=True; (*-------------------------------------------------*) (*This part runs once when we need stop timer*) TIM_SOD[0].IN:=False; (*Checking timer*) IF TIM_SOD[0].OUT THEN (*doing smth......*) END_IF; ```
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
The timer works so that `TON.Q` goes high only if `TON.IN` is continuously high for at least the duration of `TON.PT`. This makes sure that `TON.Q` only goes high if `TON.IN` is in a stable high state. This could be useful for instance to ensure that the output is only enabled if a button is pressed for at least a duration of `TON.PT`.
Typically, you set a preset time and enable the timer. When it elapses, there will be done sort of done bit set true. When you reset the enable, the time will reset as well.
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
I solved it like this in Gx-Works(Mitsubishi / FXCPU): ``` TON_1(IN:= Enable_Timer,PT:= PresetTime ,Q:= Output,ET:= TimeLeft); ``` Remember to declare TON\_1 :)
I have done this with an OMRON PLC which supports the ST language. There's a timer interrupt in the PLC, and we used it to build our own timer in ST, and then we could skip out of the PLC limitations. When the PLC power on, the code inside the interrupt task is executed every interruption, and you can write "A=A+1" inside the interrupt handler. When you start to use the timer, just record the current data of A. Let's say A1; the interval is: ``` Interval= Current_Data_Of_A-A1 ``` Then compare `Interval` to the time you want. If `Interval` is bigger than the time you want, then execute the next code.
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
I solved it like this in Gx-Works(Mitsubishi / FXCPU): ``` TON_1(IN:= Enable_Timer,PT:= PresetTime ,Q:= Output,ET:= TimeLeft); ``` Remember to declare TON\_1 :)
We also have built our own timer structure with using milliseconds counter provided by PLC, so we could make arrays of timer (Schneider Electric) when we need and exceed PLC limitation. ``` TTIMER Count: UINT timclock :INT OUT :BOOL IN: BOOL END_STRUCT; TIM_SOD=ARRAY[0..1] OF TTIMER; (*This part runs every cycle of PLC*) FOR I:=0 TO 1 DO IF TIM_SOD[I].IN (*timer on*) THEN IF (TIM_SOD[I].Count)>0 (*number of seconds left*) THEN IF ABS_INT(IN:=timclock-TIM_SOD[I].CLK)>=100 (*timclock -mSec counter*) THEN aTIM_SOD[I].Count:=TIM_SOD[I].Count-1; TIM_SOD[I].CLK:=TIM_SOD[I].CLK+100; END_IF; ELSE TIM_SOD[I].IN:=0; (*timer off*) TIM_SOD[I].Out:=1; (*Timer have run out*) END_IF; END_IF; END_FOR; (*-------------------------------------------------*) (*This part runs once when we need start timer*) TIM_SOD[0].COUNT:=H690; (*delay in seconds*) TIM_SOD[0].CLK:=TIMCLOCK; (*current value of mSec counter*) TIM_SOD[0].IN:=True; (*-------------------------------------------------*) (*This part runs once when we need stop timer*) TIM_SOD[0].IN:=False; (*Checking timer*) IF TIM_SOD[0].OUT THEN (*doing smth......*) END_IF; ```
25,682,963
I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width. Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set. In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units. Is this a browser default behavior or am I missing something?
2014/09/05
[ "https://Stackoverflow.com/questions/25682963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061340/" ]
You can find explanations about timers and how to use (declare) it in the help system of your IDE. For example, in the [CODESYS](https://en.wikipedia.org/wiki/CODESYS) help you can read about timers of the standard library. In general, you can declare timer-delay (TON) as: ``` VAR MY_TON: TON; END_VAR (* standard.library should be added to the project *) ``` Then you can use it: ``` MY_TON(IN:= IN_VALUE,PT:= TIME_SET); (*IN_VALUE - is BOOL variable that activates your timer TIME_SET - is TIME variable*) SOME_OUTPUT := MY_TON.Q; (*Q - is the timer's output, and it can be used as BOOL variable. *) ``` You can also use constants to set up your timer: ``` MY_TON(IN:= True, PT:= t#5s); ``` As a BOOL variable, the timer's output can be used in IF and WHILE statements: ``` IF MY_TON.Q THEN (*Some statements...*) END_IF WHILE MY_TON.Q DO (*Some statements...*) END_WHILE ``` All examples are run in CODESYS v3.5 SP5 and v2.3. For other IDEs there might be nuances.
The timer works so that `TON.Q` goes high only if `TON.IN` is continuously high for at least the duration of `TON.PT`. This makes sure that `TON.Q` only goes high if `TON.IN` is in a stable high state. This could be useful for instance to ensure that the output is only enabled if a button is pressed for at least a duration of `TON.PT`.
53,336,762
I am trying to add the serial number in recycler view by using the add button. need to check whether duplicate value trying to add in recycler view. add button Onclick listener code are given below ``` serialNumberAddButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!serialNumberField.getText().toString().equals("")) { // here need to check the duplicate values SerialNumberPojo serialNumberPojo = new SerialNumberPojo(serialNumberField.getText().toString()); serialNumberPojoList.add(serialNumberPojo); RecyclerView recyclerView = view.findViewById(R.id.serial_recycle); serialNumberAdapter = new SerialNumberAdapter(serialNumberPojoList, view.getContext(), ScannedDetailsFragment.this); actualQuantity.setText(String.valueOf(serialNumberAdapter.getItemCount())); mLayoutManager = new LinearLayoutManager(view.getContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(serialNumberAdapter); serialNumberAdapter.notifyDataSetChanged(); } else { messageDialog.showAlertDialogBox(getContext(), "Add or Scan Serial Number", "error"); } } }); ```
2018/11/16
[ "https://Stackoverflow.com/questions/53336762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7331939/" ]
You could do something like this: ``` SerialNumberPojo serialNumberPojo = new SerialNumberPojo(serialNumberField.getText().toString()); if (!serialNumberPojoList.contains(serialNumberPojo)) { serialNumberPojoList.add(serialNumberPojo); } ``` And in SerialNumberPojo you need to implement your own equals() like: ``` @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; SerialNumberPojo that = (SerialNumberPojo) other; if (getId() != null && getId().equals(that.getId())) { return true; } return false; } ```
You can init Recycle View in `onCreate` function. Like: ``` @Override public void onCreate(...) { ... recyclerView = findViewById(R.id.serial_recycle); serialNumberAdapter = new SerialNumberAdapter(serialNumberPojoList, view.getContext(), ScannedDetailsFragment.this); mLayoutManager = new LinearLayoutManager(view.getContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(serialNumberAdapter); ... } ``` and in your `OnClickListener` check for dublicate as write @Szymon Chaber ``` serialNumberAddButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!serialNumberField.getText().toString().equals("")) { SerialNumberPojo serialNumberPojo = new SerialNumberPojo(serialNumberField.getText().toString()); if (!serialNumberPojoList.contains(serialNumberPojo)) { serialNumberPojoList.add(serialNumberPojo); } else { // your action if found duplicate value } serialNumberAdapter.updateData(serialNumberPojoList); serialNumberAdapter.notifyDataSetChanged(); actualQuantity.setText(String.valueOf(serialNumberAdapter.getItemCount())); } else { messageDialog.showAlertDialogBox(getContext(), "Add or Scan Serial Number", "error"); } } }); ```
26,756,502
I've computed a triangulation of a region, which boundaries are described by a polygon. But the triangulation is computed for the convex hull, bigger than the region. Some of the triangles in the resulting set must be discarded. Dou you know about an algorithm for this operation?
2014/11/05
[ "https://Stackoverflow.com/questions/26756502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636662/" ]
I would combine this (triangulation of the convex hull) with another algorithm which would check if a given point is inside the polygon or not. Then, for each resulting triangle, I would check if it's median point is inside the polygon.
If you can use a 3rd party library, you can use [CGAL](http://www.cgal.org) and the following [example](http://doc.cgal.org/latest/Triangulation_2/index.html#title29) will do what you want (including the triangulation).
26,756,502
I've computed a triangulation of a region, which boundaries are described by a polygon. But the triangulation is computed for the convex hull, bigger than the region. Some of the triangles in the resulting set must be discarded. Dou you know about an algorithm for this operation?
2014/11/05
[ "https://Stackoverflow.com/questions/26756502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636662/" ]
I would combine this (triangulation of the convex hull) with another algorithm which would check if a given point is inside the polygon or not. Then, for each resulting triangle, I would check if it's median point is inside the polygon.
You can try alpha shapes. Its delaunay triangulation without edges exceeding alpha.
35,857,271
I'm attempting to write a plugin for babel, and am needing the filename of the current file that is being parsed. I know the lines of the code are passed in, but I haven't managed to find a reference to the filename. Any help?? For instance given this code what could I do ``` export default function({ types: t }) { return { visitor: { Identifier(path) { // something here?? } } }; } ```
2016/03/08
[ "https://Stackoverflow.com/questions/35857271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3325262/" ]
You can you `this` or use the 2nd parameter in a visitor (`state`) ``` Identifier(path, state) { console.log(state.file.opts.filename); } ```
For any future viewers, you can use this.file.opts.filename in a visitor function
43,100,112
Is it possible to create a CRUD system without database in spring mvc framework? If possible then which way? I made an application where i can save and update a single value but i need to save and update a list of value.
2017/03/29
[ "https://Stackoverflow.com/questions/43100112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218865/" ]
HSQLDB offers in memory DB, you can use it to do crud operations for your unit tests. You can maintain spring configuration for the Unit tests and another spring configuration for deployed code. The db configuration can be different for both, so, you run the data updates on the in-memory databse when running tests and actual database when deployed to server. Spring takes care of this seamlessly. <http://hsqldb.org/> spring boot has this [inbuild](http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html) Other ways to test out your code is to using [mockito](http://site.mockito.org/) where you test your code on mock data/objects. *Update*: there is something called [DBUnit](https://dzone.com/articles/database-unit-testing-dbunit), just found out, it can also help you test against fake db
You Can recreate a CRUD operation using File Systems In Java using a File or Excel as a Database and and then Using File Handling or Apache POI in order to Create Update or Delete.
1,281,116
I have a class designated for a certain site. In that site I have different functions to retrieve data from the database and store that data into an array. I have other functions within the same class that take the data and format it into html and returns the html containing the data from the database. For example... ``` function GetUserProfile($userID){ $query = 'SELECT * FROM users WHERE userID='.$userID; ....... blah blah blah ....... $user = mysqli->fetch_assoc(); return $user; } function FormatUserProfile($user, $showDesc = false){ $profile = '< h1 >'.$user['userName'].'< / h1 >'; if($showDesc){ $profile .= '< div >'.$user['description'].'< / div >'; } return $profile; } ``` ... So if i had a function to solely gather information, and another function to solely format that gathered information. Mainly because I will be showing the same data on different pages, but Different pages show different data, like a search would only bring up the users name, where as the users profile page would bring up the username and the description for example. Is that good practice, or is there a better way to do this?
2009/08/15
[ "https://Stackoverflow.com/questions/1281116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156814/" ]
It's a good practice. Personally, I use the following template "engine": ``` <?php class Template{ static function show($path, $arg = NULL){ include "templates/$path.php"; } static function get($path, $arg = NULL){ ob_start(); self::show($path, $info); $block = ob_get_contents(); ob_end_clean(); return $block; } } ``` In your case the template would be like this: ``` <?php echo '<h1>'.$arg['user']['userName'].'</h1>'; if($arg['showDesc']){ echo '<div>'.$arg['user']['description'].'</div>'; } ?> ``` You could unpack the array with the template arguments, but I prefer to keep it all in one place, so the code is less confusing. (You always know what is coming from the input, and what's defined in the template this way. To keep things shorter, you might use $\_ instead of $arg too.) For a small example like this, the benefit is not obvious, but for larger templates it save a lot of variable manipulation, as you can use PHP's own templating abilities.
You can use Smarty template engine or something similar. It's templates are stored separately and look like this: <http://www.smarty.net/sampleapp/sampleapp_p5.php>
16,402,982
I have the following page ![enter image description here](https://i.stack.imgur.com/eK4RI.png) **CODE** ``` <table border="0" cellspacing="1" cellpadding="1" id="echipajucator" title="Echipa Jucator"> <tr> <th><div align="left"><span>Echipa</span></div></th> </tr> </table> <table cellspacing="2" cellpadding="1" id="echipa"> <tr> <td> <select name="selectechipa" id="select" onclick="check_list()"> <option value="AC Milan" id="milan">Milan</option> <option value="Juventus" id="juve">Juventus</option> <option value="Napoli" id="nap">Napoli</option> <option value="Bayern Munchen" id="bmun">B.Munchen</option> <option value="Real Madrid" id="realm">Real Madrid</option> <option value="Valencia" id="vale">Valencia</option> <option value="P.S.G" id="psg">PSG</option> <option value="Arsenal" id="ars">Arsenal</option> <option value="Man. Untd" id="manutd">Man. United</option> <option value="Chelsea" id="chls">Chelsea</option> </select> </td> </tr> </table> ``` When I submit my form I got this table ![enter image description here](https://i.stack.imgur.com/C5rMl.png) ``` <form name="atrbjucator"> <table> <% response.setContentType("text/html"); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; String title = "Parametrii Jucator"; %> <% out.println(docType + "<html>\n" + "<head><title>"+title + "</title></head>\n"+ "<body bgcolor=\"#FDF5E6\">\n" + "<h1 align=center>" + title + "</h1>\n" + "<table border=1 align=center>\n" + "<tr bgcolor=\"#FFAD00\">\n" + "<th>Nume Parametru<TH>Valoare Parametru"); %> <%-- http://www.roseindia.net/tutorial/servlet/useBeanInServlet.html --%> <tr><td>Nume</td><td>${jucator.nume}</td></tr> <tr><td>Prenume</td><td>${jucator.prenume}</td></tr> <tr><td>Varsta</td><td>${jucator.varsta}</td></tr> <tr><td>Pozitie</td><td>${jucator.pozitie}</td></tr> <tr><td>Echipa</td><td>${jucator.selectechipa}</td></tr> <% ``` What I want to do is to add a little icon after team's name (AC Milan) acording to the selected team in the submitted table. PS: Basic knowledge in java, javascript, jsp, javabeans I tried to create a javascript in the jsp page with the table ``` function loadImages() { if (document.getElementById("select")) { document.getElementById("milan").src = "/HTML-CODE/icons/milan.png"; document.getElementById("juve").src = "/HTML-CODE/icons/juventus.png"; document.getElementById("nap").src = "/HTML-CODE/icons/napoli.png"; document.getElementById("bmun").src = "/HTML-CODE/icons/bayern.png"; document.getElementById("realm").src = "/HTML-CODE/icons/madrid.png"; document.getElementById("vale").src = "/HTML-CODE/icons/valencia.png"; document.getElementById("psg").src = "/HTML-CODE/icons/psg.png"; document.getElementById("ars").src = "/HTML-CODE/icons/arsenal.png"; document.getElementById("manutd").src = "/HTML-CODE/icons/machester.png"; document.getElementById("chls").src = "/HTML-CODE/icons/chelsea.png"; } } ``` I added the function on body as onload="loadImages()" but I got no image.
2013/05/06
[ "https://Stackoverflow.com/questions/16402982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918556/" ]
Do this just using javascript, without jsp. ``` <script> function changeimage(choice){ document.getElementById('icon').src=choice + ".png"; } </script> <img src="" id="icon" width='52' height='50'> <table cellspacing="2" cellpadding="1" id="echipa"> <tr> <td> <select name="selectechipa" id="select" onchange="changeimage(this.value);"> <option value="AC Milan" id="milan">Milan</option> <option value="Juventus" id="juve">Juventus</option> <option value="Napoli" id="nap">Napoli</option> <option value="Bayern Munchen" id="bmun">B.Munchen</option> <option value="Real Madrid" id="realm">Real Madrid</option> <option value="Valencia" id="vale">Valencia</option> <option value="P.S.G" id="psg">PSG</option> <option value="Arsenal" id="ars">Arsenal</option> <option value="Man. Untd" id="manutd">Man. United</option> <option value="Chelsea" id="chls">Chelsea</option> </select> </td> </tr> </table> ``` Use this javascript function to change images, make sure to name the images as the option value for them. And extension I am using is .png, if you don't have images in .png you may have to use `if-else` conditions. Like if you have image for Juventus in png, rest all as jpg, ``` if (choice=="Juventus") image="Juventus.png"; else image= choice+".jpg"; ``` Your function would now have ``` document.getElementById('icon').src=image; ``` Better would be to change option values as `"Juventus.png", "AC Milan.jpg",` and then strip the extension server side.
I've done it! ``` <script type="text/javascript"> function loadImage() { if (document.getElementById("jucatorechipa").innerHTML == "AC Milan") { icn.src="HTML-CODE/icons/AC Milan.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Arsenal") { icn.src="HTML-CODE/icons/Arsenal.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Bayern Munchen") { icn.src="HTML-CODE/icons/Bayern Munchen.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Chelsea") { icn.src="HTML-CODE/icons/Chelsea.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Juventus") { icn.src="HTML-CODE/icons/Juventus.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Man. Untd") { icn.src="HTML-CODE/icons/Man. Untd.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Napoli") { icn.src="HTML-CODE/icons/Napoli.png"; } if (document.getElementById("jucatorechipa").innerHTML == "PSG") { icn.src="HTML-CODE/icons/PSG.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Real Madrid") { icn.src="HTML-CODE/icons/Real Madrid.png"; } if (document.getElementById("jucatorechipa").innerHTML == "Valencia") { icn.src="HTML-CODE/icons/Valencia.png"; } } </script> ``` Using this script here: ``` <tr><td>Echipa</td><td><span id="jucatorechipa">${jucator.selectechipa}</span> <img align="top" id="icn"/></td></tr> ```
9,629
I ve seen many recipes for a longer lasting SD, but no one convinced me that this is not a tremendous flaw in the whole Raspberry concept. Targeted for students, packaged with N.O.O.B.S., etc, it become clear the newbie's happiness will last a month, and then, corruption. What a welcome message! In the past, we could buy battery powered compact flash cards for the ancient HP200LX, plug it and forget about for, say, 10 years (changing batteries every two years). The best reliable solutions proposed in this site refers to minimizing writes to the disc, strapping vital functions and rendering the RPi almost unusable, even forgetting that the kernel itself will write countless times in the same sectors due to the linux file abstraction model ( everything in linux is a file). That said, while manufacturers do not present an everlasting solution, is there another kind of SD Card electrically compatible solution or hacking that would bring Raspberry to the serious side, without inflating its size and purpose?
2013/09/16
[ "https://raspberrypi.stackexchange.com/questions/9629", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/9550/" ]
You make a lot of assumptions. The statement about 1 month is just flat-out wrong. Compact flash cards are actually worse for this kind of operation than SD-cards. I tried to install a server onto one which lasted a whole three weeks before dying. Compare that to the server I have running on an SD card on the pi for over 3 months now 24/7. But no, there are no guarentees how long it will actually last. Many SD-cards use middleware to ensure that writes do not happen to the same sector but it is a bit of a mystery which manufacturers provide it with their cards and this is the cause of most of the confusion with SD cards for the pi. Another option is to use the SD-card for the boot loader and keep your distro and a USB hard drive. This however will inflate its size. Lastly the pi is not meant as an everlasting solution. Neither is the beagle board or the Via APC (which both run of micro-sd cards). If you want a full-fledged desktop system, get a pc of your preferred form-factor (via is a good option). The pi is a development platform and should be used as such.
Well, the welcome message for a newbie would be a kind advice indeed: **always do backups**. I've experienced two or three SD failures (even from "famous" brands) and the corresponding loss of hours and hours of configuration work. Now I settled with two cards running 24/7 on two RPi's that didn't show a single hiccup, but this didn't prevent me to build, run & test a daily backup system for both systems (and my laptop too) to an external HD. And since I'm perfectly aware that the HD too will fail someday, I'm planning to add redundancy with another drive. The only effective way to bring any piece of computing to the "serious side" is to make backups and/or making it redundant.
9,629
I ve seen many recipes for a longer lasting SD, but no one convinced me that this is not a tremendous flaw in the whole Raspberry concept. Targeted for students, packaged with N.O.O.B.S., etc, it become clear the newbie's happiness will last a month, and then, corruption. What a welcome message! In the past, we could buy battery powered compact flash cards for the ancient HP200LX, plug it and forget about for, say, 10 years (changing batteries every two years). The best reliable solutions proposed in this site refers to minimizing writes to the disc, strapping vital functions and rendering the RPi almost unusable, even forgetting that the kernel itself will write countless times in the same sectors due to the linux file abstraction model ( everything in linux is a file). That said, while manufacturers do not present an everlasting solution, is there another kind of SD Card electrically compatible solution or hacking that would bring Raspberry to the serious side, without inflating its size and purpose?
2013/09/16
[ "https://raspberrypi.stackexchange.com/questions/9629", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/9550/" ]
You make a lot of assumptions. The statement about 1 month is just flat-out wrong. Compact flash cards are actually worse for this kind of operation than SD-cards. I tried to install a server onto one which lasted a whole three weeks before dying. Compare that to the server I have running on an SD card on the pi for over 3 months now 24/7. But no, there are no guarentees how long it will actually last. Many SD-cards use middleware to ensure that writes do not happen to the same sector but it is a bit of a mystery which manufacturers provide it with their cards and this is the cause of most of the confusion with SD cards for the pi. Another option is to use the SD-card for the boot loader and keep your distro and a USB hard drive. This however will inflate its size. Lastly the pi is not meant as an everlasting solution. Neither is the beagle board or the Via APC (which both run of micro-sd cards). If you want a full-fledged desktop system, get a pc of your preferred form-factor (via is a good option). The pi is a development platform and should be used as such.
There are many cheap and small USB pen drives in the market, it's a pity the Pi won't directly boot from USB. I assume that another USB socket/bus would raise the cost of the Pi too much. On the counterpart, not having to buy a new SD every month is a money saver. IMHO USB pen drives are more reliable than SD card. No benchmarks, just my experience. I really hope for a "*model C*" Raspberry Pi with dedicated USB boot.
9,629
I ve seen many recipes for a longer lasting SD, but no one convinced me that this is not a tremendous flaw in the whole Raspberry concept. Targeted for students, packaged with N.O.O.B.S., etc, it become clear the newbie's happiness will last a month, and then, corruption. What a welcome message! In the past, we could buy battery powered compact flash cards for the ancient HP200LX, plug it and forget about for, say, 10 years (changing batteries every two years). The best reliable solutions proposed in this site refers to minimizing writes to the disc, strapping vital functions and rendering the RPi almost unusable, even forgetting that the kernel itself will write countless times in the same sectors due to the linux file abstraction model ( everything in linux is a file). That said, while manufacturers do not present an everlasting solution, is there another kind of SD Card electrically compatible solution or hacking that would bring Raspberry to the serious side, without inflating its size and purpose?
2013/09/16
[ "https://raspberrypi.stackexchange.com/questions/9629", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/9550/" ]
You make a lot of assumptions. The statement about 1 month is just flat-out wrong. Compact flash cards are actually worse for this kind of operation than SD-cards. I tried to install a server onto one which lasted a whole three weeks before dying. Compare that to the server I have running on an SD card on the pi for over 3 months now 24/7. But no, there are no guarentees how long it will actually last. Many SD-cards use middleware to ensure that writes do not happen to the same sector but it is a bit of a mystery which manufacturers provide it with their cards and this is the cause of most of the confusion with SD cards for the pi. Another option is to use the SD-card for the boot loader and keep your distro and a USB hard drive. This however will inflate its size. Lastly the pi is not meant as an everlasting solution. Neither is the beagle board or the Via APC (which both run of micro-sd cards). If you want a full-fledged desktop system, get a pc of your preferred form-factor (via is a good option). The pi is a development platform and should be used as such.
You don't actually need to write to the SD Card at all, or at least not much after the initial configuration. Depending on the application you have in mind. We use the RaspberryPi in a system we ship to customers and we configured the SD Card to be mounted read only with a union file system on top. The downside you lose any changes after a reboot, the upside, you can't corrupt a read only SD card with failed writes. Have a look at <http://blog.a-netz.de/2013/02/read-only-root-filesystem/> for a guide on how to do it. You can remount the filesystem RW if you need to make changes and then mount it RO when you are done. The SD card will last approximately Forever(TM) in such device because they aren't ever really being written too. It makes the system less flexible, but you can yank the power from it and never be worried about a file system corruption. If you need writable storage that can't be lost then the use of NFS or SMB mounts to copy to could solve that problem.
54,468,853
When I add some item in the beginning, my code works, but after 1, 2 or maybe 3 items, it's not showing the new items and instead keeps showing old ones. RecycleView Class: ``` public class FilmateShikuara { private String Emri; private Double Rating; private Bitmap Image; public String getEmri() { return Emri; } public Double getRating() { return Rating; } public Bitmap getImage() { return Image; } public FilmateShikuara(String emri, Double rating, Bitmap image) { Emri = emri; Rating = rating; Image = image; } public void setEmri(String emri) { Emri = emri; } public void setRating(Double rating) { Rating = rating; } public void setImage(Bitmap image) { Image = image; } } ``` RecycleView adapter: ``` public class WatchedfilmsAdapter extends RecyclerView.Adapter<WatchedfilmsAdapter.MyViewHolder>{ private Context mContext; private List<FilmateShikuara> mData; public WatchedfilmsAdapter(Context mContext, List<FilmateShikuara> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater=LayoutInflater.from(mContext); View view=inflater.inflate(R.layout.layout_product,null); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) { myViewHolder.movieImage.setImageBitmap(mData.get(i).getImage()); myViewHolder.movieName.setText(mData.get(i).getEmri()); String rating=mData.get(i).getRating().toString(); myViewHolder.movieRating.setText(rating); } @Override public int getItemCount() { return mData.size(); } static class MyViewHolder extends RecyclerView.ViewHolder{ ImageView movieImage; TextView movieName; TextView movieRating; MyViewHolder(@NonNull View itemView) { super(itemView); movieImage=(ImageView)itemView.findViewById(R.id.MovieImage); movieName=(TextView)itemView.findViewById(R.id.MovieName); movieRating=(TextView)itemView.findViewById(R.id.Movie_Rating); } } } ``` Layout class: ``` public class Watched_MoviesList extends AppCompatActivity{ List<FilmateShikuara> productList; SQLiteDatabase db; FilmaDb dbHelper; RecyclerView recyclerView; static WatchedfilmsAdapter adapterW; ImageView homeIcon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_watched__movies_list); homeIcon=(ImageView)findViewById(R.id.HomeIcon); homeIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(v.getContext(),MainActivity.class); startActivity(intent); } }); dbHelper=new FilmaDb(this,"Filma_db",null,2); db=dbHelper.getWritableDatabase(); productList=new ArrayList<>(); recyclerView= findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ReadData(); adapterW=new WatchedfilmsAdapter(this,productList); recyclerView.setAdapter(adapterW); } public void ReadData() { Cursor c=db.rawQuery("SELECT * FROM WatchedMovie",null); while (c.moveToNext()) { String moviename=c.getString(c.getColumnIndex("Emri")); Double rate=c.getDouble(c.getColumnIndex("Rate")); byte[] image=c.getBlob(c.getColumnIndex("Photo")); Bitmap bitmap=BitmapFactory.decodeByteArray(image,0,image.length); productList.add(new FilmateShikuara(moviename,rate,bitmap)); } c.close(); } } ``` Xml: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Watched_MoviesList" android:background="#1E1E2C"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal" android:background="#141421" android:clickable="true"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:layout_marginLeft="10dp" android:layout_marginTop="12dp" android:text="Watched movies" android:textColor="@android:color/white" android:textSize="20sp" android:fontFamily="@font/roboto_bold" android:textStyle="bold"/> <ImageView android:id="@+id/HomeIcon" android:layout_width="29dp" android:layout_height="29dp" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:layout_alignParentEnd="true" android:background="@drawable/edithomeicon"/> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/editlinearlayout" android:layout_margin="0dp"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> ```
2019/01/31
[ "https://Stackoverflow.com/questions/54468853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8875695/" ]
A for loop will continue as long as the middle expression evaluates to true, i.e. a non-zero value. So in this case: ``` for(i=0; st[i]; i++) ``` The loop continues as long as `st[i]` is not 0. Since there are no elements of the array that contain 0, this ends up reading past the end of the array. Doing so invokes [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior), which in this case manifests as an indeterminate number of seemingly random values being printed.
In C, a condition is true if it evaluates to non-zero, and false if it evaluates to zero. In the case where the condition is simply `st[i]`, it is implicitly comparing the value of `st[i]` with zero to determine whether the condition is true or false. This is a pretty common thing when dealing with strings where the length is not already known (i.e. if it was passed as a pointer), since the null-terminator has a numeric value of zero. In your case, the comparison makes no sense, since your array of `int` doesn't end with a value of zero, and you already know the length of it. Why not just pass 8? The condition of `st[i]` will invoke undefined behavior since you are guaranteed to go out of bounds with that array, since there is no element with the value of zero in it.
54,468,853
When I add some item in the beginning, my code works, but after 1, 2 or maybe 3 items, it's not showing the new items and instead keeps showing old ones. RecycleView Class: ``` public class FilmateShikuara { private String Emri; private Double Rating; private Bitmap Image; public String getEmri() { return Emri; } public Double getRating() { return Rating; } public Bitmap getImage() { return Image; } public FilmateShikuara(String emri, Double rating, Bitmap image) { Emri = emri; Rating = rating; Image = image; } public void setEmri(String emri) { Emri = emri; } public void setRating(Double rating) { Rating = rating; } public void setImage(Bitmap image) { Image = image; } } ``` RecycleView adapter: ``` public class WatchedfilmsAdapter extends RecyclerView.Adapter<WatchedfilmsAdapter.MyViewHolder>{ private Context mContext; private List<FilmateShikuara> mData; public WatchedfilmsAdapter(Context mContext, List<FilmateShikuara> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater=LayoutInflater.from(mContext); View view=inflater.inflate(R.layout.layout_product,null); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) { myViewHolder.movieImage.setImageBitmap(mData.get(i).getImage()); myViewHolder.movieName.setText(mData.get(i).getEmri()); String rating=mData.get(i).getRating().toString(); myViewHolder.movieRating.setText(rating); } @Override public int getItemCount() { return mData.size(); } static class MyViewHolder extends RecyclerView.ViewHolder{ ImageView movieImage; TextView movieName; TextView movieRating; MyViewHolder(@NonNull View itemView) { super(itemView); movieImage=(ImageView)itemView.findViewById(R.id.MovieImage); movieName=(TextView)itemView.findViewById(R.id.MovieName); movieRating=(TextView)itemView.findViewById(R.id.Movie_Rating); } } } ``` Layout class: ``` public class Watched_MoviesList extends AppCompatActivity{ List<FilmateShikuara> productList; SQLiteDatabase db; FilmaDb dbHelper; RecyclerView recyclerView; static WatchedfilmsAdapter adapterW; ImageView homeIcon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_watched__movies_list); homeIcon=(ImageView)findViewById(R.id.HomeIcon); homeIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(v.getContext(),MainActivity.class); startActivity(intent); } }); dbHelper=new FilmaDb(this,"Filma_db",null,2); db=dbHelper.getWritableDatabase(); productList=new ArrayList<>(); recyclerView= findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ReadData(); adapterW=new WatchedfilmsAdapter(this,productList); recyclerView.setAdapter(adapterW); } public void ReadData() { Cursor c=db.rawQuery("SELECT * FROM WatchedMovie",null); while (c.moveToNext()) { String moviename=c.getString(c.getColumnIndex("Emri")); Double rate=c.getDouble(c.getColumnIndex("Rate")); byte[] image=c.getBlob(c.getColumnIndex("Photo")); Bitmap bitmap=BitmapFactory.decodeByteArray(image,0,image.length); productList.add(new FilmateShikuara(moviename,rate,bitmap)); } c.close(); } } ``` Xml: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Watched_MoviesList" android:background="#1E1E2C"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal" android:background="#141421" android:clickable="true"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:layout_marginLeft="10dp" android:layout_marginTop="12dp" android:text="Watched movies" android:textColor="@android:color/white" android:textSize="20sp" android:fontFamily="@font/roboto_bold" android:textStyle="bold"/> <ImageView android:id="@+id/HomeIcon" android:layout_width="29dp" android:layout_height="29dp" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:layout_alignParentEnd="true" android:background="@drawable/edithomeicon"/> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/editlinearlayout" android:layout_margin="0dp"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> ```
2019/01/31
[ "https://Stackoverflow.com/questions/54468853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8875695/" ]
A for loop will continue as long as the middle expression evaluates to true, i.e. a non-zero value. So in this case: ``` for(i=0; st[i]; i++) ``` The loop continues as long as `st[i]` is not 0. Since there are no elements of the array that contain 0, this ends up reading past the end of the array. Doing so invokes [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior), which in this case manifests as an indeterminate number of seemingly random values being printed.
`st[i]` may becomes zero (which means false in C) on some unpredictable iteration as you read the elements past the array end. It is an UB and anything may happen. modify ``` #include<stdio.h> int main() { int st[] ={1,2,3,4,5,6,7,8,0}; int i; for(i=0; st[i]; i++) printf("\n%d %d %d %d", str[i], *(str+i), *(i+str), i[str]); return 0; } ``` and it will work as expected
61,782,742
I'm trying to set up a material ui date range picker example following the code on the docs but it's giving me an error, TypeError: undefined is not a function. I've never seen useState followed by a component before and it's what's throwing the error. `React.useState<DateRange>([null, null])` <https://dev.material-ui-pickers.dev/demo/daterangepicker> Complete Code: ``` import * as React from "react"; import { TextField } from "@material-ui/core"; import { DateRangePicker, DateRange, DateRangeDelimiter } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> ); } export default BasicDateRangePicker; ```
2020/05/13
[ "https://Stackoverflow.com/questions/61782742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377364/" ]
Below is a working version. I've added in the `LocalizationProvider` and removed the `<DateRange>` Typescript syntax. ``` import React from "react"; import TextField from "@material-ui/core/TextField"; import { DateRangePicker, DateRangeDelimiter, LocalizationProvider } from "@material-ui/pickers"; import DateFnsUtils from "@material-ui/pickers/adapter/date-fns"; // choose your lib export default function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> </LocalizationProvider> ); } ``` [![Edit DateRangePicker example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/daterangepicker-example-39n9v?fontsize=14&hidenavigation=1&theme=dark)
The `DateRangePicker` component also needs the `DateFnsAdapter` and the entire block should be wrapped with `LocalizationProvider`. Your code should look like this: ``` import React from 'react'; import { TextField } from "@material-ui/core"; import DateFnsAdapter from '@material-ui/pickers/adapter/date-fns'; // choose your lib import { DateRangePicker, DateRange, DateRangeDelimiter, LocalizationProvider } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> </LocalizationProvider> ); } export default BasicDateRangePicker; ``` You can read more about the `dateAdapter` in the [quick start](https://dev.material-ui-pickers.dev/getting-started/usage#quick-start) and in the [installation](https://dev.material-ui-pickers.dev/getting-started/installation).
61,782,742
I'm trying to set up a material ui date range picker example following the code on the docs but it's giving me an error, TypeError: undefined is not a function. I've never seen useState followed by a component before and it's what's throwing the error. `React.useState<DateRange>([null, null])` <https://dev.material-ui-pickers.dev/demo/daterangepicker> Complete Code: ``` import * as React from "react"; import { TextField } from "@material-ui/core"; import { DateRangePicker, DateRange, DateRangeDelimiter } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> ); } export default BasicDateRangePicker; ```
2020/05/13
[ "https://Stackoverflow.com/questions/61782742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377364/" ]
I was also facing an error for Mui DateRangePicker with typescript, "Type 'null[]' is missing the following properties from type 'RangeInput': 0, 1" latest versions --> "@material-ui/pickers": "^4.0.0-alpha.12" , "date-fns": "^2.16.1" Working code: ``` import React from "react"; import TextField from "@material-ui/core/TextField" import { DateRangePicker, DateRangeDelimiter, LocalizationProvider, DateRange, } from "@material-ui/pickers" import DateFnsUtils from "@material-ui/pickers/adapter/date-fns" export default function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange<Date | null>>([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="from" endText="to" value={selectedDate} onChange={(date: any) => handleDateChange(date)} renderInput={(startProps: any, endProps: any) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> ) } /> </LocalizationProvider> ); } ```
The `DateRangePicker` component also needs the `DateFnsAdapter` and the entire block should be wrapped with `LocalizationProvider`. Your code should look like this: ``` import React from 'react'; import { TextField } from "@material-ui/core"; import DateFnsAdapter from '@material-ui/pickers/adapter/date-fns'; // choose your lib import { DateRangePicker, DateRange, DateRangeDelimiter, LocalizationProvider } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> </LocalizationProvider> ); } export default BasicDateRangePicker; ``` You can read more about the `dateAdapter` in the [quick start](https://dev.material-ui-pickers.dev/getting-started/usage#quick-start) and in the [installation](https://dev.material-ui-pickers.dev/getting-started/installation).
61,782,742
I'm trying to set up a material ui date range picker example following the code on the docs but it's giving me an error, TypeError: undefined is not a function. I've never seen useState followed by a component before and it's what's throwing the error. `React.useState<DateRange>([null, null])` <https://dev.material-ui-pickers.dev/demo/daterangepicker> Complete Code: ``` import * as React from "react"; import { TextField } from "@material-ui/core"; import { DateRangePicker, DateRange, DateRangeDelimiter } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> ); } export default BasicDateRangePicker; ```
2020/05/13
[ "https://Stackoverflow.com/questions/61782742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377364/" ]
The `DateRangePicker` component also needs the `DateFnsAdapter` and the entire block should be wrapped with `LocalizationProvider`. Your code should look like this: ``` import React from 'react'; import { TextField } from "@material-ui/core"; import DateFnsAdapter from '@material-ui/pickers/adapter/date-fns'; // choose your lib import { DateRangePicker, DateRange, DateRangeDelimiter, LocalizationProvider } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> </LocalizationProvider> ); } export default BasicDateRangePicker; ``` You can read more about the `dateAdapter` in the [quick start](https://dev.material-ui-pickers.dev/getting-started/usage#quick-start) and in the [installation](https://dev.material-ui-pickers.dev/getting-started/installation).
It is not working for me, I have used all alpha versions and it shows this error TypeError: Cannot read property 'keyboardDate' of undefined 99 | ...other, 100 | value, 101 | onChange, > > 102 | inputFormat: passedInputFormat || utils.formats.keyboardDate, > | ^ 103 | }; > 104 | > 105 | const restProps = { > > > and with the stable version it says it can't find DateRangePicker
61,782,742
I'm trying to set up a material ui date range picker example following the code on the docs but it's giving me an error, TypeError: undefined is not a function. I've never seen useState followed by a component before and it's what's throwing the error. `React.useState<DateRange>([null, null])` <https://dev.material-ui-pickers.dev/demo/daterangepicker> Complete Code: ``` import * as React from "react"; import { TextField } from "@material-ui/core"; import { DateRangePicker, DateRange, DateRangeDelimiter } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> ); } export default BasicDateRangePicker; ```
2020/05/13
[ "https://Stackoverflow.com/questions/61782742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377364/" ]
Below is a working version. I've added in the `LocalizationProvider` and removed the `<DateRange>` Typescript syntax. ``` import React from "react"; import TextField from "@material-ui/core/TextField"; import { DateRangePicker, DateRangeDelimiter, LocalizationProvider } from "@material-ui/pickers"; import DateFnsUtils from "@material-ui/pickers/adapter/date-fns"; // choose your lib export default function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> </LocalizationProvider> ); } ``` [![Edit DateRangePicker example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/daterangepicker-example-39n9v?fontsize=14&hidenavigation=1&theme=dark)
It is not working for me, I have used all alpha versions and it shows this error TypeError: Cannot read property 'keyboardDate' of undefined 99 | ...other, 100 | value, 101 | onChange, > > 102 | inputFormat: passedInputFormat || utils.formats.keyboardDate, > | ^ 103 | }; > 104 | > 105 | const restProps = { > > > and with the stable version it says it can't find DateRangePicker
61,782,742
I'm trying to set up a material ui date range picker example following the code on the docs but it's giving me an error, TypeError: undefined is not a function. I've never seen useState followed by a component before and it's what's throwing the error. `React.useState<DateRange>([null, null])` <https://dev.material-ui-pickers.dev/demo/daterangepicker> Complete Code: ``` import * as React from "react"; import { TextField } from "@material-ui/core"; import { DateRangePicker, DateRange, DateRangeDelimiter } from "@material-ui/pickers"; function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange>([null, null]); return ( <DateRangePicker startText="Check-in" endText="Check-out" value={selectedDate} onChange={date => handleDateChange(date)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> )} /> ); } export default BasicDateRangePicker; ```
2020/05/13
[ "https://Stackoverflow.com/questions/61782742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377364/" ]
I was also facing an error for Mui DateRangePicker with typescript, "Type 'null[]' is missing the following properties from type 'RangeInput': 0, 1" latest versions --> "@material-ui/pickers": "^4.0.0-alpha.12" , "date-fns": "^2.16.1" Working code: ``` import React from "react"; import TextField from "@material-ui/core/TextField" import { DateRangePicker, DateRangeDelimiter, LocalizationProvider, DateRange, } from "@material-ui/pickers" import DateFnsUtils from "@material-ui/pickers/adapter/date-fns" export default function BasicDateRangePicker() { const [selectedDate, handleDateChange] = React.useState<DateRange<Date | null>>([null, null]); return ( <LocalizationProvider dateAdapter={DateFnsUtils}> <DateRangePicker startText="from" endText="to" value={selectedDate} onChange={(date: any) => handleDateChange(date)} renderInput={(startProps: any, endProps: any) => ( <> <TextField {...startProps} /> <DateRangeDelimiter> to </DateRangeDelimiter> <TextField {...endProps} /> </> ) } /> </LocalizationProvider> ); } ```
It is not working for me, I have used all alpha versions and it shows this error TypeError: Cannot read property 'keyboardDate' of undefined 99 | ...other, 100 | value, 101 | onChange, > > 102 | inputFormat: passedInputFormat || utils.formats.keyboardDate, > | ^ 103 | }; > 104 | > 105 | const restProps = { > > > and with the stable version it says it can't find DateRangePicker
20,147,635
I have a 100% width table containing several cells. I want one of this cells to always show its contents in one line `white-space: nowrap` and to display an ellipsis at the end of the line if the contents exceed the table cell `text-overflow: ellipsis`. The problem i have is that the table will stop contracting it's with when reaching the cells content. So the minium width of the cell will allways be the width of its content instead the table will be pushed out as a whole. I just can't figure out how to solve this: My HTML: ``` <div class="otrCompactView"> <div class="otrLastEditTable"> <div class="otrLastEditRow"> <div class="otrLastEditor">LastEditor</div> <div class="otrLastEdited">LastModified</div> </div> </div> <div class="otrTitleRow otrRow"> <div class="otrTitle">Title asdasdasdas asd asd asd asdas as asd </div> </div> <div vlass="otrTaskRow otrRow"> </div> <div class="otrColumnsRow otrRow"> <div class="otrColumns"></div> </div> </div> ``` My CSS: ``` .otrCompactView { display: table; background: yellow; width: 100%; height: 100%; } .otrRow { display: table-row; } .otrLastEditTable { display: table; width: 100%; } .otrLastEditRow { display: table-row; } .otrLastEditor { display: table-cell; } .otrLastEdited { display: table-cell; text-align: right; } .otrTitle { border: 1px dotted red; min-width: 50px; white-space: nowrap; } ``` And a fiddle for direct testing: <http://jsfiddle.net/67B6G/>
2013/11/22
[ "https://Stackoverflow.com/questions/20147635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638344/" ]
Does [this look like what you're after](http://jsfiddle.net/5H2L5/1/)? **[updated](http://jsfiddle.net/5H2L5/2/)** HTML ``` <div class='table'> <div class='row'> <div class='cell'>Something quite long</div> </div> <div class='row'> <div class='cell'> here is some moreSomething quite long that should exceed the table cell.Something quite long that should exceed the table cell. </div> </div> </div> ``` CSS ``` .table{ margin:0; padding:0; display:table; table-layout: fixed; width:100%; max-width:100%; } .row{ display:table-row; } .cell{ display:table-cell; border:1px solid grey; } .cell:last-child{ white-space: nowrap; overflow:hidden; text-overflow: ellipsis; } ```
Here's a way to do it without using `table-layout: fixed` that allows you to keep dynamic widths with jQuery. HTML: ``` <div class="table"> <div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div> <div class="right">Lorem Ipsum</div> </div> ``` In the CSS, you use your standard ellipsis code but add `max-width: 0` (as explained [here](https://stackoverflow.com/questions/9789723/css-text-overflow-in-a-table-cell/11877033#11877033) with respect to actual `table` elements): ``` .table { display: table; width: 100%; } .left, .right { display: table-cell; padding: 0 5px 0 5px; max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } ``` If you stopped there, you'd end up with each child `div` taking up 50% of the total width of the parent `div`, so you still wouldn't have fit-to-content dynamic widths. To remedy this, I adapted [this code, which calculates the width of the text in an element,](https://stackoverflow.com/a/15302051/1652620) to calculate the width and then use that to dynamically set the width of the right column. The left column will then have the ellipsis. ``` // Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com> $.fn.textWidth = function(text, font) { if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body); $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font')); return $.fn.textWidth.fakeEl.width(); }; $('.right').on('input', function() { var $width = $(this).textWidth(); // Get width of text $width += 10; // Add left and right padding $(this).width($width); // Set width }).trigger('input'); ``` Note that the above code requires you to take `padding` into account; otherwise, the right column will have an ellipsis as well. Here's a [fiddle](https://jsfiddle.net/vincentpace/d7mg1ttn/3/). To use this in a table with multiple rows, you could modify the jQuery iterate over the cells in a column and set the width of the column to the requisite width of the widest cell in the column. Or, if you know which one is the widest, you can just direct the jQuery to get the width of that.
806
[Constellation search from April 22 2007](https://astronomy.stackexchange.com/q/46831/7982) received three good answers before it was *correctly* closed as duplicate to our canonical [Where can I find the positions of the planets, stars, moons, artificial satellites, etc. and visualize them?](https://astronomy.stackexchange.com/q/13488/7982) which was cultivated and cared-for by the late @user21. Two of the three answers there are not found in the canonical answer (in-the-sky.org, skyandtelescope.org); we might not have found that out had that question been closed earlier, the Sky and Telescope [answer](https://astronomy.stackexchange.com/a/46843/7982) was added only 40 minutes before the insta-close. Closing as duplicate is a very important tool as it directs future readers to answers they should see, I'm just asking about the speed. The Sky and Telescope answer is the first post from a new answer, the only up vote the've received is mine, and only because I stopped by to check on the question. Had the question been given another day or two before closing, perhaps by letting the community do it, they might have picked up another vote or two. New users are a low question rate SE site's life blood. They are to be encouraged and nurtured. To review: * had closing been only ~40 minutes earlier we would have lost a valuable answer not found in the duplicate * had closing been a day or two later, a new user may have received some precious first up votes for that new and valuable answer. * Even if they go and add it to the community wiki of the duplicate, they can't receive up votes, and would be discouraged from posting a separate answer where they could. **Question:** Is insta-closing of potential duplicates always the best way? In low Q-rate sites? Is there something to be said for slow-closing or eventual closing?
2021/09/23
[ "https://astronomy.meta.stackexchange.com/questions/806", "https://astronomy.meta.stackexchange.com", "https://astronomy.meta.stackexchange.com/users/7982/" ]
Remove the "pin to top" behaviour. ---------------------------------- I want this behaviour to be removed. An accepted answer should be sorted in the same way as all answers.
Keep the "pin to top" behaviour. -------------------------------- I want this behaviour to be kept. An accepted answer should be placed at the top of the list.
15,155,045
In my code I enumerate all local IIS sites and for each site I try to validate the certificate for port 443. ``` using( var sm = new ServerManager() ) { foreach( var site in sm.Sites ) { foreach( var binding in site.Bindings ) { if( binding.EndPoint.Port == 443 ) { var thumbprint = binding.CertificateHash; var storeName = binding.CertificateStoreName; //validation here... } } } } ``` This code yeilds the `storeName` being `"MY"` and `thumbprint` being some byte array that I convert into a hex representation. Now the "validation" part works like this: ``` var store = new X509Store("MY"); store.Open(OpenFlags.ReadOnly); var certs = store.Certificates; //find and validate my cert store.Close(); ``` and this code yields an empty collection. Yet if I change ``` var store = new X509Store("MY"); ``` to ``` var store = new X509Store(StoreLocation.LocalMachine); ``` then the code yields a collection with two certificates and one of them has the right thumbprint and I can validate it. Why does it happen that `Binding` returns a certificate store name but I can't find any certificates in the store with that name?
2013/03/01
[ "https://Stackoverflow.com/questions/15155045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57428/" ]
There's a difference between a store *name* and a store *location*. All of the certificates for IIS are stored in the Local Machine location, rather than one for a specific user account. This is what the constructor for `X509Store` looks like, that just takes a `StoreLocation`, that your second example is calling: ``` public X509Store(StoreLocation storeLocation) : this("MY", storeLocation) { } ``` Which is calling the [constructor](http://msdn.microsoft.com/en-us/library/f07btzah.aspx) that takes both a store name *and* a location. Your first example: ``` var store = new X509Store("MY"); ``` Is opening the `MY` store for the [`CurrentUser`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storelocation.aspx), not the local machine. So you're looking in the *wrong* store. Switch to using the constructor that takes both a name and a location.
This method will get certificate for you: ``` private X509Certificate2 GetServiceCertificate(String certificateSubjectName, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.CurrentUser) { X509Store certificateStore = new X509Store(storeName, storeLocation); foreach (X509Certificate2 certificate in certificateStore.Certificates) { if (certificate.SubjectName.Name == certificateSubjectName) { return certificate; } } return null; } ```
10,783,583
I'm using a `PasswordBox` on a `Page`. Because of the implemented workflow the user can navigate to sub pages (`NavigationWindow`) and than return with `GoBack()` to the main page. But when doing that, the password box is always empty! My job is to prevent that behaviour, but at the moment I have no clue how do achive that. It would be great if you could help me out. Thanks
2012/05/28
[ "https://Stackoverflow.com/questions/10783583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338645/" ]
It is a feature. See: [How to bind to a PasswordBox in MVVM](https://stackoverflow.com/questions/1483892/wpf-binding-to-the-passwordbox-in-mvvm-working-solution) To enable the backward navigation the state of the page needs to be stored. And that is not secure.
I don't think his exact problem is a feature, but a bug of the navigation service. In your code behind you have no easy way to distinguish between the navigation control blanking your password on navigation or the user blanking it by deleting it from the box. So if you don't consider that, your password in your viewmodel will always be blank if you navigate to another page. I used this hack to determine who called my password changed handler to update the view model: ``` private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e) { StackTrace stack = new StackTrace(); StackFrame[] stackframes = stack.GetFrames(); foreach (StackFrame stackFrame in stackframes) if(stackFrame.GetMethod().Name == "Navigate") return; ViewModelPassword = PasswordBox.SecurePassword; .... ``` Take a look here too: <http://www.wpfsharp.com/2011/04/08/wpf-navigationservice-blanks-passwordbox-password-which-breaks-the-mvvm-passwordhelper/>
84,748
I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is ``` \documentclass[a4paper,11pt]{article} \usepackage{kerkis} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsfonts} \usepackage{amsthm} \usepackage[pdftex]{graphicx} \usepackage{xcolor} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \setlength{\unitlength}{1cm} \begin{picture}(15,5) \color{blue} \put(-1,0){\line(0,1){5}} \put(0,1.5){\includegraphics[scale=0.8]{math}} \put(-1,0){\line(1,0){15}} \put(14,0){\line(0,1){5}} \put(-1,5){\line(1,0){15}} \end{picture} \end{document} ``` My output is ![](https://i.imgur.com/88L93.png) Any ideas on how to include Mathematica code in a more aesthetically way? **Edit**:At first I used package `listing` but the problem was the fraction and the fact that I don't know how to include in a convenient way `In[1]` and `Out[1]`
2012/11/29
[ "https://tex.stackexchange.com/questions/84748", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12795/" ]
You could use `listings` together with `xcolor` to include the code, for example with this MWE ``` \documentclass[a4paper,12pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage{listings,xcolor} \lstset{language=Mathematica} \lstset{basicstyle={\sffamily\footnotesize}, numbers=left, numberstyle=\tiny\color{gray}, numbersep=5pt, breaklines=true, captionpos={t}, frame={lines}, rulecolor=\color{black}, framerule=0.5pt, columns=flexible, tabsize=2 } \begin{document} \begin{lstlisting}[language=Mathematica,caption={Example code}] Integrate[{y^(-3)}*(1-(a/y)^2)^(-2),{y,r,Infinity}] \end{lstlisting} \end{document} ``` You would obtain something like ![Code example image](https://i.stack.imgur.com/vuE4j.png) and by changing the `\lstset` even adapt the colors to look more `Mathematica`ish. You could then also use external code files and something like `\lstinputlisting{yourfile.m}` to include them. This is what i prefer, because then you could just (ok in Mathematica working on one cell) code the stuff you want and change the code. Due to the input it is then automatically the most recent version of your code example. *Edit 1* The OP requested to use Math symbols and fractions in his code: One way to do that is, to add `mathescape` to the lstset as a further key. Then at any `$` in the code the mode is switched to mathmode and one can type simply math. Then one could change the code line to ``` Integrate[{y^(-3)}*(1-$\bigl(\frac{a}{y}\bigr)$^2)^(-2),{y,r,Infinity}] ``` to obtain ![Second Code with math](https://i.stack.imgur.com/8d6Lh.png) though i think it is not that nice to read (because there's still `^2` in the code and other non-LaTeX-set formulae. Finally my remark above won't work anymore, this code would - of course - not be able to run in Mathematica anymore.
Using the `listings` package, it is possible to get math mode in the mathematica code. You need to add the `mathescape` option on the `listings` environment definition, and manually place the math delimiters in the listing. I realise that this may be impractical if you want to insert a lot of code. I hope the following code makes my meaning clear. ``` \documentclass{article} \usepackage{listings} \usepackage{framed} \usepackage{xcolor} \usepackage{amsmath} \colorlet{shadecolor}{gray!20} \lstnewenvironment{mat} {\lstset{language=mathematica,mathescape,columns=flexible}} {} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \begin{shaded} \begin{mat} In[1]:= Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}] Out[1]= {ConditionalExpression[$\displaystyle-\frac{1}{2(a^2-r^2)}$, Im[r] Re[a] $\neq$ Im[a] Re[r] || (( $a+r>0$ || $a+r \notin $ Reals) && ($a<r$ || $a-r \notin$ Reals) || $r\notin$ Reals )]} \end{mat} \end{shaded} \end{document} ``` Note that I formatted the output manually. Here is the result: ![result](https://i.imgur.com/TkuZT.png)
84,748
I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is ``` \documentclass[a4paper,11pt]{article} \usepackage{kerkis} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsfonts} \usepackage{amsthm} \usepackage[pdftex]{graphicx} \usepackage{xcolor} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \setlength{\unitlength}{1cm} \begin{picture}(15,5) \color{blue} \put(-1,0){\line(0,1){5}} \put(0,1.5){\includegraphics[scale=0.8]{math}} \put(-1,0){\line(1,0){15}} \put(14,0){\line(0,1){5}} \put(-1,5){\line(1,0){15}} \end{picture} \end{document} ``` My output is ![](https://i.imgur.com/88L93.png) Any ideas on how to include Mathematica code in a more aesthetically way? **Edit**:At first I used package `listing` but the problem was the fraction and the fact that I don't know how to include in a convenient way `In[1]` and `Out[1]`
2012/11/29
[ "https://tex.stackexchange.com/questions/84748", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12795/" ]
I know this question is old and surely OP doesn't need it anymore, but recently I had similar problem and I think my solution answers the question. First thing to note is that in Mathematica FrontEnd cells can have arbitrary styles. Each styles appearance is customizable by a stylesheet. With default stylesheet even most basic cell styles i.e. `Input` and `Output` look different. In cells with some styles (e.g `Input` or `Code`) code syntax is colored, this can be achieved using already mentioned in other answers `listings` package. Cells with some styles (e.g. `Input`, `Output` or `Print`) by default use, so called `StandardForm`, which allows embedding of complicated formatting (fractions, superscripts etc.) inside code. This was partially solved in other answers by using `mathescape` functionality of `listings` package. Problem with this solution is that `mathescape` "completely escapes" to TeX. Since one can't nest `listings` environments/commands, I don't see a way to treat parts of escaped content again as code (e.g. typeset it verbatim) using `listings` only. To achieve such functionality one can use `Verbatim` environment from `fancyvrb` package. By setting proper `commandchars` we can embed, for example, `\frac` command inside code, in such way that frac's arguments are typeset verbatim. Downside of `fancyvrb` is that it doesn't offer automatic syntax coloring. Fortunately `listings` has special interface to `fancyvrb` that allows combining of reading code by `fancyvrb` and typesetting it by `listings`. Below I present usage of my [mmacells](https://github.com/jkuczm/mmacells) package, which implements solution based on `fancyvrb` + `listings` approach, with some additional features like customizable cell styles, automatic cell labels etc. There's also corresponding *Mathematica* package: [CellsToTeX](https://github.com/jkuczm/MathematicaCellsToTeX), that automatically exports *Mathematica* code to TeX code compatible with `mmacells`. *Mathematica* package is described in detail in [answer to "How best to embed various cell groups into a latex project?" question](https://mathematica.stackexchange.com/a/73589/14303) on Mathematica Stack Exchange. Usage example ============= Print screen of result: [![Mathematica cells in pdf](https://i.stack.imgur.com/Rs9tG.png)](https://i.stack.imgur.com/Rs9tG.png) TeX code: ``` \documentclass{article} \usepackage[margin=2cm]{geometry} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{mmacells} \mmaDefineMathReplacement[≤]{<=}{\leq} \mmaDefineMathReplacement[≥]{>=}{\geq} \mmaDefineMathReplacement[≠]{!=}{\neq} \mmaDefineMathReplacement[→]{->}{\to}[2] \mmaDefineMathReplacement[⧴]{:>}{:\hspace{-.2em}\to}[2] \mmaDefineMathReplacement{∉}{\notin} \mmaDefineMathReplacement{∞}{\infty} \mmaDefineMathReplacement{}{\mathbbm{d}} \mmaSet{ morefv={gobble=2}, linklocaluri=mma/symbol/definition:#1, morecellgraphics={yoffset=1.9ex} } \begin{document} Input from question with output from my Mathematica version. Input is in input form, it can be copied and pasted to Mathematica. \begin{mmaCell}[functionlocal=y]{Code} Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}] \end{mmaCell} \begin{mmaCell}{Output} \{ConditionalExpression[-\mmaFrac{1}{2 (\mmaSup{a}{2} - \mmaSup{r}{2})}, Im[r] Re[a] ≠ Im[a] Re[r] || ((a + r > 0 || a + r ∉ Reals) && ((Re[a] < r && Im[a] == 0) || a - r ∉ Reals)) || r ∉ Reals]\} \end{mmaCell} For comparison, same cells obtained by including PDFs exported from Mathematica: % You need inCell.pdf and outCell.pdf files for this to work. % \mmaCellGraphics{Input}{inCell} % \mmaCellGraphics[yoffset=3.5ex]{Output}{outCell} Same input expression, but in standard form (as if it was inputted using math assistant). Note that syntax coloring still works. \begin{mmaCell}[index=3,functionlocal=y]{Input} \mmaSubSupM{\int}{r}{∞}\{\mmaFrac{1}{\mmaSup{y}{3}\mmaSup{\big(1-\mmaSup{\big(\mmaFrac{a}{y}\big)}{2}\big)}{2}}\}y \end{mmaCell} More features: \begin{mmaCell}[ moredefined=f, functionlocal=a, local=b, pattern={x_,x}, excessargument=n, linkbuiltin=List ]{Code} (* A (* nested *) comment. *) Block[{a=3},a+2] f[x_]:=2x+1 Module[{b=c}, Print["a string \" with double quotes inside ", b/d]; b+1 ] f[z]//FullForm Sin[m,n] List[1,List[2,3]]; (* Links to documentation. *) \end{mmaCell} \begin{mmaCell}{Output} 5 \end{mmaCell} \begin{mmaCell}{Print} a string " with double quotes inside \mmaFrac{c}{d} \end{mmaCell} \begin{mmaCell}[addtoindex=1]{Output} 1+c \end{mmaCell} \begin{mmaCell}[form=FullForm]{Output} Plus[1,Times[2,z]] \end{mmaCell} \begin{mmaCell}[messagelink={message/General/argx}]{Message} Sin::argx: Sin called with 2 arguments; 1 argument is expected. >> \end{mmaCell} \begin{mmaCell}{Output} Sin[m,n] \end{mmaCell} \begin{mmaCell}{Output} \{1,\{2,3\}\} \end{mmaCell} Graphics mixed with code: \begin{mmaCell}{Code} a Graphics[{Green,Disk[]},ImageSize->50]/2 \end{mmaCell} % You need greenDisk.pdf file for this to work. % \begin{mmaCell}[moregraphics={moreig={scale=.7}}]{Output} % \mmaFrac{a \mmaGraphics{greenDisk}}{2} % \end{mmaCell} \begin{mmaCell}{Code} (* Different roles of one symbol. *) x; _x; \mmaDef{x_}; \mmaPat{x_}->2x; \mmaPat{x_}:>2\mmaPat{x}; f[\mmaPat{x_}]=2x; f[\mmaPat{x_}]:=2\mmaPat{x}; Block[{\mmaFnc{x}},2\mmaFnc{x}]; Module[{\mmaLoc{x}},2\mmaLoc{x}]; \mmaUnd{Module}; (* undefined Module symbol *) \mmaLnB{Module}; (* Module symbol with link to documentation *) Sin[x\mmaExc{,x}]; \end{mmaCell} \begin{mmaCell}[addtoindex=11]{Input} (* Nesting of "formatting boxes" *) \mmaSup{a}{\mmaSup{a}{a}} \mmaSub{a}{\mmaSub{a}{a}} \mmaSubSup{a}{\mmaSubSup{a}{a}{a}}{\mmaSubSup{a}{a}{a}} \mmaUnder{a}{\mmaUnder{a}{a}} \mmaOver{a}{\mmaOver{a}{a}} \mmaUnderOver{a}{\mmaUnderOver{a}{a}{a}}{\mmaUnderOver{a}{a}{a}} \mmaFrac{a}{\mmaFrac{a}{\mmaFrac{a}{a}}} \mmaSqrt{\mmaSqrt{a}} \mmaRadical{a}{\mmaRadical{a}{a}} \end{mmaCell} \begin{mmaCell}{Input} (* Replacements for infix operators in "Input" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}{Code} (* No replacement in "Code" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}[label={(\mmaCellIndex)custom}]{Code} (* Cell with custom label. *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnT{x}=2;(* labeled definition of x *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnL{x}(* usage of x with link to its definition *) \end{mmaCell} Implemented syntax elements: \begin{mmaCell}[ defined=defined, undefined=undefined, functionlocal=functionlocal, local=local, pattern=pattern, localconflict=localconflict, globalconflict=globalconflict, excessargument=excessargument, unknownoption=unknownoption, unwantedassignment=unwantedassignment, shadowing=shadowing, syntaxerror=syntaxerror, emphasizedsyntaxerror=emphasizedsyntaxerror, formattingerror=formattingerror, ]{Code} \mmaDef{Def} defined (* defined symbol *) \mmaUnd{Und} undefined (* UndefinedSymbol *) \mmaFnc{Fnc} functionlocal (* FunctionLocalVariable *) \mmaLoc{Loc} local (* LocalVariable *) \mmaPat{Pat} pattern (* PatternVariable *) \mmaLCn{LCn} localconflict (* LocalScopeConflict *) \mmaGCn{GCn} globalconflict (* GlobalToLocalScopeConflict *) \mmaExc{Exc} excessargument (* ExcessArgument *) \mmaOpt{Opt} unknownoption (* UnknownOption *) \mmaAsg{Asg} unwantedassignment (* UnwantedAssignment *) \mmaShd{Shd} shadowing (* SymbolShadowing *) \mmaSnt{Snt} syntaxerror (* SyntaxError *) \mmaEmp{Emp} emphasizedsyntaxerror (* EmphasizedSyntaxError *) \mmaFmt{Fmt} formattingerror (* FormattingError *) \end{mmaCell} Inline cell: \mmaInlineCell[functionlocal=a]{Code}{Module[{a=5}, a]}. Formatted inline cell: \mmaInlineCell[pattern={x_,x}]{Input}{f[x_]:=\mmaFrac{\mmaSup{x}{2}}{5}} \subsubsection*{ Inline cell inside macro argument: \mmaInlineCellNonVerb[functionlocal=x]{Code}{Solve[\mmaSqrt{x}==y,x]} } \end{document} ``` Unicode ======= There are three strategies of handling Unicode supported by `mmacells`. Code for all of them can be automatically generated by `CellsToTeX` *Mathematica* package. ### 1. No Unicode Don't use Unicode at all, use appropriate TeX commands instead. This approach works in all engines. `listings` package doesn't color elements provided by escaped commands, so they need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{mmacells} \begin{document} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{\(\pmb{\beta}\)} \(\pmb{\pm}\) \mmaSqrt{\mmaSup{\mmaUnd{\(\pmb{\beta}\)}}{2} - 4 \mmaUnd{\(\pmb{\alpha}\)} \mmaUnd{\(\pmb{\gamma}\)}}}{2 \mmaUnd{\(\pmb{\alpha}\)}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 2. Unicode input Use Unicode characters in input and automatically convert them to appropriate TeX commands by using `\mmaDefineMathReplacement`. This approach works in *pdfTeX* engine. Replacements are implemented using `listings` `literate` option, so are "excluded" from automatic coloring, and identifiers containing Unicode characters need to be wrapped with appropriate annotations. Whether replacements will be used is controlled by `mathreplacements` option. By default `Code` cells don't use replacements (`mathreplacements=none`), `Input` cells use bold replacements (`mathreplacements=bols`) i.e. will use given command wrapped with math delimiters and `\pmb`, `Output`, `Print` and `Message` cells use "light" replacements (`mathreplacements=light`) i.e. will will use given command wrapped with math delimiters. ``` \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{mmacells} \begin{document} \mmaDefineMathReplacement{±}{\pm} \mmaDefineMathReplacement{α}{\alpha} \mmaDefineMathReplacement{β}{\beta} \mmaDefineMathReplacement{γ}{\gamma} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 3. Unicode input and output Use Unicode characters in input and rely on appropriate glyphs of used fonts. This approach works in Unicode-aware engines. Since `listings` does not support Unicode, it needs to be switched off using `uselistings=false` option. With `listings` switched off no automatic coloring occurs, so all identifiers, also those not containing Unicode characters, need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{fontspec} \usepackage{mmacells} \setmainfont{FreeSerif} \setmonofont{FreeMono} \mmaSet{uselistings=false} \begin{document} \begin{mmaCell}{Input} \mmaSub{\mmaUnd{x}}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of xelatex with Unicode](https://i.stack.imgur.com/xW7Ht.png)](https://i.stack.imgur.com/xW7Ht.png)
You could use `listings` together with `xcolor` to include the code, for example with this MWE ``` \documentclass[a4paper,12pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage{listings,xcolor} \lstset{language=Mathematica} \lstset{basicstyle={\sffamily\footnotesize}, numbers=left, numberstyle=\tiny\color{gray}, numbersep=5pt, breaklines=true, captionpos={t}, frame={lines}, rulecolor=\color{black}, framerule=0.5pt, columns=flexible, tabsize=2 } \begin{document} \begin{lstlisting}[language=Mathematica,caption={Example code}] Integrate[{y^(-3)}*(1-(a/y)^2)^(-2),{y,r,Infinity}] \end{lstlisting} \end{document} ``` You would obtain something like ![Code example image](https://i.stack.imgur.com/vuE4j.png) and by changing the `\lstset` even adapt the colors to look more `Mathematica`ish. You could then also use external code files and something like `\lstinputlisting{yourfile.m}` to include them. This is what i prefer, because then you could just (ok in Mathematica working on one cell) code the stuff you want and change the code. Due to the input it is then automatically the most recent version of your code example. *Edit 1* The OP requested to use Math symbols and fractions in his code: One way to do that is, to add `mathescape` to the lstset as a further key. Then at any `$` in the code the mode is switched to mathmode and one can type simply math. Then one could change the code line to ``` Integrate[{y^(-3)}*(1-$\bigl(\frac{a}{y}\bigr)$^2)^(-2),{y,r,Infinity}] ``` to obtain ![Second Code with math](https://i.stack.imgur.com/8d6Lh.png) though i think it is not that nice to read (because there's still `^2` in the code and other non-LaTeX-set formulae. Finally my remark above won't work anymore, this code would - of course - not be able to run in Mathematica anymore.
84,748
I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is ``` \documentclass[a4paper,11pt]{article} \usepackage{kerkis} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsfonts} \usepackage{amsthm} \usepackage[pdftex]{graphicx} \usepackage{xcolor} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \setlength{\unitlength}{1cm} \begin{picture}(15,5) \color{blue} \put(-1,0){\line(0,1){5}} \put(0,1.5){\includegraphics[scale=0.8]{math}} \put(-1,0){\line(1,0){15}} \put(14,0){\line(0,1){5}} \put(-1,5){\line(1,0){15}} \end{picture} \end{document} ``` My output is ![](https://i.imgur.com/88L93.png) Any ideas on how to include Mathematica code in a more aesthetically way? **Edit**:At first I used package `listing` but the problem was the fraction and the fact that I don't know how to include in a convenient way `In[1]` and `Out[1]`
2012/11/29
[ "https://tex.stackexchange.com/questions/84748", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12795/" ]
You could use `listings` together with `xcolor` to include the code, for example with this MWE ``` \documentclass[a4paper,12pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage{listings,xcolor} \lstset{language=Mathematica} \lstset{basicstyle={\sffamily\footnotesize}, numbers=left, numberstyle=\tiny\color{gray}, numbersep=5pt, breaklines=true, captionpos={t}, frame={lines}, rulecolor=\color{black}, framerule=0.5pt, columns=flexible, tabsize=2 } \begin{document} \begin{lstlisting}[language=Mathematica,caption={Example code}] Integrate[{y^(-3)}*(1-(a/y)^2)^(-2),{y,r,Infinity}] \end{lstlisting} \end{document} ``` You would obtain something like ![Code example image](https://i.stack.imgur.com/vuE4j.png) and by changing the `\lstset` even adapt the colors to look more `Mathematica`ish. You could then also use external code files and something like `\lstinputlisting{yourfile.m}` to include them. This is what i prefer, because then you could just (ok in Mathematica working on one cell) code the stuff you want and change the code. Due to the input it is then automatically the most recent version of your code example. *Edit 1* The OP requested to use Math symbols and fractions in his code: One way to do that is, to add `mathescape` to the lstset as a further key. Then at any `$` in the code the mode is switched to mathmode and one can type simply math. Then one could change the code line to ``` Integrate[{y^(-3)}*(1-$\bigl(\frac{a}{y}\bigr)$^2)^(-2),{y,r,Infinity}] ``` to obtain ![Second Code with math](https://i.stack.imgur.com/8d6Lh.png) though i think it is not that nice to read (because there's still `^2` in the code and other non-LaTeX-set formulae. Finally my remark above won't work anymore, this code would - of course - not be able to run in Mathematica anymore.
Another way to include mathematica packages into latex is to use this package [mma.sty](http://kauers.de/software/mma/mma.sty) by [Manuel Kauers](http://kauers.de/index.html). With ``` \usepackage{mma} ``` in the preamble one can do a lot. I find it really amazing. I normally enclose it in [mdframed](https://www.ctan.org/pkg/mdframed?lang=en) environment which I think is pretty cool. See the image below: [![MathematicaCodeInLaTeX](https://i.stack.imgur.com/8qjBH.png)](https://i.stack.imgur.com/8qjBH.png) There are also example on how one can use the package in the style file **mma.sty**. **Addendum** As requested by @KevinO'Bryant, I have added a MWE which produces the two images above. ``` \documentclass[10pt,a4paper]{article} \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry} \usepackage[framemethod=tikz]{mdframed} \usepackage{mma} \newcommand{\bc}{\textcolor{blue}} % For mathematica session \mdfdefinestyle{mmabox}{% innerlinewidth=0.5pt, innerleftmargin=10pt,% innerrightmargin=10pt, innertopmargin=10pt,% innerbottommargin=10pt, roundcorner=5pt, singleextra={\path (P) -- node[minimum height=.6cm,overlay,draw,fill=white, rounded corners,very thick] {\bf Mathematica Session} (O|-P);} } \surroundwithmdframed[style=mmabox]{mma} \begin{document} \begin{mma} \In |Command|[|arg|_1,1+1] \\ \Out \mathrm{x^2+9} \\ \In |quit| \\ \Warning{name} something in text mode \\ \In |Print|["test"];\\ \Print test\\ \In |Quit| \\ \Out {\rm \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \} \} \} } \\ \end{mma} \begin{mma} \In {\mathrm{\bf f = \{ \sqrt{2}(\bc{n}+1)^{2}(\bc{n}+\bc{k}),\ 6 (\bc{n}+1) (-\bc{k} - \bc{n} - 2) \bc{k},\ \sqrt{-3}(\bc{k} + \bc{n} + 5)\};}} \\ \In {\mathrm{\bf tower = \Big\{ \{\bc{k}, 1, 1 \},\ \Big\{\bc{h}, 1, \frac{1}{\bc{k} + 1} \Big\},\ \Big\{\bc{b}, \frac{\bc{n}-\bc{k}}{\bc{k}+1}, 0 \Big\} \Big\} ;}}\\ \In {\mathrm{\bf ShiftPrimeEquivalentFactors[f,\ tower]}}\\ \Out { \mathrm{ \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \} \} \} } }\\ \end{mama} \end{document} ```
84,748
I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is ``` \documentclass[a4paper,11pt]{article} \usepackage{kerkis} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsfonts} \usepackage{amsthm} \usepackage[pdftex]{graphicx} \usepackage{xcolor} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \setlength{\unitlength}{1cm} \begin{picture}(15,5) \color{blue} \put(-1,0){\line(0,1){5}} \put(0,1.5){\includegraphics[scale=0.8]{math}} \put(-1,0){\line(1,0){15}} \put(14,0){\line(0,1){5}} \put(-1,5){\line(1,0){15}} \end{picture} \end{document} ``` My output is ![](https://i.imgur.com/88L93.png) Any ideas on how to include Mathematica code in a more aesthetically way? **Edit**:At first I used package `listing` but the problem was the fraction and the fact that I don't know how to include in a convenient way `In[1]` and `Out[1]`
2012/11/29
[ "https://tex.stackexchange.com/questions/84748", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12795/" ]
I know this question is old and surely OP doesn't need it anymore, but recently I had similar problem and I think my solution answers the question. First thing to note is that in Mathematica FrontEnd cells can have arbitrary styles. Each styles appearance is customizable by a stylesheet. With default stylesheet even most basic cell styles i.e. `Input` and `Output` look different. In cells with some styles (e.g `Input` or `Code`) code syntax is colored, this can be achieved using already mentioned in other answers `listings` package. Cells with some styles (e.g. `Input`, `Output` or `Print`) by default use, so called `StandardForm`, which allows embedding of complicated formatting (fractions, superscripts etc.) inside code. This was partially solved in other answers by using `mathescape` functionality of `listings` package. Problem with this solution is that `mathescape` "completely escapes" to TeX. Since one can't nest `listings` environments/commands, I don't see a way to treat parts of escaped content again as code (e.g. typeset it verbatim) using `listings` only. To achieve such functionality one can use `Verbatim` environment from `fancyvrb` package. By setting proper `commandchars` we can embed, for example, `\frac` command inside code, in such way that frac's arguments are typeset verbatim. Downside of `fancyvrb` is that it doesn't offer automatic syntax coloring. Fortunately `listings` has special interface to `fancyvrb` that allows combining of reading code by `fancyvrb` and typesetting it by `listings`. Below I present usage of my [mmacells](https://github.com/jkuczm/mmacells) package, which implements solution based on `fancyvrb` + `listings` approach, with some additional features like customizable cell styles, automatic cell labels etc. There's also corresponding *Mathematica* package: [CellsToTeX](https://github.com/jkuczm/MathematicaCellsToTeX), that automatically exports *Mathematica* code to TeX code compatible with `mmacells`. *Mathematica* package is described in detail in [answer to "How best to embed various cell groups into a latex project?" question](https://mathematica.stackexchange.com/a/73589/14303) on Mathematica Stack Exchange. Usage example ============= Print screen of result: [![Mathematica cells in pdf](https://i.stack.imgur.com/Rs9tG.png)](https://i.stack.imgur.com/Rs9tG.png) TeX code: ``` \documentclass{article} \usepackage[margin=2cm]{geometry} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{mmacells} \mmaDefineMathReplacement[≤]{<=}{\leq} \mmaDefineMathReplacement[≥]{>=}{\geq} \mmaDefineMathReplacement[≠]{!=}{\neq} \mmaDefineMathReplacement[→]{->}{\to}[2] \mmaDefineMathReplacement[⧴]{:>}{:\hspace{-.2em}\to}[2] \mmaDefineMathReplacement{∉}{\notin} \mmaDefineMathReplacement{∞}{\infty} \mmaDefineMathReplacement{}{\mathbbm{d}} \mmaSet{ morefv={gobble=2}, linklocaluri=mma/symbol/definition:#1, morecellgraphics={yoffset=1.9ex} } \begin{document} Input from question with output from my Mathematica version. Input is in input form, it can be copied and pasted to Mathematica. \begin{mmaCell}[functionlocal=y]{Code} Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}] \end{mmaCell} \begin{mmaCell}{Output} \{ConditionalExpression[-\mmaFrac{1}{2 (\mmaSup{a}{2} - \mmaSup{r}{2})}, Im[r] Re[a] ≠ Im[a] Re[r] || ((a + r > 0 || a + r ∉ Reals) && ((Re[a] < r && Im[a] == 0) || a - r ∉ Reals)) || r ∉ Reals]\} \end{mmaCell} For comparison, same cells obtained by including PDFs exported from Mathematica: % You need inCell.pdf and outCell.pdf files for this to work. % \mmaCellGraphics{Input}{inCell} % \mmaCellGraphics[yoffset=3.5ex]{Output}{outCell} Same input expression, but in standard form (as if it was inputted using math assistant). Note that syntax coloring still works. \begin{mmaCell}[index=3,functionlocal=y]{Input} \mmaSubSupM{\int}{r}{∞}\{\mmaFrac{1}{\mmaSup{y}{3}\mmaSup{\big(1-\mmaSup{\big(\mmaFrac{a}{y}\big)}{2}\big)}{2}}\}y \end{mmaCell} More features: \begin{mmaCell}[ moredefined=f, functionlocal=a, local=b, pattern={x_,x}, excessargument=n, linkbuiltin=List ]{Code} (* A (* nested *) comment. *) Block[{a=3},a+2] f[x_]:=2x+1 Module[{b=c}, Print["a string \" with double quotes inside ", b/d]; b+1 ] f[z]//FullForm Sin[m,n] List[1,List[2,3]]; (* Links to documentation. *) \end{mmaCell} \begin{mmaCell}{Output} 5 \end{mmaCell} \begin{mmaCell}{Print} a string " with double quotes inside \mmaFrac{c}{d} \end{mmaCell} \begin{mmaCell}[addtoindex=1]{Output} 1+c \end{mmaCell} \begin{mmaCell}[form=FullForm]{Output} Plus[1,Times[2,z]] \end{mmaCell} \begin{mmaCell}[messagelink={message/General/argx}]{Message} Sin::argx: Sin called with 2 arguments; 1 argument is expected. >> \end{mmaCell} \begin{mmaCell}{Output} Sin[m,n] \end{mmaCell} \begin{mmaCell}{Output} \{1,\{2,3\}\} \end{mmaCell} Graphics mixed with code: \begin{mmaCell}{Code} a Graphics[{Green,Disk[]},ImageSize->50]/2 \end{mmaCell} % You need greenDisk.pdf file for this to work. % \begin{mmaCell}[moregraphics={moreig={scale=.7}}]{Output} % \mmaFrac{a \mmaGraphics{greenDisk}}{2} % \end{mmaCell} \begin{mmaCell}{Code} (* Different roles of one symbol. *) x; _x; \mmaDef{x_}; \mmaPat{x_}->2x; \mmaPat{x_}:>2\mmaPat{x}; f[\mmaPat{x_}]=2x; f[\mmaPat{x_}]:=2\mmaPat{x}; Block[{\mmaFnc{x}},2\mmaFnc{x}]; Module[{\mmaLoc{x}},2\mmaLoc{x}]; \mmaUnd{Module}; (* undefined Module symbol *) \mmaLnB{Module}; (* Module symbol with link to documentation *) Sin[x\mmaExc{,x}]; \end{mmaCell} \begin{mmaCell}[addtoindex=11]{Input} (* Nesting of "formatting boxes" *) \mmaSup{a}{\mmaSup{a}{a}} \mmaSub{a}{\mmaSub{a}{a}} \mmaSubSup{a}{\mmaSubSup{a}{a}{a}}{\mmaSubSup{a}{a}{a}} \mmaUnder{a}{\mmaUnder{a}{a}} \mmaOver{a}{\mmaOver{a}{a}} \mmaUnderOver{a}{\mmaUnderOver{a}{a}{a}}{\mmaUnderOver{a}{a}{a}} \mmaFrac{a}{\mmaFrac{a}{\mmaFrac{a}{a}}} \mmaSqrt{\mmaSqrt{a}} \mmaRadical{a}{\mmaRadical{a}{a}} \end{mmaCell} \begin{mmaCell}{Input} (* Replacements for infix operators in "Input" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}{Code} (* No replacement in "Code" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}[label={(\mmaCellIndex)custom}]{Code} (* Cell with custom label. *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnT{x}=2;(* labeled definition of x *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnL{x}(* usage of x with link to its definition *) \end{mmaCell} Implemented syntax elements: \begin{mmaCell}[ defined=defined, undefined=undefined, functionlocal=functionlocal, local=local, pattern=pattern, localconflict=localconflict, globalconflict=globalconflict, excessargument=excessargument, unknownoption=unknownoption, unwantedassignment=unwantedassignment, shadowing=shadowing, syntaxerror=syntaxerror, emphasizedsyntaxerror=emphasizedsyntaxerror, formattingerror=formattingerror, ]{Code} \mmaDef{Def} defined (* defined symbol *) \mmaUnd{Und} undefined (* UndefinedSymbol *) \mmaFnc{Fnc} functionlocal (* FunctionLocalVariable *) \mmaLoc{Loc} local (* LocalVariable *) \mmaPat{Pat} pattern (* PatternVariable *) \mmaLCn{LCn} localconflict (* LocalScopeConflict *) \mmaGCn{GCn} globalconflict (* GlobalToLocalScopeConflict *) \mmaExc{Exc} excessargument (* ExcessArgument *) \mmaOpt{Opt} unknownoption (* UnknownOption *) \mmaAsg{Asg} unwantedassignment (* UnwantedAssignment *) \mmaShd{Shd} shadowing (* SymbolShadowing *) \mmaSnt{Snt} syntaxerror (* SyntaxError *) \mmaEmp{Emp} emphasizedsyntaxerror (* EmphasizedSyntaxError *) \mmaFmt{Fmt} formattingerror (* FormattingError *) \end{mmaCell} Inline cell: \mmaInlineCell[functionlocal=a]{Code}{Module[{a=5}, a]}. Formatted inline cell: \mmaInlineCell[pattern={x_,x}]{Input}{f[x_]:=\mmaFrac{\mmaSup{x}{2}}{5}} \subsubsection*{ Inline cell inside macro argument: \mmaInlineCellNonVerb[functionlocal=x]{Code}{Solve[\mmaSqrt{x}==y,x]} } \end{document} ``` Unicode ======= There are three strategies of handling Unicode supported by `mmacells`. Code for all of them can be automatically generated by `CellsToTeX` *Mathematica* package. ### 1. No Unicode Don't use Unicode at all, use appropriate TeX commands instead. This approach works in all engines. `listings` package doesn't color elements provided by escaped commands, so they need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{mmacells} \begin{document} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{\(\pmb{\beta}\)} \(\pmb{\pm}\) \mmaSqrt{\mmaSup{\mmaUnd{\(\pmb{\beta}\)}}{2} - 4 \mmaUnd{\(\pmb{\alpha}\)} \mmaUnd{\(\pmb{\gamma}\)}}}{2 \mmaUnd{\(\pmb{\alpha}\)}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 2. Unicode input Use Unicode characters in input and automatically convert them to appropriate TeX commands by using `\mmaDefineMathReplacement`. This approach works in *pdfTeX* engine. Replacements are implemented using `listings` `literate` option, so are "excluded" from automatic coloring, and identifiers containing Unicode characters need to be wrapped with appropriate annotations. Whether replacements will be used is controlled by `mathreplacements` option. By default `Code` cells don't use replacements (`mathreplacements=none`), `Input` cells use bold replacements (`mathreplacements=bols`) i.e. will use given command wrapped with math delimiters and `\pmb`, `Output`, `Print` and `Message` cells use "light" replacements (`mathreplacements=light`) i.e. will will use given command wrapped with math delimiters. ``` \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{mmacells} \begin{document} \mmaDefineMathReplacement{±}{\pm} \mmaDefineMathReplacement{α}{\alpha} \mmaDefineMathReplacement{β}{\beta} \mmaDefineMathReplacement{γ}{\gamma} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 3. Unicode input and output Use Unicode characters in input and rely on appropriate glyphs of used fonts. This approach works in Unicode-aware engines. Since `listings` does not support Unicode, it needs to be switched off using `uselistings=false` option. With `listings` switched off no automatic coloring occurs, so all identifiers, also those not containing Unicode characters, need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{fontspec} \usepackage{mmacells} \setmainfont{FreeSerif} \setmonofont{FreeMono} \mmaSet{uselistings=false} \begin{document} \begin{mmaCell}{Input} \mmaSub{\mmaUnd{x}}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of xelatex with Unicode](https://i.stack.imgur.com/xW7Ht.png)](https://i.stack.imgur.com/xW7Ht.png)
Using the `listings` package, it is possible to get math mode in the mathematica code. You need to add the `mathescape` option on the `listings` environment definition, and manually place the math delimiters in the listing. I realise that this may be impractical if you want to insert a lot of code. I hope the following code makes my meaning clear. ``` \documentclass{article} \usepackage{listings} \usepackage{framed} \usepackage{xcolor} \usepackage{amsmath} \colorlet{shadecolor}{gray!20} \lstnewenvironment{mat} {\lstset{language=mathematica,mathescape,columns=flexible}} {} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \begin{shaded} \begin{mat} In[1]:= Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}] Out[1]= {ConditionalExpression[$\displaystyle-\frac{1}{2(a^2-r^2)}$, Im[r] Re[a] $\neq$ Im[a] Re[r] || (( $a+r>0$ || $a+r \notin $ Reals) && ($a<r$ || $a-r \notin$ Reals) || $r\notin$ Reals )]} \end{mat} \end{shaded} \end{document} ``` Note that I formatted the output manually. Here is the result: ![result](https://i.imgur.com/TkuZT.png)
84,748
I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is ``` \documentclass[a4paper,11pt]{article} \usepackage{kerkis} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsfonts} \usepackage{amsthm} \usepackage[pdftex]{graphicx} \usepackage{xcolor} \begin{document} \begin{align} \nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=- \int_r^\infty \! \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2} \dfrac{\alpha^3}{y^3}\left(1- \dfrac{\alpha^2} {y^2}\right)^{-2}\,\mathrm{d}y\\ =&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3 \underbrace{\int_r^\infty \! y^{-3} \left(1-\dfrac{\alpha^2} {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI} \end{align} \setlength{\unitlength}{1cm} \begin{picture}(15,5) \color{blue} \put(-1,0){\line(0,1){5}} \put(0,1.5){\includegraphics[scale=0.8]{math}} \put(-1,0){\line(1,0){15}} \put(14,0){\line(0,1){5}} \put(-1,5){\line(1,0){15}} \end{picture} \end{document} ``` My output is ![](https://i.imgur.com/88L93.png) Any ideas on how to include Mathematica code in a more aesthetically way? **Edit**:At first I used package `listing` but the problem was the fraction and the fact that I don't know how to include in a convenient way `In[1]` and `Out[1]`
2012/11/29
[ "https://tex.stackexchange.com/questions/84748", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12795/" ]
I know this question is old and surely OP doesn't need it anymore, but recently I had similar problem and I think my solution answers the question. First thing to note is that in Mathematica FrontEnd cells can have arbitrary styles. Each styles appearance is customizable by a stylesheet. With default stylesheet even most basic cell styles i.e. `Input` and `Output` look different. In cells with some styles (e.g `Input` or `Code`) code syntax is colored, this can be achieved using already mentioned in other answers `listings` package. Cells with some styles (e.g. `Input`, `Output` or `Print`) by default use, so called `StandardForm`, which allows embedding of complicated formatting (fractions, superscripts etc.) inside code. This was partially solved in other answers by using `mathescape` functionality of `listings` package. Problem with this solution is that `mathescape` "completely escapes" to TeX. Since one can't nest `listings` environments/commands, I don't see a way to treat parts of escaped content again as code (e.g. typeset it verbatim) using `listings` only. To achieve such functionality one can use `Verbatim` environment from `fancyvrb` package. By setting proper `commandchars` we can embed, for example, `\frac` command inside code, in such way that frac's arguments are typeset verbatim. Downside of `fancyvrb` is that it doesn't offer automatic syntax coloring. Fortunately `listings` has special interface to `fancyvrb` that allows combining of reading code by `fancyvrb` and typesetting it by `listings`. Below I present usage of my [mmacells](https://github.com/jkuczm/mmacells) package, which implements solution based on `fancyvrb` + `listings` approach, with some additional features like customizable cell styles, automatic cell labels etc. There's also corresponding *Mathematica* package: [CellsToTeX](https://github.com/jkuczm/MathematicaCellsToTeX), that automatically exports *Mathematica* code to TeX code compatible with `mmacells`. *Mathematica* package is described in detail in [answer to "How best to embed various cell groups into a latex project?" question](https://mathematica.stackexchange.com/a/73589/14303) on Mathematica Stack Exchange. Usage example ============= Print screen of result: [![Mathematica cells in pdf](https://i.stack.imgur.com/Rs9tG.png)](https://i.stack.imgur.com/Rs9tG.png) TeX code: ``` \documentclass{article} \usepackage[margin=2cm]{geometry} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{mmacells} \mmaDefineMathReplacement[≤]{<=}{\leq} \mmaDefineMathReplacement[≥]{>=}{\geq} \mmaDefineMathReplacement[≠]{!=}{\neq} \mmaDefineMathReplacement[→]{->}{\to}[2] \mmaDefineMathReplacement[⧴]{:>}{:\hspace{-.2em}\to}[2] \mmaDefineMathReplacement{∉}{\notin} \mmaDefineMathReplacement{∞}{\infty} \mmaDefineMathReplacement{}{\mathbbm{d}} \mmaSet{ morefv={gobble=2}, linklocaluri=mma/symbol/definition:#1, morecellgraphics={yoffset=1.9ex} } \begin{document} Input from question with output from my Mathematica version. Input is in input form, it can be copied and pasted to Mathematica. \begin{mmaCell}[functionlocal=y]{Code} Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}] \end{mmaCell} \begin{mmaCell}{Output} \{ConditionalExpression[-\mmaFrac{1}{2 (\mmaSup{a}{2} - \mmaSup{r}{2})}, Im[r] Re[a] ≠ Im[a] Re[r] || ((a + r > 0 || a + r ∉ Reals) && ((Re[a] < r && Im[a] == 0) || a - r ∉ Reals)) || r ∉ Reals]\} \end{mmaCell} For comparison, same cells obtained by including PDFs exported from Mathematica: % You need inCell.pdf and outCell.pdf files for this to work. % \mmaCellGraphics{Input}{inCell} % \mmaCellGraphics[yoffset=3.5ex]{Output}{outCell} Same input expression, but in standard form (as if it was inputted using math assistant). Note that syntax coloring still works. \begin{mmaCell}[index=3,functionlocal=y]{Input} \mmaSubSupM{\int}{r}{∞}\{\mmaFrac{1}{\mmaSup{y}{3}\mmaSup{\big(1-\mmaSup{\big(\mmaFrac{a}{y}\big)}{2}\big)}{2}}\}y \end{mmaCell} More features: \begin{mmaCell}[ moredefined=f, functionlocal=a, local=b, pattern={x_,x}, excessargument=n, linkbuiltin=List ]{Code} (* A (* nested *) comment. *) Block[{a=3},a+2] f[x_]:=2x+1 Module[{b=c}, Print["a string \" with double quotes inside ", b/d]; b+1 ] f[z]//FullForm Sin[m,n] List[1,List[2,3]]; (* Links to documentation. *) \end{mmaCell} \begin{mmaCell}{Output} 5 \end{mmaCell} \begin{mmaCell}{Print} a string " with double quotes inside \mmaFrac{c}{d} \end{mmaCell} \begin{mmaCell}[addtoindex=1]{Output} 1+c \end{mmaCell} \begin{mmaCell}[form=FullForm]{Output} Plus[1,Times[2,z]] \end{mmaCell} \begin{mmaCell}[messagelink={message/General/argx}]{Message} Sin::argx: Sin called with 2 arguments; 1 argument is expected. >> \end{mmaCell} \begin{mmaCell}{Output} Sin[m,n] \end{mmaCell} \begin{mmaCell}{Output} \{1,\{2,3\}\} \end{mmaCell} Graphics mixed with code: \begin{mmaCell}{Code} a Graphics[{Green,Disk[]},ImageSize->50]/2 \end{mmaCell} % You need greenDisk.pdf file for this to work. % \begin{mmaCell}[moregraphics={moreig={scale=.7}}]{Output} % \mmaFrac{a \mmaGraphics{greenDisk}}{2} % \end{mmaCell} \begin{mmaCell}{Code} (* Different roles of one symbol. *) x; _x; \mmaDef{x_}; \mmaPat{x_}->2x; \mmaPat{x_}:>2\mmaPat{x}; f[\mmaPat{x_}]=2x; f[\mmaPat{x_}]:=2\mmaPat{x}; Block[{\mmaFnc{x}},2\mmaFnc{x}]; Module[{\mmaLoc{x}},2\mmaLoc{x}]; \mmaUnd{Module}; (* undefined Module symbol *) \mmaLnB{Module}; (* Module symbol with link to documentation *) Sin[x\mmaExc{,x}]; \end{mmaCell} \begin{mmaCell}[addtoindex=11]{Input} (* Nesting of "formatting boxes" *) \mmaSup{a}{\mmaSup{a}{a}} \mmaSub{a}{\mmaSub{a}{a}} \mmaSubSup{a}{\mmaSubSup{a}{a}{a}}{\mmaSubSup{a}{a}{a}} \mmaUnder{a}{\mmaUnder{a}{a}} \mmaOver{a}{\mmaOver{a}{a}} \mmaUnderOver{a}{\mmaUnderOver{a}{a}{a}}{\mmaUnderOver{a}{a}{a}} \mmaFrac{a}{\mmaFrac{a}{\mmaFrac{a}{a}}} \mmaSqrt{\mmaSqrt{a}} \mmaRadical{a}{\mmaRadical{a}{a}} \end{mmaCell} \begin{mmaCell}{Input} (* Replacements for infix operators in "Input" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}{Code} (* No replacement in "Code" cells. *) x>=y; x<=y; x!=y; x->y; x:>y; \end{mmaCell} \begin{mmaCell}[label={(\mmaCellIndex)custom}]{Code} (* Cell with custom label. *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnT{x}=2;(* labeled definition of x *) \end{mmaCell} \begin{mmaCell}{Input} \mmaLnL{x}(* usage of x with link to its definition *) \end{mmaCell} Implemented syntax elements: \begin{mmaCell}[ defined=defined, undefined=undefined, functionlocal=functionlocal, local=local, pattern=pattern, localconflict=localconflict, globalconflict=globalconflict, excessargument=excessargument, unknownoption=unknownoption, unwantedassignment=unwantedassignment, shadowing=shadowing, syntaxerror=syntaxerror, emphasizedsyntaxerror=emphasizedsyntaxerror, formattingerror=formattingerror, ]{Code} \mmaDef{Def} defined (* defined symbol *) \mmaUnd{Und} undefined (* UndefinedSymbol *) \mmaFnc{Fnc} functionlocal (* FunctionLocalVariable *) \mmaLoc{Loc} local (* LocalVariable *) \mmaPat{Pat} pattern (* PatternVariable *) \mmaLCn{LCn} localconflict (* LocalScopeConflict *) \mmaGCn{GCn} globalconflict (* GlobalToLocalScopeConflict *) \mmaExc{Exc} excessargument (* ExcessArgument *) \mmaOpt{Opt} unknownoption (* UnknownOption *) \mmaAsg{Asg} unwantedassignment (* UnwantedAssignment *) \mmaShd{Shd} shadowing (* SymbolShadowing *) \mmaSnt{Snt} syntaxerror (* SyntaxError *) \mmaEmp{Emp} emphasizedsyntaxerror (* EmphasizedSyntaxError *) \mmaFmt{Fmt} formattingerror (* FormattingError *) \end{mmaCell} Inline cell: \mmaInlineCell[functionlocal=a]{Code}{Module[{a=5}, a]}. Formatted inline cell: \mmaInlineCell[pattern={x_,x}]{Input}{f[x_]:=\mmaFrac{\mmaSup{x}{2}}{5}} \subsubsection*{ Inline cell inside macro argument: \mmaInlineCellNonVerb[functionlocal=x]{Code}{Solve[\mmaSqrt{x}==y,x]} } \end{document} ``` Unicode ======= There are three strategies of handling Unicode supported by `mmacells`. Code for all of them can be automatically generated by `CellsToTeX` *Mathematica* package. ### 1. No Unicode Don't use Unicode at all, use appropriate TeX commands instead. This approach works in all engines. `listings` package doesn't color elements provided by escaped commands, so they need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{mmacells} \begin{document} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{\(\pmb{\beta}\)} \(\pmb{\pm}\) \mmaSqrt{\mmaSup{\mmaUnd{\(\pmb{\beta}\)}}{2} - 4 \mmaUnd{\(\pmb{\alpha}\)} \mmaUnd{\(\pmb{\gamma}\)}}}{2 \mmaUnd{\(\pmb{\alpha}\)}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 2. Unicode input Use Unicode characters in input and automatically convert them to appropriate TeX commands by using `\mmaDefineMathReplacement`. This approach works in *pdfTeX* engine. Replacements are implemented using `listings` `literate` option, so are "excluded" from automatic coloring, and identifiers containing Unicode characters need to be wrapped with appropriate annotations. Whether replacements will be used is controlled by `mathreplacements` option. By default `Code` cells don't use replacements (`mathreplacements=none`), `Input` cells use bold replacements (`mathreplacements=bols`) i.e. will use given command wrapped with math delimiters and `\pmb`, `Output`, `Print` and `Message` cells use "light" replacements (`mathreplacements=light`) i.e. will will use given command wrapped with math delimiters. ``` \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{mmacells} \begin{document} \mmaDefineMathReplacement{±}{\pm} \mmaDefineMathReplacement{α}{\alpha} \mmaDefineMathReplacement{β}{\beta} \mmaDefineMathReplacement{γ}{\gamma} \begin{mmaCell}{Input} \mmaSub{x}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of pdfLaTeX with Unicode](https://i.stack.imgur.com/iGXsD.png)](https://i.stack.imgur.com/iGXsD.png) ### 3. Unicode input and output Use Unicode characters in input and rely on appropriate glyphs of used fonts. This approach works in Unicode-aware engines. Since `listings` does not support Unicode, it needs to be switched off using `uselistings=false` option. With `listings` switched off no automatic coloring occurs, so all identifiers, also those not containing Unicode characters, need to be wrapped with appropriate annotations. ``` \documentclass{article} \usepackage{fontspec} \usepackage{mmacells} \setmainfont{FreeSerif} \setmonofont{FreeMono} \mmaSet{uselistings=false} \begin{document} \begin{mmaCell}{Input} \mmaSub{\mmaUnd{x}}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}} \end{mmaCell} \end{document} ``` [![result of xelatex with Unicode](https://i.stack.imgur.com/xW7Ht.png)](https://i.stack.imgur.com/xW7Ht.png)
Another way to include mathematica packages into latex is to use this package [mma.sty](http://kauers.de/software/mma/mma.sty) by [Manuel Kauers](http://kauers.de/index.html). With ``` \usepackage{mma} ``` in the preamble one can do a lot. I find it really amazing. I normally enclose it in [mdframed](https://www.ctan.org/pkg/mdframed?lang=en) environment which I think is pretty cool. See the image below: [![MathematicaCodeInLaTeX](https://i.stack.imgur.com/8qjBH.png)](https://i.stack.imgur.com/8qjBH.png) There are also example on how one can use the package in the style file **mma.sty**. **Addendum** As requested by @KevinO'Bryant, I have added a MWE which produces the two images above. ``` \documentclass[10pt,a4paper]{article} \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry} \usepackage[framemethod=tikz]{mdframed} \usepackage{mma} \newcommand{\bc}{\textcolor{blue}} % For mathematica session \mdfdefinestyle{mmabox}{% innerlinewidth=0.5pt, innerleftmargin=10pt,% innerrightmargin=10pt, innertopmargin=10pt,% innerbottommargin=10pt, roundcorner=5pt, singleextra={\path (P) -- node[minimum height=.6cm,overlay,draw,fill=white, rounded corners,very thick] {\bf Mathematica Session} (O|-P);} } \surroundwithmdframed[style=mmabox]{mma} \begin{document} \begin{mma} \In |Command|[|arg|_1,1+1] \\ \Out \mathrm{x^2+9} \\ \In |quit| \\ \Warning{name} something in text mode \\ \In |Print|["test"];\\ \Print test\\ \In |Quit| \\ \Out {\rm \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \} \} \} } \\ \end{mma} \begin{mma} \In {\mathrm{\bf f = \{ \sqrt{2}(\bc{n}+1)^{2}(\bc{n}+\bc{k}),\ 6 (\bc{n}+1) (-\bc{k} - \bc{n} - 2) \bc{k},\ \sqrt{-3}(\bc{k} + \bc{n} + 5)\};}} \\ \In {\mathrm{\bf tower = \Big\{ \{\bc{k}, 1, 1 \},\ \Big\{\bc{h}, 1, \frac{1}{\bc{k} + 1} \Big\},\ \Big\{\bc{b}, \frac{\bc{n}-\bc{k}}{\bc{k}+1}, 0 \Big\} \Big\} ;}}\\ \In {\mathrm{\bf ShiftPrimeEquivalentFactors[f,\ tower]}}\\ \Out { \mathrm{ \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \} \} \} } }\\ \end{mama} \end{document} ```
25,424,464
In Adobe Fireworks you were always able to numerically specify the X and Y coordinates, width, and height of the area you want to crop - where is this option in Photoshop? Apologies if I'm being thick - I'm still pretty new to Photoshop! I need to be able to do this through the Photoshop editor as opposed to through script.
2014/08/21
[ "https://Stackoverflow.com/questions/25424464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3963773/" ]
You can find it in Info pallet in window/Info also there is other information like color of the pixel youre pointing.
You can use the rectangle mark tool to mark the area you want to crop, then go to Image -> Crop
8,818,551
Recently I've started on a project which requires a Cortex M3 processor. I have some previous experience with 8bit AVR microcontrollers, so I was hoping for a not to big transition. So I've bought a STM32L-Discovery kit (since low power is an important point) and started looking at some examples. However, I'm completely stuck at the beginning. When programming with AVR it was all very straightforward, just by including 2 or 3 files it was possible to write a simple main.c for like say a blinking LED. However the examples in IAR EWARM (which I'm using) all look very bloated, lots of files which make it difficult to start. I'm having the same problem with most online tutorials. Does anybody know any (very) simple tutorials which might help me. I'm thinking about purchasing "The Definitive Guide to the ARM Cortex-M3" since it seems highly recommended. This might be a very dumb question but I'm stuck for too long now and I'm feeling a bit desperate.
2012/01/11
[ "https://Stackoverflow.com/questions/8818551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143055/" ]
I completely agree with you. I am also starting out and I find it difficult to even scratch the surface! I have some good experience with PICs, but with ARMs the learning curve is really steep. For the STM32F4Discovery I am using, ST provides a number of examples. Starting from simple pin toggling. I am going through the main.c file which for every example is well commented, and try to understand from there. They have a peripherals library, so locate that and look into the declarations of the functions. I learned a few things like that. Also make sure you reference the actual manual of the ARM you are using. I think it boils down to how much time you have to spend. Speaking for myself, I don't have the time to go through the manual and understand how everything works. If you do find some good sources please post them! In closing I am pasting a couple of urls I am found useful information: <http://www.hitex.com/index.php?id=download-insiders-guides> <http://www.micromouseonline.com/category/stm32/#axzz1wMO2VjAI>
I would suggest using CMSIS and standard peripheral library for programming ARM Cortex. Here are some tutorials on how to set up things and start writing code: <http://www.embedds.com/arm-cortex-tutorials/>
1,732,221
Evaluate $\Re[\cos(1+i)]$. The trigonometric function in the expression is throwing me in a loop and need some guidance on how to evaluate this. Thanks.
2016/04/07
[ "https://math.stackexchange.com/questions/1732221", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329507/" ]
**Hint:** You should know the formulas $$\cos i\theta = \cosh \theta$$ $$\sin i\theta = i\sinh \theta$$
> > Notice, when $a\space\wedge\space b\in\mathbb{R}$: > > > * $$\cos\left(ae^{bi}\right)=\cos(a\cos(b))\cosh(a\sin(b))-\sin(a\cos(b))\sinh(a\sin(b))i$$ > > > So: * $$1+i=|1+i|e^{\arg(1+i)i}=\sqrt{2}e^{\frac{\pi i}{4}}$$ * $$\cos(1+i)=\cos\left(\sqrt{2}e^{\frac{\pi i}{4}}\right)=\cos(1)\cosh(1)-\sin(1)\sinh(1)i$$ We get that: $$\Re\left[\cos(1+i)\right]=\Re\left[\cos\left(\sqrt{2}e^{\frac{\pi i}{4}}\right)\right]=$$ $$\Re\left[\cos(1)\cosh(1)-\sin(1)\sinh(1)i\right]=\cos(1)\cosh(1)$$
1,732,221
Evaluate $\Re[\cos(1+i)]$. The trigonometric function in the expression is throwing me in a loop and need some guidance on how to evaluate this. Thanks.
2016/04/07
[ "https://math.stackexchange.com/questions/1732221", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329507/" ]
$$\cos(1+i)=\cos1\cos i-\sin1\sin i\\ \cos i={e^{ii}+e^{-ii}\over2}={e^{-1}+e\over2}\\ \sin i={e^{ii}-e^{-ii} \over2i }={e-e^{-1}\over2}i$$ so $$\Re(\cos(1+i))=\cos1\left({e^{-1}+e\over2}\right)$$
> > Notice, when $a\space\wedge\space b\in\mathbb{R}$: > > > * $$\cos\left(ae^{bi}\right)=\cos(a\cos(b))\cosh(a\sin(b))-\sin(a\cos(b))\sinh(a\sin(b))i$$ > > > So: * $$1+i=|1+i|e^{\arg(1+i)i}=\sqrt{2}e^{\frac{\pi i}{4}}$$ * $$\cos(1+i)=\cos\left(\sqrt{2}e^{\frac{\pi i}{4}}\right)=\cos(1)\cosh(1)-\sin(1)\sinh(1)i$$ We get that: $$\Re\left[\cos(1+i)\right]=\Re\left[\cos\left(\sqrt{2}e^{\frac{\pi i}{4}}\right)\right]=$$ $$\Re\left[\cos(1)\cosh(1)-\sin(1)\sinh(1)i\right]=\cos(1)\cosh(1)$$
1,732,221
Evaluate $\Re[\cos(1+i)]$. The trigonometric function in the expression is throwing me in a loop and need some guidance on how to evaluate this. Thanks.
2016/04/07
[ "https://math.stackexchange.com/questions/1732221", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329507/" ]
**Hint:** You should know the formulas $$\cos i\theta = \cosh \theta$$ $$\sin i\theta = i\sinh \theta$$
$$2\cos(a+ib)=e^{i(a+ib)}+e^{-i(a+ib)}=e^{-b}e^{ia}+e^be^{-ia}$$ Use Euler Identity: $e^{ix}=\cos x+i\sin x$
1,732,221
Evaluate $\Re[\cos(1+i)]$. The trigonometric function in the expression is throwing me in a loop and need some guidance on how to evaluate this. Thanks.
2016/04/07
[ "https://math.stackexchange.com/questions/1732221", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329507/" ]
$$\cos(1+i)=\cos1\cos i-\sin1\sin i\\ \cos i={e^{ii}+e^{-ii}\over2}={e^{-1}+e\over2}\\ \sin i={e^{ii}-e^{-ii} \over2i }={e-e^{-1}\over2}i$$ so $$\Re(\cos(1+i))=\cos1\left({e^{-1}+e\over2}\right)$$
**Hint:** You should know the formulas $$\cos i\theta = \cosh \theta$$ $$\sin i\theta = i\sinh \theta$$
1,732,221
Evaluate $\Re[\cos(1+i)]$. The trigonometric function in the expression is throwing me in a loop and need some guidance on how to evaluate this. Thanks.
2016/04/07
[ "https://math.stackexchange.com/questions/1732221", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329507/" ]
$$\cos(1+i)=\cos1\cos i-\sin1\sin i\\ \cos i={e^{ii}+e^{-ii}\over2}={e^{-1}+e\over2}\\ \sin i={e^{ii}-e^{-ii} \over2i }={e-e^{-1}\over2}i$$ so $$\Re(\cos(1+i))=\cos1\left({e^{-1}+e\over2}\right)$$
$$2\cos(a+ib)=e^{i(a+ib)}+e^{-i(a+ib)}=e^{-b}e^{ia}+e^be^{-ia}$$ Use Euler Identity: $e^{ix}=\cos x+i\sin x$
42,065,035
I have a page with different `<li>` elements with content under them. The content is hidden, and it is meant to be that when you click on the `<li>` element, the content under it, which is hidden, slides down and becomes shown. I have tried different methods, but none currently have worked as intended. Here is a JSFiddle where only the first element works, but I need it for all elements, and, if possible, then with a slide effect. Thank you. **[Link To fiddle](https://jsfiddle.net/mmLvs1za/1/)** **HTML** ``` <ul> <li id="virsraksts" class="slid"> <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3> </li> <div id="kontents" class="storijs"> <div style="height:20px;"></div> {{ post.content }} <div style="height:20px;"></div> ``` **CSS** ``` .storijs { display: none; } .para { display: block; } ``` **JS** ``` document.getElementById("virsraksts").onclick = function() { myFunction() }; function myFunction() { document.getElementById("kontents").classList.toggle("para"); } ```
2017/02/06
[ "https://Stackoverflow.com/questions/42065035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7406989/" ]
Few Issues in your code: 1) You have used duplicate IDs. IDs must be unique. getElementById only selects first element with that ID. 2) You have added div as child element in `ul`. which makes the markup invalid. You should rather put that div element in li. ``` <li id="virsraksts" class="slid"> <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3> </li> <li class="storijs"><div id="kontents"> <div style="height:20px;"></div> {{ post.content }} <div style="height:20px;"></div> </div> </li> ``` **Solution:** Use classname(`slid`) to target these elements as they have common class. and to target relevant `.kontents` element, traverse using `.next()` selector as its immediate next sibling of `.slid`: ``` $('.slid').click(function(){ $(this).next().slideToggle(); }); ``` **[Working Demo](https://jsfiddle.net/hcdnm2g2/)**
Id is unique attribute and can be assigned to one element only. Every time you will try to `getElementById` it will get first LI only. Try using Class.
42,065,035
I have a page with different `<li>` elements with content under them. The content is hidden, and it is meant to be that when you click on the `<li>` element, the content under it, which is hidden, slides down and becomes shown. I have tried different methods, but none currently have worked as intended. Here is a JSFiddle where only the first element works, but I need it for all elements, and, if possible, then with a slide effect. Thank you. **[Link To fiddle](https://jsfiddle.net/mmLvs1za/1/)** **HTML** ``` <ul> <li id="virsraksts" class="slid"> <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3> </li> <div id="kontents" class="storijs"> <div style="height:20px;"></div> {{ post.content }} <div style="height:20px;"></div> ``` **CSS** ``` .storijs { display: none; } .para { display: block; } ``` **JS** ``` document.getElementById("virsraksts").onclick = function() { myFunction() }; function myFunction() { document.getElementById("kontents").classList.toggle("para"); } ```
2017/02/06
[ "https://Stackoverflow.com/questions/42065035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7406989/" ]
Few Issues in your code: 1) You have used duplicate IDs. IDs must be unique. getElementById only selects first element with that ID. 2) You have added div as child element in `ul`. which makes the markup invalid. You should rather put that div element in li. ``` <li id="virsraksts" class="slid"> <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3> </li> <li class="storijs"><div id="kontents"> <div style="height:20px;"></div> {{ post.content }} <div style="height:20px;"></div> </div> </li> ``` **Solution:** Use classname(`slid`) to target these elements as they have common class. and to target relevant `.kontents` element, traverse using `.next()` selector as its immediate next sibling of `.slid`: ``` $('.slid').click(function(){ $(this).next().slideToggle(); }); ``` **[Working Demo](https://jsfiddle.net/hcdnm2g2/)**
In your html code you have use ID in `<li>` tag. ID should be unique. If you use different id name it will be work
11,543,182
Here's a rough image of what I'm trying to achieve (it won't compile, so consider it pseudocode). Please note that even though the example is based on public key cryptographic schemes, the question is about design patterns, templates and inheritance. ``` class CryptoProvider { public: template <typename T> virtual T Encrypt () { T data; return data; } }; class Paillier : public CryptoProvider { public: typedef int Ciphertext; Ciphertext Encrypt () { Ciphertext data; return data; } }; class ElGamal : public CryptoProvider { public: struct Ciphertext { public: int c1; int c2; }; Ciphertext Encrypt () { Ciphertext data; return data; } }; ``` Basically, I want to provide some generic functionality in CryptoProvider, which can be overridden by the derived classes if required, because otherwise I would end up with lots of duplicate code. If `Encrypt` just needs to create a variable and call another function, then I don't want to write this code in every derived class, but, if a derived class needs to do some extra processing on the data, it should be able to overwrite the base method. The biggest limitation that I've ran into is to somehow be able to override the Encrypt function by specifying completely different return types. Could somebody point me in the right direction on how to achieve this? Should I stick to traditional inheritance or should I try to go for compile-time / static polymorphism with [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? I have no idea where to start. I also want to impose the derived classes to implement certain methods, but I'm not sure how to achieve this, if the solution to the first issue requires that I discard standard inheritance (and I won't benefit from virtual methods)...
2012/07/18
[ "https://Stackoverflow.com/questions/11543182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174378/" ]
CRTP will work to provide compile-time overrideable functionality without need for virtual functions: ``` template <typename Derived> class CryptoProvider { public: typename Derived::Ciphertext Encrypt() { typename Derived::Ciphertext data; return data; } }; class PaillierBase { public: typedef int Ciphertext; }; class Paillier : public CryptoProvider<PaillierBase> { public: void test1() { Encrypt(); } }; class ElGamalBase { public: struct Ciphertext { int c1; int c2; }; }; class ElGamal : public CryptoProvider<ElGamalBase> { public: void test2() { Encrypt(); } }; ``` The return types need to be declared in a base class that must be a complete type by the time the CRTP template gets instantiated when you derive from it. The code below doesn't work, at least in pre-C11 compilers: at point P, the class ElGamal is not a complete type yet, thus CryptoProvider::Encrypt() can't be instantiated. I don't know if C11 changes anything here. It's a silly shortcoming of the language, IMHO. ``` // Doesn't work, unfortunately class ElGamal : public CryptoProvider<ElGamal> /* P */ { public: struct Ciphertext { int c1; int c2; }; void test2() { Encrypt(); } }; ```
You can create a base class called CipherText in which you hold the cipher text. Then, you can subclass that to the specific type that you need to return. You can specify the return type as a base class pointer. Of course, this answer might be right or wrong based on what you are trying to do.
11,543,182
Here's a rough image of what I'm trying to achieve (it won't compile, so consider it pseudocode). Please note that even though the example is based on public key cryptographic schemes, the question is about design patterns, templates and inheritance. ``` class CryptoProvider { public: template <typename T> virtual T Encrypt () { T data; return data; } }; class Paillier : public CryptoProvider { public: typedef int Ciphertext; Ciphertext Encrypt () { Ciphertext data; return data; } }; class ElGamal : public CryptoProvider { public: struct Ciphertext { public: int c1; int c2; }; Ciphertext Encrypt () { Ciphertext data; return data; } }; ``` Basically, I want to provide some generic functionality in CryptoProvider, which can be overridden by the derived classes if required, because otherwise I would end up with lots of duplicate code. If `Encrypt` just needs to create a variable and call another function, then I don't want to write this code in every derived class, but, if a derived class needs to do some extra processing on the data, it should be able to overwrite the base method. The biggest limitation that I've ran into is to somehow be able to override the Encrypt function by specifying completely different return types. Could somebody point me in the right direction on how to achieve this? Should I stick to traditional inheritance or should I try to go for compile-time / static polymorphism with [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? I have no idea where to start. I also want to impose the derived classes to implement certain methods, but I'm not sure how to achieve this, if the solution to the first issue requires that I discard standard inheritance (and I won't benefit from virtual methods)...
2012/07/18
[ "https://Stackoverflow.com/questions/11543182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174378/" ]
All your child classes have the `Ciphertext` type defined to be different things. This suggest making it a template parameter of `CryptoProvider`. ``` template <typename T> class CryptoProvider { public: virtual T Encrypt () { ... } typedef T Ciphertext; }; class PaillierBase : public CryptoProvider<int> { ... } ``` IMHO CRTP is unnecessary here.
You can create a base class called CipherText in which you hold the cipher text. Then, you can subclass that to the specific type that you need to return. You can specify the return type as a base class pointer. Of course, this answer might be right or wrong based on what you are trying to do.
11,543,182
Here's a rough image of what I'm trying to achieve (it won't compile, so consider it pseudocode). Please note that even though the example is based on public key cryptographic schemes, the question is about design patterns, templates and inheritance. ``` class CryptoProvider { public: template <typename T> virtual T Encrypt () { T data; return data; } }; class Paillier : public CryptoProvider { public: typedef int Ciphertext; Ciphertext Encrypt () { Ciphertext data; return data; } }; class ElGamal : public CryptoProvider { public: struct Ciphertext { public: int c1; int c2; }; Ciphertext Encrypt () { Ciphertext data; return data; } }; ``` Basically, I want to provide some generic functionality in CryptoProvider, which can be overridden by the derived classes if required, because otherwise I would end up with lots of duplicate code. If `Encrypt` just needs to create a variable and call another function, then I don't want to write this code in every derived class, but, if a derived class needs to do some extra processing on the data, it should be able to overwrite the base method. The biggest limitation that I've ran into is to somehow be able to override the Encrypt function by specifying completely different return types. Could somebody point me in the right direction on how to achieve this? Should I stick to traditional inheritance or should I try to go for compile-time / static polymorphism with [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? I have no idea where to start. I also want to impose the derived classes to implement certain methods, but I'm not sure how to achieve this, if the solution to the first issue requires that I discard standard inheritance (and I won't benefit from virtual methods)...
2012/07/18
[ "https://Stackoverflow.com/questions/11543182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174378/" ]
See another way to achieve this. Slightly round-about, though... This provides the possibility of a common implementation based on templates and derivability. Only problem is that the CipherText definition cannot be inside the derived classes. I guess this wouldn't be a big problem for you. If you can define these classes in a global scope, you could get away with the additional derivation. ``` template <typename T> class CryptoProvider { public: virtual T Encrypt() { T data; return data; } }; class PaillierBase { public: typedef int Ciphertext; }; class Paillier : public PaillierBase, public CryptoProvider<PaillierBase::Ciphertext> { public: }; class ElGamalBase { public: struct Ciphertext { public: int c1; int c2; }; }; class ElGamal : public ElGamalBase, public CryptoProvider<ElGamalBase::Ciphertext> { public: }; class CustomEncryptorBase { public: struct Ciphertext { public: char* c1; int* c2; }; }; class CustomEncryptor : public CustomEncryptorBase, public CryptoProvider<CustomEncryptorBase::Ciphertext> { public: virtual CustomEncryptorBase::Ciphertext Encrypt() { CustomEncryptorBase::Ciphertext data; // Do additional processing return data; } }; int main() { ElGamal e; ElGamalBase::Ciphertext c = e.Encrypt(); CustomEncryptor ce; CustomEncryptorBase::Ciphertext c1 = ce.Encrypt(); return 0; } ```
You can create a base class called CipherText in which you hold the cipher text. Then, you can subclass that to the specific type that you need to return. You can specify the return type as a base class pointer. Of course, this answer might be right or wrong based on what you are trying to do.
11,543,182
Here's a rough image of what I'm trying to achieve (it won't compile, so consider it pseudocode). Please note that even though the example is based on public key cryptographic schemes, the question is about design patterns, templates and inheritance. ``` class CryptoProvider { public: template <typename T> virtual T Encrypt () { T data; return data; } }; class Paillier : public CryptoProvider { public: typedef int Ciphertext; Ciphertext Encrypt () { Ciphertext data; return data; } }; class ElGamal : public CryptoProvider { public: struct Ciphertext { public: int c1; int c2; }; Ciphertext Encrypt () { Ciphertext data; return data; } }; ``` Basically, I want to provide some generic functionality in CryptoProvider, which can be overridden by the derived classes if required, because otherwise I would end up with lots of duplicate code. If `Encrypt` just needs to create a variable and call another function, then I don't want to write this code in every derived class, but, if a derived class needs to do some extra processing on the data, it should be able to overwrite the base method. The biggest limitation that I've ran into is to somehow be able to override the Encrypt function by specifying completely different return types. Could somebody point me in the right direction on how to achieve this? Should I stick to traditional inheritance or should I try to go for compile-time / static polymorphism with [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? I have no idea where to start. I also want to impose the derived classes to implement certain methods, but I'm not sure how to achieve this, if the solution to the first issue requires that I discard standard inheritance (and I won't benefit from virtual methods)...
2012/07/18
[ "https://Stackoverflow.com/questions/11543182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174378/" ]
All your child classes have the `Ciphertext` type defined to be different things. This suggest making it a template parameter of `CryptoProvider`. ``` template <typename T> class CryptoProvider { public: virtual T Encrypt () { ... } typedef T Ciphertext; }; class PaillierBase : public CryptoProvider<int> { ... } ``` IMHO CRTP is unnecessary here.
CRTP will work to provide compile-time overrideable functionality without need for virtual functions: ``` template <typename Derived> class CryptoProvider { public: typename Derived::Ciphertext Encrypt() { typename Derived::Ciphertext data; return data; } }; class PaillierBase { public: typedef int Ciphertext; }; class Paillier : public CryptoProvider<PaillierBase> { public: void test1() { Encrypt(); } }; class ElGamalBase { public: struct Ciphertext { int c1; int c2; }; }; class ElGamal : public CryptoProvider<ElGamalBase> { public: void test2() { Encrypt(); } }; ``` The return types need to be declared in a base class that must be a complete type by the time the CRTP template gets instantiated when you derive from it. The code below doesn't work, at least in pre-C11 compilers: at point P, the class ElGamal is not a complete type yet, thus CryptoProvider::Encrypt() can't be instantiated. I don't know if C11 changes anything here. It's a silly shortcoming of the language, IMHO. ``` // Doesn't work, unfortunately class ElGamal : public CryptoProvider<ElGamal> /* P */ { public: struct Ciphertext { int c1; int c2; }; void test2() { Encrypt(); } }; ```
11,543,182
Here's a rough image of what I'm trying to achieve (it won't compile, so consider it pseudocode). Please note that even though the example is based on public key cryptographic schemes, the question is about design patterns, templates and inheritance. ``` class CryptoProvider { public: template <typename T> virtual T Encrypt () { T data; return data; } }; class Paillier : public CryptoProvider { public: typedef int Ciphertext; Ciphertext Encrypt () { Ciphertext data; return data; } }; class ElGamal : public CryptoProvider { public: struct Ciphertext { public: int c1; int c2; }; Ciphertext Encrypt () { Ciphertext data; return data; } }; ``` Basically, I want to provide some generic functionality in CryptoProvider, which can be overridden by the derived classes if required, because otherwise I would end up with lots of duplicate code. If `Encrypt` just needs to create a variable and call another function, then I don't want to write this code in every derived class, but, if a derived class needs to do some extra processing on the data, it should be able to overwrite the base method. The biggest limitation that I've ran into is to somehow be able to override the Encrypt function by specifying completely different return types. Could somebody point me in the right direction on how to achieve this? Should I stick to traditional inheritance or should I try to go for compile-time / static polymorphism with [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? I have no idea where to start. I also want to impose the derived classes to implement certain methods, but I'm not sure how to achieve this, if the solution to the first issue requires that I discard standard inheritance (and I won't benefit from virtual methods)...
2012/07/18
[ "https://Stackoverflow.com/questions/11543182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174378/" ]
See another way to achieve this. Slightly round-about, though... This provides the possibility of a common implementation based on templates and derivability. Only problem is that the CipherText definition cannot be inside the derived classes. I guess this wouldn't be a big problem for you. If you can define these classes in a global scope, you could get away with the additional derivation. ``` template <typename T> class CryptoProvider { public: virtual T Encrypt() { T data; return data; } }; class PaillierBase { public: typedef int Ciphertext; }; class Paillier : public PaillierBase, public CryptoProvider<PaillierBase::Ciphertext> { public: }; class ElGamalBase { public: struct Ciphertext { public: int c1; int c2; }; }; class ElGamal : public ElGamalBase, public CryptoProvider<ElGamalBase::Ciphertext> { public: }; class CustomEncryptorBase { public: struct Ciphertext { public: char* c1; int* c2; }; }; class CustomEncryptor : public CustomEncryptorBase, public CryptoProvider<CustomEncryptorBase::Ciphertext> { public: virtual CustomEncryptorBase::Ciphertext Encrypt() { CustomEncryptorBase::Ciphertext data; // Do additional processing return data; } }; int main() { ElGamal e; ElGamalBase::Ciphertext c = e.Encrypt(); CustomEncryptor ce; CustomEncryptorBase::Ciphertext c1 = ce.Encrypt(); return 0; } ```
CRTP will work to provide compile-time overrideable functionality without need for virtual functions: ``` template <typename Derived> class CryptoProvider { public: typename Derived::Ciphertext Encrypt() { typename Derived::Ciphertext data; return data; } }; class PaillierBase { public: typedef int Ciphertext; }; class Paillier : public CryptoProvider<PaillierBase> { public: void test1() { Encrypt(); } }; class ElGamalBase { public: struct Ciphertext { int c1; int c2; }; }; class ElGamal : public CryptoProvider<ElGamalBase> { public: void test2() { Encrypt(); } }; ``` The return types need to be declared in a base class that must be a complete type by the time the CRTP template gets instantiated when you derive from it. The code below doesn't work, at least in pre-C11 compilers: at point P, the class ElGamal is not a complete type yet, thus CryptoProvider::Encrypt() can't be instantiated. I don't know if C11 changes anything here. It's a silly shortcoming of the language, IMHO. ``` // Doesn't work, unfortunately class ElGamal : public CryptoProvider<ElGamal> /* P */ { public: struct Ciphertext { int c1; int c2; }; void test2() { Encrypt(); } }; ```
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
There are other types or tables that depend on the type you want to change. If it's a dependent type, then you can use the FORCE option to change the type. If it's a table that directly or indirectly uses the type, then you will need to create a new type and a new table, migrate all the data, and finally drop and rename tables and types. See this [Oracle documentation](http://docs.oracle.com/cd/E16338_01/appdev.112/e11822/adobjmng.htm#CHDBAEHJ) for some further information.
I was looking everywhere for the syntax also, but was having a hard time finding the documentation. From the page that Codo linked... notice that the `FORCE` is between the object name and `as object` ``` create or replace type ceq_owner.type_rec_parae2 FORCE as object ( ... BONETAT_DESC VARCHAR2(250), ... ) / ```
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
There are other types or tables that depend on the type you want to change. If it's a dependent type, then you can use the FORCE option to change the type. If it's a table that directly or indirectly uses the type, then you will need to create a new type and a new table, migrate all the data, and finally drop and rename tables and types. See this [Oracle documentation](http://docs.oracle.com/cd/E16338_01/appdev.112/e11822/adobjmng.htm#CHDBAEHJ) for some further information.
Try: ``` drop type your_type force; ```
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
There are other types or tables that depend on the type you want to change. If it's a dependent type, then you can use the FORCE option to change the type. If it's a table that directly or indirectly uses the type, then you will need to create a new type and a new table, migrate all the data, and finally drop and rename tables and types. See this [Oracle documentation](http://docs.oracle.com/cd/E16338_01/appdev.112/e11822/adobjmng.htm#CHDBAEHJ) for some further information.
There are some dependency for the Object you are trying to Modify or Drop. If you want to skip this first drop the dependant Object and try to DROP or MODIFY Like in the below Screenshot [![](https://i.stack.imgur.com/tIDit.jpg)](https://i.stack.imgur.com/tIDit.jpg) Regards, Arul
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
I was looking everywhere for the syntax also, but was having a hard time finding the documentation. From the page that Codo linked... notice that the `FORCE` is between the object name and `as object` ``` create or replace type ceq_owner.type_rec_parae2 FORCE as object ( ... BONETAT_DESC VARCHAR2(250), ... ) / ```
Try: ``` drop type your_type force; ```
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
I was looking everywhere for the syntax also, but was having a hard time finding the documentation. From the page that Codo linked... notice that the `FORCE` is between the object name and `as object` ``` create or replace type ceq_owner.type_rec_parae2 FORCE as object ( ... BONETAT_DESC VARCHAR2(250), ... ) / ```
There are some dependency for the Object you are trying to Modify or Drop. If you want to skip this first drop the dependant Object and try to DROP or MODIFY Like in the below Screenshot [![](https://i.stack.imgur.com/tIDit.jpg)](https://i.stack.imgur.com/tIDit.jpg) Regards, Arul
11,674,807
I'm newbee in oracle and I try to change `varchar(50)` to `250` ```sql CREATE OR REPLACE TYPE CEQ_OWNER.TYPE_REC_PARAE2 AS OBJECT ( ... BONETAT_DESC VARCHAR2(250), ... ) / ``` I get ORA-02303: cannot drop or replace a type with type or table dependents
2012/07/26
[ "https://Stackoverflow.com/questions/11674807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943648/" ]
Try: ``` drop type your_type force; ```
There are some dependency for the Object you are trying to Modify or Drop. If you want to skip this first drop the dependant Object and try to DROP or MODIFY Like in the below Screenshot [![](https://i.stack.imgur.com/tIDit.jpg)](https://i.stack.imgur.com/tIDit.jpg) Regards, Arul
264,038
a. He looked at them to help him. b. He looked to them to help him. c. He looked at them for help. d. He looked to them for help. Which of the above sentences are grammatically correct? Which are natural? Many thanks.
2020/10/20
[ "https://ell.stackexchange.com/questions/264038", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/32659/" ]
The PPP in that article refers to the [Paycheck Protection Program](https://www.sba.gov/funding-programs/loans/coronavirus-relief-options/paycheck-protection-program), a loan program run by the [U.S. Small Business Administration (SBA)](https://en.wikipedia.org/wiki/Small_Business_Administration). As per [their website](https://www.sba.gov/funding-programs/loans/coronavirus-relief-options/paycheck-protection-program): > > An SBA loan that helps businesses keep their workforce employed during the Coronavirus (COVID-19) crisis. > > > > > The Paycheck Protection Program is a loan designed to provide a direct incentive for small businesses to keep their workers on the payroll. > > > SBA will forgive loans if all employee retention criteria are met, and the funds are used for eligible expenses. > > >
In this context, PPP stands for Paycheck Protection Program: > > The **Paycheck Protection Program (PPP)** is a $669-billion business loan program established by the 2020 US Federal government Coronavirus Aid, Relief, and Economic Security Act (CARES Act) to help certain businesses, self-employed workers, sole proprietors, certain nonprofit organizations, and tribal businesses continue paying their workers. > > > <https://en.wikipedia.org/wiki/Paycheck_Protection_Program> The article you linked actually explains this, but oddly, it's ["below the fold"](https://en.wiktionary.org/wiki/below_the_fold). > > The bill, likely to be almost identical to the one that failed in the Senate in September, includes funding for the Payroll Protection Program (PPP), extra unemployment benefits, money for schools, and liability protections for businesses. > > > I had to click the "Story Continues" button near the bottom of the page to find this sentence.
19,464,288
Hi guys so the following is happening when i try access the code, the first part is good because without having the handbag in inventory i want it to say you are carrying however if i have the handbag i want it to say you are carrying these items in your handbag but the below happens; What now? get torch ok What now? list You are carrying: torch What now? go stairs It's dark in here! What now? get handbag ok ``` What now? list You are carrying these items in your handbag: torch You are carrying these items in your handbag: wallet You are carrying these items in your handbag: keys You are carrying these items in your handbag: ring You are carrying these items in your handbag: USB You are carrying these items in your handbag: mobile You are carrying these items in your handbag: handbag ``` and here is the code ``` public void listWhatYouHave() { for (int i = 0; i < 7; i++) { if (hasItem[6]) { System.out.println("You are carrying these items in your handbag:"); switch (i) { case 0: System.out.println("torch"); break; case 1: System.out.println("wallet"); break; case 2: System.out.println("keys"); break; case 3: System.out.println("ring"); break; case 4: System.out.println("USB"); break; case 5: System.out.println("mobile"); break; case 6: System.out.println("handbag"); break; default: System.out.println("invalid item!"); break; } } else if (hasItem[i]) { System.out.println("You are carrying:"); switch (i) { case 0: System.out.println("torch"); break; case 1: System.out.println("wallet"); break; case 2: System.out.println("keys"); break; case 3: System.out.println("ring"); break; case 4: System.out.println("USB"); break; case 5: System.out.println("mobile"); break; case 6: System.out.println("handbag"); break; default: System.out.println("invalid item!"); break; } } } ``` can you help... thanks (this is java obviously) sorry for benig vague... pretty much when i dont have the handbag i want it to list what im carrying by saying 'you are carrying' however if i pickup the handbag at a point when thats picked up... i want it to say 'you are carrying these items in your handbag' but currently it prints out you are carrying just once... but you are carrying these items in your handbag is printed in everyline... i only want it once.
2013/10/19
[ "https://Stackoverflow.com/questions/19464288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897384/" ]
Your `hasItem[6]` value is true then `if (hasItem[6])` condiion will always true. Your else part wont get excuted May be you need `if(hasItem[i])` instead of `if(hasItem[6])`
I think the problem is that in the first part of your condition you only check whether the user has the hadbag and you don't check the item. The first condition should be rewritten: ``` if(hasItem[6] && hasItem[i]) { .... ``` At the same time I would refactor out the inner swich because it is twice there in the code. And I would suggest to use enumerated types instead of integer constants. EDIT: In order to prevent it to print the 'You are carrying' line multiple times you should refactor it out from the for loop. I would do it this way: ``` public void listWhatYouHave() { if (hasItem[6]) { System.out.println("You are carrying these items in your handbag:"); } else { System.out.println("You are carrying these items:"); } listItems(hasItem); } void listItems(bool[] hasItem) { for (int i = 0; i < 7; i++) { if(hasItem[i]) { switch(hasItem[i]) { // ... put your case here } } } } ``` Furthermore, if you don't want to write out the handbag being carried in the handbag you can remove it from the switch case, since it is something you use for a different purpose.
21,114,888
For the following code, ``` proctype A() { byte cond1; time = time + 1; time = time + 2; t[0] = 3; a[0] = 2; do :: (a[0] == 0)->break; :: else -> a[0] = a[0] - 1; do :: (t[0] <= t[1])->break; od; if :: (cond1 != 0) -> lock(mutex); time = time + 1; time = time + 2; t[0] = t[0] + 3; unlock(mutex); :: (cond1 == 0) -> time = time + 1; fi od; t[0] = 1000; } ``` I get the following error, ``` unreached in proctype A code.pml:15, state 20, "time = (time+1)" code.pml:14, state 23, "((mutex==0))" code.pml:14, state 23, "else" code.pml:18, state 25, "time = (time+1)" code.pml:12, state 26, "((mutex==0))" code.pml:12, state 26, "((mutex==1))" code.pml:12, state 29, "((mutex==0))" code.pml:12, state 29, "((mutex==1))" code.pml:45, state 31, "time = (time+2)" code.pml:46, state 32, "t[0] = (t[0]+3)" (7 of 43 states) ``` Why is that so? Shouldn't Promela execute for every value of cond1 (both cond1 == 0 and cond1 != 0). At least this is what is written in [here](http://spinroot.com/spin/Man/rand.html). > > During verifications no such calls are made, because effectively all options for behavior will be explored in this mode, one at a time. > > >
2014/01/14
[ "https://Stackoverflow.com/questions/21114888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760807/" ]
Here's your query, using regular expressions. You'll need to figure out to generate it in PHP: ``` SELECT * FROM operators WHERE location REGEXP '[[:<:]]1[[:>:]]' OR location REGEXP '[[:<:]]2[[:>:]]' ``` Unfortunately, this will scan all records in the operators table. Consider using an intersection table instead by normalizing the locations into a separate table like this: ``` table: operators op_id op_name -------------------------- 1 sami 2 foo 3 boo table: operator_locations op_id location --------------------------- 1 1 1 3 1 5 2 1 3 4 3 5 ``` And use joins instead of regular expressions. ``` SELECT o.* FROM operator_locations ol JOIN operators o ON o.op_id = ol.op_id WHERE ol.location = 1 OR ol.location = 2 ``` This will allow the query to use indexes. Besides performance, the savings aren't obvious here, but when you run out of room in your locations column or want to do something more complex like aggregates, you'll see the benefit.
Based on comments from Victor's answer, correct SQL was follow: ``` $where = "WHERE "; $count = count($locs); for ($i = 0; $i < $count; $i++) { $where .= "location = '". $locs[$i] ."' "; $where .= " OR location LIKE '%". $locs[$i] .",%' "; $where .= " OR location LIKE '%, ". $locs[$i] ."%' "; if ($i < $count - 1) { $where .= " OR "; } } ```
21,114,888
For the following code, ``` proctype A() { byte cond1; time = time + 1; time = time + 2; t[0] = 3; a[0] = 2; do :: (a[0] == 0)->break; :: else -> a[0] = a[0] - 1; do :: (t[0] <= t[1])->break; od; if :: (cond1 != 0) -> lock(mutex); time = time + 1; time = time + 2; t[0] = t[0] + 3; unlock(mutex); :: (cond1 == 0) -> time = time + 1; fi od; t[0] = 1000; } ``` I get the following error, ``` unreached in proctype A code.pml:15, state 20, "time = (time+1)" code.pml:14, state 23, "((mutex==0))" code.pml:14, state 23, "else" code.pml:18, state 25, "time = (time+1)" code.pml:12, state 26, "((mutex==0))" code.pml:12, state 26, "((mutex==1))" code.pml:12, state 29, "((mutex==0))" code.pml:12, state 29, "((mutex==1))" code.pml:45, state 31, "time = (time+2)" code.pml:46, state 32, "t[0] = (t[0]+3)" (7 of 43 states) ``` Why is that so? Shouldn't Promela execute for every value of cond1 (both cond1 == 0 and cond1 != 0). At least this is what is written in [here](http://spinroot.com/spin/Man/rand.html). > > During verifications no such calls are made, because effectively all options for behavior will be explored in this mode, one at a time. > > >
2014/01/14
[ "https://Stackoverflow.com/questions/21114888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760807/" ]
Here's your query, using regular expressions. You'll need to figure out to generate it in PHP: ``` SELECT * FROM operators WHERE location REGEXP '[[:<:]]1[[:>:]]' OR location REGEXP '[[:<:]]2[[:>:]]' ``` Unfortunately, this will scan all records in the operators table. Consider using an intersection table instead by normalizing the locations into a separate table like this: ``` table: operators op_id op_name -------------------------- 1 sami 2 foo 3 boo table: operator_locations op_id location --------------------------- 1 1 1 3 1 5 2 1 3 4 3 5 ``` And use joins instead of regular expressions. ``` SELECT o.* FROM operator_locations ol JOIN operators o ON o.op_id = ol.op_id WHERE ol.location = 1 OR ol.location = 2 ``` This will allow the query to use indexes. Besides performance, the savings aren't obvious here, but when you run out of room in your locations column or want to do something more complex like aggregates, you'll see the benefit.
You may explode your session value to array: ``` $locs = explode(', ' $_SESSION['locs']); ``` And SQL was follow: ``` $where = "WHERE "; $count = count($locs); for ($i = 0; $i < $count; $i++) { $where .= "location LIKE '%, ". $locs[$i] .",%' "; $where .= " OR location LIKE '%, ". $locs[$i] ."%' "; if ($i < $count - 1) { $where .= " OR "; } } ``` Or use MySQL RegEx for regular expression search Better way is to use REGEXP: ``` $where = "WHERE "; $count = count($locs); for ($i = 0; $i < $count; $i++) { $where .= "location REGEXP '(,[[:blank:]]*|^)". $locs[$i] ."(,|$)'"; if ($i < $count - 1) { $where .= " OR "; } } ``` I tested them, it's work on `"1, 2, 3"` string for any number.
12,559,017
Hi can anybody help me on this issue, like i was trying to create XML file from data in datagridview. Problem is datagridview is dynamically created n it depends on the user on how many rows n columns he creates n enters the data in it. Datagridview contains columns with integer as well as string. So initializing columns n rows is bit difficult as i am a newbie. Kindly help me on this..
2012/09/24
[ "https://Stackoverflow.com/questions/12559017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679548/" ]
Refer to accepted solution on [this](https://stackoverflow.com/questions/3109009/how-to-make-a-datatable-from-datagrid-without-any-datasource) and create a `DataTable` manually ``` DataTable dt = new DataTable(); foreach(DataGridViewColumn col in dgv.Columns) { dt.Columns.Add(col.HeaderText); } foreach(DataGridViewRow row in dgv.Rows) { DataRow dRow = dt.NewRow(); foreach(DataGridViewCell cell in row.Cells) { dRow[cell.ColumnIndex] = cell.Value; } dt.Rows.Add(dRow); } ``` After you have created this `DataTable`, create a `DataSet` and use `WriteXml` ``` DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.WriteXml("your local path here"); ```
``` private XElement GetData(DataGridView dgv) { var elem = new XElement("data"); foreach (DataGridViewRow row in dgv.Rows) { elem.Add(new XElement("row", row.Cells .Cast<DataGridViewCell>() .Select(a => new XElement(a.OwningColumn.Name, a.Value)))); } return elem; } ```
12,559,017
Hi can anybody help me on this issue, like i was trying to create XML file from data in datagridview. Problem is datagridview is dynamically created n it depends on the user on how many rows n columns he creates n enters the data in it. Datagridview contains columns with integer as well as string. So initializing columns n rows is bit difficult as i am a newbie. Kindly help me on this..
2012/09/24
[ "https://Stackoverflow.com/questions/12559017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679548/" ]
``` DataSet ds = new DataSet(); DataTable dt = (DataTable)gv.DataSource;// if data source is dynamic data table it will wokr ds.Tables.Add(dt); string xml = ds.GetXml(); ```
``` private XElement GetData(DataGridView dgv) { var elem = new XElement("data"); foreach (DataGridViewRow row in dgv.Rows) { elem.Add(new XElement("row", row.Cells .Cast<DataGridViewCell>() .Select(a => new XElement(a.OwningColumn.Name, a.Value)))); } return elem; } ```
12,559,017
Hi can anybody help me on this issue, like i was trying to create XML file from data in datagridview. Problem is datagridview is dynamically created n it depends on the user on how many rows n columns he creates n enters the data in it. Datagridview contains columns with integer as well as string. So initializing columns n rows is bit difficult as i am a newbie. Kindly help me on this..
2012/09/24
[ "https://Stackoverflow.com/questions/12559017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679548/" ]
Refer to accepted solution on [this](https://stackoverflow.com/questions/3109009/how-to-make-a-datatable-from-datagrid-without-any-datasource) and create a `DataTable` manually ``` DataTable dt = new DataTable(); foreach(DataGridViewColumn col in dgv.Columns) { dt.Columns.Add(col.HeaderText); } foreach(DataGridViewRow row in dgv.Rows) { DataRow dRow = dt.NewRow(); foreach(DataGridViewCell cell in row.Cells) { dRow[cell.ColumnIndex] = cell.Value; } dt.Rows.Add(dRow); } ``` After you have created this `DataTable`, create a `DataSet` and use `WriteXml` ``` DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.WriteXml("your local path here"); ```
``` DataSet ds = new DataSet(); DataTable dt = (DataTable)gv.DataSource;// if data source is dynamic data table it will wokr ds.Tables.Add(dt); string xml = ds.GetXml(); ```
13,571,221
I am storing Unicode text `لاہور` in MySQL, I have set tables and columns to utf8\_general\_ci. The text `لاہور` is displaying correctly in MySQL. However if I echo that with PHP it shows `??????` on the browser window. One thing to mention here: I have the whole document in Unicode and all words are displaying correctly, but they are written directly i.e. not coming from MySQL. Even if I try ``` $p="لاہور"; echo $p; ``` It displays `لاہور` in the browser. Things go wrong only when retrieving from MySQL.
2012/11/26
[ "https://Stackoverflow.com/questions/13571221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032593/" ]
This is basically a query string if you replace `;` with `&`. You can try `parse_str()` like this: ``` $string = 'name=Service_Name;nextduedate=2013-02-25;status=Active'; parse_str(str_replace(';', '&', $string)); echo $name; // Service_Name echo $nextduedate; // 2013-02-25 echo $status; // Active ```
This can rather simply be solved without regex. The use of `explode()` will help you. ``` $str = "name=Service_Name;nextduedate=2013-02-25;status=Active"; $split = explode(";", $str); $structure = array(); foreach ($split as $element) { $element = explode("=", $element); $$element[0] = $element[1]; } var_dump($name); ``` Though I urge you to use an array instead. Far more readable than inventing variables that didn't exist and are not explicitly declared.
13,571,221
I am storing Unicode text `لاہور` in MySQL, I have set tables and columns to utf8\_general\_ci. The text `لاہور` is displaying correctly in MySQL. However if I echo that with PHP it shows `??????` on the browser window. One thing to mention here: I have the whole document in Unicode and all words are displaying correctly, but they are written directly i.e. not coming from MySQL. Even if I try ``` $p="لاہور"; echo $p; ``` It displays `لاہور` in the browser. Things go wrong only when retrieving from MySQL.
2012/11/26
[ "https://Stackoverflow.com/questions/13571221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032593/" ]
This can rather simply be solved without regex. The use of `explode()` will help you. ``` $str = "name=Service_Name;nextduedate=2013-02-25;status=Active"; $split = explode(";", $str); $structure = array(); foreach ($split as $element) { $element = explode("=", $element); $$element[0] = $element[1]; } var_dump($name); ``` Though I urge you to use an array instead. Far more readable than inventing variables that didn't exist and are not explicitly declared.
It sounds like you just want to break the text down into separate lines along the semicolons, add a dollar sign at the front and then add spaces and quotes. I'm not sure you can do that in one step with a regular expression (or at least I don't want to think about what *that* regular expression would look like), but you can do it over multiple steps. 1. Use [preg\_split()](http://www.php.net/manual/en/function.preg-split.php) to split the string into an array along the semicolons. 2. Loop over the array. 3. Use [str\_replace](http://php.net/manual/en/function.str-replace.php) to replace each '=' with ' = "'. 4. Use string concatenation to add a $ to the front and a "; to the end of each string. That should work, assuming your data doesn't include quotes, equal signs, semicolons, etc. within the data. If it does, you'll have to figure out the parsing rules for that.
13,571,221
I am storing Unicode text `لاہور` in MySQL, I have set tables and columns to utf8\_general\_ci. The text `لاہور` is displaying correctly in MySQL. However if I echo that with PHP it shows `??????` on the browser window. One thing to mention here: I have the whole document in Unicode and all words are displaying correctly, but they are written directly i.e. not coming from MySQL. Even if I try ``` $p="لاہور"; echo $p; ``` It displays `لاہور` in the browser. Things go wrong only when retrieving from MySQL.
2012/11/26
[ "https://Stackoverflow.com/questions/13571221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032593/" ]
This is basically a query string if you replace `;` with `&`. You can try `parse_str()` like this: ``` $string = 'name=Service_Name;nextduedate=2013-02-25;status=Active'; parse_str(str_replace(';', '&', $string)); echo $name; // Service_Name echo $nextduedate; // 2013-02-25 echo $status; // Active ```
It sounds like you just want to break the text down into separate lines along the semicolons, add a dollar sign at the front and then add spaces and quotes. I'm not sure you can do that in one step with a regular expression (or at least I don't want to think about what *that* regular expression would look like), but you can do it over multiple steps. 1. Use [preg\_split()](http://www.php.net/manual/en/function.preg-split.php) to split the string into an array along the semicolons. 2. Loop over the array. 3. Use [str\_replace](http://php.net/manual/en/function.str-replace.php) to replace each '=' with ' = "'. 4. Use string concatenation to add a $ to the front and a "; to the end of each string. That should work, assuming your data doesn't include quotes, equal signs, semicolons, etc. within the data. If it does, you'll have to figure out the parsing rules for that.
140,949
If a company says they lost $2M in Q1 because of: > > "non-cash mark-to-market increase in warrant liabilities" > > > As I understand warrants, they allow the holder to purchase the shares at the strike price before expiry. The only way I can see this as a loss, asides from their dilutive property, is if a companies shares are trading at $10 but the warrants are exercised at $4. Since these are newly issued shares, if 1M shares are issued at $4, the company nets $4M but could've issued shares at-the-market of $10 (probably $9 bought deal discounted) and net $10M (or $9M) and thus this is viewed as a "loss" of $6M. Is my understanding correct? If not, why is this recorded as part of the net loss?
2021/05/18
[ "https://money.stackexchange.com/questions/140949", "https://money.stackexchange.com", "https://money.stackexchange.com/users/105917/" ]
Yes, the loss ultimately arises from the scenario you describe, where the warrant becomes "in the money" and requires issuing shares below market value. However, whether or not the warrant is currently in the money, it has value (and constitutes a liability to the company) based on the *probability* that it will go in the money and by how much. This is what "mark-to-market" means, and is similar to exchange-traded call options. The loss corresponds to an increase in value of the warrants from one quarter to the next, generally due to either a rise in the market price of the stock or a rise in its expected volatility.
Is this a SPAC? The below article says that companies must calculate the probability of being forced to make a cash tender offer. As this probability changes, the liability changes; and the liability change creates a non-cash profit or loss in every reporting period. > > The switch to classify the warrants as a liability stems from the cash > outlay companies could face if they’re forced to extend a tender offer > to shareholders. > > > <https://www.cfodive.com/news/spac-warrants-liability-change-SEC-CFO-accounting-antoniades/598655/>
61,253,661
``` SELECT SUBSTR(PRODID,1, 4) AS [PROD4], COUNT(*) AS [NumberOfRows] FROM [sch].[ProdTable] GROUP BY SUBSTR(PRODID,1, 4) ``` We're writing a simple select that would count how many of our products have the same first 4 characters. Our Product IDs are 10 digits/characters. When running this, however, we get: > > SQL Error [936] [42000]: ORA-00936: missing expression > > > Any idea how to make this work?
2020/04/16
[ "https://Stackoverflow.com/questions/61253661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561246/" ]
try `testdf[!duplicated(testdf$.)&!duplicated(testdf$.,fromLast = TRUE),]`
Another `base`alternative(retains row names): ``` testdf[-which(testdf$`.` %in% testdf[duplicated(testdf$.),1]),] . V2 3 B 3 ```
61,253,661
``` SELECT SUBSTR(PRODID,1, 4) AS [PROD4], COUNT(*) AS [NumberOfRows] FROM [sch].[ProdTable] GROUP BY SUBSTR(PRODID,1, 4) ``` We're writing a simple select that would count how many of our products have the same first 4 characters. Our Product IDs are 10 digits/characters. When running this, however, we get: > > SQL Error [936] [42000]: ORA-00936: missing expression > > > Any idea how to make this work?
2020/04/16
[ "https://Stackoverflow.com/questions/61253661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561246/" ]
try `testdf[!duplicated(testdf$.)&!duplicated(testdf$.,fromLast = TRUE),]`
If want to stick with pipes ``` testdf %>% group_by(testdf$.) %>% summarise(num_x=n()) %>% filter(num_x==1) ```
61,253,661
``` SELECT SUBSTR(PRODID,1, 4) AS [PROD4], COUNT(*) AS [NumberOfRows] FROM [sch].[ProdTable] GROUP BY SUBSTR(PRODID,1, 4) ``` We're writing a simple select that would count how many of our products have the same first 4 characters. Our Product IDs are 10 digits/characters. When running this, however, we get: > > SQL Error [936] [42000]: ORA-00936: missing expression > > > Any idea how to make this work?
2020/04/16
[ "https://Stackoverflow.com/questions/61253661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561246/" ]
try `testdf[!duplicated(testdf$.)&!duplicated(testdf$.,fromLast = TRUE),]`
We can use `subset` with `table` ``` subset(testdf, `.` %in% names(which(table(`.`) == 1))) # . V2 #3 B 3 ```
61,253,661
``` SELECT SUBSTR(PRODID,1, 4) AS [PROD4], COUNT(*) AS [NumberOfRows] FROM [sch].[ProdTable] GROUP BY SUBSTR(PRODID,1, 4) ``` We're writing a simple select that would count how many of our products have the same first 4 characters. Our Product IDs are 10 digits/characters. When running this, however, we get: > > SQL Error [936] [42000]: ORA-00936: missing expression > > > Any idea how to make this work?
2020/04/16
[ "https://Stackoverflow.com/questions/61253661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561246/" ]
Another `base`alternative(retains row names): ``` testdf[-which(testdf$`.` %in% testdf[duplicated(testdf$.),1]),] . V2 3 B 3 ```
We can use `subset` with `table` ``` subset(testdf, `.` %in% names(which(table(`.`) == 1))) # . V2 #3 B 3 ```
61,253,661
``` SELECT SUBSTR(PRODID,1, 4) AS [PROD4], COUNT(*) AS [NumberOfRows] FROM [sch].[ProdTable] GROUP BY SUBSTR(PRODID,1, 4) ``` We're writing a simple select that would count how many of our products have the same first 4 characters. Our Product IDs are 10 digits/characters. When running this, however, we get: > > SQL Error [936] [42000]: ORA-00936: missing expression > > > Any idea how to make this work?
2020/04/16
[ "https://Stackoverflow.com/questions/61253661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561246/" ]
If want to stick with pipes ``` testdf %>% group_by(testdf$.) %>% summarise(num_x=n()) %>% filter(num_x==1) ```
We can use `subset` with `table` ``` subset(testdf, `.` %in% names(which(table(`.`) == 1))) # . V2 #3 B 3 ```
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I have slightly updated your case with a templateUrl which is, in my opinion, much more readable. <http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview> Template here : ``` <ion-nav-bar id="signedInHeader" class="bar-light" align-title="center"> <ion-nav-buttons side="left"> <a class="button button-icon button-clear " ng-click="test()">CLICK </a> </ion-nav-buttons> </ion-nav-bar> ``` I have created a test function that is added to your directive link. ``` scope.test= function(){ alert("TEST"); } ```
Ionics CSS comes with this rule: ``` img { -webkit-user-drag: none; } ``` Removing this from ionic.css or setting it to `auto` should solve this. Update: ------- this doesn't solve the issue for the OP. But using his plunkr, removing the `ionic.css` from the document fixes the issue. Just as a hint, the answer is somewhere out there ;)
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I have slightly updated your case with a templateUrl which is, in my opinion, much more readable. <http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview> Template here : ``` <ion-nav-bar id="signedInHeader" class="bar-light" align-title="center"> <ion-nav-buttons side="left"> <a class="button button-icon button-clear " ng-click="test()">CLICK </a> </ion-nav-buttons> </ion-nav-bar> ``` I have created a test function that is added to your directive link. ``` scope.test= function(){ alert("TEST"); } ```
Some how the generated ionic code has it's title blocking its own button. ``` <ion-nav-bar id="signedInHeader" class="bar-light nav-bar-container" align-title="center" nav-bar-transition="ios"> <ion-nav-buttons side="left" class="hide"></ion-nav-buttons> <ion-nav-buttons side="right" class="hide"></ion-nav-buttons> <div class="nav-bar-block" nav-bar="cached"> ... </div> <div class="nav-bar-block" nav-bar="active"> <ion-header-bar class="bar-light bar bar-header disable-user-behavior" align-title="center"> <div class="buttons buttons-left header-item"> <span class="left-buttons"> <div ng-click="alert(123)">click me</div> </span> </div> <div class="title title-center header-item"></div> <!-- this line --> <div class="buttons buttons-right header-item"> <span class="right-buttons"> <div> <i class="icon ion-ios-cart-outline"></i> <div id="cartCount" class="assertive">1</div> </div> </span> </div> </ion-header-bar> </div> </ion-nav-bar> ``` The title is having a css in ionic.css ``` .bar .title { position: absolute; top: 0; right: 0; left: 0; z-index: 0; ... } ``` In CSS rules `position:absolute` items will be placed on top of normal flow items. There might be a way in ionic coding style that fixes this issue but I can't find it. So I fixed it by raising the buttons and make it covers the title again ``` .bar .buttons-left { position: absolute; z-index: 1; } ``` Note that after this fix the left buttons will cover the title if title text is long enough to go under it, or the title text is aligned left.
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I have slightly updated your case with a templateUrl which is, in my opinion, much more readable. <http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview> Template here : ``` <ion-nav-bar id="signedInHeader" class="bar-light" align-title="center"> <ion-nav-buttons side="left"> <a class="button button-icon button-clear " ng-click="test()">CLICK </a> </ion-nav-buttons> </ion-nav-bar> ``` I have created a test function that is added to your directive link. ``` scope.test= function(){ alert("TEST"); } ```
What you have to remember is that `ng-click` will look for a function bound to the current `$scope`, so if you do ``` ng-click="alert(123)" ``` it is looking for a function `$scope.alert` and will not find it. It does not look in the `window` object to find it.
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
You just need to add the `button` class to your image. You can add `button-clear` so that the button border is not added. ``` <img class="button button-clear" ng-click="alert(123)" src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700015-icon-27-one-finger-click-32.png" /> ``` [Working Plunker](http://plnkr.co/edit/qVoChoC78Q9VC2HVZCcB?p=preview) ====================================================================== To clarify, everyone was correct on some level: * icycool was right in that the actual issue is the z-index. The ionic button class adds `z-index: 1`. * Krytic points out that without the ionic css linked it will work (because the elements then just default to relative position and the button isn't obscured). * aorfevre's suggestion to use a link worked not because it was an anchor tag, but because the link had the button class applied.
I have slightly updated your case with a templateUrl which is, in my opinion, much more readable. <http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview> Template here : ``` <ion-nav-bar id="signedInHeader" class="bar-light" align-title="center"> <ion-nav-buttons side="left"> <a class="button button-icon button-clear " ng-click="test()">CLICK </a> </ion-nav-buttons> </ion-nav-bar> ``` I have created a test function that is added to your directive link. ``` scope.test= function(){ alert("TEST"); } ```
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I think you can't specify a directive using id? **Angular doc says:** > > The restrict option is typically set to: > > 'A' - only matches attribute name > > 'E' - only matches element name > > 'C' - only matches class name > > > Maybe you can try adding it as an attribute? ``` <ion-nav-bar signed-in-header id="signedInHeader" class="bar-light" align-title="center"> ```
Some how the generated ionic code has it's title blocking its own button. ``` <ion-nav-bar id="signedInHeader" class="bar-light nav-bar-container" align-title="center" nav-bar-transition="ios"> <ion-nav-buttons side="left" class="hide"></ion-nav-buttons> <ion-nav-buttons side="right" class="hide"></ion-nav-buttons> <div class="nav-bar-block" nav-bar="cached"> ... </div> <div class="nav-bar-block" nav-bar="active"> <ion-header-bar class="bar-light bar bar-header disable-user-behavior" align-title="center"> <div class="buttons buttons-left header-item"> <span class="left-buttons"> <div ng-click="alert(123)">click me</div> </span> </div> <div class="title title-center header-item"></div> <!-- this line --> <div class="buttons buttons-right header-item"> <span class="right-buttons"> <div> <i class="icon ion-ios-cart-outline"></i> <div id="cartCount" class="assertive">1</div> </div> </span> </div> </ion-header-bar> </div> </ion-nav-bar> ``` The title is having a css in ionic.css ``` .bar .title { position: absolute; top: 0; right: 0; left: 0; z-index: 0; ... } ``` In CSS rules `position:absolute` items will be placed on top of normal flow items. There might be a way in ionic coding style that fixes this issue but I can't find it. So I fixed it by raising the buttons and make it covers the title again ``` .bar .buttons-left { position: absolute; z-index: 1; } ``` Note that after this fix the left buttons will cover the title if title text is long enough to go under it, or the title text is aligned left.
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
You just need to add the `button` class to your image. You can add `button-clear` so that the button border is not added. ``` <img class="button button-clear" ng-click="alert(123)" src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700015-icon-27-one-finger-click-32.png" /> ``` [Working Plunker](http://plnkr.co/edit/qVoChoC78Q9VC2HVZCcB?p=preview) ====================================================================== To clarify, everyone was correct on some level: * icycool was right in that the actual issue is the z-index. The ionic button class adds `z-index: 1`. * Krytic points out that without the ionic css linked it will work (because the elements then just default to relative position and the button isn't obscured). * aorfevre's suggestion to use a link worked not because it was an anchor tag, but because the link had the button class applied.
I think you can't specify a directive using id? **Angular doc says:** > > The restrict option is typically set to: > > 'A' - only matches attribute name > > 'E' - only matches element name > > 'C' - only matches class name > > > Maybe you can try adding it as an attribute? ``` <ion-nav-bar signed-in-header id="signedInHeader" class="bar-light" align-title="center"> ```
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I think you can't specify a directive using id? **Angular doc says:** > > The restrict option is typically set to: > > 'A' - only matches attribute name > > 'E' - only matches element name > > 'C' - only matches class name > > > Maybe you can try adding it as an attribute? ``` <ion-nav-bar signed-in-header id="signedInHeader" class="bar-light" align-title="center"> ```
Ionics CSS comes with this rule: ``` img { -webkit-user-drag: none; } ``` Removing this from ionic.css or setting it to `auto` should solve this. Update: ------- this doesn't solve the issue for the OP. But using his plunkr, removing the `ionic.css` from the document fixes the issue. Just as a hint, the answer is somewhere out there ;)
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
You just need to add the `button` class to your image. You can add `button-clear` so that the button border is not added. ``` <img class="button button-clear" ng-click="alert(123)" src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700015-icon-27-one-finger-click-32.png" /> ``` [Working Plunker](http://plnkr.co/edit/qVoChoC78Q9VC2HVZCcB?p=preview) ====================================================================== To clarify, everyone was correct on some level: * icycool was right in that the actual issue is the z-index. The ionic button class adds `z-index: 1`. * Krytic points out that without the ionic css linked it will work (because the elements then just default to relative position and the button isn't obscured). * aorfevre's suggestion to use a link worked not because it was an anchor tag, but because the link had the button class applied.
Ionics CSS comes with this rule: ``` img { -webkit-user-drag: none; } ``` Removing this from ionic.css or setting it to `auto` should solve this. Update: ------- this doesn't solve the issue for the OP. But using his plunkr, removing the `ionic.css` from the document fixes the issue. Just as a hint, the answer is somewhere out there ;)
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
I think you can't specify a directive using id? **Angular doc says:** > > The restrict option is typically set to: > > 'A' - only matches attribute name > > 'E' - only matches element name > > 'C' - only matches class name > > > Maybe you can try adding it as an attribute? ``` <ion-nav-bar signed-in-header id="signedInHeader" class="bar-light" align-title="center"> ```
What you have to remember is that `ng-click` will look for a function bound to the current `$scope`, so if you do ``` ng-click="alert(123)" ``` it is looking for a function `$scope.alert` and will not find it. It does not look in the `window` object to find it.
31,081,773
I have a simple ng-click in the nav bar and it doesn't work. I've placed the html template inside of a directive but the alert does not appear. There are no other issues in my console. I'm stumped as to why this doesn't work. ``` <signed-in-header></signed-in-header> ``` My directive as a whole. ``` angular.module('CoolSite.user') .directive('signedInHeader', signedInHeader) function signedInHeader() { return { template: template, link: link, scope: { } } function link(scope, elem, attrs) { scope.alert = function() {console.log("ALERTED")} } function template() { return [ '<ion-nav-bar class="bar-light" align-title="center">', '<ion-nav-buttons side="left">', '<img ng-click="alert(123)" height="30" src="/img/logo-full.png">', '</ion-nav-buttons>', '<ion-nav-buttons side="right">', '<div ui-sref="tab.cart">', '<i class="icon ion-ios-cart-outline"></i>', '<div id="cartCount" class="assertive">1</div>', '</div>', '</ion-nav-buttons>', '</ion-nav-bar>' ].join(""); } } ``` Plunker [here](http://plnkr.co/edit/8CHdeRmDtG52PgvAbucG?p=preview).
2015/06/26
[ "https://Stackoverflow.com/questions/31081773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509401/" ]
You just need to add the `button` class to your image. You can add `button-clear` so that the button border is not added. ``` <img class="button button-clear" ng-click="alert(123)" src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700015-icon-27-one-finger-click-32.png" /> ``` [Working Plunker](http://plnkr.co/edit/qVoChoC78Q9VC2HVZCcB?p=preview) ====================================================================== To clarify, everyone was correct on some level: * icycool was right in that the actual issue is the z-index. The ionic button class adds `z-index: 1`. * Krytic points out that without the ionic css linked it will work (because the elements then just default to relative position and the button isn't obscured). * aorfevre's suggestion to use a link worked not because it was an anchor tag, but because the link had the button class applied.
What you have to remember is that `ng-click` will look for a function bound to the current `$scope`, so if you do ``` ng-click="alert(123)" ``` it is looking for a function `$scope.alert` and will not find it. It does not look in the `window` object to find it.
66,769,964
``` @ECHO on CD C:\Users\User reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d C:\Users\User\Desktop\folder\Background1.png /f reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v TileWallpaper /t REG_SZ /d 0 /f RUNDLL32.EXE USER32.DLL, UpdatePerUserSystemParameters 1 True pause ``` *The User and Folder names have been defaulted for readability*
2021/03/23
[ "https://Stackoverflow.com/questions/66769964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15419399/" ]
You cannot read and write the json file with the same with clause. Kindly use this code to get rid of that error that are the read and write buffers that not allowing you to write while reading at the same time ``` import pathlib import json import os obj = { "a": "1", "b": "2", "c": "3" } obj2 = { "d": "4", "e": "5", "f": "6" } jsonFile = "jsonFile1.json" print(obj) if os.path.exists(jsonFile) == False: print("1123") with open(jsonFile, "w") as savefile: json.dump(obj, savefile) else: with open(jsonFile, "r") as json_file: readObj = json.load(json_file) readObj.update(obj2) print(readObj) with open(jsonFile, "w") as json_file: json.dump(readObj, json_file) ```
Reading of json is answerd by Daniel. To write a json file use `json.dump(jsonDict, outfile)` to save a jsonString `jsonvar = json.dumps(jsonDict)` There are several parameters to use, take a look at the [docs](https://docs.python.org/3/library/json.html)
594,547
I am struggling with when to use "be of", its different meanings and alternatives like "have". I did read another thread on this on this site but still not quite sure. > > These two pictures **are of** 8.5-day-old mouse embryo. ([The Economist](https://www.economist.com/science-and-technology/2022/08/31/mouse-embryoids-can-now-be-grown-from-stem-cells)) > > > > > The theologian Basil the Great reported that the dominant view of hell among the believers he knew **was of** a limited, “purgatorial” suffering. ([NYT](https://www.nytimes.com/2020/01/10/opinion/sunday/christianity-religion-hell-bible.html)) > > > Some definitions say "be of" means: * possess intrinsically; give rise to. "this work is of great interest and value" * indicating a quality or other distinguishing mark by which a person or thing is characterized, identified or described. But both don't seem to fit the meaning in The Economist example on pictures. If we just use "have", do we lose some subtle meaning? For the second example on dominant views of hell, does it mean the views "have a quality/element of purgatorial suffering" or "give rise to purgatorial suffering"?
2022/09/03
[ "https://english.stackexchange.com/questions/594547", "https://english.stackexchange.com", "https://english.stackexchange.com/users/461686/" ]
The first example could be rephrased as > > These two pictures are *pictures* of 8.5-day-old mouse embryo. > > > The additional "pictures" has been dropped. To rephrase the second example similarly I would start by noting that the reference to suffering is a reference to hell, not a reference to a view. I would get > > The theologian Basil the Great reported that the dominant view of hell among the believers he knew was *hell* of a limited, “purgatorial” suffering. > > > This is not quite clear or grammatical, but indicates the believers thought that the suffering of souls in hell would be a limited, purgatorial suffering.
> > These two pictures **are of** 8.5-day-old mouse embryos. > > > You have analysed the sentence wrongly. These two pictures = noun phrase as subject are = copula of =preposition 8.5-day-old mouse embryos = noun phrase as the object of the preposition "of" **Preposition + NP = modifier** In this case, "of 8.5-day-old mouse embryos" is the adjectival complement of "These two pictures." Consider These two pictures **are** 8.5-day-old mouse embryos. -> it is patently obvious that the pictures **are** photographs - they are not mouse embryos. These two pictures **are of** 8.5-day-old mouse embryos. = These two pictures **depict** 8.5-day-old mouse embryos.
7,387,341
In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value. How do I do this in Cocoa, Objective-C ? I didn't find any predefined method for that.
2011/09/12
[ "https://Stackoverflow.com/questions/7387341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882819/" ]
You can call an NSAlert and put the NSTextField as it's accessoryView like this" ``` - (NSString *)input: (NSString *)prompt defaultValue: (NSString *)defaultValue { NSAlert *alert = [NSAlert alertWithMessageText: prompt defaultButton:@"OK" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@""]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:defaultValue]; [input autorelease]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { [input validateEditing]; return [input stringValue]; } else if (button == NSAlertAlternateReturn) { return nil; } else { NSAssert1(NO, @"Invalid input dialog button %d", button); return nil; } } ```
I believe what you are looking for is a sheet. Have a look at the [Sheet Programming Topics](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Sheets/Sheets.html#//apple_ref/doc/uid/10000002-BABFIBIA) documentation I've just updated a [Github Sample](https://github.com/Abizern/JCSSheetController) project on this. You can enter text in a field on the sheet and pass that back to the main window. This example shows how to create a view in a nib and use a custom sheet controller class which uses a block as the callback, rather than having to create and pass in a selector.
7,387,341
In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value. How do I do this in Cocoa, Objective-C ? I didn't find any predefined method for that.
2011/09/12
[ "https://Stackoverflow.com/questions/7387341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882819/" ]
You can call an NSAlert and put the NSTextField as it's accessoryView like this" ``` - (NSString *)input: (NSString *)prompt defaultValue: (NSString *)defaultValue { NSAlert *alert = [NSAlert alertWithMessageText: prompt defaultButton:@"OK" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@""]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:defaultValue]; [input autorelease]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { [input validateEditing]; return [input stringValue]; } else if (button == NSAlertAlternateReturn) { return nil; } else { NSAssert1(NO, @"Invalid input dialog button %d", button); return nil; } } ```
IN OS X 10.10: ``` NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Permission denied, sudo password?"]; [alert addButtonWithTitle:@"Ok"]; [alert addButtonWithTitle:@"Cancel"]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertFirstButtonReturn) { password = [input stringValue]; } else if (button == NSAlertSecondButtonReturn) { } ```
7,387,341
In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value. How do I do this in Cocoa, Objective-C ? I didn't find any predefined method for that.
2011/09/12
[ "https://Stackoverflow.com/questions/7387341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882819/" ]
You can call an NSAlert and put the NSTextField as it's accessoryView like this" ``` - (NSString *)input: (NSString *)prompt defaultValue: (NSString *)defaultValue { NSAlert *alert = [NSAlert alertWithMessageText: prompt defaultButton:@"OK" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@""]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:defaultValue]; [input autorelease]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { [input validateEditing]; return [input stringValue]; } else if (button == NSAlertAlternateReturn) { return nil; } else { NSAssert1(NO, @"Invalid input dialog button %d", button); return nil; } } ```
An example in Swift as of Xcode 7.2.1 and OS X 10.11: ``` let a = NSAlert() a.messageText = "Please enter a value" a.addButtonWithTitle("Save") a.addButtonWithTitle("Cancel") let inputTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24)) inputTextField.placeholderString = "Enter string" a.accessoryView = inputTextField a.beginSheetModalForWindow(self.window!, completionHandler: { (modalResponse) -> Void in if modalResponse == NSAlertFirstButtonReturn { let enteredString = inputTextField.stringValue print("Entered string = \"\(enteredString)\"") } }) ```
7,387,341
In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value. How do I do this in Cocoa, Objective-C ? I didn't find any predefined method for that.
2011/09/12
[ "https://Stackoverflow.com/questions/7387341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882819/" ]
IN OS X 10.10: ``` NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Permission denied, sudo password?"]; [alert addButtonWithTitle:@"Ok"]; [alert addButtonWithTitle:@"Cancel"]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertFirstButtonReturn) { password = [input stringValue]; } else if (button == NSAlertSecondButtonReturn) { } ```
I believe what you are looking for is a sheet. Have a look at the [Sheet Programming Topics](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Sheets/Sheets.html#//apple_ref/doc/uid/10000002-BABFIBIA) documentation I've just updated a [Github Sample](https://github.com/Abizern/JCSSheetController) project on this. You can enter text in a field on the sheet and pass that back to the main window. This example shows how to create a view in a nib and use a custom sheet controller class which uses a block as the callback, rather than having to create and pass in a selector.
7,387,341
In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value. How do I do this in Cocoa, Objective-C ? I didn't find any predefined method for that.
2011/09/12
[ "https://Stackoverflow.com/questions/7387341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882819/" ]
IN OS X 10.10: ``` NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Permission denied, sudo password?"]; [alert addButtonWithTitle:@"Ok"]; [alert addButtonWithTitle:@"Cancel"]; NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertFirstButtonReturn) { password = [input stringValue]; } else if (button == NSAlertSecondButtonReturn) { } ```
An example in Swift as of Xcode 7.2.1 and OS X 10.11: ``` let a = NSAlert() a.messageText = "Please enter a value" a.addButtonWithTitle("Save") a.addButtonWithTitle("Cancel") let inputTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24)) inputTextField.placeholderString = "Enter string" a.accessoryView = inputTextField a.beginSheetModalForWindow(self.window!, completionHandler: { (modalResponse) -> Void in if modalResponse == NSAlertFirstButtonReturn { let enteredString = inputTextField.stringValue print("Entered string = \"\(enteredString)\"") } }) ```
6,480,719
I have an e-mail field which is -not- required in my form validation. It should be able to be left blank. However, when I use the "valid\_email" parameter of the form validation's set\_rules, it still gives an error message that the e-mail is not valid when it's not supposed to check this if the field has not been filled out.
2011/06/25
[ "https://Stackoverflow.com/questions/6480719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815703/" ]
**Rule Reference** Checking the [reference](http://codeigniter.com/user_guide/libraries/form_validation.html#rulereference) on this matter tells us the following regarding the `valid email` rule: > > Returns FALSE if the form element does not contain a valid email address. > > > This would be true of an empty field, as well as a field with bad values. **Trimming** I notice in the examples provided by CodeIgniter that emails are usually not only required, and required to be valid emails, but are also trimmed. This may result in a different outcome. ``` $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); ``` During the validation process, the following is considered: ``` // If the field is blank, but NOT required, no further tests are necessary if ( ! in_array('required', $rules) AND is_null($postdata)) ``` It may be the case that the contents of your email field aren't exactly *null*, and are therefore raising flags with the `valid_email` requirement. **Possible Related Bugs** Three months prior to the date of this answer there was discussion on bitbucket regarding this very topic. The discussion can be viewed at <https://bitbucket.org/ellislab/codeigniter-reactor/issue/117/input-fields-are-automatically-required>. It's stated that using array-syntax (see below) in the markup results in similar errors even when the `required` rule is not set: ``` <input name="user[email]" /> ``` Further discussion, and patches, are available here, [http://codeigniter.com/forums/viewthread/159243](http://web.archive.org/web/20120530001055/http://codeigniter.com/forums/viewthread/159243). One suggest patch that seems to solve the issue is to replace the `is_null()` call with `empty()` in the aforementioned code: So the following: ``` if ( ! in_array('required', $rules) AND is_null($postdata)) ``` Becomes: ``` if ( ! in_array('required', $rules) AND empty($postdata)) ```
You just have to appreciate that `''` IS not a valid e-mail address. If you don't want to validate some postdata and don't care if it's empty, you shouldn't set a rule on it, like so: ``` if($this->input->post('item')) { $this->form_validation->set_rules('item', 'Item number', 'trim|alpha_numeric|max_length[30]'); } ``` In this case, if there is nothing submitted for 'item', no rule is added, so the rest of the data would go on to validation stage etc. as normal.
6,480,719
I have an e-mail field which is -not- required in my form validation. It should be able to be left blank. However, when I use the "valid\_email" parameter of the form validation's set\_rules, it still gives an error message that the e-mail is not valid when it's not supposed to check this if the field has not been filled out.
2011/06/25
[ "https://Stackoverflow.com/questions/6480719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815703/" ]
according to <https://codeigniter.com/user_guide/libraries/validation.html?highlight=validation#id28> use `permit_empty` this > > Allows the field to receive an empty array, empty string, null or > false > > > so your code looks like this: ``` $this->form_validation->set_rules('email', 'Email', 'permit_empty|valid_email'); ```
You just have to appreciate that `''` IS not a valid e-mail address. If you don't want to validate some postdata and don't care if it's empty, you shouldn't set a rule on it, like so: ``` if($this->input->post('item')) { $this->form_validation->set_rules('item', 'Item number', 'trim|alpha_numeric|max_length[30]'); } ``` In this case, if there is nothing submitted for 'item', no rule is added, so the rest of the data would go on to validation stage etc. as normal.
25,159,172
i have an application like timer in IOS. In the first screen i have button when i am click on it the timer is start and after some amount of time say 30 seconds i have run my application then i am stop my application (not in background) , i am terminating the application. I reopen my application after the timer shows 1 min, that is working fine but when i am changing the device system time then the timer shows different time. ``` NSTimeInterval oldTimeInterval = [[NSUserDefaults standardUserDefaults] doubleForKey:PunchInTimeWhenGoneBackgroundKEY]; NSTimeInterval currentTimeInterval = [[NSDate date] timeIntervalSince1970]; //if(currentTimeInterval>oldTimeInterval) //{} WORKING_TIME = WORKING_TIME + (currentTimeInterval - oldTimeInterval) + 1; if(timerWorkTime!=nil) { [timerWorkTime invalidate]; timerWorkTime = nil; } timerWorkTime = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(funCalculateWorkingTime) userInfo:nil repeats:YES]; -(void)funCalculateWorkingTime { WORKING_TIME++; workingHour = (int) WORKING_TIME / 3600; WorkingMin = (int) WORKING_TIME / 60; WorkingSecond = (int) WORKING_TIME % 60; lblWorkingTime.text = [NSString stringWithFormat:@"%.2d : %.2d : %.2d",workingHour,WorkingMin,WorkingSecond]; earnedMoney = ((float)WORKING_TIME * HOURLY_RATE)/3600.0; lblTotalEarned.text = [NSString stringWithFormat:@"$%.2f",earnedMoney]; // NSLog(@"time : %@",lblWorkingTime.text); } ``` Please do help me. Thanks in advance.
2014/08/06
[ "https://Stackoverflow.com/questions/25159172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3914085/" ]
This is standard behaviour for sans-serif fonts I believe. The glyph has extra 'room' around it for ascender/decenders/serifs AFAIK. [Codepen.io example](http://codepen.io/Paulie-D/pen/fCdsl) **HTML** ``` <h1>Decent Test</h1> <h1 class="serif" >Decent Test</h1> ``` **CSS** ``` * { margin: 0; padding: 0; } h1 { font-size: 100px; font-family:sans-serif; word-spacing: 1px; padding:0; margin:0; background: pink; margin: 50px; } h1.serif { font-family: serif; } ```
Update your CSS like below. Hopefully it will fix the issue. ``` body, html{margin:0; padding:0} h2 { font-size: 5.2em; font-family: UniSans; word-spacing: 1px; margin:0px; padding:0px; } ``` [**DEMO**](http://jsfiddle.net/LB2N5/7/)
25,159,172
i have an application like timer in IOS. In the first screen i have button when i am click on it the timer is start and after some amount of time say 30 seconds i have run my application then i am stop my application (not in background) , i am terminating the application. I reopen my application after the timer shows 1 min, that is working fine but when i am changing the device system time then the timer shows different time. ``` NSTimeInterval oldTimeInterval = [[NSUserDefaults standardUserDefaults] doubleForKey:PunchInTimeWhenGoneBackgroundKEY]; NSTimeInterval currentTimeInterval = [[NSDate date] timeIntervalSince1970]; //if(currentTimeInterval>oldTimeInterval) //{} WORKING_TIME = WORKING_TIME + (currentTimeInterval - oldTimeInterval) + 1; if(timerWorkTime!=nil) { [timerWorkTime invalidate]; timerWorkTime = nil; } timerWorkTime = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(funCalculateWorkingTime) userInfo:nil repeats:YES]; -(void)funCalculateWorkingTime { WORKING_TIME++; workingHour = (int) WORKING_TIME / 3600; WorkingMin = (int) WORKING_TIME / 60; WorkingSecond = (int) WORKING_TIME % 60; lblWorkingTime.text = [NSString stringWithFormat:@"%.2d : %.2d : %.2d",workingHour,WorkingMin,WorkingSecond]; earnedMoney = ((float)WORKING_TIME * HOURLY_RATE)/3600.0; lblTotalEarned.text = [NSString stringWithFormat:@"$%.2f",earnedMoney]; // NSLog(@"time : %@",lblWorkingTime.text); } ``` Please do help me. Thanks in advance.
2014/08/06
[ "https://Stackoverflow.com/questions/25159172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3914085/" ]
This is standard behaviour for sans-serif fonts I believe. The glyph has extra 'room' around it for ascender/decenders/serifs AFAIK. [Codepen.io example](http://codepen.io/Paulie-D/pen/fCdsl) **HTML** ``` <h1>Decent Test</h1> <h1 class="serif" >Decent Test</h1> ``` **CSS** ``` * { margin: 0; padding: 0; } h1 { font-size: 100px; font-family:sans-serif; word-spacing: 1px; padding:0; margin:0; background: pink; margin: 50px; } h1.serif { font-family: serif; } ```
You need to add `margin:0` to your `body` and to your `h2` Example : <http://jsfiddle.net/LB2N5/3/>
25,159,172
i have an application like timer in IOS. In the first screen i have button when i am click on it the timer is start and after some amount of time say 30 seconds i have run my application then i am stop my application (not in background) , i am terminating the application. I reopen my application after the timer shows 1 min, that is working fine but when i am changing the device system time then the timer shows different time. ``` NSTimeInterval oldTimeInterval = [[NSUserDefaults standardUserDefaults] doubleForKey:PunchInTimeWhenGoneBackgroundKEY]; NSTimeInterval currentTimeInterval = [[NSDate date] timeIntervalSince1970]; //if(currentTimeInterval>oldTimeInterval) //{} WORKING_TIME = WORKING_TIME + (currentTimeInterval - oldTimeInterval) + 1; if(timerWorkTime!=nil) { [timerWorkTime invalidate]; timerWorkTime = nil; } timerWorkTime = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(funCalculateWorkingTime) userInfo:nil repeats:YES]; -(void)funCalculateWorkingTime { WORKING_TIME++; workingHour = (int) WORKING_TIME / 3600; WorkingMin = (int) WORKING_TIME / 60; WorkingSecond = (int) WORKING_TIME % 60; lblWorkingTime.text = [NSString stringWithFormat:@"%.2d : %.2d : %.2d",workingHour,WorkingMin,WorkingSecond]; earnedMoney = ((float)WORKING_TIME * HOURLY_RATE)/3600.0; lblTotalEarned.text = [NSString stringWithFormat:@"$%.2f",earnedMoney]; // NSLog(@"time : %@",lblWorkingTime.text); } ``` Please do help me. Thanks in advance.
2014/08/06
[ "https://Stackoverflow.com/questions/25159172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3914085/" ]
This is standard behaviour for sans-serif fonts I believe. The glyph has extra 'room' around it for ascender/decenders/serifs AFAIK. [Codepen.io example](http://codepen.io/Paulie-D/pen/fCdsl) **HTML** ``` <h1>Decent Test</h1> <h1 class="serif" >Decent Test</h1> ``` **CSS** ``` * { margin: 0; padding: 0; } h1 { font-size: 100px; font-family:sans-serif; word-spacing: 1px; padding:0; margin:0; background: pink; margin: 50px; } h1.serif { font-family: serif; } ```
Just try to make the margin negative on your element like with -2px, you can adjust it to your Situation.
19,658,394
I am adding calendar with jQuery Here is my jQuery code of calendar ``` $(function() { $( "#dob" ).datepicker(); } ); ``` but the next and previous button cannot be seen in user interface. please suggest me wher do i have mistaken. you can check here - <http://screencast.com/t/idXD2qYlgk> please help
2013/10/29
[ "https://Stackoverflow.com/questions/19658394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656761/" ]
try adding the css , js like this and check once.. ``` <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> ```
**Try inspecting with firebug** the prev and next buttons might me there but as the sprite image is not loaded properly you the buttons are not visible. This type of problems occurs commonly but are simple to be solved !
27,222,988
I write a click hander like this; ``` $("#button1").click(function(evntData) { alert("button1 clicked."); }); ``` to invoke it immediately I do like this; ``` $("#button1").click(function(evntData) { alert("button1 clicked."); }(null)); ``` in this way it is called on start up and work fine. but later when button is clicked this event handler is not called. How can I do it? Thanks
2014/12/01
[ "https://Stackoverflow.com/questions/27222988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1651158/" ]
try this, Don't use to long multidimentional array directly in query, Use like this save in varialbe then use it, and other also care full for SQL injection, and also u have missed the comma before **NOW()** at the end of query. ``` <?php ini_set('display_errors', 1); //Adjust error reporting: error_reporting(E_ALL | E_STRICT); include('includes/session_config.inc'); require ('mysqli_connect.php'); $from_first = mysql_real_escape_string($_SESSION['postcard']['from_first']); $from_last = mysql_real_escape_string($_SESSION['postcard']['from_last']); $from_email = mysql_real_escape_string($_SESSION['postcard']['from_email']); $to_first = mysql_real_escape_string($_SESSION['postcard']['to_first']); $to_last = mysql_real_escape_string($_SESSION['postcard']['to_last']); $to_email = mysql_real_escape_string($_SESSION['postcard']['to_email']); $subject = mysql_real_escape_string($_SESSION['postcard']['subject']); $message = mysql_real_escape_string($_SESSION['postcard']['message']); $image = mysql_real_escape_string($_SESSION['postcard']['image']); $identifier = mysql_real_escape_string($_SESSION['postcard']['identifier']); $q = "INSERT INTO cards (sender_last, sender_first, sender_email, recipient_last, recepient_first, recepient_email, subject, message, image, identifier, date_entered ) VALUES ($from_first, $from_last, $from_email, $to_first, $to_last, $to_email, $subject, $message, $image, $identifier, NOW() )"; ```
Your values are strings, but you have only ending `'`: `VALUES ($_SESSION...', $_SESSION...'`, replace it with `VALUES ('{$_SESSION...}', '{$_SESSION...}'`. Also missing `,` before `NOW()` in values list
17,526,454
I have an HTML page that contains English words and Persian words. I want to know how can I detect English words and change the color of them, and detect Persian words and change the color of them to a different color. These words are dynamic and can be changed. I want to detect them by jQuery or JavaScript and change the colors. For example, given this text: ``` Hi سلام بر this این text can be برای اولین ... ``` I want to show these words in red: ``` Hi, This, Text, can, be, ``` and these words in blue: ``` بر, سلام, این, برای, اولین ```
2013/07/08
[ "https://Stackoverflow.com/questions/17526454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/737947/" ]
What about using the char code? English letters are within the first 255 chars but Persian letters aren't. html ``` <p>Hi سلام بر this این text can be برای اولین.</p> ``` javascript ``` jQuery(function($) { $("p").each(function(){ this.innerHTML = $(this).text().replace(/\S+/g, function (word) { var span = document.createElement("span"); span.className = "word "; span.className += isEnglish(word) ? 'english' : ''; span.className += isPersian(word) ? 'persian' : ''; span.appendChild(document.createTextNode(word)); return span.outerHTML; }); }); function isEnglish(word){ return word.charCodeAt(0) < 255; } function isPersian(word){ return word.charCodeAt(0) > 255; } }); ``` `[jsFiddle](http://jsfiddle.net/sWpgg/5/)`
> > or can you provide me an example? > > > Well OK: ``` // Find text in descendents of an element, in reverse document order // pattern must be a regexp with global flag // function findText(element, pattern, callback) { var nonHtmlTags= {textarea:1, option:1, script:1, style:1, svg:1, math:1}; for (var childi= element.childNodes.length; childi-->0;) { var child= element.childNodes[childi]; if (child.nodeType==1 && !(child.tagName in nonHtmlTags)) { findText(child, pattern, callback); } else if (child.nodeType==3) { var matches= []; var match; while (match= pattern.exec(child.data)) matches.push(match); for (var i= matches.length; i-->0;) callback.call(window, child, matches[i]); } } } // Find text and wrap with span elements // function highlightText(element, pattern, className) { findText(document.body, pattern, function(node, match) { var span= document.createElement('span'); span.className= className; node.splitText(match.index+match[0].length); span.appendChild(node.splitText(match.index)); node.parentNode.insertBefore(span, node.nextSibling); }); } highlightText(document.body, /[a-z]+/gi, 'english-word'); highlightText(document.body, /[\u0600-\u06FF]+/gi, 'persian-word'); ``` Note the English and Persian regexps are very naïve and will fail for unusual characters, like Latin `ï` or Arabic [`﷽`](http://www.decodeunicode.org/u+FDFD). Coming up with a more complete expression is left as an exercise for the abecedarian.
43,308,854
I would like to remove second `<p>` node and its content from: ``` <div> <p>1<div>D</div></p> <p>2</p> </div> ``` Checked [children](http://mojolicious.org/perldoc/Mojo/DOM#children) method, but it also returns all descending nodes, while I would like to get first level `<p>` nodes. ``` perl -Mojo -E' say for @{ x(" <div> <p>1<div>D</div></p> <p>2</p> </div> ")->at("div")->children } ' ``` output ``` <p>1</p> <div>D</div> <p>2</p> ```
2017/04/09
[ "https://Stackoverflow.com/questions/43308854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223226/" ]
You probably want: ``` perl -Mojo -E' say for @{ x(" <div> <p>1<div>D</div></p> <p>2</p> </div> ")->find("div > p")} ' ``` output ``` <p>1</p> <p>2</p> ``` But i'm unsure that this is what do you want..
> > Checked `children` method, but it also returns all descending nodes > > > The example you show tries to parse invalid HTML, which has an illegal `<div>` element inside a `<p>` paragraph. The parser solves this by moving the closing `</p>` to before the opening `<div>`, which is pretty much what a real browser would do. So the call to `children` is correctly finding all three children of the top-level `<div>`, not all descendants as you surmised ``` use strict; use warnings 'all'; use feature 'say'; use Mojo::DOM; say Mojo::DOM->new(<<END)->at('div'); <div> <p>1<div>D</div></p> <p>2</p> </div> END ``` ### output ``` <div> <p>1</p><div>D</div> <p>2</p> </div> ``` But you don't need it to remove the first child `<p>` element of a `<body>` element. That would look like this ``` $dom->at('body > p')->remove ``` To remove the *second* `<p>` child of a `<div>` would look like this ``` $dom->find('div > p')->[1]->remove ``` but the `<div>` element really needs a better specification
20,274
My friends' cat recently gave birth however it was later revealed that the father was the cats' son. My friend offered to let me adopt one of the kittens but I am worried that the kitten I adopt will end up having something wrong with it due to the inbreeding. My question is: **How harmful is inbreeding among cats?**
2018/05/01
[ "https://pets.stackexchange.com/questions/20274", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/11982/" ]
To answer this question, we first need to understand how incest is bad exactly. This has everything to do with genes and chromosomes. When producing offspring, a mix of the genes of the two parents is combined in the offspring. This is a random process, which is why siblings can be wildly different from eachother. Normally, both parents are unrelated, so their genes have at least some differences, creating a new combination of genes. When siblings produce offspring, however, their offspring's genes are practically draws from the same genepool. This means that there is a chance that the offspring gets two identical genes . If both mom and dad got geneA from their father, the offspring could end up with two A genes. This is where problems might occur. Small defects in genes happen all the time, and generally they are caught because of redundancy. Cats have two copies of each gene after all. In most cases, only if both versions are defect, problems arise. If both genes are identical, we will be certain that these defects will propagate. ### However: The biggest reason animals are biologically programmed to prevent incest is because incest is a evolutionary disadvantage in the long run. Most of the damage done by incest doesn't happen in the first generation. However, continuous incest, generation on generation, will enhance the effect I described above time and time again. There are many animals, especially those kept and bred as pets, that suffer an enormous amount of inbreeding. A big example are purebred dogs. Without any new genes joining the pool, the entire population of such a breed will eventually start looking incestuous. But this is on a population level. For a population of animals, incest only becomes a problem after many generations. ### Individual So how does this compare with your kitten? Let's look at the possibilities: Let's assume your cat's parents have disjoint genes: Mom has AB, dad has CD. Their offspring have four possible sets: AC, AD, BC, BD. The father of your kitten has a 1/4 chance for any of those combinations. Each of those combinations, the father shares one gene with the mom. Either A or B. These is a 1/2 chance for the father to pass on the shared gene, and there is a 1/2 chance for the mom to do so. So in the end, there is a 1/4 chance for a duplicated gene. That's pretty high, especially since this probability applies to each of the cats genes individually, so the chance for *any* duplicates is near 1, but the chance for *all* duplicates is not so high at all. How harmful is this? Unless there were already genetic defects in the family tree of the parents, I wouldn't worry too much. However, it doesn't hurt to sterilize the kitten, to prevent it from getting offspring of itself. Since that is the population effect starting to weigh in.
**Inbreeding** Inbreeding can be a problem, but in this case it probably isn't because it's only one time. (that you know of) And non-breed cats have overall less health problems. Breeders use [inbreeding](http://animals.mom.me/problems-with-inbreeding-cats-5105419.html) quite a bit to fix traits. But it can have very dangerous side effect for the health of a cat. But genetic defects need to pile up for that to happen. Do check for health before adopting: does it walk / jump / behave like a kitten that age should? And if it has problems, are you ready to pick up the bill for that? (12 weeks of age for adoption is ideal) --- **Cats with defects** Even if you have a kitten with a noticeable defect, genetic or not, it can still be a good pet. In that case you will still want a cat that can take care of itself in these ways: litter trained, eating and drinking and simple coat cleaning. I know of one cat that really has some issues, but it can eat, drink and keep itself clean. It has severe movement issues and can't hunt but it still is fun pet to have around. If you do adopt a cat with genetic defects, please do neuter them.
40,037,424
I have installed node.js along with npm module manager. I have created a package.json file and from the root directory I am trying to execute `npm install` command but I am getting `npm WARN package.json` project name (in my case it is `NodejsDemo`) `@0.0.0 No repository field`.
2016/10/14
[ "https://Stackoverflow.com/questions/40037424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5520013/" ]
From [using a package.json](https://docs.npmjs.com/getting-started/using-a-package.json) > > * As a bare minimum, a package.json must have: > + "name" > - all lowercase > > > Try lowercase name like nodejsdemo and you should add repository like ``` "repository": { "type": "git", "url": "git://git_repo_link_here" } ``` but it's only warning and it doesn't affect on installation.
If you want to create `package.json` file manually then use ``` `npm init` ``` command to create your `package.json` file > > Do this command in your root folder > > > It will ask to give some information during creation. After creating file, you can use it. and if you want to save your new modules in your package.json just do like this for example install `async module` > > npm install async --save > > > and async module name with version will appear in your package.json file
253,036
I want to shorten ``` sudo http_proxy="http://proxy:port" apt-get ______ ``` to ``` sudo rep apt-get ________ ``` Is this possible to implement in Ubuntu? ### EDIT: So I added ``` alias rapt-get="http_proxy="10.1.1.26:8080" apt-get" ``` to my `~/.bash_aliases`. I have other working aliases in this file. If I type rapt-get in the terminal, I get: ``` apt 0.8.16~exp12ubuntu10 for amd64 compiled on Apr 20 2012 10:19:39 Usage: apt-get [options] command apt-get [options] install|remove pkg1 [pkg2 ...] apt-get [options] source pkg1 [pkg2 ...] ``` `apt-get` is a simple command line interface for downloading and installing packages. The most frequently used commands are update and install. ### Commands: ``` update - Retrieve new lists of packages upgrade - Perform an upgrade install - Install new packages (pkg is libc6 not libc6.deb) remove - Remove packages autoremove - Remove automatically all unused packages purge - Remove packages and config files source - Download source archives build-dep - Configure build-dependencies for source packages dist-upgrade - Distribution upgrade, see apt-get(8) dselect-upgrade - Follow dselect selections clean - Erase downloaded archive files autoclean - Erase old downloaded archive files check - Verify that there are no broken dependencies changelog - Download and display the changelog for the given package download - Download the binary package into the current directory ``` ### Options: ``` -h This help text. -q Loggable output - no progress indicator -qq No output except for errors -d Download only - do NOT install or unpack archives -s No-act. Perform ordering simulation -y Assume Yes to all queries and do not prompt -f Attempt to correct a system with broken dependencies in place -m Attempt to continue if archives are unlocatable -u Show a list of upgraded packages as well -b Build the source package after fetching it -V Show verbose version numbers -c=? Read this configuration file -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp See the apt-get(8), sources.list(5) and apt.conf(5) manual pages for more information and options. This APT has Super Cow Powers. Seems to be working. But if i type `sudo rapt-get update`, I get sudo: rapt-get: command not found ``` (Sorry for the formatting issues, I'm on through mobile and can't see the formatting bar)
2013/02/09
[ "https://askubuntu.com/questions/253036", "https://askubuntu.com", "https://askubuntu.com/users/129716/" ]
You can also make an sh script that reads input, inserts it into the command and runs it. I would upload a file like that for you, but I do not have access to my computer.
`~/.bashrc` adds aliases for you, and only you `sudo` runs as root. Even though you may have administrator access, your user is not root. So, add your alias to `~root/.bashrc` (generally this is `/root/.bashrc`). If you'd like to add this alias for all users, add it to `/etc/profile`