text:
Q: map of boost pools? Basically im giving a very weak shot at trying to centralize memory management. Anyways, boost::pool uses chunks of certain sizes.
My orignal idea, was to overload new and delete, pass the size into a singleton which would go to the corresponding boost pool and alloc from there.
std::map<size_t, boost::pool<> > m_MemPools;

Anyways it seems like i cannot have a map of boost pools, since it MSVC9 gives me the following error,
:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\map(173) : error C2512: 'boost::pool<>::pool' : no appropriate default constructor available

Why would this be happening?
EDIT
I solved it, i ended up just wrapping it in a shared_ptr, which resolves the issue.
Just to show something, i do not use [] anymore, and it still gives this error,
class Pooly
{
public:

    Foo()
    {
    }

    void RegisterPool(__in const size_t poolSize)
    {
        if(pools.find(poolSize) == pools.end())
            pools.insert(std::make_pair(poolSize, boost::pool<>(poolSize)));
    }
private:
    std::map<size_t, boost::pool<> > pools;
};

Im guessing it has to do with std::make_pair?
Etherway wrapping it a smart pointer works fine, shouldnt this be something that should be included in boost pool though?

A: Are you using the [] operator to insert into the map?  This requires the data_type, in this case boost::pool, to be default constructible, i.e. it must have a default constructor that takes no arguments.  But boost::pool does not have a default constructor.


text:
Q: Charging 18650 Lipos with PCB and micro USB breakout board I have a circuit with 2 18650 Lipos, which are connected to a 2s PCB Protection Board which has a p+ and p- connector for out- and input. My question is whether I can charge the two batteries by connecting the v+ and grnd pins of a simple micro USB breakout board to the p+ and p- pins? Are the 5V of the USB board enough to charge the two 7.4 V batteries?
Here's the PCB board on eBay:
https://rover.ebay.com/rover/0/0/0?mpre=https%3A%2F%2Fwww.ebay.de%2Fulk%2Fitm%2F253581817900

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to find a sequence to make all values 1 for a graph where nodes with binary values have exactly 2 directed incoming and outgoing edges Hello everyone I asked this question here before, but I would like to share it again.
Imagine a graph with N nodes and each node has exactly 2 leaving directed edges and 2 incoming directed edges. Each node can take values {0,1}.
Now here is the catch, at the start all nodes have value 0 . You can visit a node however you like but when you visit a node it's value and it's connected nodes with 1 edge changes their values. Is it possible to follow a sequence where one makes all nodes values 1.
For example:
There is a graph like:
Nodes = {A,B,C,D,E}
Edges = {A -> B, A -> C,
         B -> C, B -> D,
         C -> D, C -> E,
         D -> E, D -> A,
         E -> A, E -> B }

Now when we follow sequence {A,B,C,D,E} values of each node will be as follows:

A
B
C
D
E

1
1
1
0
0

1
0
0
1
0

1
0
1
0
1

0
0
1
1
0

1
1
1
1
1

As you can see at last visit all nodes became 1.
So what I want to figure out is, is it possible to find a sequence for all possible graphs generated by the rules mentioned above?
How can I prove or disprove this? Any help would be appreciated. Thank you!

A: Some graphs may have shorter solutions, but visiting every node once will always work (with the conditions you've specified). Each node will change its value three times: once when you visit that node, and once when you visit the source of each of its incoming edges. So the value of that node will go from $0$ to $1$ to $0$ to $1$.
For an example of a graph where a shorter solution exists, consider the graph with nodes $A$, $B$, $C$, $D$, $E$, $F$ and twelve edges:

*

*The six edges $A \to B$, $B \to C$, $C \to D$, $D \to E$, $E \to F$, $F \to A$;

*The six edges $A \to C$, $B \to D$, $C \to E$, $D \to F$, $E \to A$, $F \to B$.

Then visiting nodes $A$ and $D$ is enough to toggle all six nodes, due to the edges $A \to B, A \to C, D \to E, D \to F$.


text:
Q: while and for loops no. of iterations known I read that while loop is used when number of iterations are unknown and for loop is used when number of iterations are known ... such as when I have to print a statement 5 times I have to initialize the variable in both while and for loop and also I need to give iteration condition in both (i++) and i also have to mention condition of iteration so that it loops only 5 times ... then whats the difference  ? can someone pls tell with an example
for(int i=0;i<5;i++){
    cout<<"Hello";
    }
int i=0;
while(i<5){
    cout<<"hello";
    i++;
    }

A: There is no real difference between while and for.
{
  int i = 0;
  while(i < 5){
    //stuff
    i++;
  }
}

is the same as
for(int i = 0; i < 5; i++){
   //stuff
}

But as you can see, the for is easier to use when you have a known condition.
For example, suppose you are running an algorithm that finishes when a list is empty and there is no counter variable, such as i. It's easier to understand it using a while:
while(!list.empty()){ /* stuff */ }

But you can use it the same way with a for:
for( ; !list.empty(); ){ /* stuff */ }

You choose one of them by simplicity and readability, according to each situation or to your personal preference.

A: Both a  while loop and for loop is a pretested loop, meaning it tests its expression before each iteration. An important characteristic of a  for loop and a  while loop is that it will never iterate if the test expression is false to begin with.
Now you should use the for loop instead of the while loop in any situation that  needs an initialization, except when initializations of different types are needed.
#include <iostream>

int main()
{
    for (int i = 0; i < 5; i++) {
        std::cout << "I am a for loop." << std::endl;;
    }
    int i = 0;
    while (i < 5) {
        std::cout << "I am a while loop" << std::endl;
        i++;
    }
}

I also suggest you to not use using namespace std;. You can read more about it Here.

A: While coding for a 'for' loop one should know the iterations first because it is being put before starting the loop and after putting the iterations the statements are being put;
at the same time if we are coding for a 'while' loop we can put n number of iteration anywhere inside the loop (whenever required) .
That's why it is said that 'for' loop is used when number of iterations known and 'while' loop is used when number of iterations are unknown.
Although after coding if anyone looks the code it seems like in both cases number of iterations are known ; But that statement is given for a coder while performing a code.


text:
Q: How to add a new line to a stargazer() title? I am printing descriptive statistics using stargazer().
stargazer(datdbb,out = "Summary.html",title = "Summary Statistics \\\\ 1970-1998")

I tried to add a new line to the title between Summary Statistics and 1970-1998 but unfortunately, it does not work. Does anyone know how to add a new line to the title?

A: stargazer(datdbb,out = "Summary.html",title = "Summary Statistics \\n\ 1970-1998")


text:
Q: Android, Material Design, RecyclerView doesn't show elements I have a question related to Material Design introduced in Android 5. I'm very new with UX interfaces. Now I'm trying to implement simple music player with fragment for choosing songs from storage.  Actually, that fragment contains RecyclerView. But RecyclerView doesn't show any element (it contains views with one TextView), even simple "..". I checked it with log-tracking and found that function "onBindViewHolder" was called correctly. To be honest, I have no idea what is wrong with my code. Obviously, I provide link to my project: UX
I will be gratefull for any suggestion, advice or may be pointer to the mistake.


text:
Q: javascript plugin only working when mouse enters the viewport I'm using a javascript plugin called jGravity.js and have managed to make the gravity effect work on the relevant div elements. However the script only starts when the mouse enters the viewport, rather than as soon as the page has loaded.
I've tried the following...
$(document).ready(function() {
        $('body').jGravity({
            target: 'div.text',
            ignoreClass: 'name',
            weight: '10',
            depth: 5,
            drag: true
        });
});

I thought this would enable the script to run without prompt.
Any ideas?

A: You could always add to your script the function that makes the mouse enter the viewpoint,
other than that I don't know.


text:
Q: ResourceBundle - How to point getBundle to android's resources I am trying to make use of the ResourceBundle class in my application. I am still confused/stuck in instantiating the whole thing. Especially pointing the ResourceBundle to my res folder where I have values-en, values-fr, values-sw and so on.
I have tried the following:
resourceBundle = ResourceBundle.getBundle(basename, locale);

where basename:
"myclasspackage"
"res"
"/data/data/myclasspackage/project.properties"

All of the initializations give me the same, NullPointerExpection. Please please help me.

A: ResourceBundle is for old-style Java resources in JAR files and have nothing to do with Android's resource system.

A: To access resources from a different configuration:
Resources res_curr_conf = getResources();
Configuration c = new Configuration(res_curr_conf.getConfiguration());
c.locale = whateverLocaleIWant();
Resources res_alt_conf = new Resources(res_curr_conf.getAssets(), res_curr_conf.getDisplayMetrics(), c);
// TODO - use res_alt_conf


text:
Q: Improving batch insert/update/delete in Spring Boot I am working with a Spring boot project and Oracle Database. My task is importing data from a csv file. The file includes 10000 rows; each row is equal to a row in a table and includes three attributes which are sCode, isDeleted (isDeleted=1 -> delete, isDeleted=0 -> update or insert). I am using batch size of 1000 to insert, update or delete. Each batch, I do the following steps:

*

*Use JPA findAllBySCodeInAndDepartmentId to file all rows that exist in the table (departmentId is the department of current user, (sCode, departmentId) is unique)

*Use Map to store data from the first step's result (key is sCode)

*Filter out rows in batch that have isDeleted = 1 and exist in the Map to delete (I use JPA deleteAll)

*Filter out rows that isDeleted = 0 and exist in the Map to update (I use JPA saveAll)

*Left rows in batch which were not updated or deleted (not in the Map) will be inserted into the table (I use JPA saveAll)

It takes around 5 minutes to finish importing 10000 rows
How can I shrink the amount of time to around 1 minute?


text:
Q: Get next birthdays using Doctrine Is there any way to get the next birthdays using only DQL (Doctrine Query Language)?
I have solved the problem using the SQL function DAYOFYEAR, but I would like to have a DQL solution, in case I need to migrate to MSSQL (for example) where this doesn't work.

A: You don't really need the function from MySQL. Simply use PHP's date function and use format "z". Quoting the PHP docs:

z -> The day of the year (starting from 0) -> 0 through 365

Alternatively, you can also use strftime with "%j" (or anything else that suits you)

A: I found a way to get upcoming birthdays by using native query in doctrine.
This is a quick query and according to http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html Doctrine uses ResultSetMapping the same way internally when you create DQL queries.
This finds all the birthdays the next 30 days.
Use this method with care since it will affect how the entity is loaded later. Later in the script, only those fields added to the mapping will be loaded for this entity. I loaded the list by ajax ( and addded it to session )
use Doctrine\ORM\Query\ResultSetMapping;

$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'firstname', 'firstname');
$rsm->addFieldResult('u', 'lastname', 'lastname');
$rsm->addFieldResult('u', 'birthday', 'birthday');
$rsm->addFieldResult('u', 'image', 'image');

$query = $this->entityManager->createNativeQuery("
        SELECT *
        FROM user u
        WHERE DAYOFYEAR(u.birthday)
        BETWEEN DAYOFYEAR(CURDATE()) AND DAYOFYEAR(DATE_ADD(CURDATE(), INTERVAL ? DAY))
        ORDER BY DAYOFYEAR(u.birthday) ASC
        ", $rsm);

$query->setParameter(1, '30');

$birthdays = $query->getResult();


text:
Q: is it possible to filter on a vector in-place? I'd like to remove some elements from a Vec, but vec.iter().filter().collect() creates a new vector with borrowed items.
I'd like to mutate the original Vec without extra memory allocation (and keep memory of removed elements as an extra capacity of the vector).

A: If you want to remove elements, you can use retain(), which removes elements from the vector if the closure returns false:
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);

