text:
Q: Potential energy regarding a central force I am looking at my lecture notes for mechanics and it says that for a central force $\vec F=f(r)\hat r$,
$$\vec F=-\nabla V $$ and so $$dV=-\vec F\cdot d\vec r$$
Then $$V=\int \vec F \cdot d\vec r=\int f(r)\frac{\vec r}{r}\cdot d\vec r $$
I'm fine up until this point. However, next it says that $\vec r \cdot d\vec r=r dr$ and so $$V=\int f(r) \ dr $$
I don't understand why $\vec r \cdot d\vec r=rdr.$
Could someone explain this please?

A: Note that the differential displacement, $d\vec r$, can be written in spherical coordinates $(r,\theta,\phi)$ with orthogonal unit vectors $(\hat r,\hat \theta,\hat \phi)$ as
$$d\vec r=\hat r dr+\hat \theta rd\theta+\hat \phi r\sin(\theta) d\phi$$
Then, taking the inner product with the position vector, $\vec r=\hat rr$, expressed in spherical coordinates, we find
$$\vec r \cdot d\vec r=\hat rr \cdot (\hat r dr+\hat \theta rd\theta+\hat \phi r\sin(\theta) d\phi)=rdr $$
since $\hat r\cdot \hat \theta=\hat r \cdot \hat \phi=0$.

A: $\displaystyle r\, dr
=\frac{1}{2} dr^{2}
=\frac{1}{2}d(\mathbf{r} \cdot \mathbf{r})
=\frac{1}{2}(d\mathbf{r} \cdot \mathbf{r}+\mathbf{r}\cdot d\mathbf{r})
=\mathbf{r} \cdot d\mathbf{r}$


text:
Q: Yammer REST API - Get Messages from Group I am trying to get all threaded messages from a group of yammer, but it seems that something wrong happened in the call.
The retrive all messages from the group I use this call:
/api/v1/messages/in_group/{groupId}.json?threaded=true
And when this call ends, I save the last message retrieved from the result and I execute the following call recursively until there is no more messages in the group:
/api/v1/messages/in_group/{groupId}.json?threaded=true&older_than={messageId}
It seems that the process works correctly, but when you look the data that you have retrieved from Yammer, there is some messages that appear in the Yammer group Wall that have been not retrieved using the REST API.
Do someone know why the REST API is not getting all Yammer data?
Thank you so much!
Aleu

A: From the docs https://developer.yammer.com/docs/messagesjson, here is the intended functionality of threaded=true: "threaded=true will only return the thread starter (first message) for each thread. This parameter is intended for apps which need to display message threads collapsed. threaded=extended will return the thread starter messages and the two most recent messages all ordered by activity, as they are viewed in the default view on the Yammer web interface."
Based on your question, perhaps threaded=extended would give you what you need.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kotlin: Unresolved reference: R I am new at Kotlin and it is a small error (see all code). What is going on with the "R" in my code:
Error: setContentView(R.layout.activity_main)
Error: var tv_stepsTaken = findViewById<TextView>(R.id.tv_stepsTaken)
Error: var tv_stepsTaken = findViewById<TextView>(R.id.tv_stepsTaken)
A lot of the StackOverflow is to remove import android.R. If that is the problem, where is it?
The whole code (MainActivity.kt):
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity(), SensorEventListener {
    // Added SensorEventListener the MainActivity class
    // Implement all the members in the class MainActivity
    // after adding SensorEventListener

    // we have assigned sensorManger to nullable
    private var sensorManager: SensorManager? = null

    // Creating a variable which will give the running status
    // and initially given the boolean value as false
    private var running = false

    // Creating a variable which will counts total steps
    // and it has been given the value of 0 float
    private var totalSteps = 0f

    // Creating a variable which counts previous total
    // steps and it has also been given the value of 0 float
    private var previousTotalSteps = 0f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        loadData()
        resetSteps()

        // Adding a context of SENSOR_SERVICE aas Sensor Manager
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
    }

    override fun onResume() {
        super.onResume()
        running = true

        // Returns the number of steps taken by the user since the last reboot while activated
        // This sensor requires permission android.permission.ACTIVITY_RECOGNITION.
        // So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app.
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)

        if (stepSensor == null) {
            // This will give a toast message to the user if there is no sensor in the device
            Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()
        } else {
            // Rate suitable for the user interface
            sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
        }
    }

    override fun onSensorChanged(event: SensorEvent?) {

        // Calling the TextView that we made in activity_main.xml
        // by the id given to that TextView
        var tv_stepsTaken = findViewById<TextView>(R.id.tv_stepsTaken)

        if (running) {
            totalSteps = event!!.values[0]

            // Current steps are calculated by taking the difference of total steps
            // and previous steps
            val currentSteps = totalSteps.toInt() - previousTotalSteps.toInt()

            // It will show the current steps to the user
            tv_stepsTaken.text = ("$currentSteps")
        }
    }

    fun resetSteps() {
        var tv_stepsTaken = findViewById<TextView>(R.id.tv_stepsTaken)
        tv_stepsTaken.setOnClickListener {
            // This will give a toast message if the user want to reset the steps
            Toast.makeText(this, "Long tap to reset steps", Toast.LENGTH_SHORT).show()
        }

        tv_stepsTaken.setOnLongClickListener {

            previousTotalSteps = totalSteps

            // When the user will click long tap on the screen,
            // the steps will be reset to 0
            tv_stepsTaken.text = 0.toString()

            // This will save the data
            saveData()

            true
        }
    }

    private fun saveData() {

        // Shared Preferences will allow us to save
        // and retrieve data in the form of key,value pair.
        // In this function we will save data
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)

        val editor = sharedPreferences.edit()
        editor.putFloat("key1", previousTotalSteps)
        editor.apply()
    }

    private fun loadData() {

        // In this function we will retrieve data
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        val savedNumber = sharedPreferences.getFloat("key1", 0f)

        // Log.d is used for debugging purposes
        Log.d("MainActivity", "$savedNumber")

        previousTotalSteps = savedNumber
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // We do not have to write anything in this function for this app
    }
}

A: That code is not importing R class. Often, it is like "import yourpackagename.R". Check if Android Studio suggests this import pressing option + enter (mac) or Ctrl + enter. –


text:
Q: How to Use SVG with React and ReasonML? With create-react-app and JavaScript/TypeScript, I understand I'm able to "import" an SVG as noted below. How may I do so with ReasonML?
import { ReactComponent as Logo } from './logo.svg';

function App() {
  return (

      {/* Logo is an actual React component */}
      <Logo />

  );
}

A: Create React App uses webpack to transform SVG files into React components. If you're using Reason with CRA, then all you need to do is provide a binding to the generated component. However, CRA will only transform the SVG into a component if the import statement is written exactly a certain way, which isn't how BuckleScript outputs import statements. (There's a GitHub issue about it here.) You have to import it with raw JavaScript and then bind to the imported value:
%bs.raw
{|import {ReactComponent as _Logo} from "./logo.svg"|};

module Logo = {
  [@react.component] [@bs.val] external make: unit => React.element = "_Logo";
};

/* And we can use it like a regular component: */
[@react.component]
let make = () =>

    <Logo />

;

According to the CRA docs:

The imported SVG React Component accepts a title prop along with other props that a svg element accepts.

For any of the other props you want to use, you'll have to add them to your external binding.
If you're not using CRA, then you'll need to configure your bundler to do the same transformation. I'm not familiar with the internals of CRA, but this seems to be the relevant code from its webpack configuration.

A: We can use SVGR to handle the webpack loading and then import the module as we normally would.
const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      //...
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
  //...
};

module Logo = {
  @bs.module(`../../../../src/img/logo.svg`) @react.component
  external make: {.} => React.element = "default"
}

...

<Logo /> // works

source: https://blog.logrocket.com/how-to-use-svgs-in-react/

A: I am the author of another solution that doesn't involve webpack.
It's a tool that can transform your svg files directly into .re files: https://github.com/MoOx/react-from-svg
This can create files for react (dom) or react-native(-web) (=> files generated use react-native-svg).
Feel free to try it :)
For example you can do (when the tool is installed from npm)
$ react-from-svg src/SVGs src/SVGs/components --with-native-for-reason --remove-fill

This will turns the files from svg/SVGs into React components into src/SVGs/components compatible for React Native with the Reason syntax.
The last option remove all svg fill props so you can use them as icons.
Note that the generated components accept width, height & fill props so you can adjust them when used.
Last bonus: since webpack is not involved, you can use this transformation only when you update your SVGs files & use this code directly with a Node runtime (JSX from Reason gets removed when converted to JS so the code can be consumed directly via Node without any transformation - which can be handy for tiny static sites/pages).


text:
Q: Selenium Grid Error Has anyone seen this error in CentOS, when running Selenium Grid:
SEVERE: Could not find any remote control providing the '*chrome' environment. Please make sure you started some remote controls which registered as offering this environment.
thanks!

A: I take it you started the hub but didn't start any nodes?  You must start a node so it can run the RC Server needed to handle your client request.


text:
Q: can local storage store the whole page so I have seen a lot of people using local storage to store certain parts of a web page but not an entire web page is it possible? , if so how? , if not is there a way to store an entire web pages data so the user can come back to it how they left it?

A: Since LocalStorage allows you to store about 5MB~ you can store a full webpage there and then just call it into a document.write().
The following code does it:
Storing it:
var HTML = ""; //html of the page goes here
localStorage.setItem("content", HTML);

Retrieving it:
document.write(localStorage['content']);

Although this is possible it is common practice you only save settings and load them up into the right elements rather than the entire web page.

A: This can be done if you use javascript to save document.body.innerHTML into the webstorage and you use javascript to load it back from the storage when the page is loaded next time. If the web page is not in the webstorage, you could redirect the user to the web page.
But this depends on the design of your web page and if there is session index etc in the body of the web page.
You should also think of some way to handle versions. You dont want your users only use the cached version of your web page, but it should be updated once you update your web page.
The session storage is ~5mbit, so you cant save very much, especially not pictures.

A: This is not really answering your question, but, if you are only curious how this can be done and don't need to have wide browser support, I suggest you look into Service Workers, as making websites offline is something that they solve very well.
One of their many capabilities is that they can act as a proxy for any request your website makes, and respond with locally saved data, instead of going to the server.
This allows you to write your application code exactly the same way as you would normally, with the exception of initializing the ServiceWorker (this is done only once)
https://developers.google.com/web/fundamentals/getting-started/primers/service-workers
https://jakearchibald.github.io/isserviceworkerready/

A: Local storage it's actually just an endpoint: has an IP address and can be accessed from the web.
First of all, you need to make sure that you're DNS service points on your Index page.
For example, if your Local-storage's ip is 10.10.10.10 and the files on that local-storage is organized like:

*

*contants:

*

*pages:

*

*index.html

*page2.html

*images:

*

*welcome.png

