qid
int64 10
74.7M
| question
stringlengths 15
26.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 27
28.1k
| response_k
stringlengths 23
26.8k
|
---|---|---|---|---|---|
1,815,716 | I wondering if it's possible to get the MatchData generated from the matching regular expression in the grammar below.
```
object DateParser extends JavaTokenParsers {
....
val dateLiteral = """(\d{4}[-/])?(\d\d[-/])?(\d\d)""".r ^^ {
... get MatchData
}
}
```
One option of course is to perform the match again inside the block, but since the RegexParser has already performed the match I'm hoping that it passes the MatchData to the block, or stores it? | 2009/11/29 | [
"https://Stackoverflow.com/questions/1815716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16744/"
] | No, you can't do this. If you look at the definition of the Parser used when you convert a regex to a Parser, it throws away all context and just returns the full matched string:
<http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_7_final/src/library/scala/util/parsing/combinator/RegexParsers.scala?view=markup#L55>
You have a couple of other options, though:
* break up your parser into several smaller parsers (for the tokens you actually want to extract)
* define a custom parser that extracts the values you want and returns a domain object instead of a string
The first would look like
```
val separator = "-" | "/"
val year = ("""\d{4}"""r) <~ separator
val month = ("""\d\d"""r) <~ separator
val day = """\d\d"""r
val date = ((year?) ~ (month?) ~ day) map {
case year ~ month ~ day =>
(year.getOrElse("2009"), month.getOrElse("11"), day)
}
```
The `<~` means "require these two tokens together, but only give me the result of the first one.
The `~` means "require these two tokens together and tie them together in a pattern-matchable ~ object.
The `?` means that the parser is optional and will return an Option.
The `.getOrElse` bit provides a default value for when the parser didn't define a value. | When a Regex is used in a RegexParsers instance, the **implicit def regex(Regex): Parser[String]** in RegexParsers is used to appoly that Regex to the input. The Match instance yielded upon successful application of the RE at the current input is used to construct a Success in the regex() method, but only its "end" value is used, so any captured sub-matches are discarded by the time that method returns.
As it stands (in the 2.7 source I looked at), you're out of luck, I believe. |
6,693,282 | I have an application that allows the users to delete video files. When I press the delete button, I am using
```
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// mycode........
break;
case DialogInterface.BUTTON_NEGATIVE:
// mycode.....
break;
}
}
};
```
But this message doesn't have a warning or delete icon as we see in android devices. Can anyone help me in getting those icons or using any other alert dialogs that can show those icons? | 2011/07/14 | [
"https://Stackoverflow.com/questions/6693282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/833590/"
] | I tend to use AlertDialog.Builder like they show in the official doc example
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
//Set your icon here
.setTitle("Alert!")
.setIcon(R.drawable.icon);
AlertDialog alert = builder.create();
alert.show();//showing the dialog
```
As for the actual icon look inside your sdk folder/platforms/android version #/data/res/drawable-mdpi or something | Another (dirty) way:
```
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true);
new AlertDialog.Builder(this)
.setIcon(typedValue.resourceId)
...
.show();
``` |
9,743,513 | I am reading "Effective Java" by Joshua Bloch, item 39 make defensive copy, and I have some questions. I always use the following construct:
```
MyObject.getSomeRef().setSomething(somevalue);
```
which is short for:
```
SomeRef s = MyClass.getSomeRef();
s.setSomething();
MyObject.setSomeRef(s);
```
It always works, but I guess if my `getSomeRef()` was returning a copy then my shortcut would not work, how can I know if the implementation of `MyObject` is hidden if it is safe to use a shortcut or not? | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260847/"
] | Defensive copy is a good idea, but you need to understand when and where it gets used. If the web of objects you are manipulating is internal, and it not intended to be thread safe, then the defensive copying is being mis-applied.
On the other hand, if this is web of objects that are getting exposed publicly, then you are at risk of violating [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter). If so, consider exposing a manipulator API on your `myObject`.
As a sidenote, your code sample made the `getSomeRef` look like a static API. I would suggest that you name any static API that returns a copy of some singleton accordingly (e.g. `copyOfSomething()`). Similarly for a static factory method. | I would suggest defining a `readableThing` interface or class, and deriving from it `mutableThing` and `immutableThing` interfaces. A property getter should return one of those interfaces based upon the returned item's relation to the list:
1. It should return a mutableThing if the thing may be safely modified in such a fashion that changes will be stored to the underlying list.
- It should return an readableThing if the recipient of the object cannot use it to modify the collection, but there's a possibility that future operations with the collection might affect the object.
- It should return an immutableThing if it can guarantee that the object in question will never change.
- If the intended outcome of the method is for the caller to have a mutable thing which is initialized with data from the collection, but which is not attached ot it, I would suggest having the method which accepts a mutableThing from the caller and sets up its fields appropriately. Note that such usage would make clear to anyone reading the code that the object was not attached to the collection. One could also have a helper GetMutableCopyOfThing method.
It's too bad Java doesn't inherently do a better job of indicating declaratively who "owns" various objects. Before the days of GC frameworks, it was annoying having to keep track of who owned all objects, whether they were mutable or not. Since immutable objects often have no natural owner, tracking ownership of immutable objects was a major hassle. Generally, however, any object `Foo` with state that can be mutated should have exactly one owner which regards mutable aspects of `Foo`'s state as being parts of its own state. For example, an `ArrayList` is the owner of an array which holds the list items. One is unlikely to write bug-free programs using mutable objects if one doesn't keep track of who owns them (or at least their mutable aspects). |
42,521,722 | I'm having some issues which I'm guessing are related to self-referencing using .NET Core Web API and Entity Framework Core. My Web API starting choking when I added .Includes for some navigation properties.
I found what appears to be a solution in the older Web API but I don't know how to implement the same thing for .NET Core Web API (I'm still in the early learning stages).
The older solution was sticking this in the Application\_Start() of the Global.asax:
```
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
```
I suspect this is handled in the StartUp's ConfigureService() method but I don't know much beyond there.
Or is there a more appropriate way to handle this issue? | 2017/03/01 | [
"https://Stackoverflow.com/questions/42521722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42620/"
] | ReferenceLoopHandling.Ignore “hides” the problem, not solves it. What you really need to be doing is building layers. Create domain objects to sit on top of your entities and wrap them in some sort of service/business layer. Look up the repository pattern and apply that if it helps. You’ll need to map between your entities and domain objects, and this gives you the chance to fit in some sort of mapper (automapper) and validation layer..
If your domain objects and entities are exactly the same, then you need to think more about what your doing.
For example: Do your entities have soft deletes? (IsDeleted) flag? If so, this doesn’t necessarily need to go back to the client over the web, so that’s a perfect example of where they would be different.
Either way, the answer is not to override it in JSON, it’s to change your architecture.. | If you have a `Minimal API` this will be useful:
```
using System.Text.Json.Serialization;
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt =>
{
opt.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
``` |
31,459,619 | I triggered the external .js function using $.getScript, after it's done, i am loading the content to 'div' element ('Result'). So after everything is done, i would like to perform other function like say for example alert the downloaded content (eg: #items). But, when i do alert, i don't think the whole content is yet downloaded, so it's not giving me the fully downloaded content. How can i achieve it?
```
$.getScript( "../js/script.js" )
.done(function( script, textStatus ) {
load(function(){
$('Result').html();
});
alert($('#items').html());
})
.fail(function( jqxhr, settings, exception ) {
alert( "Triggered ajaxError handler." );
});
function load(callback)
{
$("#Result").load("/somepage.aspx", function (response, status, xhr){
if ( status == "error" ) {
var msg = "error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
if(callback){
callback();
}
});
};
<div id="Result"></div>
<div id="error"></div>
``` | 2015/07/16 | [
"https://Stackoverflow.com/questions/31459619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4976920/"
] | I'm not sure your code is in right way, because you get the `js`, but on `done`, you give the html of `#result`, then alert html of `#item`! this doesn't makes any sense to me. Also what is job of `load` function that you wrote below the `$.getScript`?
**Update**
So, you made some update, I think you want to fetch one page, without any postback, isn't it? | So, after some chat, here is my solution, hope this help:
I made 2 `.html` files, `a.html` and `b.html`.
Content of `a.html`:
```
<div></div>
<script>
$.getScript("main.js", function() {
$("div").load("b.html #items");
});
</script>
```
And `b.html`:
```
<body>
<script src="main.js"></script>
</body>
```
Also content of `main.js` file:
```
$('<div></div>', {
text: 'I am alive !!!',
id: '#items'
}).appendTo('body');
```
and when I open the `a.html`, I can see `I am alive !!!`.
**Edit**:
Please note, I didn't add link of `main.js` to `a.html`.
**UPDATE**, same result with this code:
```
$.getScript("main.js").done(function() {
load();
}).fail(function(jqxhr, settings, exception) {
alert("Triggered ajaxError handler.");
});
function load() {
$("#Result").load("b.html #items", function(response, status, xhr) {
if (status == "error") {
var msg = "error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
};
``` |
51,391,193 | Is there any way that the chronometer can be paused if a method is true. I have created a simple jigsaw puzzle and added a chronometer to show the time elapse and I'm trying to stop the timer when the puzzle is Solved.On running, the application runs smoothly, with the chronometer ticking but not stopping when the game is solved. Any sort of help will be appreciated.
Here is the code;
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
chronometer = findViewById(R.id.chronometer);
stopChronometer();
startChronometer();
isSolved();
}
public static boolean isSolved() {
boolean solved = false;
for (int i = 0; i < tileList.length; i++) {
if (tileList[i].equals(String.valueOf(i))) {
solved = true;
} else {
solved = false;
break;
}
}
return solved;
}
//to start the chronometer
public void startChronometer(){
if(!running){
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running = true;
}
}
//to stop the chronometer
public void stopChronometer(){
if(running && isSolved()){
chronometer.stop();
running =false;
}
}
```
If interested in the whole code;
```
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import java.lang.*;
import java.util.ArrayList;
import java.util.Random;
import android.widget.Chronometer;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//GestureDetectView* is the class where the puzzle grid is setup
private static GestureDetectGridView mGridView;
private static final int COLUMNS =3;
private static final int DIMENSIONS = COLUMNS * COLUMNS;
private static int mColumnWidth, mColumnHeight;
//up, down, left, right are tile movements
public static final String up = "up";
public static final String down = "down";
public static final String left = "left";
public static final String right = "right";
private static String[] tileList;
private Chronometer chronometer;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.chronometer);
init();
scramble();
setDimensions();
stopChronometer();
startChronometer();
}
//to start the chronometer
public void startChronometer(){
if(!running){
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running = true;
}
}
//to stop the chronometer * PROBLEM AREA
public void stopChronometer(){
if(running && isSolved()){
chronometer.stop();
running =false;
}
}
//Grid view from GestureDetectView class
private void init() {
mGridView = (GestureDetectGridView) findViewById(R.id.grid);
mGridView.setNumColumns(COLUMNS);
tileList = new String[DIMENSIONS];
for (int i = 0; i < DIMENSIONS; i++) {
tileList[i] = String.valueOf(i);
}
}
//To shuffle the grid pieces
private void scramble() {
int index;
String temp;
Random random = new Random();
for (int i = tileList.length -1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = tileList[index];
tileList[index] = tileList[i];
tileList[i] = temp;
}
}
private void setDimensions() {
ViewTreeObserver vto = mGridView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int displayWidth = mGridView.getMeasuredWidth();
int displayHeight = mGridView.getMeasuredHeight();
int statusbarHeight = getStatusBarHeight(getApplicationContext());
int requiredHeight = displayHeight - statusbarHeight;
mColumnWidth = displayWidth / COLUMNS;
mColumnHeight = requiredHeight / COLUMNS;
display(getApplicationContext());
}
});
}
private int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
"android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
//To determine if puzzle is solved
public static boolean isSolved() {
boolean solved = false;
for (int i = 0; i < tileList.length; i++)
{
if (tileList[i].equals(String.valueOf(i))) {
solved = true;
} else {
solved = false;
break;
}
}
return solved;
}
private static void swap(Context context, int Position, int swap) {
String newPosition = tileList[Position + swap];
tileList[Position + swap] = tileList[Position];
tileList[Position] = newPosition;
display(context);
if (isSolved()) {
Toast.makeText(context, "CONGRATULATIONS, YOU WIN!", Toast.LENGTH_SHORT).show();
}
}
//To source the image pieces and add them to the puzzle grid
private static void display(Context context) {
ArrayList<Button> buttons = new ArrayList<>();
Button button;
for (int i = 0; i < tileList.length; i++) {
button = new Button(context);
if (tileList[i].equals("0"))
button.setBackgroundResource(R.drawable.piece1);
else if (tileList[i].equals("1"))
button.setBackgroundResource(R.drawable.piece2);
else if (tileList[i].equals("2"))
button.setBackgroundResource(R.drawable.piece3);
else if (tileList[i].equals("3"))
button.setBackgroundResource(R.drawable.piece4);
else if (tileList[i].equals("4"))
button.setBackgroundResource(R.drawable.piece5);
else if (tileList[i].equals("5"))
button.setBackgroundResource(R.drawable.piece6);
else if (tileList[i].equals("6"))
button.setBackgroundResource(R.drawable.piece7);
else if (tileList[i].equals("7"))
button.setBackgroundResource(R.drawable.piece8);
else if (tileList[i].equals("8"))
button.setBackgroundResource(R.drawable.piece9);
buttons.add(button);
}
mGridView.setAdapter(new CustomAdapter(buttons, mColumnWidth, mColumnHeight));
}
public static void moveTiles(Context context, String direction, int position) {
// Upper-left-corner tile
if (position == 0) {
if (direction.equals(right)) swap(context, position, 1);
else if (direction.equals(down)) swap(context, position, COLUMNS);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Upper-center tiles
} else if (position > 0 && position < COLUMNS - 1) {
if (direction.equals(left)) swap(context, position, -1);
else if (direction.equals(down)) swap(context, position, COLUMNS);
else if (direction.equals(right)) swap(context, position, 1);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Upper-right-corner tile
} else if (position == COLUMNS - 1) {
if (direction.equals(left)) swap(context, position, -1);
else if (direction.equals(down)) swap(context, position, COLUMNS);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Left-side tiles
} else if (position > COLUMNS - 1 && position < DIMENSIONS - COLUMNS &&
position % COLUMNS == 0) {
if (direction.equals(up)) swap(context, position, -COLUMNS);
else if (direction.equals(right)) swap(context, position, 1);
else if (direction.equals(down)) swap(context, position, COLUMNS);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Right-side AND bottom-right-corner tiles
} else if (position == COLUMNS * 2 - 1 || position == COLUMNS * 3 -1)
{
if (direction.equals(up)) swap(context, position, -COLUMNS);
else if (direction.equals(left)) swap(context, position, -1);
else if (direction.equals(down)) {
// Tolerates only the right-side tiles to swap downwards as opposed to the bottom-
// right-corner tile.
if (position <= DIMENSIONS - COLUMNS - 1) swap(context, position,
COLUMNS);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
} else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Bottom-left corner tile
} else if (position == DIMENSIONS - COLUMNS) {
if (direction.equals(up)) swap(context, position, -COLUMNS);
else if (direction.equals(right)) swap(context, position, 1);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Bottom-center tiles
} else if (position < DIMENSIONS - 1 && position > DIMENSIONS - COLUMNS) {
if (direction.equals(up)) swap(context, position, -COLUMNS);
else if (direction.equals(left)) swap(context, position, -1);
else if (direction.equals(right)) swap(context, position, 1);
else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show();
// Center tiles
} else {
if (direction.equals(up)) swap(context, position, -COLUMNS);
else if (direction.equals(left)) swap(context, position, -1);
else if (direction.equals(right)) swap(context, position, 1);
else swap(context, position, COLUMNS);
}
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
}
``` | 2018/07/17 | [
"https://Stackoverflow.com/questions/51391193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10039622/"
] | ```
public void stopChronometer() {
if(running && isSolved()){
chronometer.stop();
running =false;
}
}
```
change to
```
public void stopChronometer(){
if(running || isSolved()){
chronometer.stop();
running =false;
}
}
```
or you can call stopChronometer() from isSolved() method (you have to remove isSolved() from stopChronometer though). Without seeing the complete code, it's hard to answer. | I have found the solution
The issue whas that I hadn't declared the method start Chronometer(), chronomer and running as static. Thanks for the help though |
291,681 | I need to find if any lines in a file begin with `**` .
I cannot figure out how to do it because `*` is interpreted as a wildcard by the shell.
```
grep -i "^2" test.out
```
works if the line begins with a 2 but
```
grep -i "^**" test.out
```
obviously doesn't work.
(I also need to know if this line ends with a `)` but have not attempted that yet). | 2016/06/23 | [
"https://unix.stackexchange.com/questions/291681",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/176488/"
] | Use the `\` character to escape the \* to make it a normal character.
```
grep '^\*\*' test.out
```
Also note the single quote `'` and not double quote `"` to prevent the shell expanding things | ### It's not the shell
None of the answers so far has touched on the real problem. It would be helpful to explain *why* it does not work as you expect.
`grep -i "^**" test.out`
Because you have *quoted* the pattern to *grep*, `*` is *not* expanded by the shell. It is passed to *grep* as-is. This is explained in the manual page[1] for *bash*[2]:
>
> Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.
>
>
>
### It's regular ordinary regular expressions
*A regular expression is a **pattern** that describes a set of strings.*
`*` is one of the key patterns in regular expressions. By default, *grep* interprets it as follows:
>
> `* The preceding item will be matched zero or more times.`
>
>
>
This means that your pattern as it stands, `^**` does not make much sense. Possibly it tries to match the beginning of the line *zero or more times*, twice. Whatever that means.
The solution is to *quote* it:
>
> Any meta-character with special meaning may be quoted by preceding it with a backslash.
>
>
>
`grep -i "^\*\*" test.out`
---
[1] I do not recommend reading it. Please use `man dash` or similar instead.
[2] No shell was given, so I assume *bash*. |
1,489,190 | I'm using IntelliJ to do Java Development for an application where we use JSF in a few places. In the .jsp file I have defined my backing class and the code runs properly.
My question is: How do I set up my environment so that when I center click on the method names, which use EL format, IntelliJ navigates to the proper method in the proper class. | 2009/09/28 | [
"https://Stackoverflow.com/questions/1489190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It's a bit dodgy but you could override the `$` function:
```
var old$ = $;
var xml = ...;
$ = function(arg)
{
return old$(arg, xml);
}
```
I think that should work... maybe... | If you're using a method like jQuery.ajax() or jQuery.get() to retrieve the DOM from another page, just change/set the return type from "json" to "xml".
<http://docs.jquery.com/Ajax/jQuery.ajax#options> (scroll down to "dataType") |
6,226 | In my job I teach a lot of people to use macs. Since you use what you remember I'm always on the look out for funny or memorable ways to remember keyboard or system shortcuts (like you have the option to command escape, I know it's corny, but it works for newbies!).
What are the mnemonics you use to remember important keyboard or system shortcuts? Funny is a bonus.
**EDIT / UPDATE**
Sorry I've been away for a bit and haven't updated my question for a bit. A bit more info - I'm teaching a digital class of 8,9 and 10 year olds (who have a MacBook each) this year; and I'm looking for funny ways for them to remember the things you commonly do on your mac. Kids love learning shortcuts (for some reason) and any thing I can do to help them build confidence and have a laugh is great.
Here are the shortcuts that would be handy:
* Force Quit (That was my example, you
have the `option` to
`command` `escape`).
* Search (`command` `space`)
* `Command` `Tab`
* Expose (Four fingers down on the mouse pad!?)
* `Command` `Shift``K` (Connect to a nearby server in finder)
* `Apple` `Shift``A` for Applications
* Anything else you might think is handy.
I know it's a bit of a vague question, I'm just looking for any fun and easy way to teach these shortcuts. | 2011/01/11 | [
"https://apple.stackexchange.com/questions/6226",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1818/"
] | "Very much long work causes injury just because stress yanks energy gradually."
moVe V very
Marquee M much
Lasso L long
Wand W work
Crop C causes
Eye I injury
Healing J just (Jesus heals)
Brush B because
Stamp S stress
HistorY Y yanks
Erasor E energy
Gradiant G gradually
Blur --
"Optimum practice teaches attention under hard rigor."
DOdge O Optimum
Pen P Practice
Text T Teaches
Select A Attention
Shapes U Under
Hand H Hard
Rotate R Rigor
Switch X (Exchange)
Default D
Quick Mask Q
Screen F (Full) | The most obvious mnemonic is really the first letter of the action wanted in combination with `⌘`, e.g. `⌘`-`F` for 'Find'. The hard part comes when that is reserved to some other command than the intended.
I'd suggest first learning the most used shortcuts (maybe just one or two) and start using them whenever possible. After a while, when those come right from the spine, form a habit of adopting a few new shortcuts every week or month, what seems to be appropriate rate for one. Gradually one knows a conciderable amount of shortcuts. |
46,033,883 | I need middle tab bar item to look different from others. Here is an illustration:
[![enter image description here](https://i.stack.imgur.com/SvMWI.png)](https://i.stack.imgur.com/SvMWI.png)
How can I achieve this?
EDIT:
All tabs except of middle react on selection in standard way. Only middle tab looks the same when selected. | 2017/09/04 | [
"https://Stackoverflow.com/questions/46033883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400881/"
] | ```
Take a subclass of TabbarController.Remember to call `<UITabBarControllerDelegate>`
func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//
tabBar.selectionIndicatorImage = returnImageofSelectetab()
}
//Method called everytime when you select tab.
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.tabBar.selectionIndicatorImage == nil {
print("Starting point delegate: Selection indicator image is nill")
}
else {
print("Starting Point Of delegate: Selection indicator image is available")
}
//HERE i gave index where I want to set image.
if tabBarController.selectedIndex == 2 {
tabBarController.tabBar.selectionIndicatorImage = nil
}
else {
tabBarController.tabBar.selectionIndicatorImage = returnImageofSelectetab()
}
if tabBarController.tabBar.selectionIndicatorImage == nil {
print("Ending point delegate: Selection indicator image is nill")
}
else {
print("Ending Point Of delegate: Selection indicator image is available")
}
}
func returnImageofSelectetab() -> UIImage {
//HERE 'img_sel' is YOUR SELECTED IMAGE SET AS BACKGROUND OF YOUR TABBARITEM
let selTab = UIImage(named: "img_sel")?.withRenderingMode(.alwaysOriginal)
let tabSize = CGSize(width: view.frame.width / 5, height: 49)
UIGraphicsBeginImageContext(tabSize)
selTab?.draw(in: CGRect(x: 0, y: 0, width: tabSize.width, height: tabSize.height))
let reSizeImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return reSizeImage!
}
``` | You should subclass `UITabBarController` and change the appearance of the third `UITabBarItem` in its `items` array inside `awakeFromNib`.
```
class CustomTabBarController: UITabBarController {
override func awakeFromNib() {
super.awakeFromNib()
guard let items = tabBar.items else {
return
}
for i in 0 ..< items.count {
item.image = image
item.selectedImage = selectedImage
[...]
}
}
}
``` |
47,057,112 | I am trying to implement a simple program in vba and the following problem arises: How do you find a cell data in excel and put all the associated data in the textbox?
For example:
How to make that when typing the name I load the document, the data 1, 2, 3 and the average in the respective textbox.
![This is my sheet](https://i.stack.imgur.com/M1G6e.png)
I try to do it with this code, but I do not understand its operation very well, it only works for me if I search for the document
```
Private Sub btnBuscar_Click()
On Error GoTo NE
buscarCedula = InputBox("Search:")
Sheets("Hoja1").Select
Range("A4").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Find(What:=buscarCedula, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
txtCedula.Text = ActiveCell
ActiveCell.Offset(0, 1).Select
txtNombre.Text = ActiveCell
ActiveCell.Offset(0, 1).Select
txtNotaUno.Text = ActiveCell
ActiveCell.Offset(0, 1).Select
txtNotaDos.Text = ActiveCell
ActiveCell.Offset(0, 1).Select
txtNotaTres.Text = ActiveCell
ActiveCell.Offset(0, 1).Select
lblNotaDefinitiva.Caption = ActiveCell
```
Any idea or example that can guide me? | 2017/11/01 | [
"https://Stackoverflow.com/questions/47057112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8011307/"
] | Try the following REGEX instead([DEMO](https://regex101.com/r/RAAh4V/2)):
```
/<iframe.*?s*src="http(.*?)".*?<\/iframe>/
```
But beware, You CAN NOT parse HTML with REGEX properly. Please, use some XML parser instead.
Also, it seems you only want to change `http` to `https`. So for that try the following instead:
```
if(strpos($string, 'https') === false)
{
$string = str_replace("http", "https", $string);
}
``` | You can try this regex :
```
/(<iframe.+?src=".*?)(?=:)/
```
Live demo [here](https://regex101.com/r/GGU2yj/5)
Sample code in php:
```
$re = '/(<iframe.+?src=".*?)(?=:)/';
$str = '<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>';
$subst = '\\1s';
$result = preg_replace($re, $subst, $str);
echo $result;
// <p>Some random text <iframe src="https://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>
``` |
24 | Black holes have so much gravity that [even light can't escape from them](https://astronomy.stackexchange.com/questions/7/why-cant-light-escape-from-a-black-hole/8#8). If we can't see them, and the suck up all electromagnetic radiation, then how can we find them? | 2013/09/24 | [
"https://astronomy.stackexchange.com/questions/24",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/19/"
] | There are many, many ways of doing this.
[Gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens)
------------------------------------------------------------------------
This is by far the most well known. It has been mentioned by the others, but I'll touch on it.
![enter image description here](https://i.stack.imgur.com/LPNNP.gif)
Light coming from distant bodies can be bent by gravity, creating a lens-like effect. This can lead to multiple or distorted images of the object (Multiple images give rise to [Einstein rings and crosses](http://en.wikipedia.org/wiki/Einstein_ring)).
So, if we observe a lensing effect in a region where there isn't any visible massive body, there's probably a black hole there. The alternative is that we are peering through the dark matter 'halo' which surrounds (and extends passed) the luminous components of every galaxy and galaxy cluster ([See: Bullet Cluster](http://apod.nasa.gov/apod/ap060824.html)). On small enough scales (i.e. - the central regions of galaxies), this is not really an issue.
![enter image description here](https://i.stack.imgur.com/q1dP2.gif)
(This is an artist's impression of a galaxy passing behind a BH)
[Gravitational waves](http://en.wikipedia.org/wiki/Gravitational_waves)
-----------------------------------------------------------------------
Spinning black holes and other dynamical systems involving black holes emit gravitational waves. Projects like [LIGO](http://en.wikipedia.org/wiki/LIGO) (and eventually, [LISA](http://en.wikipedia.org/wiki/Laser_Interferometer_Space_Antenna)) are able to detect these waves. One major candidate of interest for LIGO/VIRGO/LISA is the eventual collision of a binary black hole system.
Redshift
--------
Sometimes we have a black hole in a binary system with a star. In such a case, the star will orbit the common barycenter.
If we observe the star carefully, its light will be [redshifted](http://en.wikipedia.org/wiki/Redshift) when it is moving away from us, and blueshifted when it is coming towards us. The variation in redshift suggests rotation, and in the absence of a visible second body, we can usually conclude that there's a black hole or neutron star there.
Salpeter-Zel'dovitch / Zel'dovitch-Novikov proposals
----------------------------------------------------
Going in to a bit of history here, Salpeter and Zel'dovitch independently proposed that we can identify black holes from shock waves in gas clouds. If a black hole passes a gas cloud, the gases in the cloud will be forced to accelerate. This will emit radiation (X-rays, mostly), which we can measure.
An improvement on this is the Zel'dovitch-Novikov proposal, which looks at black holes in a binary system with a star. Part of the solar winds from the star will be sucked in to the black hole. This abnormal acceleration of the winds will, again, lead to X-ray shock waves.
![enter image description here](https://i.stack.imgur.com/JNTmh.png)
This method (more or less) led to the discovery of [Cyg X-1](http://en.wikipedia.org/wiki/Cygnus_X-1)
Cosmic gyroscopes
-----------------
[Cyg A](http://en.wikipedia.org/wiki/Cyg_A) is an example of this. Spinning black holes act like cosmic gyroscopes — they do not easily change their orientation.
In the following radio image of Cyg A, we see these faint gas jets emanating from the central spot:
![enter image description here](https://i.stack.imgur.com/Oj75s.png)
These jets are hundreds of thousands of light years long — yet they are very straight. Discontinuous, but straight. Whatever object lies at the center, it must be able to maintain its orientation for very long.
That object is a spinning black hole.
Quasars
-------
Most quasars are thought to be powered by black holes. Many (if not all) of the candidate explanations for their behavior involve black holes with accretion disks, e.g. [the Blandford-Znajek process](http://en.wikipedia.org/wiki/Blandford%E2%80%93Znajek_process). | A black hole can also be detected by how it bends light as various bodies move behind it. This phenomenon is called [gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens), and is the most visually stunning prediction of Einstein's theory of General Relativity.
This image portrays the geometry of gravitational lensing. Light from luminous background objects are bent due to the warping of space-time in the presence of mass (here, the red dot could conceivably be the black hole in question):
![enter image description here](https://i.stack.imgur.com/AJHEK.gif)
Astronomers have discovered the existence of a super-massive black hole at the center of our very own Milky Way Galaxy, and has been dubbed [Sagittarius A\*](http://en.wikipedia.org/wiki/Sagittarius_A*).
Over a period of ten years, the trajectories of a small group of stars have been tracked, and the only explanation for their rapid movement is the existence of a highly compact object with the mass of about 4 million suns. Given the mass and distance scales involved, the conclusion is that it must be a black hole.
![Trajectories of stars around the Sagittarius A* within the Milky Way Galaxy.](https://i.stack.imgur.com/bYThB.png) |
256,062 | Small retail business running 5 computers. Thinking about getting a server to run the printers, run a pos system, run quickbooks, and do backups. My question is whether I should invest into getting a Windows server or just use a regular computer? Or is there some other way of easily doing this? My concern is that a Windows server would cost more then it would benefit. The people running the store are not very technical, so a really simple system would be preferred. | 2011/04/05 | [
"https://serverfault.com/questions/256062",
"https://serverfault.com",
"https://serverfault.com/users/77284/"
] | I would look at [Windows Small Business Server](http://www.microsoft.com/sbs/en/us/default.aspx).
Then see if you qualify for the [Microsoft Bizspark](http://www.microsoft.com/bizspark/) program.
This also could be done with a Linux distribution though the skilled Admin required for that role and configuration if Linux is outside of your scope may be more in costs than just purchasing of the SBS from MS which is simple enough that a low level Adm1n would not have much issue configuring.
On the Point of Sale System (POS) that would be to run the back end database correct? What software does that DB use? That may be a consideration before jumping on Linux especially if it utilizes MSSQL... | [Consider Windows Server 2008 Foundation](http://www.microsoft.com/windowsserver2008/en/us/foundation.aspx)
Limitations are that you can only have 15 users, can't be a child domain or domain trusts. |
58,858,546 | Epicor ERP 10.2.500 has been recently released with the addition of Epicor Functions. They can be called from within Method and Data Directives.
Do anybody has been able to do so with a Form Customization within Epicor? | 2019/11/14 | [
"https://Stackoverflow.com/questions/58858546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12372749/"
] | This is possible via a REST call to your function API. In this case, I had a function that sent an email from some inputs.
```
private void epiButtonC1_Click(object sender, System.EventArgs args)
{
//API Key is included in the query param in this example.
var request = (HttpWebRequest)WebRequest.Create("https://{appserver}/{EpicorInstance}/api/v2/efx/{CompanyID}/{LibraryID}/{functionName}/?api-key={yourAPIKey}");
request.Method = "POST";
//All REST v2 requests also sent with authentication method (Token, Basic)
//This should be Base64 encoded
string username = "userName";
string password = "passWord";
string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
//Add body to correspond to request signature
request.ContentType = "application/json";
using(var writer = new StreamWriter(request.GetRequestStream()))
{
var values = new Dictionary<string, string>;
{
{"toEmailAddress", "someEmail@email.com"},
{"fromEmailAddress","someOtherEmail@email.com"},
{"body","This is the body"},
{"subject","Hello from Client Code!"}
};
string json = JsonConvert.SerializeObject(values);
writer.Write(json);
}
using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
epiTextBoxC1.Text = result.ToString();
}
}
``` | REST endpoint is the recommended way to perform the function call as pointed out by a-moreng.
If for some reason you cannot use this, you can use a passthrough method to any server-side BO via a customization Adapter. For instance, create an updatable BAQ which you can call from a customization using the DynamicQueryAdapter.
* Pick an arbitrary table and field to save the BAQ.
* Create three string parameters to store the Function library name, the function name, and a delimited list of parameters.
* On the GetList method, create a Base Processing Directive.
* Split your delimited parameter list and convert them to the appropriate datatypes.
* Use the resulting variables to call your function.
* If desired, you can pass return variables into the ttResults of the BAQ |
53,926 | Is there a way to determine whether there exists a positive solution ($x\_i > 0$ and $y\_i > 0$) for all of the following equations to hold when $k > 2$?
$x\_1 + x\_2 + \cdots + x\_{2n} = y\_1 + y\_2 + \cdots + y\_n$.
$x^2\_1 + x^2\_2 + \cdots + x^2\_{2n} = y^2\_1 + y^2\_2 + \cdots + y^2\_n$.
$x^3\_1 + x^3\_2 + \cdots + x^3\_{2n} = y^3\_1 + y^3\_2 + \cdots + y^3\_n$.
$\cdots$
$x^k\_1 + x^k\_2 + \cdots + x^k\_{2n} = y^k\_1 + y^k\_2 + \cdots + y^k\_n$.
How about positive integer solutions?
Anyone sheds some lights on this would be highly appreciated! | 2011/01/31 | [
"https://mathoverflow.net/questions/53926",
"https://mathoverflow.net",
"https://mathoverflow.net/users/12652/"
] | One can't have $k \ge 2n$ (proof in a moment). An integer solution at the end.
If $k \le n$ then one can choose $y\_1,y\_2,\cdots,y\_n$ and $x\_{n+1},x\_{n+2},\cdots,x\_{2n}$ and solve for $x\_1,x\_2,\cdots,x\_n$. I arbitrarily decided to try this with $x\_3=3,x\_4=4$ Varying $y\_1,y\_2$ I find
$y\_1,y\_2;x\_1,x\_2,x\_3,x\_4=8,20;\frac{21-\sqrt{437}}{2},\frac{21+\sqrt{437}}{2},3,4$ Many other choices work as well (for example $11 \le x\_1 \le x\_2$).
**later** It should be easy to find solutions with $k=n$ although I have no idea about the integer case: Pick $y\_1,\cdots,y\_n$ not too small and no two too close together (say $y\_i=i$) Then the values $y^j\_1 + y^j\_2 + \cdots + y^j\_n$ determine the coefficients of the monic polynomial $f(t)=\prod\_1^n(t-y\_i)$ and vice versa. The $y\_i$ are the $n$ roots of $f$. Now pick $x\_{n+1},\cdots,x\_{2n}$ positive but "small enough".Then the desired equations $x^j\_1 + x^j\_2 + \cdots + x^j\_n=y^j\_1 + y^j\_2 + \cdots + y^j\_n-\sum\_1^nx\_{n+k}^j$ determine the coefficents of some monic polynomial $g(t)$ whose roots are $x\_1,\cdots,x\_n$. If the prechosen values are small enough (maybe $x\_{n+k}=\frac{k}{100^n}$) then the coeffcients of $g$ should be only slightly preturbed from those of $f$ so the roots $x\_1,\cdots,x\_n$ should be only slightly preturbed from $y\_1,\cdots,y\_n$
---
Here is my argument for why we can't expect $k=2n$: In this case the equations and values for $y\_1,...,y\_n$ will determine $x\_1,x\_2,\cdots ,x\_{2n}$ up to order. But we know a solution with $n$ zeros so the other solutions must be the same rearranged.
---
The (multi)sets $A=[0,4,5]$ and $B=[1,2,6]$ have equal sums of $j$th powers $j=0,1,2$. Thus the same is true for $A\cup 4A \cup 5A \cup 6A$ and $B\cup 4B \cup 5B \cup 6B$. This remains true for $j=1,2$ if we drop the common terms and the 4 $0$s leaving $$[16,20,20,25] \text{ and }[1, 2, 6, 6, 8, 10, 12, 36]$$
I haven't managed a similar trick for $[0,2,9,11]$ and $[1,4,7,10]$ (equal sum of powers for $j=0,1,2,3$) or other similar examples.
---
A potentially useful technique for the integer case: One way to verify the claim about $[6,2,1]$ and $[5,4,0]$ is to observe that the polynomial $p(t)=t^6-t^5-t^4+t^2+t-1=(t-1)(t^2-1)(t^3-1)$ has a triple root at $t=1$. In our case, consider the polynomial $\sum\_1^{2n}t^{x\_i}-\sum\_1^n t^{y\_i}-n$. It has a $k+1$-fold root at $t=1$ precisely if the desired equations hold. Hence $f(t)=t^{36}-t^{25}-2t^{20}-t^{16}+t^{12}+t^{10}+t^8+2t^6+t^2+t-4$ has a triple root at $t=1$. In fact $f=(t-1)(t^2-1)(t^3-1)(t^2-t-1)g(t)$ where $g(t)=t^{28}+2t^{27}+\cdots+13t^4+11t^3+9t^2+7t+4$ has (weakly) unimodal non-negative coefficients and the triple root at $t=1$ comes from the same $(t-1)(t^2-1)(t^3-1)=p(t)$. | For integers, this is referred to as the Tarry-Escott problem, also as multigrade equations, a search for either term should bring you much joy. I just noticed you have $n$ terms on one side, $2n$ on the other, whereas people are usually more interested in equal numbers of terms on each side. |
22,642,816 | Here's a little background into what I'm trying to achieve, in order to help make my question a bit more clear...I'm creating a Navigation Drawer where each item in the ListView looks similar to the following:
![ListItem](https://i.stack.imgur.com/Jvu0y.png)
However, I need to be able to change the color of the right side border (the blue) to a variety of different colors programmatically, so while playing around with a solution, I decided to extend a `RelativeLayout` and draw the line in the `onDraw(Canvas c);` method. My `RelativeLayout` code is as follows:
```
public class CustomRelativeLayout extends RelativeLayout {
private final Paint paint = new Paint();
public CustomRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
//Other Constructors
private void init() {
setPaintColor(Color.argb(128, 0, 0, 0));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(getMeasuredWidth() - 1, 0, getMeasuredWidth() - 1, getMeasuredHeight(), paint);
}
public void setPaintColor(int color){
paint.setColor(color);
invalidate();
}
}
```
My `NavigationDrawer`'s `ListView` also contains a header that uses this class, and it works fine as a header view. However, for each individual `ListView` item, the border isn't present. I've debugged my solution, and found that my subclassed `RelativeLayout`'s `onDraw(Canvas c);` method is called for the header view, but isn't called for each of the `ListView`'s child views provided by my `ArrayAdapter<String>`.
I know there are other ways to handle this, such as using a default `View`, setting it's background to the color I want, and aligning it to the right - but that's not my question. My question is why is my `CustomRelativeLayout`'s `onDraw(Canvas c);` method is called for the `ListView`'s header view, and not for each of the Views provided by my adapter? Any insight into this behavior would be appreciated. Also, here are the `CustomArrayAdapter` and `nav_drawer_item.xml` used with the `ListView` in case they're helpful:
```
public class SimpleDrawerAdapter extends ArrayAdapter<String> {
public SimpleDrawerAdapter(Context context, int resource,
String[] sections) {
super(context, resource, sections);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout container = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container = (CustomRelativeLayout) inflater.inflate(R.layout.nav_drawer_item, parent, false);
} else {
container = (CustomRelativeLayout) convertView;
}
((TextView)container.findViewById(R.id.nav_item_text)).setText(getItem(position));
return container;
}
}
```
nav\_drawer\_item.xml
```
<?xml version="1.0" encoding="utf-8"?>
<com.mypackage.views.CustomRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="wrap_content">
<TextView
android:id="@+id/nav_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/nav_drawer_grey"
android:textSize="@dimen/text_large"
android:layout_margin="@dimen/navigation_drawer_item_margin"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</com.mypackage.views.CustomRelativeLayout>
``` | 2014/03/25 | [
"https://Stackoverflow.com/questions/22642816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1869968/"
] | Have you tried clearing the `WILL_NOT_DRAW` flag by calling [setWillNotDraw](http://developer.android.com/reference/android/view/View.html#setWillNotDraw%28boolean%29) method in your custom layout?
>
> If this view doesn't do any drawing on its own, set this flag to allow
> further optimizations. By default, this flag is not set on View, but
> could be set on some View subclasses such as ViewGroup. Typically, if
> you override onDraw(android.graphics.Canvas) you should clear this
> flag.
>
>
> | just call it yourself each time you iterate over the list
```
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container = (CustomRelativeLayout) inflater.inflate(R.layout.nav_drawer_item,
parent, false);
if(container!=null){
container.draw()
}
} else {
container = (CustomRelativeLayout) convertView;
if(container!=null){
container.draw()
}
}
``` |
12,796,148 | I've a timer object. I want it to be run every minute. Specifically, it should run a `OnCallBack` method and gets inactive while a `OnCallBack` method is running. Once a `OnCallBack` method finishes, it (a `OnCallBack`) restarts a timer.
Here is what I have right now:
```
private static Timer timer;
private static void Main()
{
timer = new Timer(_ => OnCallBack(), null, 0, 1000 * 10); //every 10 seconds
Console.ReadLine();
}
private static void OnCallBack()
{
timer.Change(Timeout.Infinite, Timeout.Infinite); //stops the timer
Thread.Sleep(3000); //doing some long operation
timer.Change(0, 1000 * 10); //restarts the timer
}
```
However, it seems to be not working. It runs very fast every 3 second. Even when if raise a period (1000\*10). It seems like it turns a blind eye to `1000 * 10`
What did I do wrong? | 2012/10/09 | [
"https://Stackoverflow.com/questions/12796148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708058/"
] | This is not the correct usage of the System.Threading.Timer. When you instantiate the Timer, you should almost always do the following:
```
_timer = new Timer( Callback, null, TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
```
This will instruct the timer to tick only once when the interval has elapsed. Then in your Callback function you Change the timer once the work has completed, not before. Example:
```
private void Callback( Object state )
{
// Long running operation
_timer.Change( TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
}
```
Thus there is no need for locking mechanisms because there is no concurrency. The timer will fire the next callback after the next interval has elapsed + the time of the long running operation.
If you need to run your timer at exactly N milliseconds, then I suggest you measure the time of the long running operation using Stopwatch and then call the Change method appropriately:
```
private void Callback( Object state )
{
Stopwatch watch = new Stopwatch();
watch.Start();
// Long running operation
_timer.Change( Math.Max( 0, TIME_INTERVAL_IN_MILLISECONDS - watch.ElapsedMilliseconds ), Timeout.Infinite );
}
```
---
I **strongly** encourage anyone doing .NET and is using the CLR who hasn't read Jeffrey Richter's book - **CLR via C#**, to read is as soon as possible. Timers and thread pools are explained in great details there. | Is using `System.Threading.Timer` mandatory?
If not, `System.Timers.Timer` has handy `Start()` and `Stop()` methods (and an `AutoReset` property you can set to false, so that the `Stop()` is not needed and you simply call `Start()` after executing). |
12,950,959 | I was astonished that a thing this simple has been troubling me. Below is the code
```
list = []
f = open("log.txt", "rb") # log.txt file has line separated values,
for i in f.readlines():
for value in i.split(" "):
list.append(value)
print list
```
The output is
```
['xx00', '\n', 'xx01in', '\n', 'xx01na', '\n', 'xx01oz', '\n', 'xx01uk', '\n']
```
How can I get rid of the new line i.e. '\n'? | 2012/10/18 | [
"https://Stackoverflow.com/questions/12950959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695014/"
] | The correct way to do this, is:
```
with open('log.txt') as fin:
for line in fin:
print line.split()
```
By using `split()` **without** an argument, the '\n''s automatically don't become a problem (as split or split(None) uses different rules for splitting).
Or, more concisely:
```
from itertools import chain
with open('log.txt') as fin:
mylist = list(chain.from_iterable(line.split() for line in fin))
``` | If you have a bunch of lines with space separated values, and you just want a list of all the values without caring about where the line breaks were (which appears to be the case from your example, since you're always appending to the same list regardless of what line you're on), then don't bother looping over lines. Just read the whole file as a single string and call `split()` with no arguments; it will split the string on *any* sequence of one or more whitespace characters, including both spaces and newlines, with the result that none of the values will contain any whitespace:
```
with open('log.txt', 'rb') as f:
values = f.read().split()
``` |
63,092,672 | How to change color of just one side of the border of a raised button in flutter?
[![enter image description here](https://i.stack.imgur.com/GHlex.png)](https://i.stack.imgur.com/GHlex.png) | 2020/07/25 | [
"https://Stackoverflow.com/questions/63092672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12050995/"
] | Really, the import should go first.
The usual standards for the PPCG site allow answers to create a function that satisfies the challenge requirements, without actually saving it anywhere. At the time the `lambda` creates the function, `permutations` is not available, but the function is not executed, so no error occurs. If the function created by the `lambda` were to be executed at the end of this code block, `permutations` would be available at that point, so no error would occur.
However, the function created by the `lambda` does not survive to the point after the `import`. At no point in this code's execution is there actually a function that satisfies the challenge's requirements. The function's dependencies aren't available until after the function's lifetime ends.
Switching the lambda and the import would resolve this issue without requiring extra characters. | That code is a no-op. It defines a lambda which is never executed, so Python never encounters the NameError.
Actually executing the lambda before importing `itertools` would reveal the error. |
45,594,620 | **UPDATE : PROBLEM IS SOLVED**
[![enter image description here](https://i.stack.imgur.com/FnOIS.jpg)](https://i.stack.imgur.com/FnOIS.jpg)
According to this image, I am trying to open fragment according to each drawer item. Currently I've made fragment only for 'Easy' which contain **a ListView** but my app **CRASHES** everytime I press it. I've Android Nougat (v7.0) running on my phone.
Here is my code ...
**Fragment Layout (fragment\_easy.xml) :**
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="afm.pymonk.EasyFragment"
android:id="@+id/easyFragment">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/easyList"/>
</RelativeLayout>
```
**Fragment JAVA Code inside onCreateView in EasyFragment.java :**
```
View view = inflater.inflate(R.layout.fragment_easy, container, false);
String easyListContents[] = {"Introduction", "Hello World", "Operators", "Data Types",
"Simple Arithmetic Operations", "Take input from user"};
ListView easyList = (ListView) view.findViewById(R.id.easyList);
ArrayAdapter<String> easyAdapter = new ArrayAdapter<String>(EasyFragment.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, easyListContents);
easyList.setAdapter(easyAdapter);
easyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
return;
}
});
return view;
```
**Code to open fragemnt inside onNavigationItemSelected in main activity (Home.java) :**
```
int id = item.getItemId();
if (id == R.id.icon_easy) {
EasyFragment easyFragment = new EasyFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainBase, easyFragment, easyFragment.getTag()).commit();
}
```
**Device Error Log :**
[![enter image description here](https://i.stack.imgur.com/4NkTV.png)](https://i.stack.imgur.com/4NkTV.png) | 2017/08/09 | [
"https://Stackoverflow.com/questions/45594620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Return `view` not `return inflater.inflate(R.layout.fragment_easy, container, false);` in your fragment in onCreateView method.
Edited :
Implement `OnFragmentInteractionListener` in MainActvity
Ex:
```
public class MainActivity extends AppCompatActivity
implements OnFragmentInteractionListener {
// Implement the methods here
}
``` | Your `easyFragment.getTag()` call will return `null` because there was no `setTag` call, so just use some `String` tag to bind it with your fragment instead of`null`
```
manager.beginTransaction().replace(R.id.mainBase, easyFragment, "easyFrag").commit();
// ^^^^^^
```
Update :
You are using interface listener callbacks in fragment but there is no implementation in your activity so make sure to do
```
class Home extends AppCompatActivity implements OnFragmentInteractionListener {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// override methods of OnFragmentInteractionListener and provide their implementation
}
``` |
66,037,493 | I'm on a MacBook Pro M1 (and before someone says well it's because of M1 or something else, I've been programming with Flutter and M1 for weeks but then I must have to reset my M1 and after this) ... my big problem:
I can not start my project with a package that include native codes like `shared_preferences` or `sqlite`, every time I get a **error running Pod Install**.
I searched on Stack Overflow and so far nothing helped me. If I start my project without the package there are no problems, this is my Flutter code very simple:
```
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
`class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton.icon(
onPressed: ()async{
final prefs = await SharedPreferences.getInstance();
if(prefs.containsKey("test")){
print("available");
}else{
await prefs.setInt("test", 1);
}
final send = await post("xxx",body: {
"query":"SELECT * FROM NEWS"
});
print(json.decode(send.body));
},
icon: Icon(Icons.person),
label: Text("Hii")
),
),
);
}
} ,
```
This is the error I get from Flutter:
```
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer/analyzer.rb:177:in `sources'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer/analyzer.rb:1073:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer/analyzer.rb:1072:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer.rb:414:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer.rb:239:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer.rb:238:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/installer.rb:160:in `install!'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.10.0/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `<main>'
```
――― TEMPLATE END ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
[!] Oh no, an error occurred.
Search for existing GitHub issues similar to yours:
https://github.com/CocoaPods/CocoaPods/search?q=dlsym%280x7fdfa0da8bc0%2C+Init_ffi_c%29%3A+symbol+not+found+-+%2FLibrary%2FRuby%2FGems%2F2.6.0%2Fgems%2Fffi-1.14.2%2Flib%2Fffi_c.bundle&type=Issues
If none exists, create a ticket, with the template displayed above, on:
https://github.com/CocoaPods/CocoaPods/issues/new
Be sure to first read the contributing guide for details on how to properly submit a ticket:
https://github.com/CocoaPods/CocoaPods/blob/master/CONTRIBUTING.md
Don't forget to anonymize any private data!
Looking for related issues on cocoapods/cocoapods...
Found no similar issues. To create a new issue, please visit:
https://github.com/cocoapods/cocoapods/issues/new
Error output from CocoaPods:
↳
[!] Automatically assigning platform `iOS` with version `12.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
```
I edited my Podfile and specified a platform but nothing helped. Here are some details:
```
Flutter Version = 1.22.5 (I tried also the newest version 1.22.6)
Xcode Version = 12.3 (I tried also the newest version 12.4)
Cocoa-pods = 1.10.0 ((I tried also the newest version 1.10.1)
```
I installed and reinstalled many times Cocoa-pods it didn't help either | 2021/02/03 | [
"https://Stackoverflow.com/questions/66037493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15141193/"
] | Instead of `pod install`, you need to do:
```
arch -x86_64 pod install
```
Cocoapods still doesn't have full Apple Silicon support. Running commands with `arch -x86_64` forces Terminal to use Rosetta 2 instead.
If that doesn't work, try following [this article](https://medium.com/p-society/cocoapods-on-apple-silicon-m1-computers-86e05aa10d3e). | Run
```
sudo gem uninstall ffi
```
and
```
sudo gem install ffi -- --enable-libffi-alloc
``` |
30,794,566 | I'm new to R and RStudio but trying to learn and put together a ShinyApps app. I cannot get past Step 1 of the Shinyapps process, which is to install the devtools package in RStudio. I believe the underlying cause is that the "xml2" package dependency is not installed, but I can't seem to resolve that and I don't understand what to do.
I'm on Linux Mint Cinnamon 17.1 on a Dell laptop. I installed RStudio from the Software Manager. In trying to resolve the errors during devtools installation, I've tried installing R and RStudio from slightly newer package downloads using apt-get, I've tried installing `xml2` and `rversions` from RStudio (not available), I've tried using single quotes and double quotes, I've tried adding `dependency=true` to all RStudio installation attempts, I've restarted both RStudio and the machine numerous times... I'm out of ideas... help?
Following is the output from the devtools installation command inside RStudio, plus the output of "version" in case it helps.
```
install.packages("devtools")
Installing package into ‘/home/[MyHomeDir]>/R/i686-pc-linux-gnu-library/3.0’
(as ‘lib’ is unspecified)
Warning in install.packages :
dependency ‘xml2’ is not available
also installing the dependency ‘rversions’
trying URL 'http://cran.rstudio.com/src/contrib/rversions_1.0.1.tar.gz'
Content type 'application/x-gzip' length 4624 bytes
opened URL
==================================================
downloaded 4624 bytes
trying URL 'http://cran.rstudio.com/src/contrib/devtools_1.8.0.tar.gz'
Content type 'application/x-gzip' length 141487 bytes (138 Kb)
opened URL
==================================================
downloaded 138 Kb
ERROR: dependency ‘xml2’ is not available for package ‘rversions’
* removing ‘/home/[MyHomeDir]/R/i686-pc-linux-gnu-library/3.0/rversions’
Warning in install.packages :
installation of package ‘rversions’ had non-zero exit status
ERROR: dependency ‘rversions’ is not available for package ‘devtools’
* removing ‘/home/[MyHomeDir]/R/i686-pc-linux-gnu-library/3.0/devtools’
Warning in install.packages :
installation of package ‘devtools’ had non-zero exit status
The downloaded source packages are in
‘/tmp/RtmpNJIGkV/downloaded_packages’
version
_
platform i686-pc-linux-gnu
arch i686
os linux-gnu
system i686, linux-gnu
status
major 3
minor 0.2
year 2013
month 09
day 25
svn rev 63987
language R
version.string R version 3.0.2 (2013-09-25)
nickname [nickname redacted]
``` | 2015/06/12 | [
"https://Stackoverflow.com/questions/30794566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4556560/"
] | I had an **old R version (3.0.2)** running on **Ubuntu 14.04**. And this is how i had to update R:
* open the sources list `sudo vi /etc/apt/sources.list`
* Add a cran mirror (i.e. `deb http://cran.rstudio.com/bin/linux/ubuntu trusty/`)
* Add an APT-key `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E084DAB9` ([see cran](https://cran.rstudio.com/bin/linux/ubuntu/README.html))
* Now update R `sudo apt-get install r-base`
Now i was able to install `devtools`. In my case ALL, installed packaged where updated, so this could take some time. | Update to the newest version of R then follow the instructions provided in the link and you should be able to get it installed.
<https://github.com/hadley/devtools> |
47,784,649 | Have an array A = [a1, a2, ..., an] where each element in the array is either 0, 1 or 2.
Need to sort the array, but it is stated specifically use a **comparison-based algorithm**. I know it is possible to use linear time algorithms, but you are not allowed to use counting sort or other arrays.
Can anyone help me to where to start from. I'm assuming we know that 1 is the median, but what technique would you use to sort this in place? | 2017/12/13 | [
"https://Stackoverflow.com/questions/47784649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5066026/"
] | Take 1 as the pivot element. Compare with every element. If that is `0`, move it before `1` and if it is `2`, then move it after `1`.
```
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void Sort(vector<int>& A) {
int n = A.size(), i = 0, j = 0, k = n - 1;
while (j < k) {
if (A[j] == 0) swap(A[i++], A[j++]);
else if (A[j] == 2) swap(A[k--], A[j]);
else ++j;
}
}
int main() {
vector<int> A {2, 1, 2, 1, 0};
Sort(A);
copy(A.begin(), A.end(), ostream_iterator<int>(cout, " "));
return 0;
}
``` | Here is a javascript solution. Algorithm is run twice with pivot=1 and pivot=0 based on partition. You can see the algorithm performs COMPARISION rather than knowing 0, 1 or 2.
```
var array = [1,0,2,0,0,1,2,0,2,1,1,1,2,2,0,0,0,1];
console.log("Original Array " + array);
var size = array.length;
function partition(array, s, e, pivot) {
var i = s - 1;
var j = s;
while (j < e) {
if (array[j] <= pivot) {
var swap = array[i + 1];
array[i + 1] = array[j];
array[j] = swap;
i++;
}
j++;
}
return i;
}
var parti = partition(array, 0, size, 1)
console.log("After one pass " + array);
console.log("Partition " + parti);
partition(array, 0, parti + 1, 0);
console.log("Final Array " + array);
``` |
34,632,482 | I have a array of strings, but all the stings are written in upper case letters. Is there a way for me to make all the strings in the array to lower case, (and with capitalisation)
```
array = ["BOY","GIRL","MAN"]
// func to convert it to array = ["Boy","Girl","Man"]
```
Is there a way to do this, without rewriting the content of the array with lower case letters. I have a very long array of strings in upper case letters. | 2016/01/06 | [
"https://Stackoverflow.com/questions/34632482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5748109/"
] | You can use the map function like this:
```
let array = ["BOY","GIRL","MAN"]
let capitalizedArray = array.map { $0.capitalizedString}
``` | SWIFT 4:
The property capitalizedString has changed to capitalized.
```
let array = ["BOY","GIRL","MAN"]
let capitalizedArray = array.map {$0.capitalized}
``` |
18,704,039 | I have a single table which I need to pull back the 5 most recent records based on a userID and keying off of documentID (no duplicates). Basically, I'm tracking visited pages and trying to pull back the 3 most recent by user.
Sample data:
```
╔══════════════════════════════════════════════╗
║UserID DocumentID CreatedDate ║
╠══════════════════════════════════════════════╣
║ 71 22 2013-09-09 12:19:37.930 ║
║ 71 25 2013-09-09 12:20:37.930 ║
║ 72 1 2012-11-09 12:19:37.930 ║
║ 99 76 2012-10-10 12:19:37.930 ║
║ 71 22 2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝
```
Desired query results if UserID = 71:
```
╔══════════════════════════════════════════════╗
║UserID DocumentID CreatedDate ║
╠══════════════════════════════════════════════╣
║ 71 25 2013-09-09 12:20:37.930 ║
║ 71 22 2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝
``` | 2013/09/09 | [
"https://Stackoverflow.com/questions/18704039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127875/"
] | ```
SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC
``` | ```
Select USERID,DOCUMENT ID
FROM yourtable
QUALIFY ROW_NUMBER OVER(Partition by user id ORDER By document id Desc)<6
```
This works in Teradata. Hope this works in Sql Server too as its mainly ANSI SQL. |
13,709,651 | I want to find GCD of two numbers but without using division or mod operator.
one obvious way would be to write own mod function like this:
```
enter code here
int mod(int a, int b)
{
while(a>b)
a-=b;
return a;
}
```
and then use this function in the euclid algorithm.
Any other way ?? | 2012/12/04 | [
"https://Stackoverflow.com/questions/13709651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1453008/"
] | You can use the substraction based version of [euclidean algorithm](http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations) up front:
```
function gcd(a, b)
if a = 0
return b
while b ≠ 0
if a > b
a := a − b
else
b := b − a
return a
``` | A more or less direct way is the following code, which is derived from Pick's theorem:
```
int gcd(int a, int b)
{
if( a < 0)
{
a = -a;
}
if( b < 0)
{
b = -b;
}
if( a == b)
{
return a;
}
//swap the values to make the upper bound in the next loop minimal
if( a > b)
{
int swap = a;
a = b;
b = swap;
}
int temp=0;
for(int i=1; i<=a; i++)
{
temp += math.floor(b*i/a);
}
return (a*b + b - a + temp)/2;
}
``` |
19,125,507 | This would greatly improve the readability of many regular expressions I write, and when I write a single literal space in my regexes I almost always mean `\s*` anyway. So, is there a "mode" in Perl regular expressions that enables this, like `/s` to make `.` match newlines, etc.? A cursory read through `perlre` didn't give anything, but maybe I missed something or maybe there's a different way to achieve this?
Edit: What I mean is, currently I write `qr/^\s*var\s+items\s*=\s*[\s*$/`, and I'd instead like to write `qr/^ var\s+items = [ $/` and have it mean the same thing using some means- and my question is whether such a means exists. | 2013/10/01 | [
"https://Stackoverflow.com/questions/19125507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8127/"
] | I would try using drush alias files to run drush commands from the outside. Drush alias files allow you to authenticate remotely and run such commands. (some example on drush alias file - <https://drupal.org/node/1401522>).
Aegir (actually one of its components - provision) has integration with drush, so you can use commands like `provision-install` and other (see `drush help` for more). | You're looking for [Aegir Services](https://www.drupal.org/project/hosting_services):
>
> Aims to be a one-stop shop for all Web services functionality offered
> within the Aegir Hosting System. It allows for remote site management
> via the Services framework.
>
>
> |
51,131,230 | I have 3 queries in sql:
1st query:
```
select t1ID ,AVG(t2score) AS AVG1
from T1
WHERE t1m1 NOT IN (t2m1,t2m2,t2m3) and t1m2 IN (t2m1,t2m2,t2m3)
group by t1ID
```
Result
```
+------+------+
| t1ID | AVG1 |
+------+------+
| 1 | 55 |
| 2 | 45 |
| 3 | 73 |
| 4 | 69 |
+------+------+
```
2nd query :
```
select t1ID ,AVG(t2score) AS AVG2
from T1
WHERE t1m2 NOT IN (t2m1,t2m2,t2m3) and t1m1 IN (t2m1,t2m2,t2m3)
group by t1ID
```
Result
```
+------+------+
| t1ID | AVG2 |
+------+------+
| 1 | 68 |
| 2 | 56 |
| 3 | NULL |
| 4 | NULL |
+------+------+
```
3rd query
```
select t1ID ,AVG(t2score) AS AVGt3
from T1
WHERE t1m3 NOT IN (t2m1,t2m2,t2m3) and t1m1 IN (t2m1,t2m2,t2m3)
group by t1ID
```
Result
```
+------+------+
| t1ID | AVG3 |
+------+------+
| 1 | NULL |
| 2 | 70 |
| 3 | NULL |
| 4 | NULL |
+------+------+
```
How can I combine these three statements so that I get these results added together like this ( each AVG score in different column)
Desired Result:
```
+------+------+------+------+
| t1ID | AVG1 | AVG2 | AVG3 |
+------+------+------+------+
| 1 | 55 | 68 | NULL |
| 2 | 45 | 56 | 70 |
| 3 | 73 | NULL | NULL |
| 4 | 69 | NULL | NULL |
+------+------+------+------+
``` | 2018/07/02 | [
"https://Stackoverflow.com/questions/51131230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648668/"
] | ```
{SELECT t1ID, AVG(FirstT.t2score) AS AVG1, AVG(SecondT.t2score) AS AVG1, AVG(ThirdT.t2score) AS AVG1
FROM T1 t
JOIN T1 FirstT ON FirstT.t1ID = t.t1ID AND FirstT.t1m1 NOT IN (t2m1,t2m2,t2m3) AND FirstT.t1m2 IN (t2m1,t2m2,t2m3)
JOIN T1 SecondT ON SecondT.t1ID = t.t1ID AND SecondT.t1m2 NOT IN (t2m1,t2m2,t2m3) AND SecondT.t1m1 IN (t2m1,t2m2,t2m3)
JOIN T1 ThirdT ON ThirdT.t1ID = t.t1ID AND FirstT.t1m3 NOT IN (t2m1,t2m2,t2m3) and t1m1 IN (t2m1,t2m2,t2m3)enter code here
GROUP BY t1ID}
``` | creating temporary table and inserting data to it may help you |
2,542,764 | When would one choose to use Rx over TPL or are the 2 frameworks orthogonal?
From what I understand Rx is primarily intended to provide an abstraction over events and allow composition but it also allows for providing an abstraction over async operations.
using the Createxx overloads and the Fromxxx overloads and cancellation via disposing the IDisposable returned.
TPL also provides an abstraction for operations via Task and cancellation abilities.
My dilemma is when to use which and for what scenarios? | 2010/03/30 | [
"https://Stackoverflow.com/questions/2542764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84074/"
] | The main purpose of Rx is not to provide an abstraction over events. This is just one of its outcomes. Its primary purpose is to provide a composable push model for collections.
The reactive framework (Rx) is based on `IObservable<T>` being the mathematical dual of `IEnumerable<T>`. So rather than "pull" items from a collection using `IEnumerable<T>` we can have objects "pushed" to us via `IObservable<T>`.
Of course, when we actually go looking for observable sources things like events & async operations are excellent candidates.
The reactive framework naturally requires a multi-threaded model to be able to watch the sources of observable data and to manage queries and subscriptions. Rx actually makes heavy use of the TPL to do this.
So if you use Rx you are implicitly using the TPL.
You would use the TPL directly if you wish direct control over your tasks.
But if you have sources of data that you wish to observe and perform queries against then I thoroughly recommend the reactive framework. | Some guidelines I like to follow:
* Am I dealing with data that I don't originate. Data which arrives when it pleases? Then RX.
* Am I originating computations and need to manage concurrency? Then TPL.
* Am I managing multiple results, and need to choose from them based on time? Then RX. |
6,633,024 | ### Intro
So I've been experimenting with the Objective-C low-level runtime APIs defined in `<objc/runtime.h` and following [Apple's documentation](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html). You can see the results of my playing [in this gist](https://gist.github.com/1073294#file_array.m).
### Problem
I've been able to dynamically create a simple Hello World through Objective-C through only the low-level runtime APIs and C (see the gist above). It works. Now I'm trying to dynamically create a `NSMutableArray` using the same technique. Here's a snippet of the code:
```
Class nsmutablearray = objc_getClass("NSMutableArray");
id array = class_createInstance(nsmutablearray, 0);
id arrayAfterInit = objc_msgSend(array, sel_registerName("init"));
// get the count
objc_msgSend(arrayAfterInit, sel_registerName("count"))
```
But it's giving me an error:
`Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSArray count]: method only defined for abstract class. Define -[NSMutableArray count]!'`
But it works properly if I change the middle part of the snippet above to read:
```
id arrayAfterInit = objc_msgSend(nsmutablearray, sel_registerName("arrayWithCapacity:"), 10);
```
This is sort of confusing me since they should be equivalent. The first snippet should be equivalent to calling `[[NSMutableArray alloc] init]` which works as Objective-C syntax, but not when calling these C functions.
Any light shed on this would be greatly appreciated. Thanks in advance! | 2011/07/09 | [
"https://Stackoverflow.com/questions/6633024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376773/"
] | You can do it with [Google's Geocoding API](http://code.google.com/apis/maps/documentation/geocoding/). What you're actually looking for is reverse-geocoding, but it supports that too. You can have it return XML and then parse it for the postal code (a.k.a zipcode). Should be quite simple actually.
To use the API, simply access it by HTTP with the correct latitude and longitude:
<https://maps.googleapis.com/maps/api/geocode/xml?latlng=37.775,-122.4183333&sensor=true>
Then parse the XML using XPath, or your favorite XML parser (or just use JSON):
```
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//GeocodeResponse/result/address_component[type=\"postal_code\"]/long_name/text()";
InputSource inputSource = new InputSource("https://maps.googleapis.com/maps/api/geocode/xml?latlng=37.775,-122.4183333&sensor=true");
String zipcode = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
```
I haven't actually tested this bit of code (and it obviously needs exception handling), but I trust you'll be able to get it working from here.
As for getting the location itself, this previous question sums it up nicely:
[How do I get the current GPS location programmatically in Android?](https://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android) | There is no "easy way" to get the actual Zip Code of the user. You
could use the reverse geocoder function to do this but it doesn't
always return the Zip Code, nor is it always accurate. Either way,
you'll have to have location services and internet access active in
order to do it.
OR
--
Please check this [link](https://stackoverflow.com/q/5855843/614807). |
100,119 | I'm in the USA right now and would like to get some more cash with my non-US ATM card. However, a random sampling of ATMs at large banks (Wells Fargo, Citibank) has shown ATM fees in the $5-6 range, which is kind of ridiculous.
**Which major US banks have the lowest ATM fees for foreign cards?**
I've seen [this](https://travel.stackexchange.com/questions/3129/do-all-american-atms-charge-an-extra-fee-for-cash-withdrawals-on-a-foreign-card), which suggests credit unions and but not major banks (not so useful at eg. large airports). Also, [this](https://www.valuepenguin.com/banking/bank-atm-fees) crops up high on Google, but the costs don't match what I'm seeing. Extra points if you can explain which of "Non-network ATM Fee" and "ATM Operator Fee" apply in this situation.
For avoidance of doubt, I'm asking specifically about the **ATM fee charged by the US bank** here, not network fees, my bank's fees, exchange rates etc. | 2017/08/14 | [
"https://travel.stackexchange.com/questions/100119",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/1893/"
] | Most states do *not* allow ATMs to charge foreign cards a fee. California, where I live, is an exception, and the Citibank ATM has a list of states where the fee will be imposed. Either you are here or in one of the other such states.
Many 7-11s have an ATM with $2 or less fee. You might also see if your home bank has any sort of reciprocity arrangement. | I'm still looking for a more comprehensive answer, but I ended up withdrawing cash from a **Chase** ATM, which charged me a **$3** fee. |
4,929,549 | ```
if(heading == 2){
nextY = (y-1) % 20;
nextX = x;
}
```
When debugging this program, my heading is 2 and y = 0, however, when I come to this if statement, nextY becomes -1. Why is it not cycling properly? (0-19)? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4929549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546427/"
] | That's how mod operation generally works for negative numbers in programming (in all languages I tried it in).
But you can easily make number positive before doing mod
```
nextY = (y + 20 - 1) % 20;
``` | Modulo operators often return negative numbers for negative inputs. For example, C# will give you a number from `-356..359` for the expression `x % 360`.
Instead of subtracting 1 then taking modulo 20, you can add 19, which is the same thing but keeps the number positive, or you can use the ternary operator:
```
nextY = (y+19) % 20; // or
nextY = (nextY == 0) ? 19 : nextY - 1;
``` |
68,372,948 | I'm trying to see if I can use `dplyr`'s `coalesce` or something like it to combine rows in the same way `coalesce` combines columns.
I found some other similar posts but none that answer my question.
Here's a toy sample:
```
df <- read.table(sep = "|", header = F, stringsAsFactors = F, text =
"a|NA|NA|d|NA
NA|b|NA|NA|e
a|NA|c|NA|e
1|2|3|4|5
1|2|3|4|5
1|2|3|4|5
1|2|3|4|5")
> df
V1 V2 V3 V4 V5
1 a <NA> <NA> d <NA>
2 <NA> b <NA> <NA> e
3 a <NA> c <NA> e
4 1 2 3 4 5
5 1 2 3 4 5
6 1 2 3 4 5
7 1 2 3 4 5
```
I would like to combine rows 1, 2 and 3 into a single row that I can use as headers. The output should look like this:
```
V1 V2 V3 V4 V5
1 a b c d e
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
5 1 2 3 4 5
```
I was hoping something like this would work:
```
df %>%
rowwise() %>%
coalesce(1,2,3) %>%
slice(-c(1:2))
```
This worked but it feels clunky:
```
df %>%
slice(1:3) %>%
fill(everything(), .direction = "down") %>%
slice(3) %>%
bind_rows(df %>%
slice(-c(1:3)))
```
I'd like something more straightforward and elegant. | 2021/07/14 | [
"https://Stackoverflow.com/questions/68372948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7999936/"
] | You can also use the following solution:
```
library(dplyr)
library(janitor)
df %>%
mutate(across(everything(), ~ replace(.x, is.na(.x), unique(.x[!is.na(.x)[1:3]])[1]))) %>%
row_to_names(row_number = 1) %>%
slice(-c(1:2))
a b c d e
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
``` | Here is another solution using built-in functions and the native pipe operator:
```
df[1:3, ] |>
sapply(function(x) na.omit(x)[1]) |>
rbind(df[-(1:3), ])
# V1 V2 V3 V4 V5
# 1 a b c d e
# 4 1 2 3 4 5
# 5 1 2 3 4 5
# 6 1 2 3 4 5
# 7 1 2 3 4 5
``` |
201,093 | As the topic, how to prove that the only set in $\mathbb{R^1}$ which are both open and close are the $\mathbb{R^1}$ and $\emptyset$. I tried to prove by contradiction, but i can't really show that the assumption implies the contrary. | 2012/09/23 | [
"https://math.stackexchange.com/questions/201093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/42220/"
] | Let $S\subset \Bbb R$ non-empty, open and closed. Fix $x\_0\in S$. Let $I:=\{r>0:[x\_0-r,x\_0+r]\subset S\}$. As $S$ is open, $I$ is non-empty. If $I$ is bounded, let $\{r\_n\}$ be a sequence which increases to $\sup I$. Then $x\_0+r\_n\in S$ for each $n$, and as $S$ is closed, $x\_0+\sup I\in S$. But $S$ is open, so we can find $\delta>0$ such that $x\_0\pm \sup I\pm t \in S$ for $0\leq t\leq \delta$, hence $\sup I+\delta\in I$, a contradiction.
So $S=\Bbb R$.
Note that such an approach works for $\Bbb R^d$ instead of $\Bbb R$. Just replace the interval $[x\_0-r,x\_0+r]$ by the closed ball $\bar B(x^{(0)},r):=\{x\in\Bbb R^d,\max\_{1\leq j\leq d}|x\_j-x\_j^{(0)}|\leq r\}$. | Assume $U$ and its complement $V$ are both non-empty open subsets of $\mathbb R$. Then there are $x \in U$ and $y \in V$ and by switching the roles of $U$ and $V$, if necessary, we may assume $x < y$. Now let
$$a = \sup\{b \in \mathbb R : [x,b] \subseteq U \}$$
(the supremum exists since $x \in U$ and $y \not\in U$ and $x<y$). If $a \in U$ then, since $U$ is open, $a + \varepsilon \in U$ for small $\varepsilon$, contradicting the definition of $a$. Otherwise, if $a \in V$ then, since $V$ is also open, $a-\varepsilon \in V$ for small $\varepsilon$, again contradicting the definition of $a$. |
4,077,563 | I need to write a code that will copy one set of form values into another. And normally it is done by something like this:
```
<script type="text/javascript">
function copyGroup() {
if(document.formName.copy[0].checked){
document.formName.a1.value = document.formName.b1.value;
document.formName.a2.value = document.formName.b2.value;
document.formName.a3.value = document.formName.b3.value;
}
}
</script>
<form name="formName">
<input type="text" name="a1">
<br>
<input type="text" name="a2">
<br>
<input type="text" name="a3">
<br>
<input type="checkbox" name="copy" onSelect="copyGroup()"> Copy Group 1
<br>
<input type="text" name="b1">
<br>
<input type="text" name="b2">
<br>
<input type="text" name="b3">
<br>
<input type="submit">
</form>
```
However, I'd like to modify it in such a way that if the checkbox is selected and the the user went back and modified any values in group 1 -- the corresponding fields in group 2 are updated as well.
I think it can be done, but not sure how.
Thanks. | 2010/11/02 | [
"https://Stackoverflow.com/questions/4077563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434218/"
] | Hope this help:
```
function copyElement(copyFrom, whereToCopy) {
if(document.formName.copy.checked){
document.formName.elements[whereToCopy].value = copyFrom.value;
}
}
</script>
<form name="formName">
<input type="text" name="a1" onkeypress="copyElement(this, 'b1')">
<br>
<input type="text" name="a2" onkeypress="copyElement(this, 'b2')">
<br>
<input type="text" name="a3" onkeypress="copyElement(this, 'b3')">
<br>
<input type="checkbox" name="copy"> Copy Group 1
<br>
<input type="text" name="b1">
<br>
<input type="text" name="b2">
<br>
<input type="text" name="b3">
<br>
<input type="submit">
</form>
``` | Add onchange event to the elements and call your function. |
67,865,756 | I'm looking to calculate if there was an upgrade for a supplier, not the total count.
So, for each contract, for each supplier, was there an upgrade (regardless of the count/sum of upgrades)? If the result is yes, then the answer is 1.
[![enter image description here](https://i.stack.imgur.com/qNKWj.png)](https://i.stack.imgur.com/qNKWj.png)
In the example above the count of the upgrades is 9, but the answer I am looking to generate is 4.
I am guessing to calculate this I would need a combination of IF, AND, COUNTIF, MAX, but I can't seem to put it together.
Can anyone please help me out?
Thanks! | 2021/06/07 | [
"https://Stackoverflow.com/questions/67865756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16149504/"
] | Below formula should works. [Reference here](https://exceljet.net/formula/count-unique-values-with-criteria)
```
=IFERROR(ROWS(UNIQUE(FILTER(B2:B15, D2:D15>0))), 0)
``` | You could try the following:
[![enter image description here](https://i.stack.imgur.com/uINJD.png)](https://i.stack.imgur.com/uINJD.png)
Formula in `G2`:
```
=SUM((D2:D15>0)*(IFERROR(1/COUNTIFS(A2:A15,A2:A15,B2:B15,B2:B15,D2:D15,">0"),0)))
```
This is an CS-entered array formula if you are not working through MS365. |
2,928,212 | I was going through the source code of jQuery. I'm having trouble understanding the wrapping strategy for the jQuery object.
```
(function( window, undefined ) {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
....
....
....
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
```
Specifically, what I'm not able to understand stems from the first line.
1. What is the outermost unnamed container function? Why is it required?
2. Why is the container function anonymous?
3. What is the need for the outermost '(' parantheses ? | 2010/05/28 | [
"https://Stackoverflow.com/questions/2928212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293407/"
] | Duplicate of [javascript: execute a bunch of asynchronous method with one callback](https://stackoverflow.com/questions/2911822/javascript-execute-a-bunch-of-asynchronous-method-with-one-callback/2911891#2911891)
```
function createCallback(limit, fn){
var finishedCalls = 0;
return function(){
if (++finishedCalls == limit){
fn();
}
};
}
var callback = createCallback(4, function(){
alert("woot!");
});
async1(callback);
async2(callback);
async3(callback);
async4(callback);
``` | You can always use $.ajax with "async: false" in options and/or use proper callbacks (beforeSend, error, dataFilter, success and complete). |
11,250,297 | With `printf()`, I can use `%hhu` for `unsigned char`, `%hi` for a `short int`, `%zu` for a `size_t`, `%tx` for a `ptrdiff_t`, etc.
What conversion format specifier do I use for a `_Bool`? Does one exist in the standard?
Or do I have to cast it like this:
```
_Bool foo = 1;
printf("foo: %i\n", (int)foo);
``` | 2012/06/28 | [
"https://Stackoverflow.com/questions/11250297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712605/"
] | As you stated in a comment to @Jack, "6.3.1.1p1 says that the conversion rank of `_Bool` is less than the rank of all other standard integer types".
In a call to `printf`, a `char` or `short` will be promoted and passed on the stack as an `int` (or an `unsigned int`), so I would think that using `%d` as a format specifier would be fine. That also means that you don't need the explicit cast to `int`, because that will happen automatically.
The only possible issue would be with how the compiler represents a `_Bool`, something that it probably implementation defined and could vary from one compiler to another. I see two likely implementations -- 0 and 1 or 0 and -1.
For the ultimate in portability, follow @user325181's answer and use a ternary to choose between two options. Either integers (which the compiler may optimize away) or strings.
Edit: As reported in other answers, a `_Bool` is defined as an unsigned integral type that can store either 0 or 1. Because of that, and the fact that it will be promoted to an `unsigned``int` when passed to `printf()`, I would say that `%u``%d` is the most appropriate specifier. | There is no. Just handling it like an `int` by using `%d` or `%i` specifier.
[`_Bool`](http://en.wikipedia.org/wiki/Compatibility_of_C_and_C++)
>
> In C99, a new keyword, \_Bool, is introduced as the new boolean type.
> In many aspects, it behaves much like an unsigned int, but conversions
> from other integer types or pointers always constrained to 0 and 1.
> Other than for other unsigned types, and as one would expect for a
> boolean type, such a conversion is 0 if and only if the expression in
> question evaluates to 0 and it is 1 in all other cases. The header
> stdbool.h provides macros bool, true and false that are defined as
> \_Bool, 1 and 0, respectively.
>
>
>
The first way to implement it that come from into mind is by using a `char` or(`int8_t`) an `enum` and with [`bit fields`](http://en.wikipedia.org/wiki/Bit_field). But actually, it depends. It can be a `typedef` for an `int`(as I've mentioned, it's used, but is not recommend, subject to bugs) or `char` or `unsigned int` or an enum and `#define` that's commonly used.
For exampe, [Apple's implementation](http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/EXTERNAL_HEADERS/stdbool.h) uses `int`,as you can see:
```
#ifndef _STDBOOL_H_
#define _STDBOOL_H_
#define __bool_true_false_are_defined 1
#ifndef __cplusplus
#define false 0
#define true 1
#define bool _Bool
#if __STDC_VERSION__ < 199901L && __GNUC__ < 3
typedef int _Bool;
#endif
#endif /* !__cplusplus */
#endif /* !_STDBOOL_H_ */
```
Others implementations:
[`typedef int8_t _Bool;`](https://stackoverflow.com/questions/25461/interfacing-with-stdbool-h-c)
[`typedef enum
{
false = 0,
true = 1
} bool;`](http://read.pudn.com/downloads33/sourcecode/hack/firewall/105210/CDROM/lib/gcc-lib/i386-mingw32/2.95.2/include/stdbool.h__.htm)
[`typedef unsigned char Boolean; typedef _Bool Boolean;`](http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/libkern/libkern/OSTypes.h) |
24,127,587 | I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa `NSPointerArray` offers a non-typesafe version of this. | 2014/06/09 | [
"https://Stackoverflow.com/questions/24127587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126855/"
] | A functional programming approach
=================================
No extra class needed.
Simply define an array of closures `() -> Foo?` and capture the foo instance as weak using `[weak foo]`.
```swift
let foo = Foo()
var foos = [() -> Foo?]()
foos.append({ [weak foo] in return foo })
foos.forEach { $0()?.doSomething() }
``` | You could create wrapper around `Array`. Or use this library <https://github.com/NickRybalko/WeakPointerArray>
`let array = WeakPointerArray<AnyObject>()`
It is type safe. |
40,828,529 | It is my first time doing a Petri net, and I want to model a washing machine. I have started and it looks like this so far:
[![](https://i.stack.imgur.com/QIEWc.png)](https://i.stack.imgur.com/QIEWc.png)
Do you have any corrections or help? I obviously know its not correct, but I am a beginner and not aware of the mistakes you guys might see. Thanks in advance. | 2016/11/27 | [
"https://Stackoverflow.com/questions/40828529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5762696/"
] | First comments on your net's way of working:
* there is no arrow back to the `off` state. So once you switch on your washing machine, won't you never be able to switch it off again ?
* `drain` and `dry` both conduct back to `idle`. But when idle has a token, it will either go to delicate or to T1. The conditions ("program" chosen by the operator) don't vanish, so they would be triggered again and again.
Considering the last point, I'd suggest to have a different idle for the end of the program to avoid this cycling. If you have to pass several times through the same state but take different actions depending on the progress, you have to work with more tokens.
Some remarks about the net's form:
* you don't need to put the 1 on every arc. You could make this more readable by Leaving the 1 out and indicating a number on an arc, only when more than one tokens would be needed.
* usually, the transitions are not aligned with the arcs (although nothing forbids is) but rather perpendicular to the flow (here, horizontal)
* In principle, "places" (nodes) represent states or resources, and "transitions" (rectangles) represent an event that changes the state (or an action that consumes resources). Your naming convention should better reflect this | Apparently you're missing some condition to stop the process. Now once you start your washing will continue in an endless loop. |
46,481,699 | I just got DB server from infra team which configured by previous team.
I found out that the SQL Server Database can only be opened using Windows Authentication using installation name like "SQLEXPRESS\SQLEXPRESS"
I am working on this Database in local Database machine.
I am curious, why i can't use the localhost name or even IP to connect to Database even i am on the DB server itself using the SQL Server Management Studio.
[Error when connect using HostName](https://i.stack.imgur.com/v7xHQ.png)
I have verified the sa account does exist and updated the password.
When i tried connect using IP, it said The system cannot find the file specified.
[Error when connecting using IP](https://i.stack.imgur.com/uaJMr.png)
I have checked the SQL Configuration Manager, all the Client setting has been set to Enabled. Checked the Firewall, it is not set ON for the DB server. SQL DB services are up since i can connect using Windows Authentication.
I tried to PING to either hostname and IP from command prompt, it is connecting successfully and able to resolve the host name.
I have compared the DB setting with other Database which i can connect using DNS/IP, everything looks fine to me.
Appreciate if anyone can advise, what did i miss to check?
Thank you.
Best Regards,
Fanny T | 2017/09/29 | [
"https://Stackoverflow.com/questions/46481699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8643485/"
] | Just take row's parent click in adapter and catch the ID column from that click.
```
Item_ID.get(position);
```
And then pass this through the intent to the Activity where you want to show all the data. And then get that ID and query to the database to get all the data.
```
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
``` | You can use `adapter.notifyDataSetChanged();` to refresh the listview. |
6,203,189 | I'm currently trying to make some show/hide content more accessible on a large site (in excess of 30,000 pages) and I've come across a weird bug when adding tabindex where a dotted border appears when clicking on the control to open the hidden content.
The set up with *p* tag which you click to fadeIn a *div* which shows the hidden content. **I can't modify the HTML at all due to there being thousands of these across the site** so this is what I have to work with. At the moment to add tabindex i'm doing it dynamically with jQuery, adding an ever increasing tab index to each *p* tag.
My first though to get rid of this weird border was to try CSS:
```
#content div.showHide p.showHideTitle:focus,
#content div.showHide p.showHideTitle::focus,
#content div.showHide p.showHideTitle::-moz-focus-border {
outline: 0px !important; border: 0px !important;
}
```
This works in Chrome and Safari but in IE8 and Firefox 3.6 I still get the border when I click on the *p* tag. Any suggestions for how to get rid of it? | 2011/06/01 | [
"https://Stackoverflow.com/questions/6203189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690363/"
] | whats about:
```
#content div.showHide p.showHideTitle {
outline: none !important;
}
```
You are setting the outline style for the pseudo class `:focus` but this may be "to late".
Here a simple [jsFiddle](http://jsfiddle.net/GPnxS/) | Have you tried setting the `css` with your script? Something like
```
$("#content div.showHide p.showHideTitle").focus(function () {
$(this).css('border','0');
});
``` |
36,980,868 | I am taking my first steps with Angular 2 and angular in general, and I am wondering how to setup a landing page.
My goal is to show a landingpage everytime the user does not have a token in local storage or in a cookie.
My app.component.ts looks like this
```
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router';
import {NavbarComponent} from './navbar.component';
import {LoaderComponent} from './loader.component';
import {NameListService} from '../shared/index';
import {HomeComponent} from '../+home/index';
import {AboutComponent} from '../+about/index';
@Component({
selector: 'g-app',
viewProviders: [NameListService],
templateUrl: 'app/components/app.component.html',
directives: [ROUTER_DIRECTIVES, NavbarComponent, LoaderComponent]
})
@RouteConfig([
{
path: '/',
name: 'Home',
component: HomeComponent
},
{
path: '/about',
name: 'About',
component: AboutComponent
}
])
export class AppComponent {
}
```
/home and /about are also components if I understand correctly. Now I would like to have a seperate page that doesn't have access to the navbar. Which is what the user will always land on if he isn't logged in.
Would be awesome if someone could help me start out or atleast point me in a good direction, maybe point me to a good angular 2 tutorial.
This is the boilerplate I am basing my app on <https://github.com/mgechev/angular2-seed> | 2016/05/02 | [
"https://Stackoverflow.com/questions/36980868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648229/"
] | You can override the router-outlet and check on activation, if the token is present. Something like this:
```
import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
@Directive({
selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, @Attribute('name') nameAttr: string) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
}
activate(instruction: ComponentInstruction) {
if (!hasToken()) {
this.parentRouter.navigateByUrl('/login');
}
return super.activate(instruction);
}
}
```
Adapted from here: <https://github.com/auth0-blog/angular2-authentication-sample/blob/master/src/app/LoggedInOutlet.ts>
---
This can be extended to be able to work with roles and other access controlls. | You can just redirect to a specific route on load when the token is not available.
```
export class AppComponent {
constructor(private router:Router) {
if(!hasToken()) {
router.navigate(['/LoginForm']);
}
}
}
```
Alternatively you can create a custom `RouterOutlet` that checks for each route if it is allowed for the user to navigate to that route like explained in <http://www.captaincodeman.com/2016/03/31/angular2-route-security/> |
71,321,951 | I am trying to move CSV files in SFTP folder to GCS using Data Fusion. But I am unable to do it and throwing below error:
Here are the properties of both FTP and GCS plugins. Surprisingly, I could see the data in PREVIEW mode in all the stages but when I try to deploy the pipeline it fails. I tried using CSVParser as well as a TRANSFORM in between source(FTP) and sink (GCS). Still it shows the same error. I am using FTP plugin in Hub with version 3.0.0. Please help me to solve it.
[![enter image description here](https://i.stack.imgur.com/3bNhT.png)](https://i.stack.imgur.com/3bNhT.png)
And the error is as below, when I try to deploy the pipeline, eventhough Preview Data I was able to see the data.
[![enter image description here](https://i.stack.imgur.com/FhXUi.png)](https://i.stack.imgur.com/FhXUi.png) | 2022/03/02 | [
"https://Stackoverflow.com/questions/71321951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10601337/"
] | I solved this issue by changing the Pipeline execution engine from SPARK to MAPREDUCE in Data Fusion. Now it is working. | Well I have dig a lot on this, I found that this plugins have issues when running [ftp-plugins](https://github.com/data-integrations/ftp-plugins), so at the moment you can't do much on it. Fortunately, there are workarounds for this. To name a few here are some:
* You can use an old version ( Dataproc image to 1.5/1.3 ) as indicated on the public case that also makes reference to this issue. For more details about this case, you can check the link for the issue, [SFTP Source fails when deployed (SftpExecption) but not in preview](https://issuetracker.google.com/issues/217049303). Don't forget to upvote and leave a comment too.
* Another way is to use `SFTPCopy` plugin (once you pick up from the hub it should appear under `Conditions and Actions`). So you will be able to pick up the file from your SFTP into a local path and the use Source `FILE` to continue with the processing of your file. There is a small guide on [Reading from SFTP and writing to BigQuery](https://cdap.atlassian.net/wiki/spaces/DOCS/pages/1162707191/Reading+from+SFTP+and+writing+to+BigQuery)
* This one is a bit extreme but you can also use a different workflow management platform like [airflow](https://airflow.apache.org/) for file processing. |
42,906,515 | I have the following entity:
```
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
class Quote
{
use SourceTrait;
use TimestampableEntity;
private $quoteId;
private $startDate;
private $endDate;
public function getStartDate(): ?\DateTime
{
return $this->startDate;
}
public function setStartDate(\DateTime $startDate)
{
$this->startDate = $startDate;
}
public function getEndDate(): ?\DateTime
{
return $this->endDate;
}
public function setEndDate(\DateTime $endDate)
{
$this->endDate = $endDate;
}
}
```
and I have this method in the `QuoteRepository` class:
```
public function createQuoteHeader(Agreement $agreement): int
{
$em = $this->getEntityManager();
$QuoteID = $this->getNewQuoteId();
$year = $agreement->getEndDate()->diff($agreement->getStartDate(), true)->y > 0
? $agreement->getEndDate()->diff($agreement->getStartDate(), true)->y
: 0;
dump($year);
dump(gettype($year));
dump($agreement->getEndDate());
$entity = new Quote();
...
$entity->setStartDate($agreement->getEndDate()->modify('+1 day'));
dump($agreement->getStartDate());
$entity->setEndDate($agreement->getEndDate()->modify("+1 day +{$year} year"));
dump($agreement->getEndDate());
...
$em->persist($entity);
$em->flush();
return $entity->getQuoteId();
}
```
The output from the `dump()` above are as follow (same order as in code):
```
0
"integer"
DateTime {#3005
+"date": "2017-03-21 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
DateTime {#3004
+"date": "2016-03-22 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
DateTime {#3005
+"date": "2017-03-23 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
```
Somehow the wrong values are being inserted in DB:
[![enter image description here](https://i.stack.imgur.com/Ou58v.png)](https://i.stack.imgur.com/Ou58v.png)
Maybe I am missing something but should not be `StartDate` equal to `2016-03-22 00:00:00`?? | 2017/03/20 | [
"https://Stackoverflow.com/questions/42906515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719427/"
] | Let's walk through your code line by line.
```
$entity->setStartDate($agreement->getEndDate()->modify('+1 day'));
```
[`modify()`](http://php.net/manual/en/datetime.modify.php) **mutates the `DateTime` object it is called upon**.
This line added +1 day to `$agreement->getEndDate()` AND the **same** DateTime is passed to `$entity->setStartDate()`. So BOTH `$agreement->getEndDate()` and `$entity->getStartDate()` will return 2017-03-22!
```
dump($agreement->getStartDate());
```
You dumped the wrong date, hence 2016-03-22, masking the error. Should be `dump($entity->getStartDate());` and you would have noticed.
```
$entity->setEndDate($agreement->getEndDate()->modify("+1 day +{$year} year"));
```
Since `$agreement->getEndDate()` is now equal to 2017-03-22, +1 day +0 year will result in `$entity->getEndDate()` being equal to 2017-03-23.
I recommend using [`DateTimeImmutable`](http://php.net/manual/en/class.datetimeimmutable.php) to avoid all these unnecessary issues with object references. | It seems to be a problem with the object you are trying to persist. You are getting the right result when you make dump(), but the datetime object is being modified later, so when you persist the object, all of the values get your last datetime result.
I recommend you to make "clone" in your datetime objects, and set the values separetely, something like this:
```
$oDatetime1 = clone($agreement->getEndDate());
$oDatetime2 = clone($agreement->getEndDate());
$entity->setStartDate($oDatetime1->modify('+1 day'));
$entity->setEndDate($oDatetime2->modify("+1 day +{$year} year"));
``` |
58,201,577 | I have two tables CDmachine and trnasaction.
CDMachine Table with columns CDMachineID, CDMachineName, InstallationDate
Transaction table with columns TransactionID,CDMachineID,TransactionTime,Amount
I am calculating revenue using the below query but it eliminates the machine without any transaction
```
SELECT CDMachine.MachineName,
SUM(Transaction.Amount)
FROM CDMachine
LEFT JOIN TRANSACTION ON CDMachine.CDMachineID = Transaction.CDMachineID
WHERE Transaction.TransactionTime BETWEEN '2019-01-01' AND '2019-01-31'
GROUP BY CDMachine.CDMachineName
ORDER BY 2
``` | 2019/10/02 | [
"https://Stackoverflow.com/questions/58201577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10689523/"
] | Move the `WHERE` condition to the `ON` clause:
```
select m.MachineName, sum(t.Amount)
from CDMachine m left join
Transaction t
on m.CDMachineID = t.CDMachineID and
t.TransactionTime between '2019-01-01' and '2019-01-31'
group by m.CDMachineName
order by 2;
```
The `WHERE` clause turns the outer join to an inner join -- meaning that you are losing the values that do not match.
If you want `0` rather than `NULL` for the sum, then use:
```
select m.MachineName, coalesce(sum(t.Amount), 0)
``` | Even though you are using a LEFT JOIN, the fact that you have a filter on a column from the joined table causes rows that don't meet the join condition to be removed from the result set.
You need to apply the filter on transaction time to the transactions table, before joining it or as part of the join condition. I would do it like this:
```
SELECT CDMachine.MachineName,
SUM(Transaction.Amount)
FROM CDMachine
LEFT JOIN (
SELECT * FROM TRANSACTION
WHERE Transaction.TransactionTime BETWEEN '2019-01-01' AND '2019-01-31'
) AS Transaction
ON CDMachine.CDMachineID = Transaction.CDMachineID
GROUP BY CDMachine.CDMachineName
ORDER BY 2
``` |
52,804,282 | I have use two different classes:
*ListTitle.kt*
```
class ListTitle {
var id: Int? = null
var title: String? = null
constructor(id:Int, title: String) {
this.id = id
this.title = title
}
}
```
*ListDes.kt*
```
class ListDes {
var address: Int? = null
var des: String? = null
constructor(address: Int, des: String) {
this.address = address
this.des = des
}
}
```
`listOfTitle` and `listDes` are `ArrayList`s:
```
listOfTitle.add(ListTitle(1, "Hello"))
listOfTitle.add(ListTitle(2, "World"))
listDes.add(ListDes(1, "World Des"))
listDes.add(ListDes(2, "Hello Des"))
```
I want to assign `title` of `ListTitle` to `des` of `ListDes` by matching them by `id`/`address` for each element of the two lists.
How can I approach this? | 2018/10/14 | [
"https://Stackoverflow.com/questions/52804282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10503160/"
] | You can use [zip](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/zip.html) to merge two lists into one which has `Pairs` as elements.
```
val listOfTitle = listOf(ListTitle(1, "Hello"), ListTitle(2, "World"))
val listDes = listOf(ListDes(1, "World Des"), ListDes(2, "Hello Des"))
val pairList = listOfTitle.zip(listDes)
// since an element in the new list is a pair, we can use destructuring declaration
pairList.forEach { (title, des) ->
println("${title.title} ${des.des}")
}
```
**Output:**
>
> Hello World Des
>
> World Hello Des
>
>
>
**A few notes:**
You can write your classes in a shorter form in Kotlin. Just put the properties directly in the argument list of the primary constructor like shown below.
```
class ListTitle(
var id: Int? = null,
var title: String? = null
)
class ListDes(
var address: Int? = null,
var des: String? = null
)
```
* Don't overuse nullability (using `Int?` instead of `Int` for instance). Make properties only nullable if necessary. If you always pass in arguments for the specified properties there is not need for them to be nullable.
* Maybe you should choose other names for the classes (without "List" in it) since they are actually elements of a `List` in your example and not lists themselves. | If you just want to print the values you could do this:
```
listOfTitle.forEach {
val id = it.id
println(it.title + " " + listDes.filter { it.address == id }[0].des)
}
```
will print the matching `des` for each `id`:
```
Hello World Des
World Hello Des
```
The above code is supposed to work when both lists have the same length and there is always a matching `des` for each `id`
if you want to create a new list with the matching pairs:
```
val newList = listOfTitle.map { it ->
val id = it.id
Pair(it.title, listDes.filter { it.address == id }[0].des)
}
newList.forEach { println(it.first + " " + it.second) }
``` |
273,723 | I'd like to run these scans on our test/dev sites, but they're currently behind a IP restricted firewall.
Are you able to provide your public IPs so that I can whitelist them for | 2019/05/07 | [
"https://magento.stackexchange.com/questions/273723",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/76875/"
] | You can override the class **\Magento\Catalog\Block\Adminhtml\Product** using di.xml preference as describe below.
Assume you are using a custom module name "**Company\_MyModule**"
**step 1:** create **di.xml** under YOUR-MAGENTO-**ROOT/app/code/Company/MyModule/etc/adminhtml**
File: **YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/adminhtml/di.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Adminhtml\Product" type="Company\MyModule\Block\Adminhtml\Product" />
</config>
```
**step 2:** Create the class **Product.php** under **YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Block/Adminhtml**
File : **YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Block/Adminhtml/Product.php**
```
<?php
namespace Company\MyModule\Block\Adminhtml;
class Product extends \Magento\Catalog\Block\Adminhtml\Product
{
protected function _getAddProductButtonOptions()
{
/* var Array $arrAlowedTypes */
$arrAlowedTypesIds = array('simple');
$splitButtonOptions = [];
$types = $this->_typeFactory->create()->getTypes();
uasort(
$types,
function ($elementOne, $elementTwo) {
return ($elementOne['sort_order'] < $elementTwo['sort_order']) ? -1 : 1;
}
);
foreach ($types as $typeId => $type) {
if(in_array($typeId,$arrAlowedTypesIds)) {
$splitButtonOptions[$typeId] = [
'label' => __($type['label']),
'onclick' => "setLocation('" . $this->_getProductCreateUrl($typeId) . "')",
'default' => \Magento\Catalog\Model\Product\Type::DEFAULT_TYPE == $typeId,
];
}
}
return $splitButtonOptions;
}
}
```
**Step 3:** Run DI compile
```
sudo php bin/magento setup:di:compile
```
[![enter image description here](https://i.stack.imgur.com/8OblT.png)](https://i.stack.imgur.com/8OblT.png) | To disable access from direct URL.
You can override the class **\Magento\Catalog\Block\Adminhtml\Product** using di.xml preference as described below.
Assume you are using a custom module name "**Company\_MyModule**"
**step 1:** create **di.xml** under YOUR-MAGENTO-**ROOT/app/code/Company/MyModule/etc/adminhtml**
File: **YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/adminhtml/di.xml**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Controller\Adminhtml\Product\NewAction"
type="Company\My-Module\Controller\Adminhtml\Product\NewAction" />
</config>
```
**step 2:** Create the class **NewAction.php** under **YOUR-MAGENTO-ROOT/Company/MyModule/Controller/Adminhtml/**
File : **YOUR-MAGENTO-ROOT/Company/MyModule/Controller/Adminhtml/NewAction.php**
```
<?php
namespace Company\MyModule\Controller\Adminhtml\Product;
class NewAction extends \Magento\Catalog\Controller\Adminhtml\Product\NewAction
{
public function execute()
{
if (!$this->getRequest()->getParam('set')) {
return $this->resultForwardFactory->create()->forward('noroute');
}
$arrAlowedTypesIds = array('simple');
$typeId = $this->getRequest()->getParam('type');
if(!in_array($typeId,$arrAlowedTypesIds)) {
return $this->resultForwardFactory->create()->forward('noroute');
}
return parent::execute();
}
}
```
**Step 3:** Run DI compile
```
sudo php bin/magento setup:di:compile
```
[![Product page - Magento 2](https://i.stack.imgur.com/8OblT.png)](https://i.stack.imgur.com/8OblT.png) |
153,861 | So I am redoing light fixtures in my 1946 house located in the USA. I guess I'm overly scared of asbestos, and just wondering on your opinion if this household branch wire is asbestos containing.
It is hard to find images on the internet showing examples of what is and what is not. I could get this tested, but at the same time, My exposure would be very limited I think.
Would it be worth while to mist the wires with water (electricity off) to reduce dust? How do you all deal with things like this?
[![enter image description here](https://i.stack.imgur.com/6uTxR.jpg)](https://i.stack.imgur.com/6uTxR.jpg) | 2019/01/01 | [
"https://diy.stackexchange.com/questions/153861",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/94995/"
] | I've been in the industry for over 40 years and have never heard of asbestos in the old wiring insulation. It is oil-impregnated cloth I believe. The more pressing problems that I see from your photo are that the cloth insulation may start to crumble off the copper conductors when you manipulate the wires and that the junction box appears to be overfilled. If the conductors have been run through metal conduit then you should be able to pull new wires if necessary. If the conductors are encased in armored cable conduit aka BX then you may need to call in a real sparky. If the box is indeed overfilled then you can install an extension ring and get creative with the fabrication of a little frame around the extension ring before installing the new fixture. | Even if there is asbestos present in that box, I'd say the hazards of messing with the wiring are far greater than the asbestos exposure, you don't develop asbestosis from the trace exposure that would be possible here. A little reading of materials readily available online may give your concerns some perspective.
The insulation on old cloth covered wiring may be deteriorating to the point it's dangerous. It's generally best not to disturb it if you don't have to, and if you have to, be prepared to potentially create a very big job rewiring. |
69,766,994 | I am getting the below error while creating a Logic App from the portal.
>
> "Creation of storage file share failed with: 'The remote server
> returned an error: (403) Forbidden.'. Please check if the storage
> account is accessible."
>
>
>
While selecting the initial Logic App configuration, I am selecting an existing storage account, which should allow accesses from azure trusted services (configuration below).
[![enter image description here](https://i.stack.imgur.com/BvDHN.png)](https://i.stack.imgur.com/BvDHN.png)
[![enter image description here](https://i.stack.imgur.com/1blOs.png)](https://i.stack.imgur.com/1blOs.png)
This will fail if there are private endpoints defined in the storage account (like in the images below), but also without defining private endpoints. And since the "Allow Azure trusted services" setting is turned on, I believe these shouldn't disallow public traffic, and trusted services should be able to communicate with the storage account via the Azure backbone. Right?
But assuming that Azure Resource Manager is not a trusted Azure service, I whitelisted the Azure Resource Manager [IP addresses](https://saasedl.paloaltonetworks.com/feeds/azure/public/azureresourcemanager/ipv4), and the outcome was still the same.
Any idea what might be the issue(s) here? | 2021/10/29 | [
"https://Stackoverflow.com/questions/69766994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1198379/"
] | It seems not to be possible to deploy a Standard Logic App from the portal, if the targeted storage account will be hidden behind a firewall. The workaround is to [deploy the Standard Logic app via ARM template](https://github.com/VeeraMS/LogicApp-deployment-with-Secure-Storage/). What will happen is that first the Storage account & File share will be created, and and then the firewall will be enabled on it.
The resources will be created in the following order:
1. Storage account which denies the public traffic.
2. VNET and Subnets.
3. Private DNS Zones and Private Endpoints for blob, file, queue, and table services.
4. File Share (Logicapp App settings requires a file share to create the host runtime directories and files).
5. App Service Plan (Workflow standard -WS1) to host Standard Logic App resources.
6. Standard Logic App, and set network config with the VNET integration (to connect to storage account on private endpoints).
More information [here](https://techcommunity.microsoft.com/t5/integrations-on-azure/deploying-standard-logic-app-to-storage-account-behind-firewall/ba-p/2626286). | I had the same error when I deploy my logic app via Bicep, the storage account for the logic app has firewall rules set.
The error message:
>
> ##[error]undefined: Creation of storage file share failed with: 'The remote server returned an error: (403) Forbidden.'. Please check if the storage account is accessible.
>
>
>
Details of the infrastructure:
* Standard logic app in App Service Plan
* Storage Account V1
* Storage account firewall rules:
[image](https://i.stack.imgur.com/NflwU.png)
* App Settings:
[image](https://i.stack.imgur.com/lSxU9.png)
It seems when the logic app is deployed, the traffic is not going through the VNet so even the VNet setting is set to the storage account, the traffic is still denied.
After searching on the internet, found a [post](https://azurecloudai.blog/2021/02/08/deploying-azure-function-with-network-restricted-storage/) from matthewking8813.
Adding App Settings of `WEBSITE_CONTENTOVERVNET` to `1` that works for me.[MS Doc about `WEBSITE_CONTENTOVERVNET`](https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#website_contentovervnet)
I didn't set up `WEBSITE_DNS_SERVER` and has `AzureWebJobsStorage` set up already in my Bicep file.
For deploying through portal, I can't find a place to set up App Settings during creation, may need to raise a ticket to MS for this. |
10,100,940 | how does the browser differentiate a cookie is from client-side created (JavaScript) or server-side created (ASP.NET). Is it possible to delete cookie created from server side in client side and vice versa, I'm struggling to delete a cookie was created from client-side using javascript in ASP.NET code-behind. | 2012/04/11 | [
"https://Stackoverflow.com/questions/10100940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797528/"
] | >
> how does the browser differentiate a cookie is from Client side(javascript created) or serverside created (Asp.net).
>
>
>
It doesn't. A cookie is a cookie.
The closest it comes is the *HTTP Only* flag, which allows a cookie to be hidden from JavaScript. (This provides a little defence against XSS cookie theft).
>
> it is possible to delete cookie created from server side in client side and vice versa
>
>
>
Yes. A cookie is a cookie. (Again, client side code can't touch an HTTP only cookie) | As far as I know it is possible if there is not property **HttpOnly** [owasp](https://www.owasp.org/index.php/HttpOnly) [wikipedia](http://en.wikipedia.org/wiki/HTTP_cookie#HttpOnly_cookie).
In chrome, for the cookies, there is a field - **Accessible by script**, which indicates if HttpOnly is set. |
3,645,712 | this question is from Codechef.com [if anyone is still solving this question dont look further into the post before trying yourself] and although it runs right, but i need to make it a lot faster.i am a beginner in c,c++.(i know stuff upto arrays,strings and pointers but not file handling etc).So is there a way to make this program run any faster without making it complex(its ok if its complex in algorithm).
i will accept complex coding too if u mention which book u followed where it is all given :) .
i currently am following Robert Lafore.
Here is the program:-
There are N numbers a[0],a[1]..a[N - 1]. Initally all are 0. You have to perform two types of operations :
1) Increase the numbers between indices A and B by 1. This is represented by the command "0 A B"
2) Answer how many numbers between indices A and B are divisible by 3. This is represented by the command "1 A B".
Input :
The first line contains two integers, N and Q. Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above.
Output :
Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query.
Sample Input :
```
4 7
1 0 3
0 1 2
0 1 3
1 0 0
0 0 3
1 3 3
1 0 3
```
Sample Output :
```
4
1
0
2
```
Constraints :
```
1 <= N <= 100000
1 <= Q <= 100000
0 <= A <= B <= N - 1
```
***HERE IS MY SOLUTION:-***
```
#include<stdio.h>
int main()
{
unsigned int n; //amount of numbers taken
scanf("%u",&n);
unsigned int arr[n],q,a,b,count=0,j,i;
short int c;
scanf("%u",&q);//cases taken
for(i=0;i<n;++i)
{
arr[i]=0;
}
for(i=0;i<q;++i)
{
scanf("%d%u%u",&c,&a,&b);//here a,b are A and B respectively and c is either
//o or 1
if(c==0)
{
for(j=a;j<=b;++j)
arr[j]++;
}
if(c==1)
{
for(j=a;j<=b;++j)
{
if(arr[j]%3==0)
count++;
}
printf("%u\n",count);
}
count=0;
}
}
``` | 2010/09/05 | [
"https://Stackoverflow.com/questions/3645712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439970/"
] | >
> 1) Increase the numbers between indices A and B by 1. This is represented by the command "0 A B"
>
>
> 2) Answer how many numbers between indices A and B are divisible by 3. This is represented by the command "1 A B".
>
>
>
Initially numbers are 0 and thus are divisible by 3. Increment by one make the number non-divisible. Next increment - number still non-divisible. Third increment makes the number again divisible.
First optimization one can try is to not to let number grow above 2: if during increment number goes from 2 to 3, set it back to zero. Now search for the range become a simple comparison with 0. (That way array would contain instead of the number its modulo 3.)
Second optimization is to use extents instead of plain array, e.g. something similar to the [RLE](http://en.wikipedia.org/wiki/Run-length_encoding): collapse into a range all adjacent numbers with the same divisibility. Instead of numbers, the array would contain structures like that:
```
struct extent {
int start; /* 0 .. N-1; extent should have at least one number */
int end; /* 0 .. N */
int n; /* 0, 1, 2; we are only interested in the result of % */
};
```
Initially the array would contain single extent covering the all numbers `{0, N, 0}`. During increment step, a range might be split or joined with adjacent one. That representation would speed-up the counting of numbers as you would go over the array not one-by-one but in chunks. (It would still degrade to the linear search if all ranges are contain only one element.)
---
Another approach could be to use instead of the array three sets with indeces. Set #0 would contain all the indeces of numbers whose modulo 3 is 0, set #1 - 1, set #2 - 2. Since during increment operation, we need to do a search, instead of `std::set` it is better to use e.g. [`std::bitset`](http://www.sgi.com/tech/stl/bitset.html) with every bit marking the index of the number belonging to the set.
N.B. This way we do not keep the original numbers at all. We implicitly keep only the result of modulo 3.
During increment, we need to find which set the index belongs to, e.g. set #n, and *move* the index to the next (mod 3) set: set the bit to zero in the set `n`, set the bit to 1 in the set `n + 1 (mod 3)`. Counting numbers divisible by 3 now ends up being as simple as counting the non-zero bits in the set #0. That can be accomplished by creating a temp `std::bitset` as a mask with bits in range `[A,B]` set to one, masking with the temp set the set #0 and calling `std::bitset::count()` on the resulting bitset. | Your solution seems fine I think apart from lacking any bounds checking. Maybe use an 'else' when checking 'c' or a switch, but this will save you trivial amounts of time.
I don't think you'll find something as useless as this in any book. |
59,785,266 | I am beginner on rails. I want to list Brands-Products list. Brands and products must be association. I dont know what to do. Please suggest me example like this. | 2020/01/17 | [
"https://Stackoverflow.com/questions/59785266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12038747/"
] | The walker, I assume, asynchronously accesses files starting from your defined folder, `/etc/`, and as it access files and folders as it's walking, it fires events.
Every time it accesses any element, whether its a file or a folder or whatever, I would imagine it fires the `'entry'` event.
Every time it accesses a file, it fires the `'file'` event.
Every time it accesses a directory, it fires the `'dir'` event.
The first parameter to `.on` defines what events you want to register a callback to, and the second one is the callback itself, which takes as its first argument the element in question, or the path to it. | Those are function parameters. They define variable names that get values when the function is called.
```js
const myFunction = function(dir, stat) {
console.log('Got directory: ' + dir)
};
myFunction("Foo", "Bar");
```
It is just that the function is called by *code you did not write yourself*. |
116,074 | I'm searching for an simple shell script to `mv` all folders in `/var/www/uploads/` that containing **Math** or **Physics** in the name to `/mnt/Backup/`. | 2014/02/20 | [
"https://unix.stackexchange.com/questions/116074",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/51005/"
] | Granting 775 permissions on a directory doesn't automatically mean that all users in a certain group will gain `rwx` access to it. They need to either be the owner of the directory or to belong to the directory's group:
```
$ ls -ld some_dir
drwxrwxr-x 2 alex consult 4096 Feb 20 10:10 some_dir/
^ ^
| |_____ directory's group
|___________ directory's owner
```
So, in order to allow both alex and ben to have write access to `some_dir`, the `some_dir` directory itself must belong to the `consult` group. If that's not the case, the directory's owner (alex in your example), should issue the following command:
```
$ chgrp consult some_dir/
```
or to change group ownership of everything inside the directory:
```
$ chgrp -R consult some_dir/
```
This will only work if alex is a member of the `consult` group, which seems to be the case in your example.
This will not allow ben to access all of alex's directories for two reasons:
1. Not all of alex's directories will belong to the `consult` group
2. Some of alex's directories may belong to the `consult` group but alex may not have chosen to allow `rwx` group access to them.
In short, the answer depends both on group ownership and on the group permission bits set for the directory.
All of this is provided you don't use any additional [mandatory access control](http://en.wikipedia.org/wiki/Mandatory_access_control) measures on your system. | This will make alex and ben to colabrate each other in this Directory, And they can't collab in other Dir..
Modify the User group using
```
# usermod -a -G alex,ben alex
```
Then change the Permission for Folder
```
# chown alex:ben consult_documents
```
Check here i have worked it around
```
$ sudo usermod -a -G alex,ben alex
$ sudo chown alex:ben consult_documents/
cd consult_documents/
$ touch babin
drwxrwxr-x 2 alex ben 4096 Feb 20 15:19 .
drwxr-xr-x 3 alex alex 4096 Feb 20 15:17 ..
-rw-rw-r-- 1 alex alex 0 Feb 20 15:19 babin
$ su - ben
cd /home/alex/consult_documents/
ben@system99:/home/alex/consult_documents$ touch babin1
ben@system99:/home/alex/consult_documents$ ls -la
total 8
drwxrwxr-x 2 alex ben 4096 Feb 20 15:19 .
drwxr-xr-x 3 alex alex 4096 Feb 20 15:17 ..
-rw-rw-r-- 1 alex alex 0 Feb 20 15:19 babin
-rw-rw-r-- 1 ben ben 0 Feb 20 15:19 babin1
ben@system99:/home/alex/consult_documents$
```
![Have a look here](https://i.stack.imgur.com/IKZ3j.png) |
25,419,618 | I am wondering how to change the `width` of the line at the bottom of the `nav-tabs`.
On their display page <http://getbootstrap.com/components/> where the `nav-tabs` part the line at the bottom stops just before the end of the page.
But mine is keeping at 100%, wondering how do i change the `length` of that
I tried this but no luck.
```
.nav-tabs {
border-bottom-width: 50px;
border-width: 50px;
}
``` | 2014/08/21 | [
"https://Stackoverflow.com/questions/25419618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3884114/"
] | I have wrap the ul with a div and set left-right padding on it
```
<div class="navWrapper">
<ul class = "nav nav-tabs " role="tablist">
<li class="active" id="opened"><a href= "#" >Open </a></li>
<li id="completed"><a href ="completedlisting.html" >Completed </a></li>
<li id="completed"><a href ="Interestedclientsgeneral.html" >Test</a></li>
<li class="dropdown"id="reload33" ><a href= "#" class="dropdown-toggle" data-toggle="dropdown"><i class="glyphicon glyphicon-filter "></i></a>
<ul class="dropdown-menu">
<li><a href="#" id="all">Show all Results</a></li>
<li><a href="#" id="thisweek">Posted This week</a></li>
<li><a href="#" id="thismonth">Posted This Month</a></li>
</ul>
</li>
</ul>
</div>
.navWrapper{
padding:0 15px;
}
```
here is the updated **[jsFiddle link](http://jsfiddle.net/nobb0nf1/2/)**
hope this will solve your issue. | .nav-tabs {
```
border-bottom-width: 50px;
```
} |
11,935,480 | I've just finished the first working version of a more complex bash script, and I'm wrapping my head around on how to maintain the scripts version.
Why do I need this? Following [GNU Coding Standards For Commandline Interfaces](http://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html) I've added a version option which among a license and copyright header shows the current version.
Still, I don't know how to keep the version 'up-to-date'.
My idea so far is to use git tags for major | minor | patch releases, and somehow replace a variable contained in the script.
So, if I have a tag named `1.1.0`, then
```
$ myscript --version
```
Should output something like:
```
myscript 1.1.0
```
The script contains a shell variable for this:
```
version=1.1.0
```
Still, I don't now how to keep the version in sync with the latest tag? | 2012/08/13 | [
"https://Stackoverflow.com/questions/11935480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178669/"
] | The hook-based answers previously given tightly couple the synchronization of the version string with a `git commit`; however it sounds like you want it to work the other way around, i.e. the version is extracted from manually created `git tag` metadata. It turns out that in fact this is pretty much the approach the [`git` source code](https://github.com/git/git) itself uses, so let's learn how you could adopt something similar by examining its approach:
* It has a [GIT-VERSION-GEN](https://github.com/git/git/blob/master/GIT-VERSION-GEN) shell script which attempts to intelligently determine the current version. Essentially it tries to extract the version string via `git describe`, but falls back to a hardcoded default if that doesn't work. The version is written to `GIT-VERSION-FILE` at the top of the source tree.
* The [`Makefile`](https://github.com/git/git/blob/master/Makefile) invokes this script and `include`s the generated file:
```
GIT-VERSION-FILE: FORCE
@$(SHELL_PATH) ./GIT-VERSION-GEN
-include GIT-VERSION-FILE
```
Now the version is accessible to the rest of the `Makefile` via `$(GIT_VERSION)`.
* Various Make rules then use this to perform substitutions on any files which need the version string hardcoded, such as various Perl scripts:
```
$(patsubst %.perl,%,$(SCRIPT_PERL)): % : %.perl GIT-VERSION-FILE
$(QUIET_GEN)$(RM) $@ $@+ && \
INSTLIBDIR=`MAKEFLAGS= $(MAKE) -C perl -s --no-print-directory instlibdir` && \
sed -e '1{' \
[... snipped other substitutions ...]
-e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
$@.perl >$@+ && \
chmod +x $@+ && \
mv $@+ $@
```
For example if you look near the beginning of [`git-svn.perl`](https://github.com/git/git/blob/master/git-svn.perl), you'll see:
```
$VERSION = '@@GIT_VERSION@@';
```
In my source tree, this rule has compiled to a file `git-svn` which contains the line:
```
$VERSION = '1.7.11.rc0.55.gb2478aa';
```
so if I check the version of my locally compiled `git-svn`, I see:
```
$ git svn --version
git-svn version 1.7.11.rc0.55.gb2478aa (svn 1.6.17)
```
whereas if I run the rpm-based installation, I see:
```
$ /usr/bin/git svn --version
git-svn version 1.7.6.5 (svn 1.6.17)
```
This last output demonstrates that the approach works even when the source code is compiled from a released tarball which does not contain any version control metadata in the `.git/` subdirectory. This means that the version string nicely distinguishes between stable releases and development snapshots.
Although `git-svn` is a Perl script, clearly the same substitution approach would work fine for your shell-script. | >
> Still, I don't know how to keep the version 'up-to-date'.
>
>
>
I do like the post-hook recommendations. However, an alternative approach, you could also use a build system if you already have one available. Do you have an automatic build system? Jenkins or Bamboo? Our build system creates a new tag for each successful build passing all unit tests. Granted this is a script, so you may only have to run unit tests, if you have them. You can add task in your build job to increment or match the version with the tag of the successful build or latest commit which runs and passes any tests. |
35,461,643 | Commonly, to find element with property of max value I do like this
```
var itemWithMaxPropValue = collection.OrderByDescending(x => x.Property).First();
```
But is it good way from performance point of view? Maybe I should do something like this?
```
var maxValOfProperty = collection.Max(x => x.Property);
var itemWithMaxPropValue = collection
.Where(x => x.Property == maxValueOfProperty).First();
``` | 2016/02/17 | [
"https://Stackoverflow.com/questions/35461643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5520747/"
] | Both solutions are not very efficient. First solution involves sorting whole collection. Second solution requires traversing collection two times. But you can find item with max property value in one go without sorting collection. There is MaxBy extension in [MoreLINQ](https://www.nuget.org/packages/morelinq/) library. Or you can implement same functionality:
```
public static TSource MaxBy<TSource, TProperty>(this IEnumerable<TSource> source,
Func<TSource, TProperty> selector)
{
// check args
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
throw new InvalidOperationException();
var max = iterator.Current;
var maxValue = selector(max);
var comparer = Comparer<TProperty>.Default;
while (iterator.MoveNext())
{
var current = iterator.Current;
var currentValue = selector(current);
if (comparer.Compare(currentValue, maxValue) > 0)
{
max = current;
maxValue = currentValue;
}
}
return max;
}
}
```
Usage is simple:
```
var itemWithMaxPropValue = collection.MaxBy(x => x.Property);
``` | The maximum element under some specified function can also be found by means of the following two functions.
```
static class Tools
{
public static T ArgMax<T, R>(T t1, T t2, Func<T, R> f)
where R : IComparable<R>
{
return f(t1).CompareTo(f(t2)) > 0 ? t1 : t2;
}
public static T ArgMax<T, R>(this IEnumerable<T> Seq, Func<T, R> f)
where R : IComparable<R>
{
return Seq.Aggregate((t1, t2) => ArgMax<T, R>(t1, t2, f));
}
}
```
The solution above works as follows; the first overload of `ArgMax` takes a comparator as an argument which maps both instances of `T` to a type which implements comparability; a maximum of these is returned. The second overload takes a sequence as an argument and simply aggregates the first function. This is the most generic, framework-reusing and structurally sound formulation for maximum search I am aware of; searching the minimum can be implemented in the same way by changing the comparison in the first function. |
144,706 | We had a big argument last night with vague conclusions. Is the current with a frequency less than 1 Hz considered DC?
It would still resemble a wave... | 2014/12/20 | [
"https://electronics.stackexchange.com/questions/144706",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/61807/"
] | As others have already pointed out, you can have AC of as low a frequency as you wish.
I think it's worth adding, however, that at such low frequencies it *mostly* won't act much like most of us usually think of AC acting.
Just for an obvious example, you can typically think of a capacitor as allowing AC to flow through it, but as stopping DC. At extremely low frequencies like you're considering, you're probably not going to see any significant current flow, even though it is technically AC.
In particular, a capacitor basically acts like a (very gentle) high-pass filter. To pass such a low frequency well, you'd need a *tremendously* huge capacitor. By far the most common type of large capacitor is an electrolytic capacitor. An electrolytic capacitor is a little like a specialized battery--that is, part of how it works is chemical, not purely electrical. Like batteries, electrolytic capacitors can self-discharge over time. I've never tested to figure out an exact rate of self-discharge, but it wouldn't surprise me a lot if it were to self-discharge *faster* than (for example) a 0.01 Hz signal was charging it--if so, the net result would be that the capacitor never charged, and it would basically act like there was no capacitor there at all.1
The bottom line is that most AC circuits are designed for much higher frequencies, so even though there's no sharp cutoff below which a signal is no longer AC, quite a bit of typical thinking about AC circuit design may easily start to sort of fall apart as you reach such...subterranean frequencies.
Just for reference, the lowest frequency of AC in really common/wide use is probably in audio circuits. Although (again) it's not a hard cuttoff, the typical number used as the bottom-end of the audio range is 20 Hz.
There has been some work done in Extremely Low Frequency radio, but the lowest frequency of which I'm aware was around 50 Hz or so. For a 1 Hz signal, a half-wave dipole antenna would be substantially larger than planet earth.
---
1. In fairness, most electrolytic capacitors are polarized, so you normally use them for things like filters on DC power supplies. Here I'm assuming an (admittedly, less common) non-polarized electrolytic capacitor. | Of course. 1 Hz is once per second, and a second is a fairly arbitrary amount of time. If we had settled on 100 seconds per minute, 60 times per minute would have been 0.6 Hz. |
2,534,339 | debuging this class the SelectTemplate Method is run 2 times, but why?
The first time the item is always null.
```
public class PersonDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item,DependencyObject container)
{
if (item is Person)
{
Person person = item as Person;
Window window = Application.Current.MainWindow;
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode( window))
return null;
if (person.Gender == "male")
return window.FindResource("boysViewTemplate") as DataTemplate;
else
return window.FindResource("girlsViewTemplate") as DataTemplate;
}
return null;
}
}
``` | 2010/03/28 | [
"https://Stackoverflow.com/questions/2534339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/252289/"
] | If your Visual Studio is lincesed, of course it is legal. You can use the built-in publish tool in Visual Studio, or use a software like [InstallShield](http://www.flexerasoftware.com/products/installshield.htm) for the installation. | Yes absolutely as long as your license of Visual Studio is legal. |
15,667,938 | I'm confused about the iteration process in python
I have:
```
numbers = [0,1,2,3,4,5]
for i in numbers:
v = numbers
print v
```
Here is the end of loop
but, in C , C++ , Java we know the line inside the `{ }` will be executed repeatedly, or if not given curly braces then the next statement after the loop, but I'm confused here.
How many lines will be executed in the iteration?
Does it depend on indent? | 2013/03/27 | [
"https://Stackoverflow.com/questions/15667938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190689/"
] | In Python, the indentation, rather than brackets, determines block scope, so in this example both the indented lines will be executed once per iteration of the loop.
This is the single weirdest thing about Python for programmers coming from the C/Java language families, but you get used to it fairly quickly. | Just as an additional note, I think your original code is not doing what I think you want it to do - which is print the numbers 1-5 on their own line. It should be (using Python 3):
```
numbers = [0,1,2,3,4,5]
for i in numbers:
print(i)
```
If you run the following code:
```
numbers = [0,1,2,3,4,5]
v = numbers
print(v)
```
you'll get:
```
[0, 1, 2, 3, 4, 5]
``` |
4,321,386 | How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly. | 2010/12/01 | [
"https://Stackoverflow.com/questions/4321386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526090/"
] | You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
```
List<String> stringList = new ArrayList<String>();
```
You are using the interface type `List<T>` as the type, but the instance itself is an `ArrayList<T>`. | You can provide an implementation as an anonymous class:
```
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
```
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both). |
52,468,956 | ```
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz import make_dot
batch_size = 3
learning_rate =0.0002
epoch = 50
resnet = models.resnet50(pretrained=True)
print resnet
make_dot(resnet)
```
I want to visualize `resnet` from the pytorch models. How can I do it? I tried to use `torchviz` but it gives an error:
```
'ResNet' object has no attribute 'grad_fn'
``` | 2018/09/23 | [
"https://Stackoverflow.com/questions/52468956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436508/"
] | Here is how you do it with `torchviz` if you want to save the image:
```
# http://www.bnikolic.co.uk/blog/pytorch-detach.html
import torch
from torchviz import make_dot
x=torch.ones(10, requires_grad=True)
weights = {'x':x}
y=x**2
z=x**3
r=(y+z).sum()
make_dot(r).render("attached", format="png")
```
screenshot of image you get:
[![enter image description here](https://i.stack.imgur.com/hP4wV.png)](https://i.stack.imgur.com/hP4wV.png)
source: <http://www.bnikolic.co.uk/blog/pytorch-detach.html> | This might be a late answer. But, especially with `__torch_function__` developed, it is possible to get better visualization. You can try my project here, [torchview](https://github.com/mert-kurttutan/torchview)
For your example of resnet50, you check the colab notebook, [here](https://colab.research.google.com/github/mert-kurttutan/torchview/blob/main/docs/example_vision.ipynb)
where I demonstrate visualization of resnet18 model. The image of resnet18 by torchview can be seen
[here](https://i.stack.imgur.com/yigrC.png) (zoom in the image to see it)
It also accepts wide range of output/input types (e.g. list, dictionary) |
16,680,550 | I have a gridview which is bonded totally programatically . I want to hide some columns and also rich them to show them in the label.
Here is my gridview :
```
<Gridview ID=Gridview1 runat="server" ></Gridview>
```
I want to hide EmpID and UnitID . and want to show them in a label on the front-end side
```
EmpID EmpName UnitID UnitName
--------------------------------
1 jack 4 MyUnit
```
I am trying to use this code , but it is not working even gives me error
```
if (GridForUnits.Columns.Count > 1)
{
GridForUnits.Columns[1].Visible = false;
//GridForUnits.Columns[1].Visible = false;
}
```
Any Help appreciate
Thanks | 2013/05/21 | [
"https://Stackoverflow.com/questions/16680550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2407340/"
] | If you want to hide a column base on a logic, you want to use [RowDataBound](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx).
It is a bit easy to maintain in the future.
Here is the sample. You can hide or show whatever columns you like.
![enter image description here](https://i.stack.imgur.com/MKPQW.png)
```
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="EmpID" DataField="EmpID" />
<asp:TemplateField HeaderText="EmpName" >
<ItemTemplate>
<asp:Label runat="server" ID="EmpNameLabel"
Text='<%# Eval("EmpName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UnitID" DataField="UnitID" />
<asp:TemplateField HeaderText="UnitName" >
<ItemTemplate>
<asp:Label runat="server" ID="UnitNameLabel"
Text='<%# Eval("UnitName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public class Employee
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public int UnitID { get; set; }
public string UnitName { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = new List<Employee>
{
new Employee { EmpID = 1, EmpName = "One", UnitID = 100, UnitName = "One hundred"},
new Employee { EmpID = 2, EmpName = "Two", UnitID = 200, UnitName = "Two hundred"},
new Employee { EmpID = 3, EmpName = "Three", UnitID = 300, UnitName = "Three hundred"},
new Employee { EmpID = 4, EmpName = "Four", UnitID = 400, UnitName = "Four hundred"}
};
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var employee = e.Row.DataItem as Employee;
var empNameLabel = e.Row.FindControl("EmpNameLabel") as Label;
var unitNameLabel = e.Row.FindControl("UnitNameLabel") as Label;
if (employee.UnitID == 200)
{
empNameLabel.Visible = false;
unitNameLabel.Visible = false;
}
}
}
``` | Yes there is actually a easy way to do that.
You are probably receiving an error because when you `autogenerate` columns the count is always 0.
After you `Databind`, iterate through your columns and hide them by index. I too will assume you datasource is a `DataTable` for this example.
```
DataTable dt = new DataTable();
dt.Columns.Add("EmpID");
dt.Columns.Add("EmpName");
dt.Columns.Add("UnitID");
dt.Columns.Add("UnitName");
DataRow dr = dt.NewRow();
dr["EmpID"] = 1;
dr["EmpName"] = "Jack";
dr["UnitID"] = 4;
dr["UnitName"] = "MyUnit";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
//GridView1.Columns[0].Visible = false; // will error on autogenerate columns
// So after your data is bound, loop though
int columnIndexEmpID = 0;
int columnIndexUnitID = 2;
GridView1.HeaderRow.Cells[columnIndexEmpID].Visible = false;
GridView1.HeaderRow.Cells[columnIndexUnitID].Visible = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
gvr.Cells[columnIndexEmpID].Visible = false;
gvr.Cells[columnIndexUnitID].Visible = false;
}
```
You'll need to attach a `RowDataBound` event to your grid view.
```
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
```
In here, you can access your hidden values.
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (drv != null)
{
string cellValue = Convert.ToString(drv["EmpID"]);// By column name
}
}
```
As for enriching the datagrid with labels, Win has provided you an elegant solution :P |
18,504 | I'm a beginner in Japanese language. In English, "Company Name" and "Name of Company" are basically the same. In Japanese, are those two the same or different? Which one should I use?
* 会社名前
* 会社の名前 | 2014/08/31 | [
"https://japanese.stackexchange.com/questions/18504",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/4171/"
] | 会社の名前{なまえ} consists of two nouns, one describing the other. The one with の is in genitive case which is used to indicate possession in this case. It's roughly equivalent to *'s* or *of* in English: *company's name* or *the name of the company* (both are translated to 会社の名前). Note that 名前 is a native Japanese word and it uses kun-yomi reading of the kanji in this case.
As it happens often in Japanese, there's also a Sino-Japanese word with the same meaning which uses on-yomi readings only. For company name it is 会社名{かいしゃめい} or 社名{しゃめい} (not 会社名前). As a rough rule, those kind of words are usually more formal then equivalent native Japanese words.
Please also note that Japanese and English grammar don't work in the same way and order of words in both language is often different and has a different significance. You cannot really directly translate word by word. | 会社{かいしゃ}の名前{なまえ} is grammatically fine, and while compound nouns are sometimes formed by simply eliminating the の particle (e.g.,本{ほん}の棚{たな} -> 本棚{ほんだな} or 勉強{べんきょう}の不足{ふそく} -> 勉強不足{べんきょうぶそく}), in this case the word you are looking for is: 会社名{かいしゃめい} (the *on-yomi* of 名 is generally used in compound nouns and has the same meaning as 名前{なまえ} as a whole: *name*). |
3,036,386 | how do i change the item selected in a combobox selection based on a selection of a datagrid object? | 2010/06/14 | [
"https://Stackoverflow.com/questions/3036386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283166/"
] | When writing a lambda, the act of capturing variables *significantly* alters the construction of the underlying code (moving variables into fields of compiler-generated classes, that could very easily themselves be chained closure-contexts).
Not even considering the general *complexity* of doing this, it would then have two choices:
* capture all the variable values as constants; feasible and pretty simple, but could easily mean that the result of executing in the immediate window is **very** different to the result of executing in the main body (very undesirable)
* rewrite the entire code (for the reasons outlined above) on the fly (at a guess, impossible)
Given a choice between "undesirable" and "impossible", I *guess* they simply chose not to implement a feature that would be inherently brittle, *and* very complex to write. | If you still need to use Visual Studio 2013, you can actually write a loop, or lambda expression in the immediate window using also the package manager console window. In my case, I added a list at the top of the function:
```
private void RemoveRoleHierarchy()
{
#if DEBUG
var departments = _unitOfWork.DepartmentRepository.GetAll().ToList();
var roleHierarchies = _unitOfWork.RoleHierarchyRepository.GetAll().ToList();
#endif
try
{
//RoleHierarchy
foreach (SchoolBo.RoleHierarchy item in _listSoRoleHierarchy.Where(r => r.BusinessKeyMatched == false))
_unitOfWork.RoleHierarchyRepository.Remove(item.Id);
_unitOfWork.Save();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
```
Where my GetAll() function is:
```
private DbSet<T> _dbSet;
public virtual IList<T> GetAll()
{
List<T> list;
IQueryable<T> dbQuery = _dbSet;
list = dbQuery
.ToList<T>();
return list;
}
```
Here I kept getting the following error, so I wanted to print out all the items in the various repositories:
```
InnerException {"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Department_dbo.RoleHierarchy_OranizationalRoleId\". The conflict occurred in database \"CC_Portal_SchoolObjectModel\", table \"dbo.Department\", column 'OranizationalRoleId'.\r\nThe statement has been terminated."} System.Exception {System.Data.SqlClient.SqlException}
```
Then, I find out how many records are in the department repository by executing this in the immediate window:
```
_unitOfWork.DepartmentRepository.GetAll().ToList().Count
```
Which returned 243.
So, if you execute the following in the package manager console, it prints out all the items:
```
PM> for($i = 0; $i -lt 243; $i++) { $a = $dte.Debugger.GetExpression("departments[$i].OrgagnizationalRoleId"); Write-Host $a.Value $i }
```
The author for the idea can be found here: <http://ogresoft.blogspot.ca/2013/06/how-to-write-loop-or-lambda-expression.html> |
9,803,298 | Say I have a function c[i] = f(x[i], y[i]). I have the input value arrays x and y of equal length and I want to calculate the values of array c in the end. How do I get that using LINQ?
i.e. without having to write:
```
c = new double[x.Length];
for (int i = 0; i < x.Length; i++)
{
c[i] = f(x[i], y[i]);
}
``` | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300929/"
] | Use [`Zip`](http://msdn.microsoft.com/en-us/library/dd267698.aspx) method, e.g.:
```
int[] x = { 1, 2, 3 };
int[] y = { 4, 5, 6 };
var result = x.Zip(y, (i, j) => i + j);
```
or if you have already method with adequate params, simply use:
```
var result = x.Zip(y, Function);
// in this sample Function looks like:
static int Function(int x, int y)
{
return x + y;
}
``` | You can use a simple `Select`:
```
var c = x.Select((x_i, i) => f(x_i, y[i]));
```
If `c` needs to be an `int[]` instead of `IEnumerable<int>`, append `ToArray` to the end:
```
var c = x.Select((x_i, i) => f(x_i, y[i])).ToArray();
``` |
11,839,766 | in magento on order confirmation email is sent to admin in HTML format,
but i want to change it to plain text format so how and from where i can change that format only for admin, customer should get email in HTMl format as it is.
Can anyone please give me solution for this?
Thanks. | 2012/08/07 | [
"https://Stackoverflow.com/questions/11839766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537552/"
] | For future readers, **do not edit core files** as others suggest. You can achieve this in config alone with a *tiny* custom module.
I have AheadWorks' blog module installed, you may not, or you may have other modules that need their email format overridden. So, adjust accordingly.
Create `app/etc/modules/YourNameSpace_EmailFormat.xml` and add to `<depends>`, so your config is loaded last:
```
<?xml version="1.0"?>
<config>
<modules>
<YourNameSpace_EmailFormat>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Contacts/>
<AW_Blog/>
</depends>
</YourNameSpace_EmailFormat>
</modules>
</config>
```
Create `app/code/local/YourNameSpace/EmailFormat/etc/config.xml`, adding elements for all the templates you wish to override:
```
<?xml version="1.0"?>
<config>
<modules>
<YourNameSpace_EmailFormat>
<version>1</version>
</YourNameSpace_EmailFormat>
</modules>
<global>
<template>
<email>
<customer_create_account_email_template>
<type>text</type>
</customer_create_account_email_template>
</email>
</template>
</global>
</config>
```
That's it. I needed the reverse, so I had `<type>` set to `html`. This goes very well with [Yireo's Email Override module](https://github.com/yireo/Yireo_EmailOverride) so you can easily customise your templates. If converting plain text emails to HTML, be sure to change template tags like `{{var foo.bar}}` to `{{htmlescape var=$foo.bar}}` to prevent malicious code injections. | First create custom email template from `Transactions emails` and text type set as plain. Note down that template Id. and use in below file.
At `\app\code\local\Mage\Sales\Model\Order.php` `sendNewOrderEmail()` load manually template is and sent variables to that and send email. |
25,512,548 | I am trying to force my site to load in HTTPS. I can create a redirect in PHP which works for PHP files, but I want all requests forced to HTTPS - JS, CSS, Images, etc.
Here's what I have in my .htaccess:
```
ErrorDocument 401 default
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
```
I have tried various methods of this by placing the redirect in different locations and such, but everything seems to make this into a redirect loop. Any ideas what I could do to fix that?
Thank you. | 2014/08/26 | [
"https://Stackoverflow.com/questions/25512548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3563982/"
] | Keep your `http` to `https` rules before internal WP rule:
```
ErrorDocument 401 default
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
**Make sure WP's `home URL` and `site URL` also have `https` in permalink settings.** | Set a 301 permanent redirect which is more SEO friendly. Already tested:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect all traffic to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
# Wordpress rules
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
``` |
3,939,618 | let $x$ be in this interval: $[0, 2\pi]$. the exercise's request is to find the domain of this function:$$\sqrt{(\sin(x))^2 + \sin x}$$
Here's my attempt to solve it:
1. I found the domain of the square root: $$(sin (x))^2 + \sin x \geq 0$$
In this case, I've found that $$\sin x \ge 0 $$ and that: $$\sin x \ge -1 $$
in the trigonometric circle, I have found that the set of solution is only the 4th quadrant, since the sin of -1 is $3/2\pi$ (270 degree).
Is that correct? | 2020/12/08 | [
"https://math.stackexchange.com/questions/3939618",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/583624/"
] | Let $t = \sin x \,\, (-1 \leq t \leq 1)$
The domain of the function will become:
$$t^2 + t \geq 0$$
$$\implies t \in (-\infty, -1] \cup [0, +\infty)$$
But $-1 \leq t \leq 1 \implies t = -1$ or $0 \leq t \leq 1$
* $t = -1 \implies \sin x = -1 \implies x = -\dfrac{\pi}{2} + k2\pi \implies x = \dfrac{3\pi}{2}$ (since $x \in [0, 2\pi]$)
* $0 \leq t \leq 1 \implies 0 \leq \sin x \leq 1 \implies x \in [0, \pi] \cup \{2\pi\}$
Therefore, the domain is:
$$D = [0, \pi] \cup \left\{\dfrac{3\pi}{2}, 2\pi \right\}$$ | What if $\sin x(\sin x+1)=0?$
Else we need $\sin x(\sin x+1)>0$
If $\sin x>0,\sin x+1>0\iff\sin x>-1\implies \sin x>$ max$(0,-1)$
$\implies2n\pi\le x\le2n\pi+\pi$
What if $\sin x<0?$ |
105,826 | Wearing a hat has become so widespread in the orthodox community but what is it’s origin? Is it based off of anything from the Torah or Chazal? How old is the custom to wear a hat? And when did it become so widespread? | 2019/07/23 | [
"https://judaism.stackexchange.com/questions/105826",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/16397/"
] | This is actually a very complicated question. I will begin by discussing any religious or Torah requirements regarding a head covering, then talk about hats and their relationship to Jews.
There is no religious origin to wear a "hat." By all accounts wearing a hat is a non Jewish custom. The closest thing to an official Torah based Jewish head covering is a Sudra, which is some sort of turban like head covering. The Talmud says If one wants to cover his head one should wear a head covering that wraps around the head such as a turban and say the blessing "Blessed are you Lord our God who crowns Israel with splendor."
>
> כי פריס סודרא על רישיה לימא ברוך עוטר ישראל בתפארה
>
>
> When he spreads a sudra over his head he should say: ‘Blessed is He who crowns Israel with glory’
>
>
>
Brachot 60b, Talmud Standard Vilna edition
Non Jews in Europe did not wear anything resembling a turban and apparently neither did Jews so we start seeing written accounts by 13th century Ashkenazi Jews that the blessing was no longer being said.
>
> A) R. Asher ben Shaul of Narbonne (13th century France) in his Sefer haMinhagot (pg. 141) [15] recorded that the blessing was not cited in his region:
>
>
> ומי שעוטר מצנפת כמו שעושין בספרד מברך עוטר ישראל בתפארה שדומה לעטרת, והזכיר ישראל מפני שכינה שהיא שורה עליהם, ולא יתכן שילכו בגלוי ראש ועל כן קשר להם כתרים בסיני לכל אחד, וכן אמרו בתלמוד (קידושין לא א) שכינה למעלה מראשי, ולא כן הגוים. מכל מקום (הוא) משמע שאע”פ שאין אנו מתעטרין במצנפת אנו מתעטרין בכובעין דין הוא שנברך עוטר ישראל אלא שאין מנהגנו לומר כן, ונראה בעיני שהמנהג שלנו שאין אנו מברכין משום דאין כל ישראל מכסין ראשיהם והולכין בגילוי הראש.
>
>
> Asher recognized that עוטר ישראל בתפארה was an appropriate blessing for the turban because “it resembles a crown” (דומה לעטרת).
>
>
>
We see similar accounts in the 14th century.
>
> B) R. David Abudirham, a resident of 14th century Christian Spain, in his enumeration of the morning blessings in Sefer Abudirham [16] (1339) skips any version of the head-covering blessing. In a later chapter he wrote [17]:
>
>
> ועוד מוסיף בגמ’ כשמניח סדינו על ראשו מברך עוטר ישראל בתפארה על שם (שם קג, ד) המעטרכי חסד ורחמים ועל שם (ישעיה מט, ג) ישראל אשר בך אתפאר. והטעם לברכה זו לפי שהיו עוטרים מצנפת כדי שלא ילכו בגלוי הראש. ואמר כאן ישראל לפי שהשכינה שורה עליהם ולא על הגוים. ובכל ארץ ישמעאל נוהגין לאומרה מפני שהם מניחים מצנפת על ראשם, אבל באלו הארצות אין נוהגין לאמרה כי אינם מניחין מצנפת. אבל נוהגין לומר ברכה אחרת שאינה נזכרת בגמרא …
>
>
> The intention of Abudirham appears to be that in Christian Spain (“these lands”) the turban was not worn by Jews and therefore no headdress blessing was said, unlike in North Africa and the Levant [18].
>
>
>
Source: <https://www.uncensoredjudaism.com/en/archives/1857>
While these sources don't conclusively prove when Jews started wearing a hat in Europe, it does say that the European Jewish community had broken with traditional Jewish dress and had actually removed a Talmudic blessing from their religious practice. The sources above indicate that many Jews didn't wear a headcovering at all (not even a kippah!). It therefore makes sense that the blessing would not be re-instituted for "the hat" that is now in common use since the hat was clearly a later use of a gentile article of clothing.
It should be noted that now almost no Jewish communities say this blessing when putting on a head covering. This and all the other dressing related blessings have been relegated to a fixed part of the "morning" service and are now said in synagogues, completely separated from the acts they were tied to in Talmudic times. I have only seen certain Rambam based groups who continue the proper practice of saying this blessing with a turban style head covering.
---
Jews in Europe (and other parts of the world) were often forced to wear clothes that distinguished them from non Jews. This way Christians and Muslims would be able to tell who was and wasn't a Jew based on their style of clothes. There were many styles of hats that Jews in Europe were forced to wear that were different based on location or time, but many times these articles of clothe were meant to embarrass or humiliate the Jews on top of setting them apart. [Here is an example from the 14th Century.](https://en.wikipedia.org/wiki/Jewish_hat#/media/File:Codex_Manesse_S%C3%BC%C3%9Fkind_von_Trimberg.jpg) [Here is another example from Germany in the 13th century.](https://en.wikipedia.org/wiki/Jewish_hat#/media/File:GermanJews1.jpg) You can see many more sources and styles from going to [this Wikipedia article.](https://en.wikipedia.org/wiki/Jewish_hat) It seems fair to say that Jews would not want to say the blessing of "crowning Israel with glory/splendor" over an article of clothing they were forced to wear by non Jews in order to humiliate them.
In more recent times Jews were not forced to wear distinctive types of hats or clothing and many took the custom to wear clothes that didn't make them stand out by copying their non Jewish neighbors. Many theorize that this led to the wearing of hats that we see by Hassidic Jews in our days. When this officially began to happen is hard to tell. | The idea of a religious head covering seems to have been a מנהג since ancient times, as seen in Sepher Shemuel II 15:30
>
> לוְדָוִ֡ד עֹלֶה֩ בְמַעֲלֵ֨ה הַזֵּיתִ֜ים עֹלֶ֣ה | וּבוֹכֶ֗ה וְרֹ֥אשׁ לוֹ֙ חָפ֔וּי וְה֖וּא הֹלֵ֣ךְ יָחֵ֑ף וְכָל־הָעָ֣ם אֲשֶׁר־אִתּ֗וֹ חָפוּ֙ אִ֣ישׁ רֹאשׁ֔וֹ וְעָל֥וּ עָלֹ֖ה וּבָכֹֽה
>
>
> And Daveed ascended upon the Mount of Olives, and weeping as he went up with his head covered, and he went barefoot; all of the people that were with him, each man covered his head and wept as they ascended
>
>
> |
16,602,807 | In JAVA I am trying to programmatically tell if 2 images are equal when displayed on the screen (AKA same image even though they have different [color spaces](https://en.wikipedia.org/wiki/Color_space). Is there a piece of code that will return a boolean when presented 2 images?
One of the examples I have is a RGB PNG that I converted to a greyscale PNG. Both images look the same and I would like to prove this programmatically. Another example is two images where they display the exact same color pixels to the screen but the color used for 100% transparent pixels has changed. | 2013/05/17 | [
"https://Stackoverflow.com/questions/16602807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473290/"
] | You can try this
[Example](https://web.archive.org/web/20121108205937/http://www.lac.inpe.br/JIPCookbook/6050-howto-compareimages.jsp)
***Wayback Machine to the rescue here***
They explain how to compare two images | If you mean exactly the same, compare each pixel.
If you mean compare a RGB image and a greyscale image, you need to convert the RGB to greyscale first, for doing this, you need to know how you did RGB->Greyscale before, there're different ways of doing this and you could get different results.
Edit, if the method it used in RGB->Greyscale is liner, you could work out a,b,c in the formula `grey = a*R + b*G + c*B` by comparing 3 pixels. |
5,056,897 | What should I learn first if I want to build a web application? I just had an excellent idea that I want to work on for a few years myself. I don't have any experience programming besides doing HTML and some bits of CSS. I'm a novice in using the command line (Terminal) in Linux but I have been trying to improve myself on that part. | 2011/02/20 | [
"https://Stackoverflow.com/questions/5056897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426313/"
] | I agree with Marc's comment above, but I guess what you're looking for is probably something like [RavenDB](http://ravendb.net/). It's developed specifically with .NET in mind, so would probably seem more "C# friendly" than others such as CouchDB or MongoDB, etc.
Keep in mind, however, that the different NoSQL implementations have different strengths and weaknesses beyond simply what language/platform is more natively considered during their development. It may very well be true that RavenDB would seem more natural to a .NET developer, but a different database may be better suited to the job at hand depending on the data persistence needs.
Here's [a quick breakdown](http://nosql.mypopescu.com/post/978742866/document-databases-compared-couchdb-mongodb-ravendb) of some other feature comparisons that I just found. As you can see there's more to each tool than its .NET driver. A little Googling of NoSQL database comparisons will yield more information. If you have more specific data persistence needs or can elaborate more on the project in question we may be able to provide more advice.
**Edit:** (In response to your comment above) To perhaps help you narrow down your choices, here's my experience so far:
Of the three that I've mentioned, the only one I've actually used in .NET is MongoDB. It didn't "feel" as native for .NET purposes, but it wasn't difficult or unwieldy in any way. It was easy enough to use and performed its intended task very well.
I've used CouchDB from JavaScript code, as opposed to from .NET code. It's considered to be a very JavaScript friendly database and I've been toying with the idea of connecting to it directly from client-side AJAX calls. But it should be just as easy from within .NET. That's the beauty of a RESTful API, really. Anything should be able to interact with it as easily as interacting with any service. From within .NET code, something like RestSharp may make using CouchDB very easy and feel more .NET-native. | Mongo recently released and is subsequently supporting a native C# driver. Source code is on Github. See here for more details: <http://www.mongodb.org/display/DOCS/CSharp+Language+Center> |
16,954,556 | I have a file with numbers like this:
0.122
1.44
5.44
I want to write a shell script that will give me percentage for the following criteria:
* % of data less than 0.1
* % of data between 0.1 and 0.2
* % of data between 0.2 and 0.5
* % of data greater than 1
I am trying with awk, but not able to get it through...
Any help would be appreciated. | 2013/06/06 | [
"https://Stackoverflow.com/questions/16954556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336045/"
] | Something like this would do:
```
awk '
$1 < 0.1 { c[0]++ }
$1 < 0.2 { c[1]++ }
$1 < 0.5 { c[2]++ }
$1 > 1 { c[3]++ }
END {
c[2] -= c[1];
c[1] -= c[0];
t = c[0] + c[1] + c[2] + c[3];
print (c[0]/t) * 100, (c[1]/t) * 100, (c[2]/t) * 100, (c[3]/t) * 100
}' input
``` | ```
cat file | python -c 'import numpy,sys; a=[float(l.strip()) for l in sys.stdin];b=numpy.histogram(a,bins = [0,.1,.2,.5,1,max(a)])[0];print [x*100/sum(b) for x in b]'
``` |
34,776,161 | I was exploring ways how to implement a general-purpose/DSL language for .NET platform. From what I saw, there are several tools that make language implementation (parsing source code) relatively easy. *Irony*, *Yacc*, *ANTLR*… the problems with these projects are that some are not evolving, some generate slow parsers, some cannot run on .NET Core CLR etc. There is always some obstacle that pushes me towards solution “write your own parser”.
So I was wondering… **is it possible to write my own parser and connect/integrate it with Roslyn?** Are there any books, tutorials or examples how it can be done? | 2016/01/13 | [
"https://Stackoverflow.com/questions/34776161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498611/"
] | Roslyn is not meant for this.
The best you'll be able to do with Roslyn is generate a C# (or VB) SyntaxTree & Compilation after you parse your language by hand, letting Roslyn take care of the type system & codegen.
And this will only work at all if your language can be completely translated to C# (or VB) syntax. | I know this is an old thread, but your best bet (in visual studio at least) is to create an IVsSingleFileGenerator that converts your code into c# or other Roslyn language. |
308,552 | I want to install packages by yum in the background as the following
```
yum -y install ntp &
```
but this example isn't working and yum installation not installing in the background. How to fix my command in order to enable `yum` to install the `ntp` in the background ?
```
# yum -y install ntp &
[1] 26960
09:03:15 root@ereztest:~ # Loaded plugins: rhnplugin
This system is receiving updates from RHN Classic or RHN Satellite.
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package ntp.x86_64 0:4.2.6p5-10.el6.1 will be installed
--> Finished Dependency Resolution
``` | 2016/09/08 | [
"https://unix.stackexchange.com/questions/308552",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/153544/"
] | Use the `-q` flag for the background job to suppress output.
From the `yum` man pages:
>
> -q, --quiet
>
>
> Run without output. Note that you likely also want to use -y.
>
>
> | It appears yum is running in the background (evidenced by the `[1] 26960` line in the output -- here, 26960 is the process id of the background'd yum), but it is still sending some output to the terminal. To get around this, add an output redirect for stdout and/or stderr as appropriate:
```
yum -y install ntp >/tmp/yum-out 2>&1 &
```
Here `>/tmp/yum-out` redirects the output (stdout) to the file /tmp/yum-out, and the `2>&1` makes error output (stderr) go to the same file. This way, if you want to go back and look at the output later (for example, if an error occured), it's all saved in the `/tmp/yum-out` file. |
8,441,749 | In general, whenever you're representing a range of any kind, you have several choices for what kinds of values to choose for the beginning and ending of your range. For example, if you want to have a range containing the integers 1, 2, 3, 4, 5 you could choose these possible values:
* begin = 0, end = 5 (aka begin < x <= end)
* begin = 1, end = 5 (aka begin <= x <= end)
* begin = 0, end = 6 (aka begin < x < end)
* begin = 1, end = 6 (aka begin <= x < end (the C++ STL and many other libraries seem to choose this)).
I'm not sure what measures I should use to choose one of these options. | 2011/12/09 | [
"https://Stackoverflow.com/questions/8441749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/167958/"
] | I was hoping someone would give me a link to a nice paper that [E.W. Dijkstra](http://en.wikipedia.org/wiki/Edsger_W._Dijkstra) wrote on the topic. I managed to plug just the right search terms into Google, and found the link I was looking for. The paper is ["Why numbering should start at 0" and also covers why ranges should be represented with a half open interval [begin, end)](http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html).
The basic argument has several pieces:
1. Direct experience with a programming environment (the programming language Mesa at Xerox PARC) that had support for all 4 different choices resulted in people standardizing on [start, end) because of frequent errors made with all the other choices.
2. If you have an interval that starts at 0, having the start be -1 or something similar is just awkward and broken. This argues strongly for the interval starting at `begin` (i.e. all the begin <= x choices).
3. The math for determining the interval size, for computing the start of the next adjacent interval, and a whole bunch of other similar things just works out nicely if end is one past start. For example, the size is `end - begin`. And `end` is the `begin` of the next adjacent interval. There are fewer chances for off-by-one errors in your calculations.
* On a related note, the empty range is `[begin, begin)`, and very obvious. It would have to be the rather awkward `[begin, begin - 1]` if it were closed on both sides. This is especially awkward of your range begins at 0. | I personally would choose the option
* begin = 1, end = 5 (aka begin <= x <= end)
I like to keep my structures as clear and similar to the human reasoning as possible. If you tell someone "the numbers between 1 and 5" both 1 and 5 are meant to be in the set.
Of course if there are good technical reasons to use something else why not but if there are none I would choose the option which is easier to understand at the first glance. |
6,794,344 | Using [`Text::Ngram`](http://search.cpan.org/perldoc?Text%3a%3aNgram) I have
```
my $c = ngram_counts($text, 3);
my %ct = %($c);
```
which doesn't work (`Scalar found where operator expected`). I think this is a combination of not knowing what I'm doing (still not very good with Perl) and being confused about what exactly I'm getting as output from Text::Ngram. Help? I just want to look at the generated n-grams:
```
my @keys = sort {$ct{$a} cmp $ct{$b} } keys %ct;
foreach my $k (@keys) {
print "$k: $ct{$k}\n"
}
```
Edit: Stupid error on my part, thanks everyone. | 2011/07/22 | [
"https://Stackoverflow.com/questions/6794344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341362/"
] | Use curly braces to dereference the hash reference:
```
my %ct = %{ $ct }; # %$ct would also work
```
And you probably want to use `<=>` for numerical sorting instead of the ASCII-betical sorting `cmp`. | There's no need to make a copy into another hash, just use the reference.
```
my $c = ngram_counts($text, 3);
my @keys = sort {$c->{$a} <=> $c->{$b} } keys %$c;
foreach my $k (@keys) {
print "$k: $c->{$k}\n"
}
```
See <http://perlmonks.org/?node=References+quick+reference> for some easy to remember rules for dealing with references. |
366,720 | Currently my code is organized in the following tree structure:
```
src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
```
Where the `module*.py` files contains the source code and the `test_module*.py` contains the `TestCase`s for the relevant module.
With the following comands I can run the tests contained in a single file, for example:
```
$ cd src
$ nosetests test_filesystem.py
..................
----------------------------------------------------------------------
Ran 18 tests in 0.390s
OK
```
How can I run all tests? I tried with `nosetests -m 'test_.*'` but it doesn't work.
```
$cd src
$ nosetests -m 'test_.*'
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
```
Thanks | 2008/12/14 | [
"https://Stackoverflow.com/questions/366720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36131/"
] | If they all begin with `test` then just `nosetest` should work. Nose automatically searches for any files beginning with 'test'. | I'll give a [Testoob](http://www.testoob.org) answer.
Running tests in a single file is like Nose:
```
testoob test_foo.py
```
To run tests in many files you can create suites with the Testoob collectors (in each subpackage)
```
# src/subpackage?/__init__.py
def suite():
import testoob
return testoob.collecting.collect_from_files("test_*.py")
```
and
```
# src/alltests.py
test_modules = [
'subpackage1.suite',
'subpackage2.suite',
]
def suite():
import unittest
return unittest.TestLoader().loadTestsFromNames(test_modules)
if __name__ == "__main__":
import testoob
testoob.main(defaultTest="suite")
```
I haven't tried your specific scenario. |
88,422 | I would like to enable all members of an organic group to subscribe to a reminder, that sends an e-mail depending on a date field.
To be more specific: The group has a group content with a date field. Now I would like a mail being sent a specific time before this date becomes actual.
Would would the best way to do this? | 2013/10/09 | [
"https://drupal.stackexchange.com/questions/88422",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/5950/"
] | When it comes to right on schedule or specific time, you need to have crontab on server. Role of cron tab will be none other than calling your cron.php file which in turn allows all modules to set the cron. But this is half of the process since with core drupal cron process you can not have much control on setting schedule time, so you can use [elysia cron module](https://drupal.org/project/elysia_cron) to extend drupal core cron.This was cron part
Now inorder to trigger email you can implement hook\_cronapi() as an example,
```
function mymodule_cron_cronapi($op, $job = NULL) {
$items['send_email'] = array(
'description' => 'Send email to group users',
'rule' => '0 * * * *', // Every Hour at **:00
'callback' => 'mymodule_email_group_callback',
);
return $items;
}
```
cron callback
```
function mymodule_email_group_callback() {
// load all group content from that content type.
// loop through all nodes check date
// if true
// get all subscribers and loop through them
// send email
}
``` | Off the top of my head I think [Maestro](http://drupal.org/project/maestro) can do this with a `Batch Task` or a `Batch Function Task`. In drupal typically `Cron` is setup to run periodically, say every hour or every 15 minutes.
If you truly want a `specific time` for these notifications to go out you need a (cron) task that runs every minute for example and examines if there are notifications to send now as time passes.
Alternatively you could use some sort of Job/Worker queue that Drupal talks to. |
203,233 | Context
=======
A player amidst one of the groups decided to try his hand at DM'ing for the first time. It's going relatively well despite teething trouble (primarily from a mismatch of expected ideas after forgoing a session 0 against multiple people suggesting it).
Skip forward a few sessions and level 5 where the first encounter happens where the player group outnumbers the monster group, and a pair of martials decide to try flanking, an optional rule that's used as standard in that group. This did not go down well with the DM who was ruffled at the attempt and stated rather firmly that we should not presume optional rules are in play. He said this on a table that people had been using without asking, with the DM stating that they were in fact "expected optional rules"; ASI-Feat choice, Cleaving, and Multiclassing.
This is a fair ruling; but his response got me curious.
Question
========
As a result of this, I became curious if there had been an official poll (or some other measure) of popularity of optional rule usage? I have no intent of using this against the DM (nor is it likely he will see anything based on this), and it is solely for my own knowledge.
In my searches I only found ones for house-rules, which I am not interested in including as that's a different kettle of fish. | 2022/12/06 | [
"https://rpg.stackexchange.com/questions/203233",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/77409/"
] | Unfortunately, there isn't
--------------------------
There aren't any unofficial, or official, metrics on the optional rules that different tables use across the world.
As for your situation, I don't think that getting this information will be helpful or useful, even if it was available. While having it would be interesting, it doesn't really move the needle for a table's choices if they were to disagree.
*If* you don't enjoy playing with the rules your DM and table play with, and the DM is unwilling to change, then it's up to you to decide if the fun you're having (or not having) is worth your time at that table.
On data
-------
Data is a tricky thing, there's a lot of 'data' out there. But there is a difference between good data and bad data. This is akin to the stack's theory of pearls, not sand. Bad data is the sand - there's a lot out there, and it's our job to find the good data within - the pearls.
We must be careful with what we present as good data here, because others may not be as aware - just look at the rise of misinformation around the world. Judging good and bad is hard, but it's a judgement we should set aside time to make before posting - it'll improve the experience and information for everyone that visits. | I'll be a bit of a contrarian; While I agree that trying to pressure a DM on which optional rules to allow, or any other ruling, is undesirable and often counterproductive, I am not enthused with the idea of a **secret set** of "expected optional rules".
Without explicitly knowing flanking is active, I would not expect the DM to use it against me, and as a DM, I would not expect players to try to use it. It's a bit like traps in a dungeon, except it's **traps in the rules system**, which is supposed to be the **firm foundation** upon which tales are built.
You are supposed to be **having fun**, and perceived traps make things less fun, **for both you and your DM** - you expected flanking to work and it didn't, and they didn't expect their monsters to be flanked, lessening their perceived Challenge. Don't pressure, and don't nag, and instead try to work together to make the new DM feel secure and supported in their rulings. |
2,483,755 | I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).
Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.
Is there a way to mimic the "sudo" command behavior (ask for user password) to temporarily gain root privileges and perform the particular task ? If so, which functions would I use ?
Thank you very much for your help ! | 2010/03/20 | [
"https://Stackoverflow.com/questions/2483755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279259/"
] | You can't gain root privileges, you must start out with them and reduce your privileges as needed. The usual way that you do this is to install the program with the "setuid" bit set: this runs the program with the effective userid of the file owner. If you run `ls -l` on `sudo`, you'll see that it is installed that way:
```
-rwsr-xr-x 2 root root 123504 2010-02-25 18:22 /usr/bin/sudo
```
While your program is running with root privileges, you can call the `setuid(2)` system call to change your effective userid to some non-privileged user. I believe (but haven't tried this) that you could install your program as root with the setuid bit on, immediately reduce privilege, and then restore privilege as needed (it's possible, however, that once you lower your privilege you won't be able to restore it).
A better solution is to break out the piece of your program that needs to run as root, and install it with the setuid bit turned on. You will, of course, need to take reasonable precautions that it can't be invoked outside of your master program. | Normally this is done by making your binary suid-root.
One way of managing this so that attacks against your program are hard is to minimize the code that runs as root like so:
```
int privileged_server(int argc, char **argv);
int unprivileged_client(int argc, char **argv, int comlink);
int main(int argc, char **argv) {
int sockets[2];
pid_t child;
socketpair(AF_INET, SOCK_STREAM, 0); /* or is it AF_UNIX? */
child = fork();
if (child < 0) {
perror("fork");
exit(3);
} elseif (child == 0) {
close(sockets[0]);
dup2(sockets[1], 0);
close(sockets[1]);
dup2(0, 1);
dup2(0, 2); /* or not */
_exit(privileged_server(argc, argv));
} else {
close(sockets[1]);
int rtn;
setuid(getuid());
rtn = unprivileged_client(argc, argv, sockets[0]);
wait(child);
return rtn;
}
}
```
Now the unprivileged code talks to the privileged code via the fd comlink (which is a connected socket). The corresponding privileged code uses stdin/stdout as its end of the comlink.
The privileged code needs to verify the security of every operation it needs to do but as this code is small compared to the unprivileged code this should be reasonably easy. |
54,994,600 | The following code snippet works fine until I uncomment the `plt.legend()` line:
```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-1, 1)
y = np.linspace(-1, 1)
X, Y = np.meshgrid(x, y)
Z = np.sqrt(X**2 * Y)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, label='h=0')
ax.plot(np.zeros_like(y), y, np.zeros_like(y), label='singular points')
# plt.legend()
plt.show()
```
I get the following error:
`'Poly3DCollection' object has no attribute '_edgecolors2d'`
I thought the cause may have been that I had played around with the `framealpha` and `frameon` parameters of plt.legend() in 2d plots, but I restarted the runtime (I'm working in a Google Colab Jupyter Notebook), clearing all variables, and the problem persisted.
What might be causing this error? | 2019/03/05 | [
"https://Stackoverflow.com/questions/54994600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9270181/"
] | Hi I found that is a bug still the library developers are trying to figure out it.
I have found the following thread about the issue in [git](https://github.com/matplotlib/matplotlib/issues/4067)
Their suggestion they have given is to get the plotting
```
surf = ax.plot_surface(X, Y, Z, label='h=0')
surf._facecolors2d=surf._facecolors3d
surf._edgecolors2d=surf._edgecolors3d
```
**If the matplotlib version is matplotlib 3.3.3 try below**
```
surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d
``` | Update to @AmilaMGunawardana's answer
-------------------------------------
As of `matplotlib 3.3.3`, `_facecolors3d` and `_edgecolors3d` do not exist. So, instead of this:
```
surf._facecolors2d = surf._facecolors3d
surf._edgecolors2d = surf._edgecolors3d
```
that would lead to a similar `AttributeError`, try this:
```
surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d
```
I had to make this an answer, instead of a comment, due to low rep. |
30,097,626 | I have two nested states, consisted of a parent abstract state and a child state:
```
.state('app.heatingControllerDetails', {
url: "/clients/:clientId/heatingControllers/:heatingControllerId",
abstract: true,
views: {
'menuContent': {
templateUrl: "templates/heatingController.html",
controller: 'HCDetailsCtrl'
}
}
})
.state('app.heatingControllerDetails.wdc', {
url: "/wdc",
views: {
'hc-details': {
templateUrl: "templates/heatingControllers/wdc.html",
controller: 'WdcDetailsCtrl'
}
},
resolve:{
hcFamily: [function(){
return 'wdc';
}]
}
})
```
and two controllers are:
```
.controller('HCDetailsCtrl',function($scope){
$scope.$on("$ionicView.enter", function (scopes, states) {
...
});
})
.controller('WdcDetailsCtrl',function($scope){
$scope.$on("$ionicView.enter", function (scopes, states) {
...
});
})
```
When I invoke state app.heatingControllerDetails.wdc, both controllers are created, but $ionicView.enter is only invoked on the parent controller. Any idea?
In heatingController.html, hc-details view is defined as follows:
```
<ion-content class="has-header" ng-show="hc">
<div ui-view name="hc-details"></div>
<div class="disableContentDiv" ng-hide="hc.state=='Online'"></div>
</ion-content>
``` | 2015/05/07 | [
"https://Stackoverflow.com/questions/30097626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908173/"
] | Please correct the sql query section in your code
currently it is
```
$sel = "select cf_id from client_file where cf_id='".$_POST['rmvfile']."'";
```
it should be
```
$sel = "select * from client_file where cf_id='".$_POST['rmvfile']."'";
```
As now it is fetching only cf\_id, you didn't get the other fields. | You have not closed your image-tag properly and the quotes are not closed as well
```
<img src="image/delete1.png" alt="delete" style="width:10px;height:10px"
title="Remove" onclick="myFunction('.$fet['cf_id'].');">
```
And as stated by manikiran, check the if.condition. |
21,631,723 | I have drop-down box where users can select Yes or No, if user selects Yes from the drop-down then i want to show a confirmation box that shows Yes or No option. If only user selects Yes in the confirmation box then i want to proceed calling my other function which makes an update to the backend database. If user selects No in the confirmation box then i don't want to proceed and cancel the operation. Here is my drop-down code:
```
OnSelectedIndexChanged="CheckDropDownSelection"
runat="server" AppendDataBoundItems="true" Height="16px">
<asp:ListItem Text="-- Please Selet --" Value="-- Please Selet --"></asp:ListItem>
<asp:ListItem Text="YES" Value="YES"></asp:ListItem>
<asp:ListItem Text="NO" Value="NO"></asp:ListItem>
</asp:DropDownList>
```
here is my code behind:
```
protected void CheckDropDownSelection(Object sender, EventArgs e)
{
if (ddl_CloseTask.SelectedValue == "YES")
{
CloseTask();
}
else
{
}
}
protected void CloseTask()
{
// here is where i close the task
}
``` | 2014/02/07 | [
"https://Stackoverflow.com/questions/21631723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1669621/"
] | The code has too many Yes/No. I hope it won't confuse to user -
If a user selects **YES** in **DropDownList**, a **Confirmation Message** will be prompted.
If the user selects **YES** in **Confirmation Message**, **DropDownList** will post back to server.
```
<asp:DropDownList ID="ddl_CloseTask" Width="157px"
AutoPostBack="true"
OnSelectedIndexChanged="CheckDropDownSelection"
runat="server"
AppendDataBoundItems="true" Height="16px">
<asp:ListItem Text="-- Please Selet --" Value="-- Please Selet --"></asp:ListItem>
<asp:ListItem Text="YES" Value="YES"></asp:ListItem>
<asp:ListItem Text="NO" Value="NO"></asp:ListItem>
</asp:DropDownList>
<script type="text/javascript">
var selectlistId = '<%= ddl_CloseTask.ClientID %>',
selectlist = document.getElementById(selectlistId);
selectlist.onchange = function() {
if (selectlist.options[selectlist.selectedIndex].value == "YES") {
if (confirm("Are you sure you want to do this?")) {
__doPostBack(selectlistId, '');
}
}
};
</script>
```
Credit to [this answer](https://stackoverflow.com/a/8697129/296861).
Updated:
--------
If the user selects **NO** from the **Confirmation Box**, set **DropDownList** value to the first value.
```
<script type="text/javascript">
var selectlistId = '<%= ddl_CloseTask.ClientID %>',
selectlist = document.getElementById(selectlistId);
selectlist.onchange = function() {
if (selectlist.options[selectlist.selectedIndex].value == "YES") {
if (confirm("Are you sure you want to do this?")) {
__doPostBack(selectlistId, '');
} else {
// User selected NO, so change DropDownList back to 0.
selectlist.selectedIndex = 0;
}
}
};
</script>
``` | You would want to prompt the user on the "onchange" event of your DropDownList control. You can add the call to your javascript function in the aspx markup or in the code behind. (I used the code behind in this case).
So, your code behind would look something like this:
```
protected void Page_Load( object sender, EventArgs e )
{
ddl_CloseTask.Attributes.Add("onchange", "return validate(this);");
}
protected void CheckDropDownSelection(object sender, EventArgs e)
{
if (ddl_CloseTask.SelectedValue == "YES")
{
CloseTask();
}
else
{
// do stuff
}
}
private void CloseTask()
{
// do stuff
}
```
And your aspx markup would look something like this:
```
<asp:DropDownList ID="ddl_CloseTask" runat="server" AutoPostBack="True" OnSelectedIndexChanged="CheckDropDownSelection">
<asp:ListItem Text="-- Please Select --" Value="-- Please Select --" />
<asp:ListItem Text="YES" Value="YES" />
<asp:ListItem Text="NO" Value="NO" />
</asp:DropDownList>
<script type="text/javascript">
function validate(ddl) {
var selected = ddl.options[ddl.selectedIndex].value;
if (selected == 'YES' && !confirm('Close the task?')) {
return false;
}
__doPostBack(ddl.id, '');
}
</script>
``` |
56,561,444 | I have following scenario:
I have compound object which includes lists in it, I want to pass a 'path' to it like - Result.CustomerList.Name
Result is an object that contains List of Customer, but also contains many other lists of different types. I want to get to the Names of the customers in this particular case.
What I have so far
```
private static object GetPropertyValue(this object obj, string propertyPath)
{
var fullPath = propertyPath.Split('.');
for (int i = 0; i <= fullPath.Length - 1; i++)
{
if (obj == null) { return null; }
var part = fullPath[i];
Type type = obj.GetType();
PropertyInfo propInfo = type.GetProperty(part);
if (propInfo == null)
{
//if its a list
if (obj.GetType().GetInterfaces().Any(
k => k.IsGenericType
&& k.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
//get list generic argument
var argumentType = obj.GetType().GetGenericArguments()[0];
//cast obj to List of argumentType
}
else return null;
}
obj = propInfo.GetValue(obj, null);
}
return obj;
}
```
I cant get the syntax or how to cast to List or List it doesnt work or List
I dont understand what i have missing or how to do it.
EDIT::
During runtime might be CustomerList, AddressList or PaymentList or any other type of list. I need a method to be able to retrieve the property value within any type of list during runtime.
EDIT2::
Example of Result object
```
public class SearchResults
{
public List<Customer> Customers { get; set; }
public List<Payment> Payments { get; set; }
public List<Address> Addresses{ get; set; }
public int totalCount { get; set; }
public bool success { get; set; }
}
public class Customer
{
public string Name { get; set; }
public long Id { get; set; }
}
public class Payment
{
public string BankName{ get; set; }
public long Id { get; set; }
}
```
So a path like Result.Payments.BankName should return me whatever. Problem is that I cant make it generic for the method to access any of the lists. | 2019/06/12 | [
"https://Stackoverflow.com/questions/56561444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257267/"
] | On Ubunutu, For Dbeaver 6, it is found in
```
$HOME/.local/share/DBeaverData/workspace6/General/.dbeaver
``` | I've just tried to move configuration for dbeaver 7.3.1 from one win machine to another, and if you copy&paste folder:
>
> C:\Users\your\_user\_name\AppData\Roaming\DBeaverData\
>
>
>
you will get everything works quite smoothly |
203,471 | I want to list all the current running services and output it to a .csv file. Does anyone know how to do this? | 2010/11/18 | [
"https://serverfault.com/questions/203471",
"https://serverfault.com",
"https://serverfault.com/users/60731/"
] | A bit of *good old* shell script:
`@echo off`
`setlocal`
`set SERVICES=`
`for /f "skip=1 tokens=*" %%S in ('%SystemRoot%\System32\net.exe start') do call :ADD_SERVICE %%S`
`echo Running services are : [%SERVICES%]`
`endlocal`
`goto END`
`:ADD_SERVICE`
`set SERVICE=%*`
`if "%SERVICE%" == "" goto END`
`if "%SERVICE%" == "The command completed successfully." goto END`
`set SERVICES=%SERVICES%%SERVICE%,`
`goto END`
`:END` | Might I be evil and suggest the Cygwin variant:
```
net start | sed -e '1,2d' -e ':a' -e N -e 's/\n /,/' -e ta > services.csv
``` |
644,523 | If $f(x)= x+b$ when $x≤1$ and $f(x)= ax^2$ when $x > 1$, what are all values of $a$ and $b$ where $f$ is differentiable at $x=1$?
Please explain. Thank you very much for your help. | 2014/01/20 | [
"https://math.stackexchange.com/questions/644523",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/122526/"
] | Hints:
1) The function **must** be continuous at $\;x=1$, so
$$1+b=\lim\_{x\to 1^-}f(x)=\lim\_{x\to 1^+}f(x)=a\implies a-b=1$$
2) Both one-sided differentials must be equal, so:
$$\lim\_{x\to 1^-}\frac{f(x)-f(1)}{x-1}=\lim\_{x\to 1^-}\frac{x+b-(1+b)}{x-1}=\ldots$$
$$\lim\_{x\to 1^+}\frac{f(x)-f(1)}{x-1}=\lim\_{x\to 1^+}\frac{ax^2-(1+b)}{x-1}=\ldots$$
Well, it gets even easier than what I thought as you don't even get a linear system for $\;a,b\;$ ...complete the exercise now. | You need to find values of $a$ and $b$ so that:
1) $f$ is continuous. I.e., $1+b=a\cdot 1^2$.
and
2) $f'$ is continuous. I.e., $1=2\cdot a\cdot1$. |
30,840 | In Philip K. Dick's **Do Androids Dream of Electric Sheep?** why did Deckard get a citation at the end from his police department? Because he retired too many andys in a single day? I thought the police wants to retire as many as possible. Sounds to me like he should get a bonus. | 2013/01/22 | [
"https://scifi.stackexchange.com/questions/30840",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/11801/"
] | He *was* being rewarded.
[Merriam-Webster's definition](http://www.merriam-webster.com/dictionary/citation) of "Citation":
>
> 1 : an official summons to appear (as before a court)
>
>
> 2
>
>
> * a : an act of quoting; especially : the citing of a previously settled case at law
> * b : excerpt, quotation
>
>
> 3: mention: as
>
>
> * a : **a formal statement of the achievements of a person receiving an academic honor**
> * b : **specific reference in a military dispatch to meritorious performance of duty**
>
>
>
>
> ---
>
>
> Examples of CITATION
>
>
> * He was issued a citation.
> * He received a citation for reckless driving.
> * **gave her a citation for bravery**
>
>
>
The word "citation" can be either positive *or* negative depending on context. | Like user [John Rennie](https://scifi.stackexchange.com/users/4144/john-rennie) said in a comment, Deckard got a citation because he "retired" (i.e. executed) six androids, which was a remarkable feat. A citation is another word for commendation, so that's a good thing.
Excerpt from the book:
>
> A moment later the orange, triangular face of Ann Marsten appeared on the screen. "Oh, Mr. Deckard — Inspector Bryant has been trying to get hold of you. **I think he's turning your name over to Chief Cutter for a citation. Because you retired those six** — "
>
>
> "I know what I did," he said.
>
>
> "**That's never happened before**. Oh, and Mr. Deckard; your wife phoned. She wants to know if you're all right. Are you all right?"
>
>
> |
5,040,000 | is there any way to create events for NSDate ? here is my code
```
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:date];
myDate.text = dateStr;
```
for example if date = 12 FEB ;
myDate .text = @"Mother Day";
something like this | 2011/02/18 | [
"https://Stackoverflow.com/questions/5040000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319097/"
] | This is a way to implement your scenario with extension methods. While, as others have noted, it would make sense to keep the logic to turn your strings to HTML within MyClass, in certain scenarios it might make sense to use this approach.
```
public class MyClass
{
public String varA{ get; set; }
public String[] varB{ get; set; }
}
public static class MyExtensions {
public static string ToHtml(this string input, string format)
{
return string.Format(format, input);
}
public static string ToHtml(this string input)
{
return ToHtml(input,"<p>{0}</p>");
}
public static string ToHtml(this IEnumerable<string> input, string wrapperformat, string elementformat)
{
string body= input
.Select(s => string.Format(elementformat,s))
.Aggregate((a,b)=> a+b);
return string.Format(wrapperformat,body);
}
public static string ToHtml(this IEnumerable<string> input)
{
return ToHtml(input,"<ul>{0}</ul>","<li>{0}</li>");
}
}
``` | If you changed `ToHtml` to except a value:
```
public static string ToHtml(string a)
{
// your code here - obviously not returning ""
return "";
}
```
then you can call it like so:
```
MyClass c = new MyClass();
c.varA = "some text";
c.varA = MyClass.ToHtml(c.varA);
```
But, I maybe WAY off what you require. |
18,502 | As far as I'm aware, the two most common ways to choose a setting for your campaign are one of these:
* The GM makes it up pre-game, or
* the GM has some source book containing the desired setting.
Also, when the players make characters, one of these two ways are most often used:
* The players bring filled out character sheets to the first session, or
* the players create their characters in the first session of play.
I'm a big fan of creating the PC group as a collaborative effort, each player having final say over his own character, but having the advantage of getting inspiration from others. It also serves well for avoiding the awkward "trust building phase", since it is easy to establish how PC's know each other pre-game.
What I want is a way of letting the players have the same kind of influence on the setting, meaning that also the setting will be created as a collaborative effort.
The more successful campaigns I have run always let the players choose the purview of the campaign, before we actually started playing, meaning the players (not necessarily the characters) have some sort of incentive to actually play along. "We want to take the throne from Bob the Cruel. He needs some killin'!"
Oftentimes people seems to believe that the GM has a mandate over the type of campaign. If he invites to a specific kind of campaign, then I guess it's true, but if he just invites people to play, without specifics, then I believe that everyone should have an equal say.
This should go for settings as well. If I host a D&D campaign, some people might dislike Eberron as a setting, for example, but wouldn't mind Forgotten Realms. Forcing a setting on the players seems to be a good way to disconnect the players from their characters, making gaming sessions pretty dull.
So suppose I want to host a new campaign, but I want the players to connect to the setting as well as their characters, by letting them have some kind of say over it. How would you go along doing this?
So far, I have thought about the following:
* Giving players the opportunity to establish helpful/hostile NPC's that his character knows,
* Giving the players the opportunity to establish locations that in some way matters to the character.
Is there more I could do? I have a hard time coming up with more than this. For that sake, I could use a solid *method* for doing the above, without pushing players to discomfort. It is important for me that the world doesn't feel flat. | 2012/10/31 | [
"https://rpg.stackexchange.com/questions/18502",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/4555/"
] | It's a great idea to get your players involved in building the setting. Make sure that everyone wants to be involved in this stage of course. It can do more harm than good to force people to create something if they aren't feeling it.
The Dresden Files RPG lets players cooperate in building the city they will be playing in. There are [City Creation Rules](http://www.faterpg.com/dl/df/citycreation.html) in the SRD. However, those ideas aren't an imperative process and work best for the Urban Fantasy genre.
You could use this as a general method (in D&D terms, since that was your example):
1. In the group pick three themes and threats (up to three)
2. Each player defines a location in the area of the campaign
3. Each player then gets to add a theme or threat to another players location
4. Another player gets to add a face to a location
5. Repeat 2-4 until the group feels like there is enough
6. Create characters with links to the created ideas
A **theme** is an overarching statement about the game. *Fame and Fortune Over The Next Hill* suggests a game of ragtag adventurers looking for a big job while *Comes The Holy Light of Dawn* would suggest a new age triumphing over an ancient evil.
A **threat** is a person, creature or force that threatens the part of the world you're playing in. On a campaign level you could be talking about your Bob the Cruel example, Sauron or the Empire. Locally, you might be worried about the kobolds in the mine, the dragon that demands tribute every 20 years or the spirit of a bridge closing a route because it feels under-appreciated.
When a player creates a **location**, they can be as loose or defined about it as they feel like. This could be a village, city, landmark or whatever. The location itself should have some kind of hook to it.
Some players may want to keep their location to add themes, threats or faces. That's ok too. Encourage input on ideas.
**Faces** are the people of a local area who are important to the story. They may be friendly or hostile to the player characters, but unlike a threat they are unlikely to be disturbing the status quo. Examples include a holy order of knights, a thieves guild and the friendly barkeep. | You will likely run into problems when a players believe that you as the GM don't portrait aspects of the campaign settings the way they intended it.
>
> **GM:** You encounter a group of yellow Frogstar soldiers.
>
>
> **Player:** Yellow? But I wanted them to be green!
>
>
> **GM:** You never said they are supposed to be green.
>
>
> **Player:** But it's just common sense for them to be green! *sigh* Can't you get anything right?
>
>
>
To avoid such situations there are two options:
One is to make sure that every single detail of the setting is agreed upon. When you do that, designing the campaign world will likely take longer than playing the campaign. This can also be an interesting experience, but it is not what you came for.
The other is that you as the GM demand creative control over the world as soon as the game is in progress and make clear that you can decide on every detail which wasn't explicitely agreed on beforehand (better write everything down in that case). The players will not like it when you misportrait "their" city or "their" NPC, but it's the only way to prevent the game from being interrupted by discussions all the time. |
33,326 | The Attorney-General is seventh in the line of succession to the Presidency of the United States.
Does an ***Acting*** Attorney-General replace the former Attorney-General in the line of succession? | 2018/11/09 | [
"https://law.stackexchange.com/questions/33326",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/534/"
] | The presidential line of succession is governed by the U.S. Constitution, specifically [Article II section 1](https://en.wikisource.org/wiki/Constitution_of_the_United_States_of_America#Section_1_2):
>
> In Case of the Removal of the President from Office, or of his Death, Resignation, or Inability to discharge the Powers and Duties of the said Office, the Same shall devolve on the Vice President, and the Congress may by Law provide for the Case of Removal, Death, Resignation or Inability, both of the President and Vice President, declaring what Officer shall then act as President, and such Officer shall act accordingly, until the Disability be removed, or a President shall be elected.
>
>
>
The [25th amendment](https://en.wikisource.org/wiki/Additional_amendments_to_the_United_States_Constitution#Amendment_XXV) reinforces this and says "Whenever there is a vacancy in the office of the Vice President, the President shall nominate a Vice President who shall take office upon confirmation by a majority vote of both Houses of Congress."
So, after the vice president, the constitution lets Congress pass laws governing the rest of the succession. This is governed by the [Presidential Succession Act](https://en.wikipedia.org/wiki/Presidential_Succession_Act).
[3 U.S. Code Chapter 1, Section 19](https://www.law.cornell.edu/uscode/text/3/19) lays out the rest of the line of succession: Next come the Speaker of the House of Representatives (subsection a) and the President pro tempore of the Senate (subsection b) and "then the officer of the United States who is highest on the following list, and who is not under disability to discharge the powers and duties of the office of President shall act as President: Secretary of State, Secretary of the Treasury, Secretary of Defense, Attorney General, Secretary of the Interior, Secretary of Agriculture, Secretary of Commerce, Secretary of Labor, Secretary of Health and Human Services, Secretary of Housing and Urban Development, Secretary of Transportation, Secretary of Energy, Secretary of Education, Secretary of Veterans Affairs, Secretary of Homeland Security" (subsection d).
So you have the Attorney General at number 7. However, the next subsection says the following (emphasis mine).
>
> (e) Subsections (a), (b), and (d) of this section shall apply only to such officers as are eligible to the office of President under the Constitution. Subsection (d) of **this section shall apply only to officers appointed, by and with the advice and consent of the Senate**, prior to the time of the death, resignation, removal from office, inability, or failure to qualify, of the President pro tempore, and only to officers not under impeachment by the House of Representatives at the time the powers and duties of the office of President devolve upon them.
>
>
>
I think the bolded text answers your question. The Acting Attorney General has not been confirmed by the Senate, so is not in the presidential line of succession.
Now there is potentially room to argue that, if the Acting Attorney General has been confirmed by the Senate for some other office (most likely Deputy Attorney General), then they qualify. Of course, there is no case law to clarify this, since the presidential succession has never gone beyond what is listed in the constitution. However, I don't think it's a very compelling argument, particularly for the current Acting Attorney General who was not appointed on the basis of his previous confirmation.
(Interestingly, [a Bill was introduced to the House in 2003](https://www.congress.gov/bill/108th-congress/house-bill/2319/text) that would have explicitly removed acting officers from the line of succession. Ultimately, that Bill did not progress.) | **No**
A cabinet member is only a cabinet member when they are confirmed not just because they are temporarily doing a cabinet member’s job. |
5,920,352 | I'm trying to add a image to a togglebutton in WPF - C#. The thing is that the assignment I'm working on can't be made with the use of XAML at all. I've tried to set the Content property to an image, but all I get is a normal togglebutton, which isn't helping my cause at all.
```
myToggleButton = new ToggleButton();
myImage = new Image();
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("myImageResource.bmp", UriKind.Relative);
bmi.EndInit();
myImage.Source = bmi;
myToggleButton.Content = myImage;
```
Hope I supplied enough info, if not please ask for more.
Updated @Phil Wright:
When I ad an image like this:
```
myImage = new Image();
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("myImageResource.bmp", UriKind.Relative);
bmi.EndInit();
myImage.Source = bmi;
```
it works...
Update @Matt West:
```
myGrid.Children.add(MyToggleButton); // This gives me an empty ToggleButton
myGrid.Children.add(MyImage); // This gives me an image with content
``` | 2011/05/07 | [
"https://Stackoverflow.com/questions/5920352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/715752/"
] | As requested here is the code that works for me in its entirety:
```xml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Name="_Root">
</Grid>
</Window>
```
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var tb = new ToggleButton();
var image = new Image();
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("/Images/6.png", UriKind.Relative);
bmi.EndInit();
image.Source = bmi;
tb.Content = image;
_Root.Children.Add(tb);
}
}
}
```
Where the image is a resource; as noted before those last two lines make no sense, if you can get the image to display on its own it should also display inside the button. | Are you sure that the provided bitmap resource is able to be located. If not then the image will be empty and so occupy no space and hence the toggle button looks empty. |
42,039,069 | I created this package, I need it in a project but couldn't install it, this error appears:
>
> Could not install package 'Mshwf.NiceLinq 1.0.9'. You are trying to
> install this package into a project that targets
> '.NETFramework,Version=v4.5', but the package does not contain any
> assembly references or content files that are compatible with that
> framework. For more information, contact the package author
>
>
>
I don't know why this happen, in another project (Console) I changed the framework to 4.6 and other versions and it wasn't a problem, but this only happen in this project (MVC and Web API):
this is the nuspec file:
```
<?xml version="1.0"?>
<package >
<metadata>
<id>Mshwf.NiceLinq</id>
<version>1.0.9</version>
<title>Nice LINQ</title>
<authors>MShawaf</authors>
<owners>Mshawaf</owners>
<projectUrl>https://github.com/mshwf/NiceLinq</projectUrl>
<iconUrl>https://raw.githubusercontent.com/mshwf/NiceLinq/master/logo.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>See it as: WHERE ID IN (1, 2, 3, 7, 9, 22, 30, 101)</description>
<releaseNotes>Minor changes.</releaseNotes>
<copyright>Copyright 2016</copyright>
<tags>LINQ IEnumerable Where Contains Search Filter</tags>
</metadata>
</package>
``` | 2017/02/04 | [
"https://Stackoverflow.com/questions/42039069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6197785/"
] | Go to the folder:
```
C:\Users\[username]\.nuget\packages\[package name]\1.0.0.4\lib
```
Rename the folder with the .net version of your project.
Suppose I am using .net framework 4.6.1 my folder name should be `net461` | I had similar issue which i fixed by removing the packages.config(you can edit the file if you don't want to remove) file and then made sure both the package i was using was built using the same .net version as the Project i was using it in(for me the package was built using 4.6 while my console project was targeting earlier version of .net). |
49,653,410 | I am trying to achieve a filter with `mat-autocomplete` that is similar to the following example;
[trade input example](https://www.checkatrade.com/)
So I am trying to achieve the functionality so that when a user begins to type in the trade they are looking for filters based on a partial string match anywhere in the string and highlight this in the option.
[![cheackatrade screenshot](https://i.stack.imgur.com/5LDEK.png)](https://i.stack.imgur.com/5LDEK.png)
I current have in my .html
```
<mat-form-field class="form-group special-input">
<input type="text" placeholder="Select a trade" aria-label="Select a trade" matInput [formControl]="categoriesCtrl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" md-menu-class="autocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{ option.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
```
where my .ts is
```
categoriesCtrl: FormControl;
filteredOptions: Observable<ICategory[]>;
options: ICategory[];
categorySubscription: Subscription;
constructor(fb: FormBuilder, private router: Router, private service: SearchService, private http: Http) {
this.categoriesCtrl = new FormControl();
}
ngOnInit() {
this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
this.options = categories;
this.filteredOptions = this.categoriesCtrl.valueChanges
.pipe(
startWith(''),
map(options => options ? this.filter(options) : this.options.slice())
);
});
}
ngOnDestroy() {
this.categorySubscription.unsubscribe();
}
filter(val: string): ICategory[] {
return this.options.filter(x =>
x.name.toUpperCase().indexOf(val.toUpperCase()) !== -1);
}
```
`ICategory` is a basic interface.
```
export interface ICategory {
value: number;
name: string;
}
```
And the service getCategories() just returns all the categories from an api.
The code is currently working and built per this example;
[Angular Material mat-autocomplete example](https://material.angular.io/components/autocomplete/examples)
I would like to add the effect of highlighting the term in the option string? Is this possible at all? | 2018/04/04 | [
"https://Stackoverflow.com/questions/49653410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545438/"
] | You can use a custom pipe to highlight the partial match whenever the user types in something in the filter.
```
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
transform(text: string, search): string {
const pattern = search
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
.split(' ')
.filter(t => t.length > 0)
.join('|');
const regex = new RegExp(pattern, 'gi');
return search ? text.replace(regex, match => `<b>${match}</b>`) : text;
}
}
```
---
[Demo](https://stackblitz.com/edit/angular-nue8pb) | To solve the undefined, you should just check for the present of the search string, sometimes you have none on the control:
```
export class HighlightPipe implements PipeTransform {
transform(text: string, search): string {
if (search && text && typeof search === 'string' && typeof text === 'string') {
const pattern = search
.replace(/[\-\[\]\/{}()*x+?.\\^$|]/g, '\\$&')
.split(' ')
.filter(t => t.length > 0)
.join('|');
const regex = new RegExp(pattern, 'gi');
return search ? text.replace(regex, match => `<strong>${match}</strong>`) : text;
}
return text;
}
}
```
Also note some of regex has been thinned out as some escapes were not necessary.
Finally in the HTML you should now use [innerHTML] rather than just piping the object text:
```
<mat-option [innerHTML]="optionText | highlight: searchValue"></mat-option>
``` |
32,004,967 | I have two rows of checkboxes and labels.Although horizontal alignment is not an issue , however there is a problem of vertical alignment of second column.How can I achieve a symmetry in this case?
```
<div class="form-inline">
<div class="form-group">
<div class="col-md-4">
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox0" value="0">Sunday</label>
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox1" value="1">Monday</label>
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox2" value="2">Tuesday</label>
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox3" value="3">Wednesday</label>
</div>
<div class="col-md-4">
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox4" value="4">Thursday</label>
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox5" value="5">Friday</label>
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox6" value="6">Saturday</label>
</div>
</div>
```
[JSfiddle](https://jsfiddle.net/vwkkf7ts/)
As you can see the alignment of Moday and Friday (checkbox and label) is not proper. | 2015/08/14 | [
"https://Stackoverflow.com/questions/32004967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421910/"
] | [I've updated your fiddle](https://jsfiddle.net/vwkkf7ts/7/) with a fixed width on the wrapping div `.col-md-4` and positioned the labels using float with the width of each label set to take 1/3 of the parents width using the `calc` function:
```
label{
float: left;
width: calc(100%/3)
}
``` | What if you wrap each checkbox with a col-sm-3 box?
```
<div class="col-sm-3">
<label class="radio-inline">
<input type="checkbox" name="inlineRadioOptionsWeek" id="Checkbox3" value="3">Wednesday</label>
</div>
```
<https://jsfiddle.net/hobs766o/1/> |
93,712 | I'm building an application that caters to a specific set of people for example construction workers *[edit: removed "students, or coffee drinkers"]*. So for instance, an app for construction workers that can handle photo annotation for pipes, logging their working hours, viewing a blueprint, and contacting city officials for permits.
After some interviews, I've found that they want 6 features. Each of these features could be an app on its own. Some people might use two of 6 features while others use all of them
My question is: will combining all the features into one app introduce extra pain for my users that only use one thing in the app? | 2016/05/04 | [
"https://ux.stackexchange.com/questions/93712",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/78630/"
] | I've actually been involved in something similar, and with more than six in one. In the end we went with the approach of having the main home screen of the app display an icon and label for each of the apps. This main screen also provided navigation to the *overall help* page and *overall settings* page. Below is a rough mockup of how it was designed:
[![enter image description here](https://i.stack.imgur.com/4IICP.png)](https://i.stack.imgur.com/4IICP.png)
I say "overall settings" because the settings icon at top right was for things like using iCloud, Backing up to Dropbox, Passcode Lock, Theme Colour, App Screen Layout, etc. In other words, settings that were for the entire app as a whole.
The "overall help" was just about the main app screen and what some of the overall settings meant.
Once the user tapped on each of the app options, the resulting screen also had an option for them to navigate back to the main "Apps" screen. And, depending on the app, they may have also had a dedicated 'help' or 'settings' screen.
Of course, in your case it may not need to be this advanced, but the point of sharing my example is because this works. User feedback has been extremely positive and this design is something that has evolved over time based on user feedback. | If done intuitively you might avoid "extra pain" for users by exploring the following approach:
For one app offering a group of users – let's say construction workers – multiple task-based features, only display relevant features based on the type of construction worker. The user could identify this via a first-time setup process, or perhaps the process is facilitated by an administrator using role-based authorization.
The goal is to provide the user only a UI that is applicable to their needs.
Additionally, the user should be able to add/remove features or make such requests to an admin as their job requirements change. |
64,105,244 | I want the container direction as "row" above md size screen and "column" below md size screen?
How can I implement it?
```
<Grid container direction = "row"(in large screens)/direction = "column"(in small screens)>
```
I tried something this.
```
<Grid container classes={gridDirection}>
gridDirection: {
direction = "row",
[theme.breakpoints.down('md')]: {
direction = "column",
},
}
```
but it is not working probably because "direction" is a react prop and not a CSS style.
Is there a way to access these react props inside stylesheet file? | 2020/09/28 | [
"https://Stackoverflow.com/questions/64105244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10429886/"
] | The easiest way and I believe the modern way is to use the sx attribute. Then let MUI handle the breakpoints for you.
These are the default MUI breakpoints as of writing.
```
xs = extra-small: 0px
sm = small: 600px
md = medium: 900px
lg = large: 1200px
xl = extra-large: 1536px
```
xs and sm are generally considered to be mobile/small tablet. MUI is mobile first, so xs will be set and not overwritten until the size is md or larger in my example below.
```
<Grid container sx={{ flexDirection: { xs: "column", md: "row"} }}>
</Grid>
``` | At least as on date of answering here, Material UI supports `direction` or `flexDirection` attributes with component, with these attributes supporting responsive value based on breakpoints mapped object passed to it.
For example, in your case, if direction="row" is needed on large screens and direction="column" is needed for small screens, then the prop can be passed in as:
`direction={{xs:'row', lg:'column'}}`, thus letting MUI prop handle it with the Grid element as:
`<Grid container direction={{xs:'row', lg:'column'}}> ... </Grid>`
This is the right style to use it in your code, for this case, in my opinion, though other alternative answers here also work well. |
765,612 | Is it possible to have Ubuntu Desktop running in an LXC/LXD container on top of Ubuntu Server, displaying Ubuntu Desktop's graphical X session on the physical screen that Ubuntu Server outputs to?
Whether it makes sense or not, my idea is to separate the Server "PC" from the Desktop "PC". I intend to set up an Intel NUC machine as a personal web server as well as a HTPC machine connected to my TV. | 2016/04/30 | [
"https://askubuntu.com/questions/765612",
"https://askubuntu.com",
"https://askubuntu.com/users/301931/"
] | (Not definitely true:)That won't work!(/Not definitely true) What would work though, is doing it the other way round: install the Desktop on your machine and then use LXD to run the web server.
Also, if you have a current NUC box, you should have processor virtualization and could run KVM. I'm not familiar with that, but it seems your chances are better with a true VM solution... | This might help
<https://github.com/ustuehler/lxc-desktop>
It seems you can run multiple desktop instances in lxc containers, however I'm not sure why you would want the server part to have a desktop interface |
28,633,390 | I'm trying to implement a custom error message for my bean validation.
I've annotated my field `firstName` with the validation rule `@Size( min = 2, max = 40, message = "errors.firstName.size" )`.
In my `message.properties` I added a message key `errors.firstName.size=First Name must be between {min} and {max} chars`. However, in my Thymeleaf generated view just the message key appears (as the screenshot shows).
![Wrong message key](https://i.stack.imgur.com/JjWSL.png) | 2015/02/20 | [
"https://Stackoverflow.com/questions/28633390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685202/"
] | Try putting your message key in `ValidationMessages.properties` instead of `message.properties`.
>
> The ValidationMessages resource bundle and the locale variants of this
> resource bundle contain strings that override the default validation
> messages. The ValidationMessages resource bundle is typically a
> properties file, ValidationMessages.properties, in the default package
> of an application.
>
>
>
Source: <http://docs.oracle.com/javaee/6/tutorial/doc/gkahi.html>
Also, the validation annotation should be `@Size(min = 2, max = 40, message = "{errors.firstName.size}")`, [as heRoy said](https://stackoverflow.com/a/28634756/178982). | Try to add curly braces to your message key as below :
```
@Size(min = 2, max = 40, message = "{errors.firstName.size}")
``` |
31,251,910 | I'm getting the infamous Run-time error when I run this code, and I don't understand why:
`With ThisWorkbook.Sheets("Data")
.Range(Cells(row1, column1), Cells(row2, column1)).Copy
End With`
row1, column1 and row2 are all defined as Integers.
The error pops up for the second line of code.
Can I get some insight please? | 2015/07/06 | [
"https://Stackoverflow.com/questions/31251910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5086294/"
] | You forgot the "." before `Cells` (as you are within the `With` scope of the Sheet Data)
```
With ThisWorkbook.Sheets("Sheet2")
.Range(.Cells(1, 1), .Cells(2, 2)).Copy
End With
```
Tested the above example and now it works for me. | Where are you coping the range to. The proper format is
source.copy destination
```
Sheets("Count").Range("C2:D3").Copy Sheets("Count").Range("E2:F3")
``` |