If you want to modify the elements in place, you have to do that in a for x in vec.iter_mut().

A: If you truly want to mutate the vector's elements while filtering it, you can use the nightly-only method Vec::drain_filter, an extremely flexible tool:
#![feature(drain_filter)]

fn main() {
    let mut vec = vec![1, 2, 3, 4];
    vec.drain_filter(|x| {
        if *x % 2 == 0 {
            true
        } else {
            *x += 100;
            false
        }
    });
    assert_eq!(vec, [101, 103]);
}

It also allows you to get the removed elements as the return value of the entire method is an iterator!

A: Till Vec::drain_filter gets stable, we can solve the problem with homebrewed rust:
fn main() {
    let mut v = vec![1, 2, 3, 4];
    let mut i = 0;
    while i < v.len() {
        if v[i] % 2 == 0 {
            v.remove(i);
        } else {
            v[i] += 100;
            i += 1;
        }
    }
    println!("{:?}", v);  // [101, 103]
}

BTW remove() is an O(n) operation but doesn't allocate memory.
Playground

A: I am providing my take for this problem as I was unaware of the retain method:
impl<T> RemoveFilter<T> for Vec<T> {}
pub trait RemoveFilter<T>: BorrowMut<Vec<T>> {
    fn remove_filter<F: for<'b> FnMut(&'b T) -> bool>(&mut self, mut cb: F) {
        let vec: &mut Vec<T> = self.borrow_mut();
        let mut write_to = 0;
        let mut read_from = 0;
        while read_from < vec.len() {
            let maintain = cb(&mut vec[read_from]);
            if maintain {
                vec.as_mut_slice().swap(read_from, write_to);
                write_to += 1;
            }
            read_from += 1;
        }
        vec.resize_with(write_to, || panic!("We are shrinking the vector"));
    }
}

It will shift the elements as it iterates and then remove anything that is left behind. I think this is code may easily modified to solve other problems.


text:
Q: My jQuery doesn't seem to be working with Wijmo Grid I built a smart data grid full of cells that will identify (on blur) whether or not they were changed, and if the value went up or down.
Here's what it looks like. The grey tooltip appears when the user hovers a box that has been changed and tells them what the value was when the page first loaded.

I'd like to convert this to a Wijmo Grid, but keep the same up/down scripts to show when and how values are changed. However, when I initialize the table as a Wijmo grid, suddenly my scripts stop working in all browsers.
Question: Why does this happen and is there an easy fix? Can you not access Wijmo cells with traditional jQuery and Javascript?
Partial HTML Code (Full code and working example without Widjmo here):

            March
            April
            May

            <input type="text" value="12000" />
            <input type="text" value="1000" />
            <input type="text" value="100000" />