So you can point your DNS like:
10.10.10.10/index  ->  /contants/pages/index.html
In most of the web frameworks (web framework it's a library that provide built in tools that enable you to build your web site with more functionality and more easily) their is a built in module called 'route' that provide more functionality like this.
In that way, from you index.html file you can import the entire web site, for example:

and in your routes you define for example:
For all the files with the .html extension, route to -> 10.10.10.10/contants/pages/
For all the files with the .png/.jpg extension, route to -> 10.10.10.10/contants/images/

A: Local storage is usually for storing key and value pairs, storing a whole page will be a ridiculous idea. Try instead a Ajax call which Returns an partial view. Use that for the purpose of manipulation in DOM


text:
Q: What does the phrase "be matched by GitHub" mean?
You can also sponsor the work of LaTeX team members through the GitHub sponsor program at the moment for Frank, David and Joseph. Your contribution will be matched by GitHub in the first year and goes 100% to the developers.

What does it mean by "be matched by GitHub"?

A: In simple terms, this is saying that GitHub will contribute an amount of money equal to your contribution. The phrase matching contribution is often used to describe the act of employers paying into employees' retirement funds at a rate equal to that of the employees' personal contributions.
Similar constructions are matching donation and matching gift. See the Wikipedia page for matching funds for more context.


text:
Q: Как сделать Итого в MySql Нужно выбрать названия специальностей и количество студентов по каждой, а также всего , вот так:
    специальность 1              111
    специальность 2              222
    ...
    всего                        999

Вот что я сделал:
select
specialty.name as specialty_name,
    count(id_grupa) as student_count
from grupa
left join specialty on
 specialty.id=grupa.id_specialty
left join student on
 student.id_grupa=grupa.id
group by specialty_name
order by student_count;

Не знаю как теперь вывести Всего:


text:
Q: Hide and Show Other controls inside UIView, When Expand and Collapse a UIView I am trying a Expand and Collapse UIView when user click on button, I use below code to perform this operation.
bool isShown = true;
-(IBAction)btnClick:(id)sender{

    if (!isShown) {
        [UIView animateWithDuration:0.25 delay:0.1f
                            options:UIViewAnimationOptionTransitionFlipFromTop  animations:^{
                                myView.frame =  CGRectMake(0, 275, 320, 50);

                            } completion:nil];
        isShown = true;
    } else {
        [UIView animateWithDuration:0.25 delay:0.1f
                            options:UIViewAnimationOptionCurveEaseOut  animations:^{
                                myView.frame =  CGRectMake(0, 75, 320, 250);

                            } completion:nil];
        isShown = false;
    }
}

Problem:
When i Add Controls inside myView like UILabel and UITextView, those controls still showing when i collapse my view. I mean i don't want to show controls inside myView when i make my View Collapse and when i expand show all controls. I try to hide when i collapse but the animation doesn't look good.
And default frame size of myView is  myView.frame =  CGRectMake(0, 275, 320, 50);


text:
Q: Forcing garbage collection in JavaScript class I posted this question and what I can gather from the responses is that I need to force the garbage collector to remove code which has been removed from the DOM but where references still exist in memory. I've looked around and I can't seem to find a proper solution, in 2017, is there a viable way to collect the garbage?
Scenario
function class_blah() {
    this.var_blah = 'blah';

    this.func_blah = function () {};
}

var blah = new class_blah();

/** Stuff happens here... **/

Then say I remove that dynamically loaded script and load some more content in to the DOM, how I can get garbage collector to now remove that?
The linked question should give you a better idea in regards to the issue I'm facing.


text:
Q: VBA - Define range variables through looping I'm wondering if it's possible to define range variables through a for..next loop?
Something like that
Public Sub DefineRanges()
 Dim i As Long
 Dim rngLine1, rngLine2 As Range

 For i = 1 To 2
    Set Replace("rngLinex", "x", i) = ThisWorkbook.Sheets("Sheet1").Range("A" & i)
 Next i
End Sub

or like that
Public Sub DefineRanges()
 Dim i As Long
 Dim rngLine1, rngLine2 As Range

 For i = 1 To 2
    Set rngLine & i = ThisWorkbook.Sheets("Sheet1").Range("A" & i)
 Next i
End Sub

Thank you in advance.

A: As @JohnColeman stated use an array of ranges:
Sub defineranges()
Dim i As Long
Dim RngArr(1 To 2) As Range

For i = 1 To 2
    Set RngArr(i) = ThisWorkbook.Worksheets("Sheet1").Range("A" & i)
Next i

For i = 1 To 2
    Debug.Print RngArr(i).Value
Next i
End Sub


text:
Q: How can I create cells or grids in C++ for a randomized maze? I'm trying to create a randomized maze in C++, but I can't start because I don't know how to create grids or cells. How could I create it? And I also want to create it using ASCII characters. how can i store it in array? (can any one give a sample code and some explanation so i can understand it better)
Another question: What data stuctures should I need to learn and use? I'm planning to use Eller's algorithm or Kruskal's algorithm.
Thank you guys for helping me! im a begginer programmer, and i want to learn about this, because this is a part of my project, thank you vary much!

A: Are you looking for Maze generation algorithms (more)? Is your problem with the algorithms, or graphics?
The typical algorithms work by considering each "cell" in the maze as a vertex of a graph, start with all "walls", and remove a set of walls that corresponds to a spanning tree. (So in order to randomize it, many of them start with random weights and find the minimum spanning tree.) For small mazes at least, you don't need any special data structure to represent the cells; you can just think of each cell as a pair (x,y) (its coördinates). And you don't need any data structure (adjacency matrix / adjacency list) to store the edges of the graph either, because the neighbours of (x,y) are just (x,y±1) and (x±1,y) (ignoring those that fall outside the boundaries).
In any case, once you have the spanning tree, you know exactly which of the walls "exist" and which do not, so you have a complete description of the maze. If you're going to draw the maze, you know which ones to draw.
To draw with ASCII characters, you just pass through each row one by one: draw the "upper walls" (put a "--" if the wall between (x,y) and (x,y+1) exists), then draw the actual row (put a "|" if the wall between (x,y) and (x+1,y) exists). Finally draw the bottom boundary.

A: You probably want to store your maze in a 2-dimension char array.  You can declare an array with or without initializing it in C++.
char a[30][10];  // declares a char array of 30 rows and 10 columns.

// declare an array with 3 rows and 3 columns, and provide initial values
char ticTacToeBoard[3][3] = {{'x', 'x', 'o'},
                             {'o', 'o', 'x'},
                             {'x', 'o', ' '}
                            };

You could change the initial values to '|' and '-' for walls in your maze, and use a space character, ' ', for the passageways.
Either initialization method works, but you always use the elements the same way.  Here's how you clear the board in the initialized array above.
// clear the board
for (int row=0; row<3; row++) {
    for (int col=0; col<3; col++) {
        ticTacToeBoard[row][col] = ' ';
    }
}

If you want to read the value of an element (useful when you're trying to navigate a maze), you use the same subscript notation as when you're setting its value.
char y = a[2][2]; // reads the character in row 2, column 2

A: Vertical Wall: |
Horiz. Wall: _
If you're using fixed-width fonts:
 _____
| |  _
|_  | |
 __ | |
|_____|

I'm not sure exactly what to do, but here's where I'd start.
Determine where on your grid the start and end points will be.  Then, create a single path, with whatever squiggles you want.  Basically, it should be random movement, checking each time that there is still a way for this path to reach the end.  Then, remove a certain amount of walls from this path, and create other paths from these holes.  Continue this until you run out of empty space.  Then, perhaps, ensure that no shorter paths have been created.  If they have, block those up.


text:
Q: AnimatorSet - Getting Error: Only one ModelAnimator may play on a ModelRenderable at a time I'm trying to play multiple animations one after another, but I can't seem to get it to work. It's giving me the error:
Only one ModelAnimator may play on a ModelRenderable at a time

I've followed the instructions from this Stackoverflow Answer:
https://stackoverflow.com/a/55684795/11110509
private void animateModel(ModelRenderable modelRenderable) {

        AnimationData danceData = modelRenderable.getAnimationData("Armature|Pecking.002");
        ModelAnimator modelAnimator = new ModelAnimator(danceData, modelRenderable);

        AnimationData danceData2 = modelRenderable.getAnimationData("Armature|Walking");
        ModelAnimator modelAnimator2 = new ModelAnimator(danceData2, modelRenderable);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(modelAnimator).before(modelAnimator2);
        animatorSet.start();

    }

What am I doing incorrectly?

A: As far as I know, since 1.16, ModelAnimator and ModelRenderable.getAnimationData are not supported anymore.
If you must use version less than 1.16,
   List<Animator> animatorList = new ArrayList();
   animatorList.add(modelAnimator);
   animatorList.add(modelAnimator2);
   animatorSet.playSequentially(animatorList);
   animatorSet.start();

You can do like above.
I haven't tested the code since i am using sceneform 1.16.


text:
Q: How to set shiro principal's property as thymeleaf tag attribute? I have a demand that I want to use a shiro principal's property as thymeleaf tag's attribute.
I use the lib thymeleaf-extras-shiro, it's true to use like this.

    <shiro:principal property='imgUrl'/>

but I want to set the property 'imgUrl' as tag '' attribute 'href'.
so anybody could tell me about this?
Thank you.

A: I haven't looked at thymeleaf-extras-shiro in a while but it might be something like:

// or maybe


text:
Q: How to test that an input string in C is of the correct 'format'? I've written a simple calculator app in C and it works pretty well so far but I'm missing one thing: how to ensure the user has entered an input in the correct form e.g. "6 + 7". Is there any way I can test for that?
Here is my code so far:
/*A simple calculator that can add, subtract and multiple. TODO: Division
and add error handling i.e. if not an expected input!*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char input[10];
  int result;
  printf("Welcome to the calculator! The available operations are +, - and *.\n");
  while (1) {
    printf("What would you like to calculate?\n");
    fgets(input, 10, stdin); /*Getting user input in form e.g. 4 + 7*/

    /*Ideally test for input should go here*/

    /*Separating user input into the numbers and operators, using strtok and
    space as a delimiter*/
    char *firstNumber = strtok(input, " ");
    char *operator = strtok(NULL, " ");
    char *secondNumber = strtok(NULL, " ");

    /*Converting the separated numbers to integers*/
    int firstInt = atoi(firstNumber);
    int secondInt = atoi(secondNumber);

    if (strcmp(operator, "+") == 0) {
      result = firstInt + secondInt;
    } else if (strcmp(operator, "-") == 0) {
      result = firstInt - secondInt;
    } else if (strcmp(operator, "*") == 0) {
      result = firstInt * secondInt;
    } else {
      printf("That ain't a valid operator sonny jim. Try again:\n");
      continue;
    }

    printf("Your result is %d.\n", result);

    int flag = 0;

    while (flag == 0) {
      printf("Would you like to do another calculation? (yes or no)\n");
      fgets(input, 10, stdin);
      if (strcmp(input, "yes\n") == 0) {
        flag = 1;
      } else if (strcmp(input, "no\n") == 0) {
        flag = 2;
      } else {
        printf("That isn't a valid response. Please respond yes or no.\n");
      }
    }
    if (flag == 2) {
      break;
    }
  }

  return 0;

}