Here is my current jQuery code (Full code and working example without Widjmo here):
$(function() {
    // Initializes data grid as a Widjmo Grid (currently commented out)
    //$("#data-grid").wijgrid();

    // Array to store the initial values in grid
    var initialValues = [];

    // Assigns an index ID to each cell in the grid
    $('input').each(function(index) {
        initialValues[index] = $(this).val();
        $(this).data('id', index);
    });

    // Checks cell(s) for changes on blur (lose focus)
    $("input").blur(function() {
        var $t = parseInt($(this).val(), 10);
        var $s = parseInt(initialValues[$(this).data('id')], 10);

        // Value has changed
        if($t != $s) {
            var sign = "";
            if($t-$s > 0) {
                sign="+";
            }
            $(this).parent().children(".tooltip").remove();
            $(this).parent().append("
Initial " + $s + "
Change " + sign + ($t-$s) + "
");
        }

        // Value is no different from intial value
        if($t == $s) {
            $(this).removeClass("up down");
            $(this).parent().children(".tooltip").remove();
            $(this).parent().children(".up-indicator, .down-indicator").remove();
        }

        // Value is greater than initial
        else if($t > $s) {
            $(this).removeClass("up down");
            $(this).parent().children(".up-indicator, .down-indicator").remove();
            $(this).addClass("up");
            $(this).parent().append("

");
        }

        // Value is less than initial
        else if($t < $s) {
            $(this).removeClass("up down");
            $(this).parent().children(".up-indicator, .down-indicator").remove();
            $(this).addClass("down");
            $(this).parent().append("

");
        }

        // Conpute the net change
        netChange(initialValues);
    });

    // Displays tooltip of changed items
    $("input").hover(function() {
        $(this).parent().children(".tooltip").toggle();
    });

    // Computes the net change in the data grid
    function netChange(initialValues) {
        var runningTotal = 0;
        $('input').each(function() {
           runningTotal += parseInt($(this).val(), 10);
        });

        var intialTotal = 0;
        for (var i = 0; i < initialValues.length; i++) {
            intialTotal += parseInt(initialValues[i], 10);
        }

        var changes = $(".up, .down").length;

        $("#items").text(changes + " Items");
        $("#net").text("Net: " + (runningTotal - intialTotal));
    }
});

A: The Wijmo plugin code uses $.browser.msie in their code which is deprecated in jQuery 1.3 and completely removed in jQuery 1.9. See jQuery documentation: http://api.jquery.com/jQuery.browser/ and below was the comment in bold on why it was removed.

We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.

Your tooltip code work once after I chose the earlier version of jQuery 1.8 in the fiddle.
Fixed fiddle: http://jsfiddle.net/Fgdec/13/

In your fiddle you had selected jQuery 1.9 which did not had the $.browser.msie, so It was throwing the below error in chrome console.
Uncaught TypeError: Cannot read property 'msie' of undefined jquery.wijmo-open.all.2.3.8.min.js:31
(anonymous function) jquery.wijmo-open.all.2.3.8.min.js:31
(anonymous function) jquery.wijmo-open.all.2.3.8.min.js:61
Uncaught TypeError: Cannot read property 'msie' of undefined jquery.wijmo-complete.all.2.3.8.min.js:34
(anonymous function) jquery.wijmo-complete.all.2.3.8.min.js:34
(anonymous function) jquery.wijmo-complete.all.2.3.8.min.js:34


text:
Q: Is a vector of symbols used as singular or plural? I am writing a technical report and having trouble with singular/plural. For example, A is a vector composed by a number of components:
A = [x, y, z]
Then should I used A as plural or singular? Which one of the followings is correct?

*

*A is the output signals from [...]

*A are the output signals from [...]

A: Your question is a little confusing because you ask about "a vector of signals," but you don't use those words in your example.
Vector is the key word. A vector of signals is singular, because there's only one vector. If you had two vectors of signals, it would be plural.
Since vector is the key word, you should use it to be clear:

A is the vector of output signals...

If you don't want to do that, use the word represents instead of "is":

A represents the output signals...

A: I realize this is probably too late to help you but I suggest that when defining A you use "A = [x,y,z] is the vector of outputs..." rather than "A = [x,y,z] is the outputs..."  That way both sides of the copula "is" will be singular, not one singular and one plural.


text:
Q: If I have an array of values, how do I join some together separated by a dash? Say I have an array that looks like this:
array1 = button.attr('id').split('-');
["slider", "step", "value", "speed", "rebecca", "nitzsche", "st", "george", "s", "college"]

What I want to do is to take every element after speed, so everything after array1[3] to the end, and mush it all into 1 string separated by a - so it looks like this: rebecca-nitzsche-st-george-s-college.
How do I do this?

A: You can simply use slice and then join, like so:
var array = ["slider", "step", "value", "speed", "rebecca", "nitzsche", "st", "george", "s", "college"];
array.slice(4).join('-')

// It will return => "rebecca-nitzsche-st-george-s-college"


text:
Q: Unable to read android spinner value I am new to Android Development and just trying out various examples to familiarize.
I am unable to read and display the values from the spinner tool.
Checked out various examples from Stackoverflow and other sites but still getting blank values.
Kindly let me know where I am missing out.
public void onClick(View view) {
    EditText weight = (EditText)findViewById(R.id.editText1);
    EditText height = (EditText)findViewById(R.id.editText2);

    TextView output = (TextView)findViewById(R.id.textView3);

    Spinner wtype = (Spinner)findViewById(R.id.spinner1);
    Spinner htype = (Spinner)findViewById(R.id.spinner2);

    String w = weight.getText().toString();
    String h = height.getText().toString();
    String s1 = wtype.getSelectedItem().toString();
    String s2 = htype.getSelectedItem().toString();

    output.setText(w+h+s1+s2);
}

In the above code, the values for w and h get displayed where as the values for s1 and s2 do  not for all criteria...
It is just a simple BMI calculator. The strings.xml contains the following text.
<string-array name="weight_type">
    <item>kgs</item>
    <item>pounds</item>
</string-array>
<string-array name="height_type">
    <item>metres</item>
    <item>feet</item>
    <item>inches</item>
</string-array>

By default, kgs and metres and shown. I click on the button to print the 2 default values but nothing happens..
I have tried changing the drop down values and click the button again.
Still no result !!!!
Tried with example from http://www.mkyong.com/android/android-spinner-drop-down-list-example/
Still I am unable to get the result. The only difference was that I didnt use TOAST but tried to write the output to a TextView....
Could anyone post a working code pls !!!

A: First of all findViewById has to be declared in onCreate() method.
Then like below get your Selected Item in a String:
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int pos, long arg3)
            {
            // TODO Auto-generated method stub
               String s1 = parent.getItemAtPosition(pos).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

Then in your onClik method you only have to do is to set text:
String w = weight.getText().toString();
String h = height.getText().toString();
String s1 = wtype.getSelectedItem().toString();
String s2 = htype.getSelectedItem().toString(); // Just like S1 as above make another Spinner S2 Listener.

output.setText(w+h+s1+s2);


text:
Q: Override fastfail in the dll to prevent whole app crash on STACK_BUFFER_OVERRUN (0xc0000409) I use the C++ dll in the Delphi Application.
The dll is compiled with /GS-.
There is a bug in the dll causing crash of the whole appication with windows error 0xc0000409
This error occurs in the dll, so I can't debug it.
Is there any way to catch such exception so that I could just reload the dll or at least get a chance to properly shutdown the application?

A: No, there's no way to catch the 0xc0000409 exception. This is by design.
The rationale is that this is a security risk. The application is not in a state where it can safely proceed.


text:
Q: Attaching a file to a page without adding to media library? We are using WP for our new intranet, which will primarily be used for documentation and archiving. We have some pages where we want to attach PDFs, documents, images, etc. However, we do not want these media items to be added to the media library when we attach them to a page; i.e., if the page is deleted, the media items are also deleted. Is there a way to do this?
Thanks!

A: There is no such a solution out of the box, and any files uploaded to WP are publically available to anyone who can access the domain, so you might want to keep that in mind.
You'll need to code a solution, possibly as follows:

*

*on post creation, use wp_insert_post to create the require folder.

*Use something like glob($root_folder.$post_slug . "/*.{jpg,jpeg,png,pdf}",GLOB_BRACE) to list all files in the post-specific folder . (Note, if the slug is ever changed, you'll need to manually rename the folder or automate it somehow.

*Use before_delete_post to delete the folder & all files.


text:
Q: Reversing an array by recursively splitting the array in C++ string recursion(int arr[], int arrSize) {

if(arrSize == 1){
    return to_string(arr[0]);
}
string letterLeft, letterRight, letterFull;

//logic1: Normal Recursion
//letterFull = to_string(a[n-1]) + " " + recursion(a, n-1);

//logic2: D&C ------------------------------------------------------ <
letterLeft += recursion(arr, arrSize/2);
letterRight += recursion(arr + arrSize/2, arrSize-arrSize/2) + " ";
letterFull += letterRight + letterLeft;

return letterFull;
}

I recently used the 'logic2: D&C' for splitting an array recursively to reverse them (more like Divide and Conquer).
(i.e. if 2,5,4,1 is given as input, output should be 1,4,5,2).
It passed all test case like the example I just gave. Yet, I felt like I don't really understand the flow of recursion. I am here to get help from someone in explaining what happens in the 'logic2: D&C' step-by-step with an example flowchart & values if possible?
PS:

I took help from https://stackoverflow.com/a/40853237/18762063 to implement this 'logic2: D&C'.
Edits - Made little changes to argument list.

A: It is unclear why there are used objects of the type std::string. To reverse an array of objects of the type char there is no need to use the class sdt::string. This is just inefficient. The function can look the following way
void recursion( char arr[], size_t arrSize )
{
    if ( not ( arrSize < 2 ) )
    {
        std::swap( arr[0], arr[arrSize-1] );
        recursion( arr + 1, arrSize - 2 );
    }
}

A: The point of divide and conquer algorithms is breaking your data down to smaller and smaller pieces while processing it.
If you want to reverse an array for example, than the following should happen:

*

*The data is split into 2 equal parts and the order of these parts gets switched (so the back half becomes the front half, and the front half becomes the back half)

*The 2 split parts are then also broken down to 2-2 equal parts, and get reversed.

*And so on, until the splits are 1 length, so they can't be split any further, resulting in a fully reversed array.

Reading material on D and C algorithms


text:
Q: How to assign array of record to other variable? In the below code I get strange (or not) results for OldRecord[0].Value after I assign NewRecord := OldRecord; it seems that both OldRecord[0].Value and NewRecord[0].Value are set to new.
type
  TMyRec = array of record
    Name: string;
    Value: Variant;
    // more fields
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  OldRecord, NewRecord: TMyRec;
begin
  SetLength(OldRecord, 1);
  OldRecord[0].Name := 'Test';
  OldRecord[0].Value := 'old';

  ShowMessage(OldRecord[0].Value); // old

  // SetLength(OldRecord, 1);
  NewRecord := OldRecord;
  NewRecord[0].Value := 'new';

  ShowMessage(OldRecord[0].Value); // new
  ShowMessage(NewRecord[0].Value); // new
end;

What am I missing here?


text:
Q: Dependency Injection of services into an Entity Framework Core database context I have been attempting to use DI to inject services into my DB Context. For example, a User Resolver service for audit logging purposes. I have some extensions to ChangeTracker that audit created, modified and deleted properties and also an audit logger that logs the changed properties of the entity. For these to work effectively and seamlessly I need to determine the logged in user. In EF Core 1.1, I got this working by simply adding my IUserResolverService to the constructor.
When I attempted to upgrade to 2.0, I started to run into all sorts of issues as the tooling did not handle the extended constructor. I eventually removed it and everything started working, but without a reliable way of determining the logged in user.
I have tried to find an answer to this on many occasions now, and searching only uncovers a mountain of articles about injecting the context itself into things like controllers.
Can this be achieved in EF Core without breaking tooling, etc.? Is there a way to inject a service through Startup ConfigureServices?

A: I ran into a very similar situation.  I ended up just injecting it manually in Startup but still resolving the dependencies.  I don't love this and wish the services would be injected into the DbContext constructor.  Here is my solution below:
public interface IUserContextProvider {
  User GetCurrentUser();
}

public class MvcUserContextProvider : IUserContextProvider {

  protected IHttpContextAccessor Accessor { get; set; }

  public MvcUserContextProvider(IHttpContextAccessor accessor) {
    Accessor = accessor;
  }
  public User GetCurrentUser() {
    //  Probably need some error handling and Special case pattern when
    // context is null.
    return (User) Accessor.HttpContext.User.Identity;
  }
}

public interface IEntityFrameworkOverrides {
  void EntityInitializing(ModelBuilder modelBuilder, IMutableEntityType entity);

  void EntityChanged(EntityEntry entity);
}

public abstract class UserAwareOverride : IEntityFrameworkOverrides {
  protected IUserContextProvider UserProvider { get; private set; }
  protected UserAwareOverride(IUserContextProvider userProvider)
  {
    UserProvider = userProvider;
  }
  public abstract void EntityInitializing(ModelBuilder modelBuilder, IMutableEntityType entity);

  public abstract void EntityChanged(EntityEntry entity);
}

public class ApplicationContext : IdentityDbContext<User> {

  private static bool ConfigurOverridesSet = false;
  protected static readonly List<IEntityFrameworkOverrides> EFOverrides = new List<IEntityFrameworkOverrides>();

  public static void ConfigureOverrides(IEnumerable<IEntityFrameworkOverrides> overrides) {
    if (ConfigurOverridesSet) {
     throw new NotSupportedException("Cannot set overrides on SplitFamContext More than once.");
    }
    EFOverrides.AddRange(overrides);
    ConfigurOverridesSet = true;
  }

  public ApplicationContext(DbContextOptions<ApplicationContext> options)
    :base(options) { }
}

And then in Startup I just did this:
public IServiceProvider ConfigureServices(IServiceCollection services) {
  services.AddMvc();

  var builder = new ContainerBuilder();

  services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  services.AddSingleton<IUserContextProvider, MvcUserContextProvider>();

  services.AddDbContext<ApplicationContext>(options => {

  options.UseNpgsql(
    Configuration.GetConnectionString("ApplicationContext"));
  });

  services.AddIdentity<User, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationContext>()
    .AddDefaultTokenProviders();

  builder.Populate(services);
  this.ApplicationContainer = builder.Build();

  // Create the IServiceProvider based on the container.
  return new AutofacServiceProvider(this.ApplicationContainer);
}

public void Configure(
  IApplicationBuilder app,
  IHostingEnvironment env,
  ILoggerFactory loggerFactory,
  IApplicationLifetime appLifetime) {
  if (env.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
  }
  loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseMvc();

  var userContexProvider = app.ApplicationServices.GetService<IUserContextProvider>();
  ApplicationContext.ConfigureOverrides(new List<IEntityFrameworkOverrides>(){
    new SoftDeleteOverrides(userContexProvider),
    new TrackCreatedOverride(userContexProvider),
    new TrackModifiedOverride(userContexProvider)
  });

  appLifetime.ApplicationStopped.Register(() => {
    this.ApplicationContainer.Dispose();
  });
}

Probably needs some tweaks and I don't love it but it could be a work around until you can inject services into DbContext...
Another approach you could use is to get a static HttpContext like in older versions of MVC.  Solution found here:  https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/
I still haven't tried the Thread.CurrentPrincipal.Identity yet either nor do I know of any problems with the same.


text:
Q: C# Google Sheets API - Delete Row I searched everything already on the whole internet :) and did not find a solution for this.
I can add new rows, update old rows and do a lot of things in google sheets via C#, but I can't delete a row in a google sheet... can someone, please help me with this?
[EDITED]
OK, I finally found how to delete the rows...
So, what I had to do was first to build list of all indexes that are to be deleted. After doing that I had to build list of key pairs values with start and end of the index to delete, BUT for the end I had to add +1, as it seems like starts and ends are not deleted, only things that are between..
Finally I had to loop the list of key pairs from the end till the start and this deleted the rows...
The code to delete is here. Maybe this will help someone else who is looking how to delete rows in google sheets:
   List<KeyValuePair<int, int>> _listStartEndIndexToDelete = new List<KeyValuePair<int, int>>();
    List<int> _tempListOfAllIndex = new List<int>();

    for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
    {
        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            _tempListOfAllIndex.Add(i);
        }
    }

    for (int rowNumber = 0; rowNumber <= _tempListOfAllIndex.Count() - 1; rowNumber++)
    {
        int tempStart = _tempListOfAllIndex[rowNumber];
        if(rowNumber != _tempListOfAllIndex.Count() - 1)
        {
            while (_tempListOfAllIndex[rowNumber] + 1 == _tempListOfAllIndex[rowNumber + 1])
            {
                rowNumber++;
                if (rowNumber == _tempListOfAllIndex.Count() - 1) { break; }
            }
        }

        int tempEnd = _tempListOfAllIndex[rowNumber] + 1;

        KeyValuePair<int, int> tempPair = new KeyValuePair<int, int>(tempStart, tempEnd);
        _listStartEndIndexToDelete.Add(tempPair);
    }

    for(int keyValuePair = _listStartEndIndexToDelete.Count()-1; keyValuePair >= 0; keyValuePair--)
    {
        List<Request> deleteRequestsList = new List<Request>();
        BatchUpdateSpreadsheetRequest _batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
        Request _deleteRequest = new Request();
        _deleteRequest.DeleteDimension = new DeleteDimensionRequest();
        _deleteRequest.DeleteDimension.Range = new DimensionRange();
        _deleteRequest.DeleteDimension.Range.SheetId = SheetIDnumberWhereDeleteShouldBeDone;
        _deleteRequest.DeleteDimension.Range.Dimension = "ROWS";
        _deleteRequest.DeleteDimension.Range.StartIndex = _listStartEndIndexToDelete[keyValuePair].Key;
        _deleteRequest.DeleteDimension.Range.EndIndex = _listStartEndIndexToDelete[keyValuePair].Value;

        deleteRequestsList.Add(_deleteRequest);
        _batchUpdateSpreadsheetRequest.Requests = deleteRequestsList;
        sheetsService.Spreadsheets.BatchUpdate(_batchUpdateSpreadsheetRequest, SheetIDInternal).Execute();
    }

A: I checked the links that You provided here, but non of them solved the problem.
For example this one:
Request request = new Request()
  .setDeleteDimension(new DeleteDimensionRequest()
    .setRange(new DimensionRange()
      .setSheetId(0)
      .setDimension("ROWS")
      .setStartIndex(30)
      .setEndIndex(32)
    )
  );

The problem is that, there is no such a thing like .setDeleteDimension under Request. This shouldn't be such a problem, but it is....
Below You can find my code. What does it do, is to take data from one sheet (internal) and put it to another sheet (internal archive). When this is done (and this works well), I want to delete data from internal as it is already archived... and that part is not working. I just don't know how to delete the rows.. if anyone could have a look on this, it would be great. Thanks for your help...
public void RunArchiveInternal2(bool testRun)
{
    //internal
    string SheetIDInternal = "googlesheetid_internal";
    string RangeInternal = testRun ? "test_task tracking" : "Task Tracking - INTERNAL";
    SpreadsheetsResource.ValuesResource.GetRequest getRequestInternal = sheetsService.Spreadsheets.Values.Get(SheetIDInternal, RangeInternal);
    ValueRange ValuesInternal = getRequestInternal.Execute();

    //internal archive
    string SheetIDInternalArchive = "googlesheetid_internal_archive";
    string RangeInternalArchive = testRun ? "test_archive_internal" : "Sheet1";
    SpreadsheetsResource.ValuesResource.GetRequest getRequestInternalArchive = sheetsService.Spreadsheets.Values.Get(SheetIDInternalArchive, RangeInternalArchive);
    ValueRange ValuesInternalArchive = getRequestInternalArchive.Execute();

    //Get data from internal and put to internal archive
    List<IList<object>> listOfValuesToInsert = new List<IList<object>>();

    for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
    {
        List<object> rowToUpdate = new List<object>();

        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            rowToUpdate = (List<object>)ValuesInternal.Values[i];
            listOfValuesToInsert.Add(rowToUpdate);
        }
    }
    SpreadsheetsResource.ValuesResource.AppendRequest insertRequest = sheetsService.Spreadsheets.Values.Append(new ValueRange { Values = listOfValuesToInsert }, SheetIDInternalArchive, RangeInternalArchive + "!A1");
    insertRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
    insertRequest.Execute();

    //delete things from internal
    BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
    List<DeleteDimensionRequest> requests = new List<DeleteDimensionRequest>();

    for (int i = ValuesInternal.Values.Count() - 1; i >= 1; i--)
    {
        DeleteDimensionRequest request = new DeleteDimensionRequest();
        //Request request = new Request();

        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            request.Range = new DimensionRange
            {
                Dimension = "ROWS",
                StartIndex = i,
                EndIndex = i
            };
            requests.Add(request);
        }
    }
    batchUpdateSpreadsheetRequest.Requests = requests;//this is wrong
    SpreadsheetsResource.BatchUpdateRequest Deletion = sheetsService.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SheetIDInternal);
    Deletion.Execute();
}


text:
Q: Typescript Error in mongoose schemas pre method: Unexpected aliasing of 'this' to local variable I'm trying to implement authentication based on MongoDB and NestJS for an Ionic application and getting the following error message after making a POST request to the route api/users:

[Nest] 85372   - 03/26/2020, 14:04:49   [ExceptionsHandler] Cannot read property 'password' of undefined +23790ms

Inside my users.schema.ts file a get the errror message:

Unexpected aliasing of 'this' to local variable.eslint(@typescript-eslint/no-this-alias)

My users.schema.ts looks like this (commented the line with the error):
import * as mongoose from 'mongoose';
import * as bcrypt from 'bcryptjs'

export const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        unique: true,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

UserSchema.pre('save', function (next) {
    const user = this; // This is marked as an error in vs code
    if (!user.isModified('password')) return next();

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err);
        bcrypt.hash(this.user.password, salt, (err, hash) => {
            if (err) return next();
            this.user.password = hash;
            next();
        });
    });
});

UserSchema.methods.checkPassword = (attempt, callback) => {
    bcrypt.compare(attempt, this.user.password, (err, isMatch) => {
        if (err) return callback(err);
        callback(null, isMatch);
    })
}

I tried to implement the same schema with an arrow function, but then I get the following error message after making a POST request to api/users:

[Nest] 85947   - 03/26/2020, 14:09:30   [ExceptionsHandler] Cannot read property 'isModified' of undefined +22567ms

UserSchema.pre('save', (next) => {
    if (!this.user.isModified('password')) return next();

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err);
        bcrypt.hash(this.user.password, salt, (err, hash) => {
            if (err) return next();
            this.user.password = hash;
            next();
        });
    });
});

What am I doing wrong here?

A: You cannot use arrow functions, because you loose the track of this. Read the official documentation of arrow functions, there are some very good examples about "what is this in an array function". MDN Arrow function expressions
There are two solutions:
Remove the arrow-function callback for bcrypt
UserSchema.pre('save', function (next) {
  if (!this.isModified('password')) return next();

  bcrypt.genSalt(10, function (err, salt) {
    if (err) return next(err);
    bcrypt.hash(this.user.password, salt, (err, hash) => {
      if (err) return next();
      this.user.password = hash;
      next();
    });
  });
});

Disable eslint rule and always use the user variable
UserSchema.pre('save', function (next) {
  const user = this;
  if (!this.isModified('password')) return next();

  bcrypt.genSalt(10, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) return next();
      user.password = hash;
      next();
    });
  });
});


text:
Q: How to pass the predefined messages from one page to another page using php I want to pass a predefined message from a PHP page to another.i having button if user clicks the button its will redirect to the contact form page when its redirect it will show the predefined message in a message box.
e.g. let's say that I have these message:
$message="Dear xxxxxxxx Team,

I am interested in an xxxxx.

Kind Regards,
xxxx";

and I want to pass them from index.php to contactform.php.
I trying like with URL
Get a xxxxx - Messenger Test Account

but it not working can anyone tell me how to make it work

A: try this <?php echo urlencode($message);?>
like this
<a href="contact_form.php?message=<?php echo urlencode($message);?>"  class="tbutton large">Get a xxxxx - Messenger Test Account

METHOD : 2
use session to store your static message like
$message "some message";
$_SESSION['static_message'] = $msg;

Now use simple link without passing the parameter
Get a xxxxx - Messenger Test Account

Now on contact_form.php you can access this like
$message = $_SESSION['static_message'];

NOTE : you have to start the session on the top of the page where you are using session by using line  session_start();

A: You can't pass long strings in a GET parameter.
Your best bet is using Sessions
session_start(); //This must happen on each page where the session is used!
$_SESSION["message"] = <<<MESSAGE
Dear xxxxxxxx Team,

I am interested in an xxxxx.

Kind Regards,
Raja
MESSAGE;

Then on your contact page you'd echo it out on the page like this:
<?= $_SESSION["message"] ?>

Note that you must use session_start() at the top of the contact page as well!
Also, it might be a good idea to wipe the session clean ($_SESSION = array();) after you're done with it.

A: You can use $_SESSION variables to this, so on the first page (index.php) you could use:
<?php
session_start();
$_SESSION['message'] = 'Dear xxxxxxxx Team, I am interested in an xxxxx. Kind Regards, Raja';
?>

So you assign the value of a session variable.
and on contact.php it would be just simply
<?php echo $_SESSION['message']; unset($_SESSION['message']); session_destroy(); ?>

You can change the echo part to suit your needs. Unset destroys the value of the variable and session_destroy discards the whole session.
Hope this helps.

A: To pass predefined message, one way is, add form in index.php with required action and between the form add submit button and one hidden field of for predefined message.
ex:
    <form name="test" id="test" action="contact_form.php">
    <input type="hidden" name="msg" is="msg" value="I am interested in an xxxxx"/>
    <input type="submit" value="Messenger Test Account"/>
    </form>

You can get message on contact_form.php page using echo $_POST['msg'];
The other way is,
Get a xxxxx - Messenger Test Account

on contact_form.php check
isset($_GET['message'] && $_GET['message']==1) { echo "I am interested in an xxxxx"; }

But the best way is the first one where we pass message using post method.


text:
Q: Initialize non existing keys in OrderedDict with default values like defaultDict Is there any way to access the non existing keys in OrderedDict with default values like which we do in defaultDict
Ex.
od = OrderedDict({'a':1})
print(od['b'])  # Output: KeyError: 'b'

This is the real problem KeyError is thrown in the following implementation
l =['a','b','c','b']
od = OrderedDict({})

for k in l:
    od[k] += 1 # KeyError

This implementation is intentionally avoided
for k in l:
    if k in od:
        od[k] += 1
    else:
        od[k] = 1

A: Just inherit from OrderedDict and redefine __getitem__:
from collections import OrderedDict

class OrderedDictFailFree(OrderedDict):
    def __getitem__(self, name):
        try:
            return OrderedDict.__getitem__(self, name)
        except KeyError:
            return None

od = OrderedDictFailFree({'a': 1})
print(od['b'])

A: This is certainly doable, as Yevgeniy Kosmak's answer shows. However, keep in mind that in Python >=3.7 (or even >=3.6 as long as you're using the default CPython implementation), all dictionaries now maintain insertion order anyway. So in the event that you don't need compatibility with older versions, and the only thing you need is keys that maintain order, you may very well not need OrderedDict at all. defaultdict will maintain its order just as well.
There are still some differences between OrderedDict and dict/defaultdict, however, which may or may not affect your use case. These include:

*

*Equality checks between two OrderedDicts check not only keys/values, but order as well. (This is not true of two defaultdicts, or an OrderedDict checked against a defaultdict.)

*An OrderedDict's move_to_end() method can efficiently move a key/value pair to the front or end.

*An OrderedDict's popitem() method can optionally pop and return the first key/value instead of the last. (dict's popitem() returns the last-inserted key/value—or, prior to 3.7, an arbitrary pair.)

*Prior to 3.8, dict/defaultdict didn't directly support reverse iteration, such as with reversed(). However, in 3.6 or 3.7 you can still achieve this with an intermediary list or tuple.

Note: Even if dict now replicated all of OrderedDict's functionality, the latter would still probably not be removed from Python. Existing older programs already use OrderedDict, and Python usually tries not to break existing code with new minor version releases (e.g. 3.6 to 3.7) unless there's a compelling reason, like adding new keywords to the syntax. See here for more info on the Python versioning system, and here for details on backwards compatibility specifically.

A: It seems we could use od.setdefault('b',0) although it's not that elegant solution.
od = OrderedDict({'a':1})
print(od.setdefault('b',0)) # od.get('b',0) could be used if intention is not to change od

l =['a','b','c','b','b']
od = OrderedDict({})

for k in l:
    od[k] = od.setdefault(k,0) + 1 # set key to 0 if there in no key k and increment by 1


text:
Q: How to count the times a particular item appears in a query output I have a query with a lot of tables and joins. So a simple Count(column) and Group By isn't working correctly.
The query returns an item list. I want to calculate how many times each item appears in that list.
Here's my query:
SELECT DECODE(BOM.ORGANIZATION_ID,203, 'CEC', 328, '3PL', 204, 'SIM') ORGANIZATION_CODE,
  BOM.ORGANIZATION_ID,
  MSI.SEGMENT1 "PARENT_ITEM",
  MSIC.SEGMENT1 "COMPONENT_ITEM",
  SUM(NVL(MMT.TRANSACTION_QUANTITY,0)) * NVL(SUM(CIC.ITEM_COST),0) "ANNUAL_MONEY",
  SUM(NVL(MMT.TRANSACTION_QUANTITY,0)) "ANNUAL_QTY_USG",
  NVL(SUM(CIC.ITEM_COST),0) "AVG_COST",
  SUM(NVL(MSI.POSTPROCESSING_LEAD_TIME,0) + NVL(MSI.PREPROCESSING_LEAD_TIME,0)) LEAD_TIME