A: Not necessarily the best way, but I would use sscanf this way:
    int firstInt;
    int secondInt;
    char operator;
    if (3 != sscanf(input, "%d %c %d %1[^\n]", &firstInt, &operator, &secondInt, &temp)) {
      printf("Invalid input Billy!\n");
      continue;
    }

sscanf should return 3 if it successfully read in the values from the input string. If it would return 4 that would mean it read some trailing non whitespace characters which is invalid. The added benefit of this approach is that you don't need to parse the operands elsewhere with atoi.
Whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char input[10];
  char temp[2];
  int result;
  printf("Welcome to the calculator! The available operations are +, - and *.\n");
  while (1) {
    printf("What would you like to calculate?\n");
    fgets(input, 10, stdin); /*Getting user input in form e.g. 4 + 7*/

    /*Ideally test for input should go here*/
    int firstInt;
    int secondInt;
    char operator;
    if (3 != sscanf(input, "%d %c %d %1[^\n]", &firstInt, &operator, &secondInt, temp)) {
      printf("Invalid input Billy!\n");
      continue;
    }

    if ('+'== operator) {
      result = firstInt + secondInt;
    } else if ('-' == operator) {
      result = firstInt - secondInt;
    } else if ('*' == operator) {
      result = firstInt * secondInt;
    } else {
      printf("That ain't a valid operator sonny jim. Try again:\n");
      continue;
    }

    printf("Your result is %d.\n", result);

    int flag = 0;

    while (flag == 0) {
      printf("Would you like to do another calculation? (yes or no)\n");
      fgets(input, 10, stdin);
      if (strcmp(input, "yes\n") == 0) {
        flag = 1;
      } else if (strcmp(input, "no\n") == 0) {
        flag = 2;
      } else {
        printf("That isn't a valid response. Please respond yes or no.\n");
      }
    }
    if (flag == 2) {
      break;
    }
  }
  return 0;
}

A: The first test you should do is for length. You only allow input of ten characters. That's one for the operator, two for spaces, one for the \n, and one for the NUL terminator. That leaves only 5 characters to be split amongst the two operands. So, if the user inputs 543 * 65, you've already truncated the \n. An input of 5432 * 65, and you start losing important data. The way I would implement a length check is to search for the \n:
if (input[0] && input[strlen(input) - 1] != '\n'), you know the input has been truncated.† Next, you need to check for the validity of the characters. If you keep your strtok() method, you can do input checking when you convert the string to an integer if you use the preferred function strtol()†† with far better error checking. As for the operator, you already have checks on that. For formatting of input: check for NULL pointers. If strtok() doesn't find a space delimiter, it will return a NULL pointer, which you would then try to read from later in your program.
†: I personally would make my input character limit larger: at least 25
††: man strtol for more information

A:
string in C is of the correct 'format'?

A simpler approach uses " %n" at the end to record  the offset of the scan - if it made it that far.  Akin to @Chris Dodd comment.
int firstNumber;
char operator[2];
int secondNumber;

int n = 0;
sscanf(input, "%d %1[+-] %d %n", &firstNumber, operator, &secondNumber, &n);
//  v---v--------------------  Scan complete?
if (n > 0 && input[n] == '\0') Success();
//           ^--------------^  No extra junk at the end?
else Fail();