FROM BOM_BILL_OF_MATERIALS BOM
LEFT JOIN MTL_SYSTEM_ITEMS MSI
ON MSI.ORGANIZATION_ID    = BOM.ORGANIZATION_ID
AND MSI.INVENTORY_ITEM_ID = BOM.ASSEMBLY_ITEM_ID
AND MSI.ENABLED_FLAG      = 'Y'
AND MSI.BOM_ENABLED_FLAG  = 'Y'
LEFT JOIN CST_ITEM_COSTS CIC
ON CIC.ORGANIZATION_ID    = BOM.ORGANIZATION_ID
AND CIC.INVENTORY_ITEM_ID = BOM.ASSEMBLY_ITEM_ID
AND CIC.COST_TYPE_ID      = 1
LEFT JOIN MTL_MATERIAL_TRANSACTIONS MMT
ON MMT.INVENTORY_ITEM_ID     = BOM.ASSEMBLY_ITEM_ID
AND MMT.ORGANIZATION_ID      = BOM.ORGANIZATION_ID
AND MMT.TRANSACTION_TYPE_ID IN (33,34,17)
LEFT JOIN MTL_TRANSACTION_TYPES MTT
ON MTT.TRANSACTION_TYPE_ID = MTT.TRANSACTION_TYPE_ID
LEFT JOIN BOM_INVENTORY_COMPONENTS BIC
ON BIC.BILL_SEQUENCE_ID = BOM.COMMON_BILL_SEQUENCE_ID
AND NVL(bic.disable_date, sysdate+1) > sysdate
LEFT JOIN BOM_COMPONENTS_B BCB
ON BIC.COMPONENT_SEQUENCE_ID = BCB.COMPONENT_SEQUENCE_ID
LEFT JOIN BOM_STRUCTURES_B BSB
ON BCB.BILL_SEQUENCE_ID = BSB.BILL_SEQUENCE_ID
LEFT JOIN MFG_LOOKUPS ML
ON ML.LOOKUP_CODE  = BIC.WIP_SUPPLY_TYPE
AND ML.LOOKUP_CODE = BIC.ENFORCE_INT_REQUIREMENTS
AND ML.LOOKUP_TYPE = 'MTL_EAM_ITEM_TYPE'
LEFT JOIN MTL_SYSTEM_ITEMS MSIC
ON MSIC.ORGANIZATION_ID    = BOM.ORGANIZATION_ID
AND MSIC.INVENTORY_ITEM_ID = BIC.COMPONENT_ITEM_ID
LEFT JOIN BOM_OPERATIONAL_ROUTINGS BOR
ON BOR.ASSEMBLY_ITEM_ID   = BOM.ASSEMBLY_ITEM_ID
AND BOR.ORGANIZATION_ID   = BOM.ORGANIZATION_ID
WHERE BOM.ORGANIZATION_ID = NVL(:P_ORG_ID,BOM.ORGANIZATION_ID)
AND EXISTS
  (SELECT 'X'
  FROM MTL_MATERIAL_TRANSACTIONS MMT
  WHERE MMT.TRANSACTION_DATE >= ADD_MONTHS (SYSDATE,-12)
  AND MSI.INVENTORY_ITEM_ID IS NOT NULL
  )
GROUP BY BOM.ORGANIZATION_ID,
  MSI.SEGMENT1,
  MSIC.SEGMENT1
ORDER BY ORGANIZATION_CODE,
  MSIC.SEGMENT1

My output is like this now:
I want to have another column which counts each item occurence in the output.

A: That's called conditional aggregation and you can do it with CASE EXPRESSION :
SELECT <col1>,<col2>..,
       COUNT(CASE WHEN column ='Specific Val' THEN 1 END) as cnt
FROM YourTable
GROUP BY  <col1>,<col2>..,

In MySQL this is also fine:
SUM(column = 'Specific Val')

Because expressions are treated as 1 and 0 .

A: wouldn't count(distinct column) work here since you're already using a group by

A: You can also try this:
select count(*) from
(your query)
where column='value to be checked'

A: Would this be what you are looking for:
SELECT ColumnName, COUNT(*)
FROM TableName
GROUP BY ColumnName;

On the location of TableName you can also use a (SELECT ....).


text:
Q: Packing nested structs in C++ Using Visual Studio 2017, the following gives...
struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

struct BBB
{
    AAA d;
    char a4;
};

int main()
{
    std::cout << sizeof(AAA) << "\n"; // gives 16
    std::cout << sizeof(BBB) << "\n"; // gives 24
    getchar();
    return 0;
}

The Question is... how do I get sizeof(BBB) to be 16.

A: Use #pragma pack(push, 1) or #pragma pack(1) to enforce compiler not to line up structure members on 2 byte or 4 byte boundaries which makes it easier and faster for the processor to handle. So the structure contains secret padding bytes to make this happen. But this increases memory usage because of padding.
Its a precise explanation here

A: struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

#pragma pack(1)

struct BBB
{
    AAA d;
    char a4;
};

int main()
{
    std::cout << sizeof(AAA) << "\n"; // gives 16
    std::cout << sizeof(BBB) << "\n"; // gives 17
    getchar();
    return 0;
}

A: Try with below code :
#pragma pack(1)
struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

#pragma pack(1)
struct BBB
{
    AAA d;
    char a4;
};

int main(int argc, char *argv[])
{
    std::cout << sizeof(AAA) << "\n"; // gives 15
    std::cout << sizeof(BBB) << "\n"; // gives 16
    getchar();

    return 0;
}

The result will be :
15
16

structs, and unions have stricter alignment requirements that ensure consistent aggregate and union storage and data retrieval. There is suggested alignment for the scalar members of unions and structures.
Structure size must be an integral multiple of its alignment, which may require padding after the last member.
#pragma pack statement change the alignment of a structure.

A: using
#pragma pack(1)

will results into sizeof(AAA) to be 15 and sizeof(BBB) to be 16.


text:
Q: GPRS AT-commands for Siemens cell phone I've a task - remote temperature monitoring. Hardware is atmega328 microcontroller, simple analog temperature sensor and old cell phone Siemens cx75 (this device has a GPRS module).  So, I'm looking for AT commands to send some bytes of data via GPRS from this phone. There are many documents about GPRS commands, but I've found just for modems insteed of cell phones.
Maybe someone can help me? Or is it easier to use another solution?
UPDATE:
I've some progress:
First of all I set PDP context:
at+cgdcont=1,"ip","mts"
OK

Then
at+cgatt=1
OK

at+cgact=1
OK

It's ok, I've been attached to packet domain service and PDP context
So, what should I do next? I have tried some modem commands, such as
at+cipstart=0,"tcp","178.xxx.xxx.xxx","8001"

but I've got
ERROR

A: According to @S List 's link, there is no opportunity of gprs-connection using clear atmega328. It's seem the easiest way is to use GRPS-shield.


text:
Q: Very strange behavior with array declaration I have a simple function:
    DoRead(double *writeArray){
//GblOutData is an array of length 80, where each element is 1
    writeArray=GblOutData;
//prints out 1
    printf("%f",writeArray[5]);
    return 0;
    }

what happens when I call DoRead():
double data[80];
DoRead(data);
printf("%f",data[5]);
//prints out 0.000000 instead of 1

I can't figure out why this is happening. Any ideas?

A: All that the line
writeArray=GblOutData;

does is change the meaning of the variable writeArray inside the function DoRead(). When it returns, the outer variable data has not changed. You want to copy the contents, possibly with memcpy:
memcpy(writeArray, writeArray=GblOutData, 80*sizeof *writeArray);

A: You need to pass the address to data. One solution can be (but personally I wouldn't do something like this):
DoRead(double **writeArray){
 *writeArray=GblOutData;
  ....
}

DoRead((double**) &data);


text:
Q: How to chose Color depending on System Background Color in Swift 5? I am currently working with SwiftUI Colors.
Problem: I have a Card Component which has a Background Color of systemGray6. This works fine for most Views (all Views with systemBackground Background Color).
However, I have some Modal Views which come with tertiarySystemBackground. This doesn't change anything in LightMode, but changes the Background Color in DarkMode to the same as systemGray6. As a result, the Background and the Card have the same Color and the Card is not visible anymore.
My Solution so far:
struct Card: View {
    var isInsideModal: Bool = false

    var body: some View {
        // Some Content
        .background(isInsideModal ? Color.systemGray6 : Color.systemGray5) // I added this in an Extension of Color
    }
}

Question: Is there any Possibility of automating this Behavior without always having to explicitly pass the desired Background Color to the Card View?
Thanks for your help.

A: You could create Color Sets in your xcassets folder. It provides you with the ability to choose different Appearances depending on whether your app is operating under dark or light mode.


text:
Q: Angular moving scope variable from controller to directive I have created a directive like this
  .directive('optionLabel', function() {
    'use strict';
    return {
      replace: true,
      restrict: 'AE',
      template: '

{{ optionLabel }}

'
    };
  })

Right now the Scope optionLabel is set in each of the controllers that uses this directive as such.
$scope.optionLabel = labelService.getOptionLabel(search.searchType);

How could I set this in the directive directly, rather than doing this code repeated in like 5 controllers ?

A: You can use link in which you have access to your scope :
.directive('optionLabel', function() {
'use strict';
return {
  replace: true,
  restrict: 'AE',
  template: '

{{ optionLabel }}

',
link: function(scope, element, attrs) {
scope.optionLabel = labelService.getOptionLabel(search.searchType);
};
})

Don't forget to inject labelService in your directive.


text:
Q: Cocoapods Podspec Source HTTP Authentication Support I am looking into setting up a private repo that allows distributing binary .framework files (so no source code) via Cocoapods.
The actual repo will be hosted on a Git server, just like the Cocoapods page suggests and the actual .framework files will be hosted on a different server that would allow accessing the .framework files via HTTPs.
Let's say I add this in the .podspec file:
spec.source           = { :http => 'https://myhostserver.com/Releases/v1.0.0/MyLibrary.framework.zip' }

From reading the documentation it's not clear to me what kind of authentication does Cocoapods support for referencing the .framework file via HTTPs.
I had a look at both
http://guides.cocoapods.org/making/private-cocoapods.html
https://guides.cocoapods.org/syntax/podspec.html#source

A: CocoaPods' Downloader is using CURL for downloading files under the hood. If you want to use HTTP, you can setup your authentication credentials in the ~/.netrc file.


text:
Q: Determinant from matrix entirely composed of variables I don't want the answer, but I'd love to kick in the right direction. I'm really not sure how to approach this question.
$$\begin{align}
& -6 = det\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix} \\
& x = det\begin{bmatrix}
a & b & c \\
2d & 2e & 2f \\
g+3a & h+3b & i+3c \\
\end{bmatrix}
& \text{Solve for }x
\end{align}$$
I believe if I set $a=1$, $e=2$, and $i=3$ (all other variables $0$), the determinant of the first matrix is $6$, and then for the second matrix is $12$. These were arbitrary variable initializations and can be any number. The relationship between the two (a scalar multiple of 2) will be the same irrespective of what I set the variables to.
I can then infer that the determinant of the second matrix is $2*det[A]$ or $-12$ because I'm investigating the relationship between the two matrices rather than actually calculating anything. I imagine this is a cheap way out, though. But, from this method I do get $x = -12$, which I believe is the correct answer.
What is the proper way of solving this? I don't want the answer, but I'd like to know the process.

A: Your answer will be closely related to the $-6$ that was given. You are NOT supposed to find values of $a,b,c,d,...$ that "work". You are supposed to use pure theory.
A) when you add a multiple of one row to another row, the determinant stays the same.
B) multiplying a row by a constant multiplies the determinant by __.