Detecting if a space exists is tricky.  This answer and "%d %c %d" would pass `"5-7".  If  spaces are required about the operator, use
"%d%*[ ]%1[+-]*[ ]%d %n"

Notice the " " in " %n" allows scanning to be tolerant of a trailing '\n'.  Use as desired.


text:
Q: Beautiful soup get text for multiple pages I try to scrape news pages of a German party and store all information in a dataframe ("python beginner"). There exist only a small problem, when I want to store the whole text or even the date into the dataframe. It seems like that only the last element of the text (p ... /p) will be stored in the row. I think the problem occurs because the iteration over the loop is misleading.
import pandas as pd
import requests
from time import sleep
from random import randint
from time import time
import numpy as np
from urllib.request import urlopen

data = pd.DataFrame()
teaser = ()
title = []
content = ()
childrenUrls = []
mainPage = "https://www.fdp.de"
start_time = time()
counter = 0

#for i in list(map(lambda x: x+1, range(3))):
for i in range(3):

    counter = counter + 1
    sleep(randint(1,3))
    elapsed_time = time() - start_time
    print('Request: {}; Frequency: {} requests/s'.format(counter, counter/elapsed_time))
    url = "https://www.fdp.de/seite/aktuelles?page="+str(i)
    #print(url)
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')

    uls = soup.find_all('div', {'class': 'field-title'})

    for ul in uls:
        for li in ul.find_all('h2'):
            for link in li.find_all('a'):
                url = link.get('href')
                contents = link.text
                print(contents)
                childrenUrls = mainPage+url
                print(childrenUrls)

                childrenPages = urllib2.urlopen(childrenUrls)
                soupCP = BeautifulSoup(childrenPages, 'html.parser')

                #content1 = soupCP.findAll('p').get_text()
                #print(content1)

                for content in soupCP.findAll('p'):
                    #for message in content.get('p'):
                    content = content.text.strip()
                    print(content)

                for teaser in soupCP.find_all('div', class_ = 'field-teaser'):
                    teaser = teaser.text.strip()
                    print(date)

                for title in soupCP.find_all('title'):
                    title = title.text.strip()
                    print(ttt)

                df = pd.DataFrame(
                    {'teaser': teaser,
                     'title' : title,
                    'content' : content}, index=[counter])

                data = pd.concat([data, df])
    #join(str(v) for v in value_list)

A: You have to save the text from each loop in a list, and not in a simple string variable. On each iteration, your code redefines the values on the variables; which leads to losing the previous data.
A good approach, is to use list comprehension here. Replace the last 3 for loops of your code with this:
content = [x.text.strip() for x in soupCP.find_all('p')]
teaser = [x.text.strip() for x in soupCP.find_all('div', class_='field-teaser')]
title = [x.text.strip() for x in soupCP.find_all('title')]

df = pd.DataFrame(
    {'teaser': teaser,
     'title': title,
     'content': content}, index=[counter])

data = pd.concat([data, df])

A simple explanation of list comprehension:
The line content = [x.text.strip() for x in soupCP.find_all('p')] is equivalent to:
content = []
for x in soupCP.find_all('p'):
    content.append(x.text.strip())


text:
Q: Is map(sum,zip(*list)) the fastest way to sum columns of list of arbitrary length? I would like to know if anyone can suggest a way to sum lists that is faster than map(sum, zip(*list)).
Example:
import timeit

print timeit.Timer('''
[ (a[x]+b[x]+c[x]) for x in xrange(len(a)) ]
''', '''
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
''').timeit(number = 1000)

print timeit.Timer('''
map(sum,zip(*d))
''', '''
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
d = [a,b,c]''').timeit(number = 1000)

print timeit.Timer('''
[sum(x) for x in zip(*d)]
''', '''
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
d = [a,b,c]''').timeit(number = 1000)

Results:
0.0317891459248 #list comprehension
0.0406545608382 #sum with zip
0.0532605665307 #map sum with zip

Note: I know I am nitpicking, but I'm just curious if anyone has a better suggestion.

A: How about this one?
print timeit.Timer('''
d.sum(axis=0)
''', '''
import numpy as np
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
d = np.array([a,b,c])''').timeit(number = 1000)

Of course, this assumes that your lists contain some sort of numeric type...


text:
Q: max sum of consecutive digits in a number i need to write a function that adds up consecutive digits in a number and returns the biggest sum of them. i wrote a function that receives to arguments, (m,t). m- stands for the number(int), and t (int also) stands for the numbers of consecutive digits to sum. now i want it to go through all the digits in the number and at the end to return me the max.
i dont figure out why my code doesnt work:
def sum_digits(m, t):
    str_m= str(m)

    for i in range(len(str_m)):
        if t+i<len(str_m):
            num= str_n[i:t+i]
            num1='+'.join(num)
            num2= str(eval(num1))
            lst= list(num2)
        else:
            break

return max (lst)

A: The reason yours doesn't work is that lst is getting reset every iteration. I think you intended to set it at the beginning and add to it each iteration. Also:
Ahhhh!!!! You don't need eval!
def max_sum(m, t):
    digits = map(int, str(m))
    max_sum = cur_sum = sum(digits[:t])
    for i, x in enumerate(s[t:], t):
        cur_sum += x - digits[i - t]
        max_sum = max(max_sum, cur_sum)
    return max_sum

Also, this has O(log m) running time (or O(n) if n is the number of digits in m), rather than the naive O(t * log m) (or O(t * n)).

A: >>> def maxSum(m, t):
...   m = str(m)
...   answer = 0
...   for digits in (m[i:i+t] for i in range(len(m)-t+1)):
...     answer = max(answer, sum(int(d) for d in digits))
...   return answer
...
>>> maxSum(1234567, 3)
18


text:
Q: sizeof derived already from base is it possible to return the sizeof a derived class already from base class/struct?
imho the size of a class is a kind of property of itself, like the weight of a human being. But I don't want to write the same function in every class.
many thanks in advance
Oops
PS: so code to make my question more clear:
template <typename T>
struct StructBase {
    size_t size<T>(){
        return sizeof(T);
    }
};

struct MyStruct: public StructBase<MyStruct> {
    double d1;
    double d2;
    double d3;
    MyStruct(): d1(0), d2(0), d3(0){}
    //I do not want to do this here
    //size_t size(){ //return size<MyStruct> ;}
};

int main(void) {
   MyStruct m;
   std::cout << m.size(); //nop ?!?
}

A: Since base classes are not supposed to know about classes derived from them (that would create a circular dependency), a base class method can't even know what extra fields have been added to a derived class. Moreover, sizeof can't be polymorphic -  it only works on static types and structures. Hence there is no point trying something like sizeof(*this).
So it's not going to work.
Update: well, now it is a completely different question. With templates this may even work FWIW (I don't have an IDE to try it out). But notice that now you practically have a template function with a type parameter which can be anything - restricted to derived classes only by you, the programmer. And overall, I don't see what you actually win with this solution - which may be due to lack of context as well.

A: You can't overload the sizeof operator. And I'm not sure what you are asking:
class A {
   int x, y;
};

then:
size_t n = sizeof( A );

gives you the size of class A - I don't see where derivation comes into this.
Edit: and regarding your expanded question, I don't see why you can't say:
MyStruct m;
std::cout << sizeof( m );

Note that size is not a property like weight - weight can change, and is different for different instances. The size of a class must be known by the compiler at compile time and cannot ever change.

A: class A {
  int a;
}

class B : A {
 int b;
}

The size of B (2xint) is twice the size of A (1xint), sizeof does NOT refer to an object but to a type. I know what you want to do, but polymorphism only works with objects, not types. So if you do sizeof(A) and expect it to return the size of B, think twice, the processor has no way to know that you wanted the size of B instead of A, since they are differents ;-)

A: Here is an example of how this could be done:
template <typename T>
struct StructBase {
    unsigned int const size;
    StructBase<T>():size(sizeof(T)) { }
};

struct MyStruct: public StructBase<MyStruct> {
    double d1;
    double d2;
    double d3;
    MyStruct(): d1(0), d2(0), d3(0){}
    //I do not want to do this here
    //size_t size(){ //return size<MyStruct> ;}
};

indeed it is very easy, but there is one drawback: the size of every struct that's derived from structBase will have one more variable, and depending on the other variables the size could be increased significantly:
in this example the size of MyStruct is 24 bytes without the baseclass StructBase but with the baseclass it is 32 bytes. that's something what you maybe do not like to have in every case.
regards
Oops


text:
Q: How to get javascript to prompt a question a set number times Im trying to write a simple program that asks the user to guess a random number a set number of times.
So far I have the following:
<!DOCTYPE html>
<html>
<head>
    <title>Decisions and Loops</title>
</head>
<body>

</body>
<script>

var rNum = Math.ceil(Math.random() * 30);

var myInput = Number (prompt ("Please enter your Guess: "));

if (myInput == rNum) {
    alert("Good guess");
    }
    else if (myInput >= rNum){
        alert((prompt ("Sorry, guess if too low, try again"));
    }
    else {
    alert((prompt ("Sorry, guess if too high, try again"));
    }

</script>
</html>

Two issues
1. For some reason this is not working.
2. How do I get the program to iterate through the loops a number of times?
Any assistance would be appreciated.

A: var rNum = Math.ceil(Math.random() * 30);

var myInput;
var numTimesToAsk = 3;

for (var i = 0; i < numTimesToAsk; i++) {
    myInput = Number (prompt ("Please enter your Guess: "));
    if(myInput === rNum) {
      alert("Good guess");
      break; //if you want the loop to stop here since they guessed correctly
    } else if (myInput >= rNum) {
      alert("Sorry, guess is too low, try again");
    } else {
      alert("Sorry, guess is too high, try again");
    }
}

A: A basic implementation with few logic fixes could be like this:
// To limit the number of prompts, or else loop might go on forever
var max_try = 5;

function ShowQuiz() {
   var rNum = Math.ceil(Math.random() * 30);
   var myInput = Number(prompt("Please enter your Guess: "));

   if (myInput == rNum) {
      alert("Good guess");
   } else if (myInput < rNum) {
      alert("Sorry, your guess is too low, try again");
      if (--max_try > 0) ShowQuiz()
   } else {
      alert("Sorry, your guess is too high, try again");
      if (--max_try > 0) ShowQuiz()
   }
}

ShowQuiz();


text:
Q: GlassFish 4 cannot Deploy I use GlassFish4 in Eclipse for Java Dynamic Web Development. GlassFish cannot deploy my project anymore. I have already tried several methods on stackoverflow and on the internet in general to fix it.
I can't even access the admin console via localhost:4848. I see the surface of the glassfish console but it says "Status: The Admin Console Application is not yet installed."
This is my error:
 [2018-05-05T20:28:14.580+0200] [glassfish 4.1] [INFO] [NCLS-CORE-00093] [javax.enterprise.system.core] [tid: _ThreadID=104 _ThreadName=Thread-23] [timeMillis: 1525544894580] [levelValue: 800] [[
  Problem while attempting to install admin console!
org.jvnet.hk2.config.TransactionFailure: A ApplicationRef with the same key "__admingui" already exists in Server server
    at org.jvnet.hk2.config.ConfigSupport._apply(ConfigSupport.java:209)
    at org.jvnet.hk2.config.ConfigSupport.apply(ConfigSupport.java:139)
    at com.sun.enterprise.v3.admin.adapter.InstallerThread.install(InstallerThread.java:166)
    at com.sun.enterprise.v3.admin.adapter.InstallerThread.run(InstallerThread.java:99)
Caused by: java.lang.IllegalArgumentException: A ApplicationRef with the same key "__admingui" already exists in Server server
    at org.jvnet.hk2.config.WriteableView$ProtectedList.add(WriteableView.java:648)
    at com.sun.enterprise.v3.admin.adapter.InstallerThread$1.run(InstallerThread.java:161)
    at org.jvnet.hk2.config.ConfigSupport._apply(ConfigSupport.java:180)
    ... 3 more
]]

I appreciate every kind of help.

A: I assume that you are working with a local instance of the glassfish application server. You could check if you acomplished the requirements listed in the GF 4.1 Release Notes before you did the installation.
Another action you can take is to verify the integrity of your domain.xml configuration file using the command asadmin verify-domain-xml from your installation-directory/bin folder
You say you cannot access the admin console, but is your server even running? (http://localhost:8080/).
You can also take a look at the server.log for some more hints on what is going on, which you can find in installation-directory/domains/domain-name/logs, or try to do a manual deployment via asadmin and see what happens.


text:
Q: Elixir/Erlang and Cowboy - How to use supervisors When you use Mix to create an application, it always adds a root supervisor file to the project. Note how the 'child spec' array in the supervise function is empty.
app.ex:
defmodule App.Supervisor do
    use Supervisor

    def start_link do
        Supervisor.start_link(__MODULE__, :ok)
    end

    def init(args) do
       supervise([], [strategy: :one_for_one])
    end
end

An entry point for the application is also created for you. Working through some of the examples I found online, I wrote the following:
defmodule App do
    def start(_type, _args) do
        dispatch = :cowboy_router.compile([
            {
                :_,
                [
                    # Simple JSON test.
                    {"/test", app.Handle.test, []},
                ]
            }
        ])

        {:ok, _} = :cowboy.start_http(
            :http,
            100,
            [{:port, 8080}],
            [{ :env, [{:dispatch, dispatch}]}]
        )

        App.Supervisor.start_link()
    end
end

This application works, but it also works if I remove the call to App.Supervisor.start_link() in App.start().
So what's the supervisor for in this case? If the child spec for the supervisor is empty, then what's the point of it?
For example, in the Elixir example found here - https://github.com/IdahoEv/cowboy-elixir-example/blob/master/lib/cowboy_elixir_example.ex - You can see that the call to start the supervisor is commented out on line 65.
But in an official Cowboy Erlang example, this file - https://github.com/ninenines/cowboy/blob/master/examples/hello_world/src/hello_world_app.erl - Creates a similar root supervisor with no child spec, and then calls it in the main application file here, on line 22 - https://github.com/ninenines/cowboy/blob/master/examples/hello_world/src/hello_world_app.erl

A: There is a higher level concept than supervision tree: application.
A project usually consists of many applications. Each of them can have its own supervision tree. If you have Erlang and Elixir installed properly with wx widgets, you can see it by running:
:observer.start

This opens a graphical user interface. Go to Applications tab and click on application names on the right. It only shows processes following OTP principles. If your example is similar to those from cowboy repository, then you should see all your acceptors under ranch.
Supervisor with empty worker list does nothing. It is there, in case you need to add some processes later. It doesn't do any harm to start it, but it also isn't necessary. It might be the case, that programmers didn't bother to delete after they started project from template.
There are two kinds of applications:

*

*active applications - which use processes to do their job (for example ranch), they should start and stop as a unit

*library applications - which just provide some code, that is run in context of other processes (for example json decoders/encoders)

Usually active applications have top level supervisor and library applications don't.


text:
Q: Unable to loading data into gridview I am using WCF service to display data into gridview but it not properly displaying(Columns are displaying out of order)
Following is my seperate class file containing properties to be added to IList object
        Code:
    Class1.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace ServiceTest
    {
        public class Class1
        {
            public int index { get; set; }
            public string name { get; set; }
            public int id { get; set; }
        }
    }

This is Service interface
IService1.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Collections;

namespace ServiceTest
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
      IList<Class1> GetD();

    }
}

This is service class that implements IService.cs
    Service1
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.Collections;
namespace ServiceTest
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {

        public IList<Class1> GetD()
        {

            IList<Class1> lst = new List<Class1>();
            for (int i = 0; i < 50; i++)
            {
                Class1 c = new Class1();
                c.index = i;
                c.name = "Madhavi " + i;
                c.id = i + 1;
                lst.Add(c);
            }
            return lst;
        }

    }
}

Below is my consumer code having one gridview databound control.
    And consumer code
 protected void Page_Load(object sender, EventArgs e)
    {
        //IList i = new ArrayList();
        Service1Client s = new Service1Client();
       // i = s.GetD();
        GridView1.DataSource = s.GetD();
        GridView1.DataBind();
    }

A: Sounds as if you have AutoGenerateColumns set to true for the GridView1. You can instead try explicitly specifying the columns in the .aspx file in the order that you would like these columns to appear and bind each column with the appropriate field from the Datasource.
<asp:GridView runat="server" id="GridView1">
     <Columns>
     </Columns>
</GridView>


text:
Q: make query for filtering where object is in queryset ive got three models
-Company
-Queue
-User
Company and Queue have a one to one relationship
User and Queue have a many to many relationship. Users can be in many queues, and more importantly, a queue can contain many users
How do I write a query that filters for companies whose queue contains a specified user? joined_companies should contain companies whose queues contain user
(companies.queue.users is a queryset of Users)
    def get(self, request, **kwargs):
        user = request.user

        companies = Company.objects.all()

        joined_companies = companies.filter(queue__users__contains=user)

A: Just remove contains, you also do not need the first query, the scope of filter is all objects:
    user = request.user
    companies = models.Company.objects.filter(queue__users=user)

contains lookup does not work, because you are looking for an User object instance instead of an value:
username = request.user.username
companies = models.Company.objects.filter(queue__users__username__contains=username)


text:
Q: Access element of the struct in array of structs Hi I have a task to implement the Fleet protocol which has two functions:
addNewCar - adds a new car object to the Fleet.
- Parameter car: car to add to the Fleet
- Returns: false if the car with same id already exists in the Fleet, true – otherwise.
deleteCar - Deletes the car with the specified id from the Fleet.
- Returns: true if the car with same id existed in the Fleet, false – otherwise.
listCarsByModel - returns 10 car models containing the specified string.
If there are several cars with the same model, brand's name is added to car's model in the format "brand - car",
otherwise returns simply "car".
listCarsByBrand - returns 10 car models whose brand contains the specified string,
result is ordered by brand.
struct Car {
    let id: String; // unique identifier
    let model: String;
    let brand: String;
}

protocol Fleet {
    func addNewCar(car: Car) -> Bool

    func deleteCar(id: String) -> Bool

    func listCarsByModel(searchString: String) -> Set<String>

    func listCarsByBrand(searchString: String) -> [String]

}

class FleetImpl: Fleet {
    var cars: [Car] = []

    func addNewCar(car: Car) -> Bool {
        if let i = cars.firstIndex(where: { $0.id == car.id }) {
            print(i)
            return false
        } else {
            cars.append(car)
            print(car)
            return true
        }
    }

    func deleteCar(id: String) -> Bool {

        return true
    }

    func listCarsByModel(searchString: String) -> Set<String> {

    }

    func listCarsByBrand(searchString: String) -> [String] {

    }
}

I've used method firstIndex(where:). But the function adds new car to the array with existing id. (i.e. two or more cars with the same id)
How can I access that 'id' property of Car struct in order to manipulate that data?
Please help me out
This is the test code:
func test(fleet: Fleet) {
    assert(!fleet.deleteCar(id: "1"))
    assert(fleet.addNewCar(car: Car(id: "1", model: "1", brand: "Lex")))
    assert(!fleet.addNewCar(car: Car(id: "1", model: "any name because we check id only", brand: "any brand")))
    assert(fleet.deleteCar(id: "1"))
    assert(fleet.addNewCar(car: Car(id: "3", model: "Some Car3", brand: "Some Brand2")))
    assert(fleet.addNewCar(car: Car(id: "4", model: "Some Car1", brand: "Some Brand3")))

    var byModels: Set<String> = fleet.listCarsByModels(searchString: "Car")
    assert(byModels.count == 10)

byModels = fleet.listCarsByModels(searchString: "Some Car")
    assert(byModels.count == 4)
    assert(byModels.contains("Some Brand3 - Some Car1"))
    assert(byModels.contains("Some Car2"))
    assert(byModels.contains("Some Car3"))
    assert(!byModels.contains("Some Car1"))
    assert(byModels.contains("Some Brand1 - Some Car1"))

var byBrand: [String] = fleet.listCarsByBrand(searchString: "Brand")
    assert(byBrand.count == 10)

byBrand = fleet.listCarsByBrand(searchString: "Some Brand")
    assert(byBrand.count == 4)
    assert(byBrand[0] == "Some Car1")
    assert(byBrand[1] == "Some Car2" || byBrand[1] == "Some Car3")
    assert(byBrand[2] == "Some Car2" || byBrand[2] == "Some Car3")
    assert(byBrand[3] == "Some Car1")
}

test(fleet: FleetImpl())

A: Maybe a set instead of an array would work better in this case as we're dealing with unique elements. Also note that rather than using firstIndex(where) I'm using first(where) which will return the car rather than index.
import UIKit

struct Car: Hashable {
    let id: String
    let model: String
    let brand: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

protocol Fleet {
    func addNewCar(car: Car) -> Bool
    func deleteCar(id: String) -> Bool
    func listCarsByModel(searchString: String) -> [String]
    func listCarsByBrand(searchString: String) -> [String]
}

class FleetImpl: Fleet {
    var cars = Set<Car>()

    func addNewCar(car: Car) -> Bool {
        guard !cars.contains(where: { $0.id == car.id }) else { return false }

        cars.insert(car)
        return true
    }

    func deleteCar(id: String) -> Bool {
        guard let car = cars.first(where: { $0.id == id }) else { return false }

        cars.remove(car)
        return true
    }

    func listCarsByModel(searchString: String) -> [String] {
        let searchedCars = cars.filter { $0.model.lowercased().contains(searchString.lowercased()) }.sorted { $0.brand < $1.brand }
        var formattedModels = [String]()
        searchedCars.forEach { car in
            if let car = searchedCars.first(where: { $0.model == car.model && $0.id != car.id }) {
                let carName = [car.model, car.brand].joined(separator: " - ")
                formattedModels.append(carName)
            } else {
                formattedModels.append(car.model)
            }
        }
        return Array(formattedModels.prefix(10))
    }

    func listCarsByBrand(searchString: String) -> [String] {
        let searchedBrands = cars.filter { $0.brand.lowercased().contains(searchString.lowercased()) }.sorted { $0.brand < $1.brand }.map { $0.model }
        return Array(searchedBrands.prefix(10))
    }

}


text:
Q: Display report in visualforce page i want to display a report on a visualforce page. I found this snippet of code but it brings back a blank page. What piece am i missing to have it show the report data?
<apex:page showHeader="false" sidebar="false">
  <apex:iframe src="/00OQ0000000Gdbm"/>
</apex:page>

A: I use code that looks like this to show a report in a Visualforce page.  I've left out details that would get in the way:
<apex:page standardController="CustomOb__c"  extensions="CobjController">
<apex:sectionHeader title="Manage Stuff"/>
<apex:form>
...

<apex:outputPanel id="MissingAttRpt" >
<apex:iframe src="/00O0000000AAJlV?isdtp=lt" scrolling="true"  height="1588px"  width="100%"/>
</apex:outputPanel>

...
</apex:form>
</apex:page>

The outputPanel is used so that the report can be re-rendered without refreshing the whole page.
Try getting rid of the showHeader and sidebar properties.


text:
Q: Radix Sort C code to sort uint64_t looking only at 32 MSB bits? I use the uint64_t Radix sort provided by Louis Ricci (answered Aug 24 '15 at 18:00) Radix_Sort_Uint64. Amazingly fast.
I have a data structure which contains 2, uint32_t items and want to sort a large array (20+ million) looking only at the first or last 32 bits, but I want the sort routine to move the entire 64 bit package as a unit.
Is there a C language uint64 Radix sort which orders based on a subset of the entire 64 bit quanta as if the data were masked with 0X1111111100000000?

A: Example C code. It uses fewer local variables than the example linked to in the original post, allowing a C compiler to use registers for those variables. This program takes less than 0.5 second to sort 20 million (20*1024*1024 = 20971520) 64 bit unsigned integers by the upper 32 bits on my system (Intel 3770K 3.5ghz cpu, Windows 7 Pro 64 bit).
/*  radix sort via upper 32 bits of 64 bit unsigned integers */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef unsigned long long uint64_t;

void RadixSort(uint64_t * pData, uint64_t * pTemp, size_t count)
{
    size_t mIndex[4][256] = { 0 };      /* index matrix */
    size_t * pmIndex;                   /* ptr to row of matrix */
    size_t i, j, m, n;
    uint64_t u;

    for (i = 0; i < count; i++) {       /* generate histograms */
        u = pData[i];
        mIndex[3][(u >> 32) & 0xff]++;
        mIndex[2][(u >> 40) & 0xff]++;
        mIndex[1][(u >> 48) & 0xff]++;
        mIndex[0][(u >> 56) & 0xff]++;
    }

    for (j = 0; j < 4; j++) {           /* convert to indices */
        pmIndex = mIndex[j];
        n = 0;
        for (i = 0; i < 256; i++) {
            m = pmIndex[i];
            pmIndex[i] = n;
            n += m;
        }
    }

    for (i = 0; i < count; i++) {       /* radix sort */
        u = pData[i];
        pTemp[mIndex[3][(u >> 32) & 0xff]++] = u;
    }
    for (i = 0; i < count; i++) {
        u = pTemp[i];
        pData[mIndex[2][(u >> 40) & 0xff]++] = u;
    }
    for (i = 0; i < count; i++) {
        u = pData[i];
        pTemp[mIndex[1][(u >> 48) & 0xff]++] = u;
    }
    for (i = 0; i < count; i++) {
        u = pTemp[i];
        pData[mIndex[0][(u >> 56) & 0xff]++] = u;
    }
}

#define COUNT (20*1024*1024)            /* number of elements */

static clock_t dwTimeStart;             /* clock values */
static clock_t dwTimeStop;

int main( )
{
uint64_t * pData;
uint64_t * pTemp;
uint64_t r;
size_t i;

    /* allocate memory */
    pData  = (uint64_t *)malloc(COUNT*sizeof(uint64_t));
    if(pData == NULL){
        return 0;
    }
    pTemp  = (uint64_t *)malloc(COUNT*sizeof(uint64_t));
    if(pTemp == NULL){
        free(pData);
        return 0;
    }

    for(i = 0; i < COUNT; i++){         /* generate test data */
        r  = (((uint64_t)((rand()>>4) & 0xff))<< 0);
        r |= (((uint64_t)((rand()>>4) & 0xff))<< 8);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<16);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<24);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<32);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<40);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<48);
        r |= (((uint64_t)((rand()>>4) & 0xff))<<56);
        pData[i] = r;
    }

    dwTimeStart = clock();
    RadixSort(pData, pTemp, COUNT);     /* sort array */
    dwTimeStop = clock();
    printf("Number of ticks %d\n", dwTimeStop-dwTimeStart);
    for(i = 1; i < COUNT; i++){         /* check sort */
        if((pData[i-1]>>32) > (pData[i]>>32)){
            break;
        }
    }
    if(i != COUNT)
        printf("sort error\n");
    free(pData);
    return(0);
}

A: The register optimized code from RGCLGR ["RADIX_SORT_UINT64_32R()"] is significantly faster than the original code sorting on only the 32 most significant bits:
  Time= 1.851 sec = 15.648%, RADIX_SORT_FFFF0000  , hits=4, 0.463 sec each  << OLD
  Time= 1.552 sec = 13.120%, RADIX_SORT_UINT64_32R, hits=4, 0.388 sec each  << NEW

It takes an average of 83.8% as long to run averaged over 4 runs with an array with 36.2 million values, 100% of which are distinct.
After each run, the results of each sort are bit shifted >> 32, compared and are identical.
Comparing to QSort and the previous version of Radix_Sort() on all 64 bits:
Time=  6.125 sec = 62.359%, QSORT_UINT64_ARRAY   , hits=1
Time=  0.832 sec =  8.468%, RADIX_SORT_64        , hits=1  << OLD
Time=  0.770 sec =  7.842%, RADIX_SORT_UINT64_REG, hits=1  << NEW

The QSort takes almost 8 times as long as this new version.
The original 'RADIX_SORT_64()' function is 8% slower.
Generalizing the code from RGCLGR to 48 and 64 bits and comparing sorting a uint64_t[32M] on 64, 48 and 32 bits with the RGCLGR method:
Time=  3.130 sec = 20.342%, RADIX_SORT_UINT64_REG, hits=4, 0.782 sec each
Time=  2.336 sec = 15.180%, RADIX_SORT_UINT64_48R, hits=4, 0.584 sec each
Time=  1.540 sec = 10.007%, RADIX_SORT_UINT64_32R, hits=4, 0.385 sec each

Note the expected linearity between 20%, 15% and 10% program time for 64, 48 and 32 bits considered for sort.

A: // =============================================================================
// Create 2 identical uint64[]s, mirror the first 32 bits in the last, sort one
// with qsort and the other with RadixSort11110000() and compare the results
int test_uint64_32_sort(EV_TIME_STR *tsa)  {
uint64_t *la1, *la2;
int ii, lcount=3615232, zmem=0, debug=0, ucount=1, ri, er12=0, ep=63;
time_t tt;  // This Time!
float rssec=2.0f;  // RadixSort_SEConds elapsed time from Radixsort()
    time_event(E_GENERATE_RANDOM_ARRAY, tsa, E_TIME_EVENT, 1, 0);
    srand((unsigned) time(&tt));
    la1=(uint64_t *)alloc_check((lcount)*8, zmem=0, "LLong_ara_1", debug);
    la2=(uint64_t *)alloc_check((lcount)*8, zmem=0, "LLong_ara_2", debug);

    for(ii=0; ii < lcount; ii++)  {  // Look only SHORT range
        ri = rand();  // Random int
        la1[ii] = ri << 32 + (0XFFFFFFFF - ri);  // Reflect val in lower 32
    }

    // Make identical copies in the other []
    time_event(E_MEMCPY_DOUBLE_ARRAY, tsa, E_TIME_EVENT, 1, 0);
    memcpy((void *) la2, (void *) la1, lcount * sizeof(uint64_t));

    time_event(E_QSORT_UINT64_ARRAY, tsa, E_TIME_EVENT, 1, 0);
    qsort(la1, lcount, sizeof(uint64_t), comp_uint6411110000);

    time_event(E_RADIX_SORT64_11110000, tsa, E_TIME_EVENT, 1, 0);
    radixSort11110000(la2, lcount, &rssec, &ucount);

    time_event(E_SPLIT_RGBJ_MEM,   tsa, E_TIME_EVENT, 1, 0);
    for(ii=er12=0; ii < lcount; ii++)  {
        if(la1[ii] != la2[ii])  {
            er12++;
            if((--ep) > 0)  {
                printf("II %d) Er%d, l1=0X%016llX, l2=0X%016llX\n",
                    ii, ep, la1[ii], la2[ii]);  FF_SO;  }
        }  // Count Error Mismatches
        if(!(ii%100000))  {
            printf("II %d) l1=0X%016llX, l2=0X%016llX\n",
                ii, la1[ii], la2[ii]);  FF_SO;  }
    }
    printf("T63S: Er1/2 = %d \n", er12);  FF_SO;
    if(ucount)  {
        printf("T63S: RadixSort time = %.3f ms, unique=%d = %.3f%%\n",
            rssec*1.0E3f, ucount, (100.0f * ucount / lcount));  FF_SO;
    }
    free_bb(la1);  free_bb(la2);
}

// =============================================================================
// Based on original code from https://ideone.com/JHI0d9
// and suggestions from  Ian Abbott
// https://stackoverflow.com/questions/47080353/radix-sort-c-code-to-sort-uint64-t-looking-only-at-32-msb-bits
// Hacked code may be unsuitable for any use and should not be used by anyone
// Sort uint64[] by looking ONLY at the
uint64_t *radixSort11110000(uint64_t *arrayA, uint32_t size)  {
register uint64_t *array=arrayA;  // Slam arg into Register!
register uint64_t std;  // STanDard to compare others for uniqueness
register int dist=0;  // Distinct, unique values found if *UCount arg is TRUE
register int ii;  // Loop control
int64_t rtime, mtns;  // Time in NanoSeconds!!!
    rscounts4_t counts;
    memset(&counts, 0, 256 * 4 * sizeof(uint32_t));
    uint64_t * cpy = (uint64_t *)malloc(size * sizeof(uint64_t));
    uint32_t o4=0, o3=0, o2=0, o1=0;
    uint32_t t4, t3, t2, t1;
    register uint32_t x;
    // calculate counts
    for(x = 0; x < size; x++) {
        t4 = (array[x] >> 32) & 0xff;
        t3 = (array[x] >> 40) & 0xff;
        t2 = (array[x] >> 48) & 0xff;
        t1 = (array[x] >> 56) & 0xff;
        counts.c4[t4]++;
        counts.c3[t3]++;
        counts.c2[t2]++;
        counts.c1[t1]++;
    }
    // convert counts to offsets
    for(x = 0; x < 256; x++) {
        t4 = o4 + counts.c4[x];
        t3 = o3 + counts.c3[x];
        t2 = o2 + counts.c2[x];
        t1 = o1 + counts.c1[x];
        counts.c4[x] = o4;
        counts.c3[x] = o3;
        counts.c2[x] = o2;
        counts.c1[x] = o1;
        o4 = t4;
        o3 = t3;
        o2 = t2;
        o1 = t1;
    }
    // radix
    for(x = 0; x < size; x++) {
        t4 = (array[x] >> 32) & 0xff;
        cpy[counts.c4[t4]] = array[x];
        counts.c4[t4]++;  }
    for(x = 0; x < size; x++) {
        t3 = (cpy[x] >> 40) & 0xff;
        array[counts.c3[t3]] = cpy[x];
        counts.c3[t3]++;  }
    for(x = 0; x < size; x++) {
        t2 = (array[x] >> 48) & 0xff;
        cpy[counts.c2[t2]] = array[x];
        counts.c2[t2]++;  }
    for(x = 0; x < size; x++) {
        t1 = (cpy[x] >> 56) & 0xff;
        array[counts.c1[t1]] = cpy[x];
        counts.c1[t1]++;  }
    free(cpy);
    return array;
}  // End radixSort_11110000().

// #############################################################################
// From: http://ideone.com/JHI0d9
// RadixSort---
typedef union {
    struct {
        uint32_t c4[256];
        uint32_t c3[256];
        uint32_t c2[256];
        uint32_t c1[256];
    };
    uint32_t counts[256 * 4];
}  rscounts4_t;

// =============================================================================
// Compare only the MSB 4 bytes of a uint64 by masking each with
// 0XFFFFFFFF00000000 before comparison
int comp_uint6411110000(const void *a, const void *b)  {
    return (
      (
        ( ( *( (uint64_t *)a ) ) & 0XFFFFFFFF00000000ULL ) >
        ( ( *( (uint64_t *)b ) ) & 0XFFFFFFFF00000000ULL )
      )
     -
      (
        ( ( *( (uint64_t *)a ) ) & 0XFFFFFFFF00000000ULL ) <
        ( ( *( (uint64_t *)b ) ) & 0XFFFFFFFF00000000ULL )
      )
    );
}  // End Comp_Uint64_11110000().

// Both sorted arrays were identical.
// T63S: Er1/2 = 0
// TE: Top 90% events in desc order (7/312):
//  Time=  0.157 sec = 71.282%, QSORT_UINT64_ARRAY   , hits=1
//  Time=  0.029 sec = 13.119%, RADIX_SORT64_11110000, hits=1
//  Time=  0.026 sec = 11.872%, GENERATE_RANDOM_ARRAY, hits=1

// mult 71.282  /13.119  -> 5.433493
// The RadixSort is over 5x faster that the qsort

Perhaps the QSort comparitor could be handled more efficiently


text:
Q: Adding a image in ext tab panel I am new to ext js.How do i add an image as a logo of my application in the header of ext tab panel?
Following is my code:-
Ext.define('MyApp.view.main.Main', {
extend: 'Ext.tab.Panel',
xtype: 'app-main',
requires: [

'MyApp.view.main.MainController',
'MyApp.view.main.MainModel',
'MyApp.view.main.List'
],
controller: 'main',
viewModel: 'main',
defaults: {
styleHtmlContent: true
},
tabBarPosition: 'bottom',
items: [
{
title: 'Home',
iconCls: 'fa-home',
layout: 'fit',
items: [{
xtype: 'mainlist'
}]
}
]
});

I need to add a logo in place of 'myapp' which is appearing as title. I want it something like the below image:-

A: To Answer this I created a new app in Extjs6 and did some modification which is below to get the logo.
Place the image and css in your resource folder then add below css in your css file.
.my-logo-icon {
background-image: url(../images/newpowered.gif) !important;

}
then place css path in app.json to get the css.
{
 "path": "resources/css/styles.css"
}

Now in your code call this css at iconCls
iconCls: 'my-logo-icon'

complete code is
Ext.define('MyApp.view.main.Main', {
extend: 'Ext.tab.Panel',
xtype: 'app-main',
requires: [
    'Ext.plugin.Viewport',
    'Ext.window.MessageBox',
    'MyApp.view.main.MainController',
    'MyApp.view.main.MainModel',
    'MyApp.view.main.List'
],
controller: 'main',
viewModel: 'main',
ui: 'navigation',
tabBarHeaderPosition: 1,
titleRotation: 0,
tabRotation: 0,
header: {
    layout: {
        align: 'stretchmax'
    },
    title: {

        flex: 0
    },
    iconCls: 'my-logo-icon'
},
tabBar: {
    flex: 1,
    layout: {
        align: 'stretch',
        overflowHandler: 'none'
    }
},
responsiveConfig: {
    tall: {
        headerPosition: 'top'
    },
    wide: {
        headerPosition: 'left'
    }
},
defaults: {
    bodyPadding: 20,
    tabConfig: {
        plugins: 'responsive',
        responsiveConfig: {
            wide: {
                iconAlign: 'left',
                textAlign: 'left'
            },
            tall: {
                iconAlign: 'top',
                textAlign: 'center',
                width: 120
            }
        }
    }
},
items: [{
    title: 'Home',
    iconCls: 'fa-home',
    // The following grid shares a store with the classic version's grid as well!
    items: [{
        xtype: 'mainlist'
    }]
}, {
    title: 'Users',
    iconCls: 'fa-user',
    bind: {
        html: '{loremIpsum}'
    }
}, {
    title: 'Groups',
    iconCls: 'fa-users',
    bind: {
        html: '{loremIpsum}'
    }
}, {
    title: 'Settings',
    iconCls: 'fa-cog',
    bind: {
        html: '{loremIpsum}'
    }
}]});

And out put image is

A: You can also do it like this:
items       : [{
        title     : "<img src='../resources/images/whatever.png'>",
        xtype     : 'home-page',
        bodyCls   : 'menu-tabs' // optional

    }, {

}]

and if you want the tab to be a little taller just use this as css
div[class~="menu-tabs"] div[class~="x-box-scroller-body-vertical"] div[class~="x-box-target"] a[class~="x-tab-default"] span[class~="x-tab-wrap-default"] span[class~="x-tab-button-default"]{
    height: 50px;
}


text:
Q: How do I properly chroot Nginx and uwsgi? I have a pretty good idea of how to do this, I just wanted to make sure I wasn't going to be seriously screwing stuff up before I deployed it.  I have a web application which uses uwsgi and nginx, and I wanted to chroot the app to a specific directory.  I was planning on chrooting both nginx and uwsgi to the same directory.  Now, I know how to do this, but would this be all I need to do to make it secure (in terms of jailing it), or is there anything else I should do?  Alternatively, is chrooting one of them unnecessary?  i.e., should I just chroot uwsgi or nginx and leave the other alone?

A: chroot is a good start in securing your webserver, but it only works correctly when uwsgi is working/configured correctly.
If you are really looking for a secure environment you would also want to configure selinux/apparmour to restrict what your web server has access to. In this way even if your web server is compromised and/or mis-configured the damage would be limited to only being able to access what the web server had access to.
You still aren't really secure in the strictest sense. Other things that you would be interested in are things like what user the web server is running as, what permissions the web server has, what permissions you are allowing to applications your web server is running, how updates are being applied, what other processes are running, and so on.
Once you are comfortable with all of those things you would look more into social engineering aspects of things, like, are your passwords secure, what about users using your system, are you securing data to/from your web server.
In short you can probably never do enough to make something secure depending on your definition of secure, but chroot is probably fine for what you are doing.


text:
Q: Ruby on Rails Else If Question I have an application where in the layout I have a user_name div which will display different things based on whether or not they are logged in, are an admin, etc. Right now my code is the following:
  <% if current_user.role == "admin" %>

You are an admin!

      <%= link_to "Edit Profile", edit_user_path(:current) %>
   <%= link_to "Logout", logout_path %>
  <% elsif current_user %>
   <%= link_to "Edit Profile", edit_user_path(:current) %>
   <%= link_to "Logout", logout_path %>
  <% else %>
<%= link_to "Register", new_user_path %>
<%= link_to "Login", login_path %>
<% end %>

I have a current_user helper already and everything was working fine when the code was just:
<% if current_user %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
    <%= link_to "Register", new_user_path %>
    <%= link_to "Login", login_path %>
<% end %>

Now when I make it an elsif statement, when I am logged in as an admin it works and I get the text displayed with the correct links. When I am not an admin user/logged out, I get a undefined method `role' for nil:NilClass error...  Also my current_user stuff is declared in my application controller as follows:
helper_method :current_user

private

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

Any ideas what I can do to display the result I want? "If they are a user with the role attribute equal to admin they get some text and the logged in links, if they are just a user they get the logged in links, and if they are not logged in they get the register and login links.
Thanks!

A: Hide the role check in the current user loop, which has the side effect of simplifying your conditional.
<% if current_user %>
  <%= content_tag(:p, "You are an admin!", :id=>"admintxt") if current_user.role == "admin" %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>

A: <% if current_user and current_user.role == "admin" %>

This should prevent the error when there is no user logged in, but you could restructure the whole block in order to remove the redundant tests against current_user being nil.

A: <% if current_user %>
  <% if current_user.role == "admin" %>

You are an admin!

    <%= link_to "Edit Profile", edit_user_path(:current) %>
    <%= link_to "Logout", logout_path %>
  <% else %>
    <%= link_to "Edit Profile", edit_user_path(:current) %>
    <%= link_to "Logout", logout_path %>
  <% end %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>

or with Rails >= 2.3
<% if current_user.try(:role) == "admin" %>

You are an admin!

  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% elsif current_user %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>


text:
Q: Reason Why this Happens in c i am using gcc and i have written this code and intentionally loop is written wrong
int main() {
  int a[3][3];
  int i=0;
  int j=0;
  int num=0;
  for(i=0;i<4;i++) {
    for(j=0;j<4;j++) {
      a[i][j]=0;
    }
  }
  for(i=0;i<2;i++)
    for(j=0;j<2;j++)
      printf("%d",a[i][j]);
  return 0;
}