A: I just solved this by expanding the determinants, and then comparing the two equations. You may be shocked when you do the same. One determinant turns out to be an integer multiple of the other, and so you can very quickly solve for $x$. One way: Actually expand the two determinants and compare. You are clearly supposed to be solving for $x$. Expand and have faith. ;))

A: $$\begin{align}
 det\begin{bmatrix}
a & b & c \\
2d & 2e & 2f \\
g+3a & h+3b & i+3c \\
\end{bmatrix}
=\det \begin{bmatrix}
a & b & c \\
2d & 2e & 2f \\
g & h & i \\
\end{bmatrix}+\det \begin{bmatrix}
a & b & c \\
2d & 2e & 2f \\
3a & 3b & 3c \\
\end{bmatrix}=\det \begin{bmatrix}
a & b & c \\
2d & 2e & 2f \\
g & h & i \\
\end{bmatrix}=2\det \begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix}
\end{align}$$
It would be useful for you in future  if you can prove what i have done is valid always.
(splitting up into two matrices is valid and taking out a multiple from a row as well)


text:
Q: PayPal REST API returning 500-Error when trying to create payment-object I try to integrate the PayPal PLUS API into my NativeScript Mobile App. When creating a payment (calling this API: https://developer.paypal.com/docs/api/payments/#create_payment) with the shortened call displayed on the side I keep getting a 500-Error. Sadly I did not find out how to display the message of it.
I am running my code on an iOS Emulator (Xcode 7) via NativeScript.
I tried the following curl-call, which worked for me:
What I tried with curl:
curl -v -X POST https://api.sandbox.paypal.com/v1/payments/payment \
-H "Content-Type:application/json" \
-H "Authorization: Bearer <my-token>" \
-d '{
  "intent": "sale",
  "payer": {
      "payment_method": "paypal"
  },
  "transactions": [
  {
      "amount": {
      "total": "30.11",
      "currency": "EUR",
      "details": {
          "subtotal": "30.00",
          "tax": "0.07",
          "shipping": "0.03",
          "handling_fee": "1.00",
          "shipping_discount": "-1.00",
          "insurance": "0.01"
      }
  },
  "item_list": {
      "items": [
      {
          "name": "hat",
          "description": "Brown hat.",
          "quantity": "5",
          "price": "3",
          "tax": "0.01",
          "sku": "1",
          "currency": "EUR"
      },
      {
          "name": "handbag",
          "description": "Black handbag.",
          "quantity": "1",
          "price": "15",
          "tax": "0.02",
          "sku": "product34",
          "currency": "EUR"
      }
    ]}
  }
  ],
  "redirect_urls": {
  "return_url": "http://www.paypal.com/return",
  "cancel_url": "http://www.paypal.com/cancel"
  }
}'

responding a 201-Created response.
Now I created an XHR-Object in TypeScript with the same elements. My code so far:
    var oReq = new XMLHttpRequest();
    oReq.open("POST", PayPalEndpoints.getPaymentEndpoint, true);
    oReq.setRequestHeader('Authorization', "Bearer " + access_token);
    oReq.setRequestHeader('Accept', "application/json");
    oReq.onreadystatechange = function () {
        console.log("state changed - new state: " + oReq.readyState + " and Status: " + oReq.status);
        if (oReq.readyState === 4) {
            if (oReq.status === 200) {
                var response = JSON.parse(oReq.responseText);
                console.log("response = " + response);
            } else {
                console.log("Error: " + oReq.status + " Message: " + oReq.responseText);
            }
        }
    };

    oReq.send({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "transactions": [
        {
            "amount": {
                "total": "30.11",
                "currency": "EUR",
                "details": {
                "subtotal": "30.00",
                "tax": "0.07",
                "shipping": "0.03",
                "handling_fee": "1.00",
                "shipping_discount": "-1.00",
                "insurance": "0.01"
            }
            },
            "item_list": {
                "items": [
                    {
                        "name": "hat",
                        "description": "Brown hat.",
                        "quantity": "5",
                        "price": "3",
                        "tax": "0.01",
                        "sku": "1",
                        "currency": "EUR"
                    },
                    {
                        "name": "handbag",
                        "description": "Black handbag.",
                        "quantity": "1",
                        "price": "15",
                        "tax": "0.02",
                        "sku": "product34",
                        "currency": "EUR"
                    }
                ]
            }
        }
        ],
        "redirect_urls": {
            "return_url":"http://www.paypal.com/return",
            "cancel_url":"http://www.paypal.com/cancel"
        }
    });

which is (like mentioned above) not working for me. Does someone know, how to display the error message from that XHR-Object? Or maybe someone even sees what might be wrong with my code. If you need an API call that worked (via XHR):
    var oReq = new XMLHttpRequest();
    var encodedString = base64.encode(this.authorizationBasic);
    oReq.open("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", false);
    oReq.setRequestHeader('Authorization', "Basic " +  encodedString);

    oReq.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
    oReq.setRequestHeader('Accept', "application/json");
    oReq.setRequestHeader('Accept-Language', "en_US");

    oReq.onreadystatechange = function () {
        console.log("state changed - new state: " + oReq.readyState + " and Status: " + oReq.status);
        if (oReq.readyState === 4) {
            if (oReq.status === 200) {
                var response = JSON.parse(oReq.responseText);
                OAuthAccessor.access_token = response.access_token;
                console.log("access_token set");
            } else {
                console.log("Error: " + oReq.status + " Message: " + oReq.responseText);
            }
        }
    };

    oReq.send('grant_type=client_credentials');

API reference:
Integration pdf:
https://www.paypalobjects.com/webstatic/de_DE/downloads/PayPal-PLUS-IntegrationGuide.pdf
Call reference:
https://developer.paypal.com/docs/integration/direct/make-your-first-call/
The call I shortened:
https://developer.paypal.com/docs/api/payments/#create_payment

A: If someone is doing research on an equal problem:
You need to change the
 oReq.setRequestHeader('Accept', "application/json");

to
oReq.setRequestHeader('Grant-Type', "application/json");

and you need to pass the data in the send-Method as a json-string, so call:
 oReq.send(JSON.stringify(data));

with "data" being your JSON String.


text:
Q: How outliers influence your results? and what are good and bad leverage points? I am confused between outliers and leverage points. And the difference between good and bad leverage points in time series analysis.
Can somebody help me?


text:
Q: Determine the constants $A$, $B$ and $C$ that satisfy the following equality $$\frac{19}{x^3+x^2-14x+6} = \frac{A}{x-3}+\frac{Bx+C}{x^2+4x-2}$$
The answer is $A = 1, B = -1, C =-7$.

A: This method is known as partial fractions.
First, note that $x^3+x^2-14x+6=(x-3)(x^2+4x-2)$, so the first step should be clear:
If $$\frac{19}{x^3+x^2-14x+6} = \frac{A}{x-3}+\frac{Bx+C}{x^2+4x-2}=\frac{A(x^2+4x-2)+(Bx+C)(x-3)}{x^3+x^2-14x+6},$$
then we have that
$A(x^2+4x-2)+(Bx+C)(x-3)=19+0*(x^2)+0*(x)$
for this to be true, we require that $-2A-3C=19$, $B+A=0$, and that $4A-3B+C=0$. The intuition here, is that all of the coefficients for $x^2$, $x$, and $1$ should line up on both sides of the equality.
From this linear system, we can deduce that
$$\begin{bmatrix}-2 & 0 & -3\\ 1 & 1 & 0\\ 4 & -3 & 1
\end{bmatrix} \cdot \begin{bmatrix}A \\ B \\C \end{bmatrix}=\begin{bmatrix}19 \\ 0 \\ 0\end{bmatrix}$$
(Alternatively you can solve the $3\times3$ system of linear equations using standard methods.)
From here, you determine the solutions:
$$\begin{bmatrix}A \\ B \\C \end{bmatrix}=\begin{bmatrix}1 \\ -1 \\ -7\end{bmatrix}$$

A: Since the identity holds for all $x$, you can get the values of $A$, $B$, $C$ by judicious choice of $x$.

*

*Multiply both sides of the identity by $(x-3)$, then substitute $x=3$. Since $x^3+x^2-14x+6=(x-3)(x^2+4x-2)$, this gives $\frac{19}{19}=A$, so $A=1$.

*Multiply both sides by $x$ and let $x\to\infty$. This gives $0=A+B$, so $B=-1$.

*Set $x=0$. This gives $\frac{19}6=-\frac A3-\frac C2$, so $C=-7$.


text:
Q: jquery mobile make a phone call when pressing a button I'm building a mobile website using HTML 5 and CSS with Query mobile
I have a button like this
Contact me for a meeting

I would like add an "action" so when a user click he can call a phone number.
Please note the application is running in the browser, I would like to know if there is a build in function in query or other solution. Thanks

A: Take a look here - http://jquerymobile.com/demos/1.0a2/docs/pages/link-formats.html
I think the tel: protocol will do it for you


text:
Q: Does the data object have a maximum query length? I have an old vb6 program which queries an access 2000 database. I have a fairly long query which looks something like this:
Select * from table where key in ( 0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 19, 20, 21, 24, 27, 29, 30, 35, 38, 39, 40, 42, 43, 44, 46, 47, 49, 50, 53, 56, 59, 60, 61, 63, 64, 65, 66, 67, 68, 72, 76, 80, 84, 86, 89, 90, 91, 93, 94, 98, 99, 10041, 10042, 10045, 10046, 10047, 10049, 10057, 10060, 10089, 32200, 32202, 32203, 32204, 32205, 32207, 32214, 32245, 32303, 32314, 32403, 32405, 32414, 32415, 32503, 32703, 32803, 32903, 33003, 33014, 33102, 33103, 33303, 33403, 33405, 33601, 33603, 33604, 33614, 33705, 33714, 33901, 33903, 33914, 34001, 34105, 34114, 34203, 34303, 34401, 34501, 34601, 34603, 34604, 34605, 34803, 41001, 41005, 41007, 41013, 42001, 42005, 42007, 42013, 43001, 43002, 44001, 44007, 46001, 46007, 99999, 9999999)