when I do a[i][j]=0; or a[i][j]=1; it goes to infinite loop but when I enter other than 0 or 1 it executes correctly.
Can anybody tell me why this happens?


text:
Q: After setting EntityState.Unchanged the entity properties are lost I have an ASP.Net MVC project where I add in a View a student entity
to my Entity Framework 6 repository.
class Student
  public long Id { get; set; }
  public virtual Book Favorite { get; set; }

class Book
  public long Id { get; set; }
  public string Title { get; set; }

The Favorite property is set from a drop down in the view.
In the controller on post, only the Id for the book is set.
To tell Entity Framework, to only add the student, but not to add
the referenced book, I set the EntityState for the Book to Unchanged as
described here
After saving my changes, I have the correct student record in the database and also the book record remains unchanged, but
whenever I query now the book from my repository (not via the student), I get a book entity
back where only the Id is set and Title and all other properties are null.
My Controller (simplified):
public ActionResult Create()
{
    StudentViewModel result = new StudentViewModel();
    result.BookList = new SelectList(DbContext.Books, "Id", "Name");
    return View(result);
}

[HttpPost]
public ActionResult Create(StudentViewModel viewModel)
{
    DbContext.Entry(viewModel.NewStudent.Favorite).State = EntityState.UnChanged);
    DbContext.Add(viewModel.NewStudent);
    DbContext.SaveChanges();

    Book missingProperties =
        DbContext.Books.Single(book => book.Id == viewModel.NewStudent.Favorite.Id);
}

My View (simplified):
@using System.Linq
@model StudentViewModel
@using (Html.BeginForm())
{
    ...
    @Html.TextBoxFor(model => model.NewStudent.Name)
    @Html.DropDownListFor(model => model.NewStudent.Favorite.Id, Model.BookList)
    ...
}

A: The problem is, that the Entity Framwork DbContext caches entities.

With lazy loading, you simply need to make some reference to the related data and the Entity Framework will check to see whether it's been loaded into memory. If not, the Entity Framework will create and execute a query behind the scenes, populating the related data.
By default, Visual Studio will define newly created models to set LazyLoadingEnabled to true.

(from MSDN)
Once loaded from db, it will not be loaded again for the DbContext lifetime.
EntityState.UnChanged prevents Entity Framework only from storing the entity back to the database. But whenever the entity is retrieved from context a second time, not the correct value from database is taken, but the modified, that is now also in cache.
It is additionally necessary to refresh the modified entity. Attach it in the DbContext and then reload it.
Book result = Attach(book);
Entry(book).Reload();

I think, this answers the issue, but I am not sure if GuruStron answer uses the better pattern.

A: You should query for Favorite the db, before saving new student(and check if there is one there, cause you should not anything what comes from client=), that would get the book to the context, so you just set it to the student:
Book book = DbContext.Books.Single(book => book.Id == viewModel.NewStudent.Favorite.Id);
if(book!=null)
{
    viewModel.NewStudent.Favorite = book;
}
else
{
    throw new Exception();
}
DbContext.Add(viewModel.NewStudent);
DbContext.SaveChanges();


text:
Q: Optional exception catching Is it possible to make an exception that is optional to be caught?
In other words, an exception that can either:

*

*be caught in a try-catch block

*or skipped if no try-catch block exists for it

To visualize, I have a ReportedException, which is just a plain subclass of RuntimeException, and want to be able to catch it when it's needed:
try
{
    hideWindow();
}
catch (ReportedException ex)
{
    // Window could not be hidden.
    // Exception has already been caught and logged by parseInput(),
    // and now we're going to do something more.

    printAdditionalErrorMessage();
}

Note: I edited the above example to better fit my question.
or skip catching if the result is irrelevant:
hideWindow(); // We don't care if there was an error or not.
openAnotherWindow();

I know I can leave the catch block empty and have the same thing as above, but I use ReportedException very often and it would make my code highly unreadable.
If it's impossible (I suspect it is), what alternative/walkaround would you recommend?
P.S. The method names used in the examples are just foo's and bar's.
EDIT: I know I don't need to catch RuntimeExceptions. What I want is to ignore them if they occur.

A: Exceptions should be used for exceptional situations.
From your example, if the window not being hidden is a typical event, it shouldn't throw an exception. If that is your function, then use a return value to indicate whether it was successful instead of throwing an exception. Then you can safely ignore the return value when you don't care if it succeeded or not.
If you do not have control over that method, then you can wrap it in another method that catches the exception and turns it into a return value. E.g.
private boolean tryHideWindow() {
    try {
        hideWindow();
    }
    catch (ReportedException ex) {
        return false;
    }
    return true;
}

If you need some parameters of the exception to determine what to do, then you could return the exception instead.
private static class MyReturnType {
    private final Throwable thrown;
    private final OrigRtnType returnVal;
    public MyReturnType(Throwable thrown) {
        this.thrown = thrown;
        this.returnVal = null;
    }
    public MyReturnType(OrigRtnType returnVal) {
        this.thrown = null;
        this.returnVal = returnVal
    }
    public boolean wasExceptionThrown() {
        return thrown != null;
    }
}

private MyReturnType tryHideWindow() {
    try {
        OrigRtnType returnVal = hideWindow();
    }
    catch (ReportedException ex) {
        return new MyReturnType(ex);
    }
    return new MyReturnType(returnVal);
}

This is an answer to your question, but it is not necessarily a good idea. As others will doubless comment, using exceptions for program flow is less than ideal.

A: I'm a little fuzzy on how to use ThreadLocal (and there are apt to be some other tupos), but something like this:
public class IgnorableException {

     static class DontIgnoreCount  {
         int count;
     }

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<DontIgnoreCount> dontIgnoreCount =
         new ThreadLocal<DontIgnoreCount>();

     static void incrementDontIgnore() {
         DontIgnoreCount counter = dontIgnoreCount.get();
         if (counter == null) {
             counter = new DontIgnoreCount();
             dontIgnoreCount.set(counter);
         }
         counter.count++;
     }

     static void decrementDontIgnore() {
         DontIgnoreCount counter = dontIgnoreCount.get();
         // Must not be null here
         counter.count--;

     static bool shouldSignal() {
         DontIgnoreCount counter = dontIgnoreCount.get();
         return counter.count > 0;
     }
}

To use, invoke DontIgnoreCount.incrementIgnoreCount() early in try range, and DontIgnoreCount.decrementIgnoreCount() late in finally range.
When signalling an exception that follows this protocol, only signal it if shouldSignal returns true.
void iWannaCatchException() {
    try {
        IgnornableException.incrementDontIgnore();
        int x = someOptionallySignallingMethod();
    }
    catch (...) {
        ...
    }
    finally {
        IgnorableException.decrementDontIgnore();
    }
}

void iDontWannaCatchException() {
    int x = someOptionallySignallingMethod();
}

int someOptionallySignallingMethod() {
    if (somethingBad) {
        if (IgnorableException.shouldSignal()) {
            throw new BadException();
        }
    }
    return 42;
}

Note that not shown above are any throws clauses you'd have to add to keep the compiler happy.  This mechanism would not remove the need for those.
You could also inplement a delegate/observer scheme, replacing the simple counter with a stack of observer objects, and pass a message to the observer vs throwing the exception.  But this, by itself (without coupled exceptions/try ranges) would not allow blowing away the stack to the appropriate recovery point.

A: It sounds like you want to use exceptions for flow control, rather than for reporting truly exceptional cases.
Using exceptions for flow control is typically frowned upon. The common approach is to return a success/failure indication as the return value of the function.

A: You can use something like this:
try{
    hideWindow();
}catch (ReportedException ex){
    // ingore

}catch (NullPointerException ex){
       killWindow();
}finally  {
    //to do something more.
}


text:
Q: How to correctly get command output while using Command Applet in MATE? I have added Command Applet to the MATE Panel.
I planed to use a command with some scripting inside to check server availability - something like
wget --quiet https://someserver -O - | grep -s somedata > /dev/null && echo "S OK" || echo "S FAIL!"

or
curl -s https://someserver | grep -s somedata > /dev/null && echo "S OK" || echo "S FAIL!"

I have added this command to Preferences.
In terminal it works as expected, but Command Applet shows only # inside:

I tried to move the long command to script file, but got the same result.

A: It is really simple, one have to save the command into script file like /home/user/bin/script.sh, make it executable by chmod +x /home/user/bin/script.sh and then enter this path /home/user/bin/script.sh in Command field of Command Applet.


text:
Q: What does the single period / dot "." in YAML means? Can any one explain what a single dot (.) means in YAML. Following is the configuration file in YAML:
api_platform:
  resource: .
  type: api_platform
  prefix: /api

The above resource key has a . value.

A: A period (.) has no intrinsic meaning on YAML, because nothing has any intrinsic meaning on YAML.
A single period simple means "a string containing .".
Only the application doing the processing can give the YAML contents any meaning. As far as the YAML parser goes, the YAML document is valid or invalid, represents certain structure or not; but that does not imply meaning.
In the context of the Symfony Routing component (the configuration you shows belongs to that component), how that specific period is interpreted it depends on the route loader being used, in this case the api_platform loader.
This route loader, which you can find on api-platform/core/src/Bridge/Symfony/Routing/ApiLoader.php has no use for the resource key. It's not used on the class at all.
So effectively, the period means nothing at all. It is there simply because it's a required configuration key for the Routing component.


text:
Q: Configuration.GetConnectionString returns null when running asp.net core on VS Code but fine on Visual Studio Here is my appsettings.json file
{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Port=5432;Database=db;User ID=postgres;Password=root"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

This is how I retrieve the connection string:
// Only works when run through visual studio not on vs code
Configuration.GetConnectionString("DefaultConnection")

My launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceRoot}\\src\\Chlx\\bin\\Debug\\netcoreapp1.0\\Chlx.dll",
            "args": [],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": false,
            "internalConsoleOptions": "openOnSessionStart",
            "launchBrowser": {
                "enabled": true,
                "args": "${auto-detect-url}",
                "windows": {
                    "command": "cmd.exe",
                    "args": "/C start ${auto-detect-url}"
                },
                "osx": {
                    "command": "open"
                },
                "linux": {
                    "command": "xdg-open"
                }
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceRoot}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command.pickProcess}"
        }
    ]
}