However, when I look at the RecordSource of the data object, it seems that the query is being truncated to this (which is obviously not syntactically valid and throws an error):
Select * from table where key in ( 0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 19, 20, 21, 24, 27, 29, 30, 35, 38, 39, 40, 42, 43, 44, 46, 47, 49, 50, 53, 56, 59, 60, 61, 63, 64, 65, 66, 67, 68, 72, 76, 80, 84, 86, 89, 90, 91, 93, 94, 98, 99, 100

My data source looks like this:
 Begin VB.Data dtaList
     Caption         =   "dtaList"
     Connect         =   "Access 2000;"
     DatabaseName    =   ""
     DefaultCursorType=   0  'DefaultCursor
     DefaultType     =   2  'UseODBC
     Exclusive       =   0   'False
     Height          =   345
     Left            =   960
     Options         =   0
     ReadOnly        =   0   'False
     RecordsetType   =   1  'Dynaset
     RecordSource    =   ""
     Top             =   4440
     Visible         =   0   'False
     Width           =   2295
  End

I've tried running the full query in the access database itself which works fine.
Is this a limitation in the VB.Data object, or is there some other explanation? Is there any way I can get around this issue?
Unfortunately I am unable to upgrade to a newer version of access.

A: The truncated version of the SQL statement you posted  is 246 characters long, so it appears that something along the line is limiting the length of the SQL string to somewhere around 255 characters. As you have discovered by pasting the query into Access itself, the actual size limit of an Access query string is much larger (around 64,000 characters, I believe).
I remember running across a similar issue years ago but my problem was an INSERT statement that was writing some rather long strings to the database. The workaround in that case was to use a parameter query (which I realize, in hindsight, that I should have been using anyway). It greatly shortened the length of the SQL string because the parameters were passed separately. Unfortunately that workaround probably wouldn't help you because even if you dynamically created a parameterized version of the query it wouldn't be all that much shorter than the current SQL string.
Another workaround would be to write all of those numbers for the IN clause as rows in a temporary table named something like [inValues], and then use the query
SELECT [table].*
FROM
    [table]
    INNER JOIN
    [inValues]
        ON [table].[key] = [inValues].[key]


text:
Q: Bootstrap Modal and user sign in form ) I am quite new in Ruby so please be indulgent ;-)
I am trying to set up the sign in form within a bootstrap modal but I am keeping the same message errore as it follow :
NameError in Pages#home
Showing /Users/raphaelbendenoun/code/isrcovoit/app/views/pages/home.html.erb where line #78 raised:
undefined local variable or method `resource' for #<#:0x00000101366738>
Extracted source (around line #78):
75:
 id="myModalLabel">Modal header

76:

77:

78:     <%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => 'form-horizontal'}) do |f| %>
79:

80:             <%= f.input :email, :required => false, :autofocus => true %>
81:             <%= f.input :password, :required => false %>
Rails.root: /Users/raphaelbendenoun/code/isrcovoit

Application Trace | Framework Trace | Full Trace
app/views/pages/home.html.erb:78:in `_app_views_pages_home_html_erb__571334819088820889_2157665500'
Here is my code :

    <button type="button" class="close"  aria-hidden="true">×</button>

 id="myModalLabel">Modal header

    <%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => 'form-horizontal'}) do |f| %>

            <%= f.input :email, :required => false, :autofocus => true %>
            <%= f.input :password, :required => false %>
            <%= f.input :remember_me, :as => :boolean if devise_mapping.rememberable? %>

        <%= f.button :submit, "Sign in", :class => 'btn btn-primary', :data => { :dismiss => "modal"} %>
        <% end %>

What am I missing ??
Thx so much for the help, all the tips are welcomed


text:
Q: WPF Change between controls I have a simple application where I have a main screen with some operations, and a second screen that you access when first one is done and you press a button. See image:

Brown areas are fixed left menus, that will always appear in the same location.
Blue areas are the screens that change from one to another.
Red area is trying to simulate a MDIContainer from WindowsForms.
How can I simulate that container to:

*

*Mantain the left static menu

*Change dynamically my content due to some events/actions?

A: The best way would be first to use a grid control to lay out the controls (as Blam suggested) like so:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <!-- Menu control. (Whichever you see fit. The menu could be established
         within this control, or you could use a custom UserControl depending
         on your needs.) -->
    <StackPanel />

    <!-- Content control -->
    <ContentPresenter Name="ContentHolder"
                      Grid.Column="1" />
</Grid>

Depending on your design pattern, there are a couple of ways to get your content to appear as desired.
If you are using MVVM, the ContentPresenter control could be bound to a ViewModel in the data context of your main window, like so:
    <ContentPresenter Name="ContentHolder"
                      Grid.Column="1"
                      Content="{Binding ContentData}" />

And a corresponding property would exist in your ViewModel, such as:
    public ViewModelBase ContentData{
      get { return _contentData; }
    }

If that's a lot of Greek to you, you are probably not using MVVM as your design pattern.  In that case, the code behind of your main window class could handle setting the content of the ContentPresenter with an event handler.
The gist of your event handler could be something like this:
    public void HandleNavigationChange(SwitchCondition sc){
      UserControl newContent = null;

      switch (sc) {
        case SwitchCondition.NavigationItem1:
          newContent = new NavigationItem1();
          break;

        case SwitchCondition.NavigationItem1:
          newContent = new NavigationItem1();
          break;
        //ETC
      }

      ContentHolder.Content = newContent;
    }

You could then call this method from menu item clicks, or if you like, from children controls.

A: <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="2*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" Text="Static"/>
    <ContentControl x:Name="content1" Grid.Row="0" Grid.Column="1" Visibility="Visible" >
        <StackPanel>
            <TextBlock Text="One" />
            <Button Click="btn1_click" Content="Button1"/>
        </StackPanel>
    </ContentControl>
    <ContentControl x:Name="content2" Grid.Row="0" Grid.Column="1" Visibility="Hidden" >
        <StackPanel>
            <TextBlock Text="Two" />
            <Button Click="btn2_click" Content="Button2"/>
        </StackPanel>
    </ContentControl>
</Grid>

        private void btn1_click(object sender, RoutedEventArgs e)
        {
            content1.Visibility = System.Windows.Visibility.Hidden;
            content2.Visibility = System.Windows.Visibility.Visible;
        }

        private void btn2_click(object sender, RoutedEventArgs e)
        {
            content1.Visibility = System.Windows.Visibility.Visible;
            content2.Visibility = System.Windows.Visibility.Hidden;
        }

If you can put the button above like in a menu area
Can do me dynamic stuff with Frame and Page content
This example shows passing data to the Page constructor
nextPage is a Page
could also be a UserControl
<Frame Name="SrchItemEditField" />

PageDocFieldDetail nextPage = new PageDocFieldDetail(df);
SrchItemEditField.Content = nextPage;


text:
Q: Convert RTP to RTSP in Jetson Nano How Do I convert the RTP (provided by jetson.utils.videoOutput("rtp://@:1234")) to RTSP so that the same can ve streamed and be viewed over network.
I tried with FFserver as well as Streamer, but don't have much of an expertise in those.

A: The dev branch of jetson-inference/jetson-utils has native support for RTSP output. See:
https://forums.developer.nvidia.com/t/convert-rtp-to-rtsp/239731/3


text:
Q: Meteor app runnning on localhost (hosted on MacBook) does not work from other devices I have a Meteor app running on my MacBook with OSX 10.11.5 (El Capitain)
I'm trying to test my Meteor app on different devices connected to the same Wireless Network as the Mac. For that I ran ifconfig and took note of the Mac's ip (192.168.2.109). When I go to 192.168.2.109:3000 on the Mac, it works. However, it does not work in any other device.
There's also another important point: I ran the very same project from on another machine (using Ubuntu 14.04) and everything went fine. I was able to access the app from all the devices connected to the network.
Moving on, I also tried to run the app like this too (but didn't work): meteor --port=http://192.168.2.109:3000 --mobile-server=http://192.168.2.109
I checked the OSX Firewall and it's disabled.
I tried to follow the anwsers from these questions:

*

*https://forums.meteor.com/t/running-mobile-app-in-device-problems-connecting-with-server/4197/12

*Accessing Meteor local web server from another local device on Mac 10.8

*Meteor - accessing the app using public ip

*https://apple.stackexchange.com/questions/213332/how-to-access-web-dev-servers-running-on-localhost-with-non-standard-ports-from
But none of them worked.
Has anyone experienced this before? Some guidance would be appreciated! Thanks.

A: You have to set the environment variable ROOT_URL. So in your case, CLI input should be:
ROOT_URL="http://192.168.2.109" meteor --port 3000
If you are just using the default port of 3000, you don't need the --port 3000, I showed it in case you wanted to use a different port.
You can read more about environment variables here: Meteorpedia: Environment Variables It should be noted that this is an older resource not up to date with all the latest specifications. However, my search of the Meteor Guide didn't reveal the specific answer to your question.


text:
Q: Getting clicked id and using it in another function I've got a few boxes containing image, text and checkbox:

    test<input name="choice" value="1" id="test" type="checkbox" onchange="onCheckboxChanged(); checkTotal();" disabled>

I try to take the id (testbox) when I click anywhere in the label and use it in this function:
var onCheckboxChanged = function(checkbox){
var test = document.getElementById('test');
var testbox = document.getElementById('testbox');
var structure = document.getElementById('structure');
var structurebox = document.getElementById('structurebox');

if(structure.checked){
    test.disabled = false;
    structurebox.style.backgroundImage='url(green.png)';
}
else{
    test.disabled = true;
    structurebox.style.backgroundImage='url(grey.png)';
}

if(test.disabled){
    testbox.style.backgroundImage='url(red.png)';
}
else {
    if(test.checked){
        testbox.style.backgroundImage='url(green.png)';
    }
    else{
        testbox.style.backgroundImage='url(grey.png)';
    }
}
};

I can just copy/paste the code and change id's but I've got over 70 boxes and there will be more. I tried:
document.getElementsByName("skill")[0].getAttribute('id')

but it probably takes all id's from boxes with name "skill". I guess I should use something similar to this and it works but I don't know how to connect it to my code so I can use clicked id from this function in my function (as var would be the best).

A: Avoid inline javascript as muchj as you can, also instead of document.write you can use .innerHTML.
Try this to attach a onclick event listener to each label and get the clicked labels ID:
var all_labels = document.getElementsByName("skill");
for (var i = 0; i < all_labels.length; i++) {
    all_labels[i].onclick = function () {
        alert(this.getAttribute('id'));
    };
};

Demo here

A: I think your problem is that you want to code your logic only once and apply it to all your checkboxes etc, right?
If so, I think JQuery will help you alot in doing so.
I don't really know what you want to achieve but I can give you a quick example of how to make use of JQuery and the ability of JQuery to use a context to retrieve elements which logically belong to each other.
If you have a markup with tons of checkboxes and beside each box you have a text box for example like this:

    test <input name="choice" class="CheckBox" type="checkbox"/> <input type="text" class="TextBox"/>

    test <input name="choice" class="CheckBox" type="checkbox"/> <input type="text" class="TextBox"/>

    test <input name="choice" class="CheckBox" type="checkbox"/> <input type="text" class="TextBox"/>

    test <input name="choice" class="CheckBox" type="checkbox"/> <input type="text" class="TextBox"/>

You can use a simple JQuery technique to write an event when the checkbox changes and then query the related text box to do something with it:

$(".CheckBox").change(function(){
    var ctx = $(this).parent();
    var myTextBox = $(".TextBox", ctx);

    $(myTextBox).val("test");
});

I hope this is enough to help you get an idea of how this works.
To play around with it, here is the example: http://jsfiddle.net/Elak/mcEQa/1/


text:
Q: Sentence meaning in a board game Ok so this is a game where each player controlls an explorer, and at a certain time we have to choose a person to became the traitor.
The following is written:

"Oldest player (not necessarily the oldest explorer)"

In the sentence inside the () does this mean that we have to choose the oldest player (actual person) or we can choose the oldest explorer (in character)?
My doubt is because the sentence makes it (to me at least) seem like its an option not a manditory requirement so speaking in english terms only and ignoring the game rules does this mean we HAVE to pick the oldest player or its an option and we can pick the oldest explorer?
P.S the game is "betrayal at the house of the hill"

A: The meaning is the oldest player, regardless of whether their explorer is the oldest or not.
The circumlocution is required because if the oldest player might be controlling the oldest explorer, so they couldn't absolutely eliminate the possibility that the person referred to is the one controlling the oldest explorer.


text:
Q: Starting an Application via LaunchPad vs. starting via Alias from Console Mac Mini Monterey:
I have defined an Alias "jedit" to jEdit.app. If I start "jedit" from the commandline, jEdit starts and allows to edit all of my files. If I start jEdit by clicking on "jEdit.app" in the Applications-Folder, jEdit starts but most folders can not be read. I cannot modify anything.
What can I do?

A: My preferred Editor is jEdit which is implemented in Java. On my Mac mini, initially almost everything went more or less well. The problem arose, after having installed an actual Java Engine on Saturday.
Initially the JVM could not be found. Consequently jEdit could not be launched. After having fixed that problem, jEdit could only read file from the "Development"-Directory, when started via Launchpad. The behaviour is completely different, wenn jEdit is started via commandline by the mentioned Alias.
To get jEdit working properly again, it is necessary to perform some several funny steps, which are not documented and not really understandable.
Step 1
cd /Application/jEdit.app/Contents/PlugIns
ln -s <directory_to-jdk> jdk
cd ..

Edit Info.plist and add the following lines somewhere in the file
<key>JVMRuntime</key>
<string>jdk</string>

Step 2
cd ~/Library
sudo chmod a+w Application\ Support


text:
Q: How do I read a scanning electron microscopy (SEM) image and an element of the photo I'm trying to figure out the information I can take of this image. What I did found out is the following information :
The increase is 600 times.
The voltage is 30.1 kilowatts.
The relief corresponds to 0.1mm or 0.01cm.
Now, I need to choose an element of the photo and somehow measure with my own 1 or 2 cm, and then transform them in their actual sizes.
Can you help me with some guidance, please ? Thank you !


text: Q: Convert position Transform to RectTransform I made a scene in Unity before release 4.6 using Transform and since release 4.6 I'm using RectTransform. My problem is that when I attach LocalPosition from value RectTransform to Transform it's a different position and scale. How to convert value from RectTransform to Transform?


text:
Q: Allow background-image to behave like  I'm creating a homepage using Twitter Bootstrap, and I want to create a "hero image" (that does NOT use bootstrap's hero unit.) I want a large picture at the top of the page, that you can put text on. You can't use img tags because any headings you type appear below the image. I then tried using divs with background-image:, but then the image won't adjust to fit the browser, nor will the entire image appear, it just shows part of it behind the text. I tried manually setting the div size, but I want the image to automatically adjust to the browser.

A: Here is a simplistic solution that uses absolute positioning for the heading.
I have centered the text of the heading and your needs might require something other than what I have provided.
The container
 takes on the size and shape of the elements it contains, the image and the header.  Since the header is absolutely positioned it is taken out of the document flow and the div is now the same size as the image that is contained within it.  Adding position: relative; to the containing
 allows you to position the
 relative to the container
 rather than some other ancestor element like another containing
,  or .
CSS
#hero {
    margin: 0 auto;
    max-width: 800px;  /* not required for re-sizing */
    position: relative;
}
#hero img {
    max-width: 100%;  /* for re-sizing in browser */
}
#hero h2 {
    position: absolute;
    top: 65%;
    left: 0;
    width: 100%;
    text-align: center;
}

HTML

Some Heading

A: You can always try using css z-index property
#bg_img {
    position: fixed;
    z-index: -100;
}

The z-index property specifies the stack order of an element.
So whatever text/headings you have, they will always appear on the heading not behind it


text:
Q: setState to nested object delete value I have the following state:
const [state, setState] = React.useState({
    title: "",
    exchangeTypes: [],
    errors: {
        title: "",
        exchangeTypes: "",
      }
})

I am using a form validation in order to populate the state.errors object if a condition is not respected.
function formValidation(e){
    const { name, value } = e.target;
    let errors = state.errors;

    switch (true) {
      case (name==='title' && value.length < 4):
        setState(prevState => ({
            errors: {                            // object that we want to update
                ...prevState.errors,             // keep all other key-value pairs
                [name]: 'Title cannot be empty' // update the value of specific key
            }
        }))
        break;
      default:
        break;
    }

  }

When I do so, the object DOES update BUT it deletes the value that I have not updated.
Before I call formValidation
My console.log(state) is:
{
    "title": "",
    "exchangeTypes: [],
    "errors": {
            title: "",
            exchangeTypes: "",
    }
}

After I call formValidation
My console.log(state) is:
{
    "errors": {
            title: "Title cannot be empty",
            exchangeTypes: ""
        }
}

SO my other state values have disappeared. There is only the errors object.
I followed this guide: How to update nested state properties in React
What I want:
{
    "title": "",
    "exchangeTypes: [],
    "errors": {
            title: "Title cannot be empty",
            exchangeTypes: "",
    }
}

What I get:
   {
        "errors": {
                title: "Title cannot be empty",
                exchangeTypes: "",
        }
    }

A: unlike the setState in class component, setState via useState doesn't automatically merge when you use an object as the value. You have to do it manually
setState((prevState) => ({
  ...prevState, // <- here
  errors: {
    // object that we want to update
    ...prevState.errors, // keep all other key-value pairs
    [name]: 'Title cannot be empty', // update the value of specific key
  },
}));

A: Though you can certainly use the useState hook the way you're doing, the more common convention is to track the individual parts of your component's state separately. This is because useState replaces state rather than merging it, as you've discovered.
From the React docs:

You don't have to use many state variables. State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it.

So in practice, your code might look like the following:
const MyComponent = () => {
  const [title, setTitle] = useState('');
  const [exchangeTypes, setExchangeTypes] = useState([]);
  const [errors, setErrors] = useState({
    title: "",
    exchangeTypes: "",
  });

  function formValidation(e) {
    const { name, value } = e.target;

    switch (true) {
      case (name === 'title' && value.length < 4):
        setErrors({
          ...errors,
          [name]: 'Title cannot be empty'
        });
        break;
      default:
        break;
    }
  }

  return (
    ...
  );
};


text:
Q: saving a PORT as static const member How do i store a PORT or DDR or such as static const member?
What i am trying todo is, instead of using #define TEMPERATURE_PORT PORTC inside of my class header i would like to store a static const member with that value and iniziallise this inside of a settings.h to have all my defines at one place.
class Temperatur
{
private:
    static const volatile uint8_t m_port;
};

settings.h which gets included last
const uint8_t Temperatur::m_port = PORTC;

This acutally causes the
Error   24  'Temperatur::m_port' cannot be initialized by a non-constant expression when being declared

I use the assignement is inside of the settings.h which get included right after that file:
#include "Sensors/Temperatur.h"
#include "Sensors/Microphone.h"
//... some more includes here
//load the static and const settings
#include "settings.h"

This does already work for some other values but not for PORT and DDR.
Some more information:
The Port is defined as:
#define PORTC _SFR_IO8(0x08)

which is defined as:
#define _SFR_IO8(io_addr) ((io_addr) + __SFR_OFFSET)

And this is a fixed value since the __SFR_OFFSET is defined as 0x00 or 0x20 depending on some marko value.
Is it maybe the definition of the makro for the _SFR_IO8 because it has a simple calculation? If so how do i solve this?

A: This compiles fine for me:
#define __SFR_OFFSET 0x00
#define _SFR_IO8(io_addr) ((io_addr) + __SFR_OFFSET)
#define PORTC _SFR_IO8(0x08)

class Temperatur
{
private:
    static const volatile uint8_t m_port;
};

const volatile uint8_t Temperatur::m_port = PORTC;

The only thing that I found you might be missing is the volatile keyword in the assignment.


text:
Q: Efficient way of row/column sum of a IndexedRowmatrix in Apache Spark I have a matrix in a CoordinateMatrix format in Scala. The Matrix is sparse and the entires look like (upon coo_matrix.entries.collect),
Array[org.apache.spark.mllib.linalg.distributed.MatrixEntry] = Array(
  MatrixEntry(0,0,-1.0), MatrixEntry(0,1,-1.0), MatrixEntry(1,0,-1.0),
  MatrixEntry(1,1,-1.0), MatrixEntry(1,2,-1.0), MatrixEntry(2,1,-1.0),
  MatrixEntry(2,2,-1.0), MatrixEntry(0,3,-1.0), MatrixEntry(0,4,-1.0),
  MatrixEntry(0,5,-1.0), MatrixEntry(3,0,-1.0), MatrixEntry(4,0,-1.0),
  MatrixEntry(3,3,-1.0), MatrixEntry(3,4,-1.0), MatrixEntry(4,3,-1.0),
  MatrixEntry(4,4,-1.0))

This is only a small sample size. The Matrix is of size a N x N (where N = 1 million) though a majority of it is sparse. What is one of the efficient way of getting row sums of this matrix in Spark Scala? The goal is to create a new RDD composed of row sums i.e. of size N where 1st element is row sum of row1 and so on ..
I can always convert this coordinateMatrix to IndexedRowMatrix and run a for loop to compute rowsums one iteration at a time, but it is not the most efficient approach.
any idea is greatly appreciated.

A: It will be quite expensive due to shuffling (this is the part you cannot really avoid here) but you can convert entries to PairRDD and reduce by key:
import org.apache.spark.mllib.linalg.distributed.{MatrixEntry, CoordinateMatrix}
import org.apache.spark.rdd.RDD

val mat: CoordinateMatrix = ???
val rowSums: RDD[Long, Double)] = mat.entries
  .map{case MatrixEntry(row, _, value) => (row, value)}
  .reduceByKey(_ + _)

Unlike solution based on indexedRowMatrix:
import org.apache.spark.mllib.linalg.distributed.IndexedRow

mat.toIndexedRowMatrix.rows.map{
  case IndexedRow(i, values) => (i, values.toArray.sum)
}

it requires no groupBy transformation or intermediate SparseVectors.


text:
Q: VBA - Picture Excel to Outlook with image resizeing I put together a code which works pretty well, however the picture that is pasted on the email is a bit too small, I would like to make it bigger but I am struggling to find the right code.
Another issue is that the signature is right next to the picture while I would like it to be a few rows below.
Can anyone bring these two features to my code?
Sub Print_and_send()
Dim Sht As Excel.Worksheet
Set Sht = ThisWorkbook.ActiveSheet

Dim rng As Range
Set rng = Sht.Range("D3:Y42")
    rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture

Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")

Dim OutMail As Object
Set OutMail = OutApp.CreateItem(0)

Dim vInspector As Object
Set vInspector = OutMail.GetInspector

Dim wEditor As Object
Set wEditor = vInspector.WordEditor

With OutMail
    .To = "youremail"
    .CC = "youremail"

    .Subject = "Test"
    .display

     wEditor.Paragraphs(2).Range.Paste

End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub

A: You could refer to this code:
 For Each shp In wordDoc.InlineShapes
        shp.ScaleHeight = 90
        shp.ScaleWidth = 90
    Next

For more information, Please refer to this link:
Resize a pasted JPEG in a MailItem