My tasks.json
{
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [
                "${workspaceRoot}\\src\\Chlx\\project.json"
            ],
            "isBuildCommand": true,
            "problemMatcher": "$msCompile"
        }
    ]
}

Do you know how to fix this?

A: You run the program from the root (solution level) and not from the project. Change your "cwd" in the launchsettings.json to ${workspaceRoot}\src\Chlx\

A: The Configuration property is defined in the Startup class and it is initialized thru dependency injection. Here is the sample for a project created with dotnet new mvc -au Individual
  public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }


text:
Q: how to compare i-node numbers of files in C how would you be able to check if the files have the same/different i-node numbers in C?
Because I want the rightly get the source and destination file information, where the files need to be rightly tested if they are the same.
Code:
#define BUFFER 100 // ** increased - file path can get pretty long
#define buffersize     4096
#define copymode      0644

void error(char *, char *);
int file_exist(char *filename)
{
    struct stat buffer;
    return (stat (filename, &buffer) == 0);
}

int main()
{
    int ac;
    char *avc[4096];
    int     in_fd, out_fd, chars_n;
    char    buf[BUFFERSIZE];

    char ch, sourceFile[20], targetFile[20];
    FILE *source, *target;
    printf("Enter name of file to copy\n");
    fgets(source_file, 20, stdin);

    source = fopen(sourceFile, "r");
    *avc = sourceFile;
    if( source == NULL )
    {
        printf("Press any key to exit...\n");
        exit(1);
    }

    printf("Enter name of target file\n");
    fgets(targetFile, 20, stdin);

    // open(path, O_WRONLY | O_CREAT | O_TRUNC, mod);
    if (file_exist (targetFile))
    {
        printf("File exists. \n");
    }
    else
        target = fopen(targetFile, "w");

    int dFN;
    dFN = malloc(strlen(targetFile) + strlen(av[2] + 1));

    if( target == NULL )
    {
        fclose(source);
        printf("Press any key to exit...\n");
        exit(1);
    }

    while( ( ch = fgetc(source) ) != EOF )
        fputc(ch, target);

    printf("File copied successfully.\n");

    fclose(source);
    fclose(target);

    if ( ac != 3 ){
        fprintf( stderr, "usage: %s source destination\n", *avc);
        exit(1);
    }
    if ( (in_fd=open(avc[1], O_RDONLY)) == -1 )
        error("Cannot open ", avc[1]);

    if ( (out_fd=creat( avc[2], copymode)) == -1 )
        error( "Cannot creat", avc[2]);

    while ( (chars_n = read(in_fd , buf, buffersize)) > 0 )
        if ( write( out_fd, buf, chars_n ) != chars_n )
            error("Write error to ", av[2]);
    if ( chars_n == -1 )
        error("Read error from ", avc[1]);

    if ( close(in_fd) == -1 || close(out_fd) == -1 )
        error("Error closing files","");

    return 0;
}

void error(char *s1, char *s2)
{
    fprintf(stderr,"Error: %s ", s1);
    perror(s2);
    exit(1);
}

A: Use the stat(2) or fstat function call, which returns various informations about a file, including its inode number.
See for example http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html


text:
Q: I'm having an issue with my Purge command (Discord.js) When I use the command, if there are messages older than 14 days and there are a few messages not older than 14 days, I'm able to delete those messages not older than 14 days, but still get the 14 days error. I want it to return the error only if there are 0 messages not older than 14 days.
Please help.
My code:
File name: purge.js
module.exports = {

        name: "purge",
        aliases: ['clear'],
        category: "moderation",
        permissions: "MANAGE_MESSAGES",
        description: "Deletes messages from a channel.",
        usage: "purge [amount of messages] [ignore pinned messages]",

    execute: async (message, args) => {
        if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You don't have enough perms! You require: [MANAGE_MESSAGES]")

        message.delete()
        if (!args[0]) {
            message.channel.bulkDelete(100)
          .then().catch(e => {
            message.channel.send(e.message)
              })
            .then(messages => message.channel.send(`**Succesfully deleted ${messages.size - 1} messages**`).then(msg => msg.delete({ timeout: 5000 }))).catch(() => null)
            return

        }
        else if (args[0] === "true") {

        const fetched = await message.channel.messages.fetch({ limit: 100 });
        const notPinned = fetched.filter(fetchedMsg => !fetchedMsg.pinned);

        await message.channel.bulkDelete(notPinned)
            .then().catch(e => {
            message.channel.send(e.message)
              })
            .then(messages => message.channel.send(`**Succesfully deleted ${messages.size - 1} messages.**`).then(msg => msg.delete({ timeout: 5000 }))).catch(() => null)
            return

      }

        else if (parseInt(args[0]) > 100) {
            return message.channel.send("**Please Supply A Number Less Than 100!**");
        }

        else if (parseInt(args[0]) < 1) {
            return message.channel.send("**Please Supply A Number More Than 1!**");
        }
        if (args[1] === "true") {

          const fetched = await message.channel.messages.fetch({ limit: args[0] });
          const notPinned = fetched.filter(fetchedMsg => !fetchedMsg.pinned);

          await message.channel.bulkDelete(notPinned)
            .then().catch(e => {
            message.channel.send(e.message)
              })
            .then(messages => message.channel.send(`**Succesfully deleted ${messages.size - 1} messages**`).then(msg => msg.delete({ timeout: 5000 }))).catch(() => null)
            return

        }
        else {
            message.channel.bulkDelete(args[0])
            .then().catch(e => {
            message.channel.send(e.message)
            })
            .then(messages => message.channel.send(`**Succesfully deleted ${messages.size - 1} messages**`).then(msg => msg.delete({ timeout: 5000 }))).catch(() => null)
            return
        }

    },
};

A: bulkDelete can take a 2nd argument called filterOld.
As the name suggests, that makes discord.js ignore all messages older than 14 days.
Example:
message.channel.bulkDelete(notPinned, true)
message.channel.bulkDelete(args[0], true)

A: Use message.channel.bulkDelete(<amount>, true)


text:
Q: Dynamic Excel Formulas For Ranges
*

*How can I make a formula that:

*

*I can vertically drag down on Sheet2...

*That TEXTJOINS two arrays (total of 28 vertical cells) of data on Sheet1...

*Which after it TEXTJOINS those 28 cells, goes to the next row in Sheet2...

*Looks at the same column but different row numbers then after it does this 8 times in total...

*Changes to the next column while looking at the same rows from iteration 1.

*In short, I want a formula that keeps the column letter static for 8 rows then changes to the next column after those 8 rows.

*The referenced image below should make it clearer of the objective I'm going for.
Referenced Image
An alternative if this is impossible/hard is to code a python script that types the formulas with using loops then I'll just copying those to excel.
Much appreciated!

A: You can use the INDEX function, with mathematical arguments for the row and column, to return the desired ranges.
For example:
MOD(ROWS($1:1)-1,8)*13+122

will generate the repeating series: 122,135,148,161...213
and
=INT((ROWS($1:1)-1)/8)+1

will generate the repeating series 1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2, …
So to put that in a formula, which will change the ranges as you state, for, let us say, columns B:D, you could use:
=TEXTJOIN(,TRUE,INDEX(prepVertical!$B:$D,MOD(ROWS($1:1)-1,8)*13+122,INT((ROWS($1:1)-1)/8)+1):INDEX(prepVertical!$B:$D,MOD(ROWS($1:1)-1,8)*13+134,INT((ROWS($1:1)-1)/8)+1))

If you need to reference more columns, just change B:D to refer to the desired column range.


text:
Q: How to access wireless network properties to configure a new connection in Windows 10 At my University, I need to connect to a secure network that requires pre-configuring authentication settings in my computer's network properties.
On Windows 7, you could access these settings via right-click on an available wireless network and choosing "Properties".  This doesn't work for me in Windows 10; double-clicking or right-clicking on a network does nothing.
As someone explained here, you can go to the Network & Sharing Center and click a network you're already connected to, then get to the properties.  However, I need to access the properties for a network to which I'm not yet connected in order to initially set up the configuration.
In Windows 10, what is the route to access the connection properties dialog for a wireless network that can be seen as available but for which the connection has not yet been configured?

A: The OP's request has not been addressed, but ignored.
In Windows 10 you can NOT edit an already configured wireless networks settings without being connected to it first. In Windows 7 you can.
In Windows 10 you can create networks manually, which exposes the GUI they want, and you can delete them as well.
But to edit them afterwards you have to at least attempt to connect to them. However if you mess up those settings and put it in a state where it would never connect it cannot be edited and must be deleted.
This is as step backwards from Windows 7.

A: I'm thankful I got this to work but I'm also embarassed how it was hidden in plain sight.

*

*Right Click on your network icon in the taskbar and click "Open Network and Sharing Center"

*

*Find setup a new connection

*

*Select Manually Connect to a wireless network

*

*Now, is where you will enter the SSID and applicable security info for your network. Even if you aren't connected, you can create a profile and access advanced properties

A: It would seem like a recent Win 10 update changed the way to access the wireless "advance" properties.
In my case the way to access this is via "Control Panel".
Then click "Network and Internet", then on the right side, click "Network and Sharing Center". Then you'll see the "Setup a new connection or network". Afterwards follow procedures from Insane's post above.