text:
Q: Need help testing the then part after a promise I'm trying to unit test my node application and I am having challenges testing the then part after a promise inside the method I'm testing.
// toBeTested.js
const { fun1 } = require("./somejs");
const { fun2 } = require("./someotherjs");
const { fun3 } = require("./anotherjs");

exports.somefunction = ({ p1, p2, p3, p4 }) => {

    fun1(p1, p2)// fun1() returns a promise
        .then(
            results => {
                fun2(fun3(results), p3, p4);
            }
        )
}

Here's the test file, the fun2 and fun3 doesn't seem to be getting called for some reason.
// toBeTested.test.js
const { somefunction } = require("./toBeTested.js");
const { fun1 } = require("./somejs");
const { fun2 } = require("./someotherjs");
const { fun3 } = require("./anotherjs");

jest.mock("./somejs.js", () => {
    return {
        fun1: jest.fn((p1, p2) => {
            return Promise.resolve(() => {
            });
        })
    }
});

jest.mock("./someotherjs.js", () => {
    return {
        fun2: jest.fn((p1, p2, p3) => { })
    }
});

jest.mock("./anotherjs.js", () => {
    return {
        fun3: jest.fn((p1) => {
            return [];
        })
    };
});

const mockObj = {
    p1: "p1",
    p2: "p2",
    p3: "p3",
    p4: "p4"
};

afterEach(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
});

describe("Test toBeTested.js", () => {
    it("somefunction() - success", () => {
        somefunction(mockObj);
        expect(fun1).toHaveBeenCalled();
        expect(fun1).toHaveBeenCalledWith(mockObj.p1, mockObj.p2);
        expect(fun3).toHaveBeenCalled(); // Fails here
        expect(fun2).toHaveBeenCalled(); // Fails here too
    });
})

Thank you.
P.S: I'm still a beginner when it comes to jest and node js development.

A: The problem is that fun3 and fun2 are called asynchronously. You should wait to expect them after fun1 resolves:
describe("Test toBeTested.js", () => {
   it("somefunction() - success", async () => {
       somefunction(mockObj);
       expect(fun1).toHaveBeenCalledWith(mockObj.p1, mockObj.p2);
       await expect(fun1.mock.results[0]).resolves;
       expect(fun3).toHaveBeenCalled();
       expect(fun2).toHaveBeenCalled();
   });
})

References

*

*mockFn.mock.results

*.resolves


text:
Q: How to simplify the maths to determine the mutual inductance between two multi-layer rectangular coils of arbitrary dimensions? I am experimenting with wireless power transfer. The maths to directly determine mutual inductance between two multi-layer rectangular coils of arbitrary area, separated by an arbitrary distance, angle and ratio of turns is very complex mathematically.
Is there a mathematical simplification, i.e. a canonical formula that can be used for this calculation?

A: As far as I know there is no simple formula for this. You can either do a double integral to determine how the flux generated by one coil interacts with the other. Or you can do a numerical analysis using finite elements or other methods.
Or, practically, you can simply build a prototype system and measure the effect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twythonstreamer filter on a specific user I'm trying to use Twythonstreamer on a specific Twitter account and I found a thread asking the same thing from years ago, but I still can't seem to get it to work.  But maybe I misunderstood the answer.
I currently have:
stream = MyStreamer(consumer_key, consumer_secret, access_token, access_token_secret)
stream.statuses.filter(track='7831092', tweet_mode='extended')


text:
Q: How do I print characters with an index number? I am a beginner programmer swift
I have a string variable and need print characters with index
my code is :
let responcsestring = NSString(data: data, encoding: NSUTF8StringEncoding)

A: Use the substringWithRange method to generate a substring for a given range.
For example this will print the first character:
let substring = someString.substringWithRange(NSRange(location: 0, length: 1))

print(substring)

A: Another way is to use the Swift stdlib String type and access it's character array.
let responsestring = String(data: data, encoding: NSUTF8StringEncoding)
let secondCharacter = responsestring.characters[1]

Here's an interesting
Blog post about strings and their different representations in Swift.

A: be careful!! func characterAtIndex(index: Int) -> unichar returns unichar (aka UInt16)
import Foundation
var s = "alpha".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i))
}

prints
0 97
1 108
2 112
3 104
4 97
5 0

...
var s = "♡仿♥".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i), UnicodeScalar(res!.characterAtIndex(i)))

}

prints
0 9825 ♡
1 20223 仿
2 9829 ♥
3 0

not every unicode character can be represented as two bytes long sequence (UInt16)!. you are better to use swift's String type directly
var s = "".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i))

}

prints
0 55399
1 56893
2 0

even though the original string is exactly one character long.
let s = "".characters.count // 1

... you can use an index for characters view to string
let s = ""
let idx = s.characters.startIndex
for i in 0..<s.characters.count {
    print(i, s[idx.advancedBy(i)])
}

prints
0


text:
Q: How prevent editText add "." if initialized to accept float values only? editText initialized to accept float values as following
EditText in Xml
 <EditText
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_gravity="center_horizontal"
    android:inputType="numberDecimal"
    android:padding="10dp"
    style="@style/AlertDialog.AppCompat"
    android:hint="enter value"
    android:autoText="false"
    android:theme="@style/dialog_blue_button" />

i want prevent input = "." as follow
onClick event where user add input
   @Override
public void onClick(View v) {
    if (v.getId() == R.id.ok) {
        String text = edit.getText().toString();
        if (!text.matches("") && !text.matches(".")) {

            float s = Float.parseFloat(edit.getText().toString());
            if (s > 0) {
                communicator.input(s);
                dismiss();
            }
        }
    } else {
        dismiss();
    }

}

problem
this code prevent user enter single integer for example 1 or 8 not accepted but 12 accepted

A: Try this insted of your code :
@Override
  public void onClick(View v) {
      if (v.getId() == R.id.ok) {
          String text = edit.getText().toString();
          if (!text.equals("") && !text.equals(".")) {

              float s = Float.parseFloat(edit.getText().toString());
              if (s > 0) {
                  communicator.input(s);
                  dismiss();
              }
          }
      } else {
          dismiss();
      }

  }

A: Change it like this:
if (!text.isEmpty() && !text.matches("^\\.$"))

^\\. $
The ^ indicates the beginning of a String. Since . is a special char and will match any character you have to escape it with \\.
The $ indicates the end of the String. This regex will only match a String which consists of only a dot.


text:
Q: Ember association returns class instead of instance I'm using Ember 1.13, Ember data 1.13.
Whenever I do findRecord to send a request to an api endpoint, all the information gets returned correctly and is placed into the store correctly which I can view in Ember-inspector/data.
Then when I try to get an association from the main model that I requested, it gives me back a Class instead of an instance even though I can see in Ember-inspector/data that the association and both models are there.
ember-inspector

request code:
var business = this.store.findRecord('business', 1);

I've also tried with a then function:
this.store.findRecord('business', 1).then(function(business) {};

Then I try and get the association:
var businessPreference = business.get('businessPreference');

This returns a class:
Class {__ember1441932015632: null, __nextSuper: undefined, __ember_meta__: Object}

And gives me undefined if I try and get a property from it
businessPreference.get('cancellationWindow');
undefined

Notes: I am currently trying this in a component. I have injected the store in order to do this. It was also doing the same thing from the model hook but was correctly returning the association in the afterModel hook which is very strange.
UPDATE:
We are using JSONAPIAdapter and JSONAPISerializer.
business model

businessPreference model

Here is the response returned from api. This is JSONAPI 1.0 compliant. We added normalizeResponse function to JSONAPISerializer to immediately return the JSONAPI payload

A: Trylet business = this.store.findRecord('business', 1).then(function(business) {return business;}); That should return the model to the variable once the promise resolves...


text:
Q: Why i am getting heap memory issue while selecting record using queryForList() of JdbcTemplate while selecting large record (above 4000) using below code I am facing heap memory issue.
I have increase heap sizeof JVM upto 4 GB
query = "select * from  tablename where folderindex is not null and checkflag!='1' and trunc(creation_date) < trunc(sysdate-"+no_OFDays+") order by UNIQUE_ID asc";

        ds = DBConnection.getDbConnection();
        jdbcTemplate = new JdbcTemplate(ds);
        rows = jdbcTemplate.queryForList(query);
        logger.info("NO Documents at mount point: "+rows.size());

A: how many row of table?
first if many row, you must adapt fetch_size. then, it will make a network call for fetch_size.
second, use jdbcTemplete.query("...", new RowCallbackHandler() { ... }).


text:
Q: Remove Android webview margin right and left I am working on a webview app , my problem is that there is a margin on the right and left and i am a beginner i dont know how to remove them please help.
note:please be specific in your answers for eg:add this code in the full screen content in the java box called layout.
Thanks a lot in advance, here is the codes:
1- layout- full screen activity folder
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        WebView view = (WebView) this.findViewById(R.id.webView);
        view.setWebViewClient(new WebViewClient());
        view.loadUrl("http://google.com");

        view.getSettings().setJavaScriptEnabled(true);

        mVisible = true;
        mControlsView = findViewById(R.id.webView);
        mContentView = findViewById(R.id.webView);

        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

// Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);

    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

2-android manifest in the manifest folder
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eizeasta.resale">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".FullscreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

3-activity full screen in the java folder
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0099cc"
    tools:context="eizeasta.resale.FullscreenActivity">

    <!-- The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc. -->

    <TextView
        android:id="@+id/fullscreen_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:keepScreenOn="true"
        android:text="@string/dummy_content"
        android:textColor="#33b5e5"
        android:textSize="50sp"
        android:textStyle="bold" />

    <!-- This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows. -->

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        android:layout_gravity="center" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:id="@+id/fullscreen_content_controls"
            style="?metaButtonBarStyle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="bottom|center_horizontal"
            android:background="@color/black_overlay"
            android:orientation="horizontal"
            tools:ignore="UselessParent">

        </LinearLayout>

    </FrameLayout>

</FrameLayout>

A: I found the problem, just added this code and the webview fitted the fullscreen.
mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);

A: Are there any other xml files other than the one you have mentioned? You might have another layout which is the parent. The parent layout having a margin could explain whats going on.


text:
Q: Exibir input baseado no option de um select Eu quero exibir um input baseado no option que eu escolher através de um select.
Se eu selecionar 1 ele mostra o input 1, se eu selecionar 2 ele mostra o 2 mas dá um hide() no 1. Atualmente o código está assim:

$('.select').on({change: listChildren}).trigger('change');

function listChildren(){

  if ( $(this).val() != '' ) {
    children = $('option').val();
    $("#" + $(this).val() ).show();
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<select name='options' class="select">
  <option value=''>Select</option>
  <option value='option-1'>Option 1</option>
  <option value='option-2'>Option 2</option>
  <option value='option-3'>Option 3</option>
</select>

<input type="text" placeholder="exemplo 1" class="one" style="display: none" id="option-1"/>
<input type="text" placeholder="exemplo 2" class="two" style="display: none" id="option-2"/>

Estou conseguindo mostrar, mas não conseguindo fazer o hide().

A: Adicione uma class a todas as input. Depois basta colocar um hide() na class e assim no grupo e um show() pelo id no elemento específico:

      $('.select').on({change: listChildren}).trigger('change');

      function listChildren(){

        if ( $(this).val() != '' ) {
          children = $('option').val();
          $(".input").hide();
          $("#" + $(this).val() ).show();
        }

      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name='options' class="select">
      <option value=''>Select</option>
      <option value='option-1'>Option 1</option>
      <option value='option-2'>Option 2</option>
      <option value='option-3'>Option 3</option>
    </select>

    <input type="text" placeholder="exemplo 1" class="one input" style="display: none" id="option-1" />

    <input type="text" placeholder="exemplo 2" class="two input" style="display: none" id="option-2" />


text:
Q: DataTables.net Excel export returns no results in Progressive Web App I've implemented the Excel export functionality of the DataTables in my Progressive Web Application. It is working fine in mobile web browser when I'm trying to access my website directly using URL (both iOS & Android). But when I try to use it inside my app (PWA), it doesn't work.
Note: I've included only html5 buttons
iOS: It displays a blank page.
Android: Nothing happens.
var dt = $("#dt-table").DataTable({
    "ajax": {
        "url": "GetTableInfo"
    },
    "buttons": [
        {
            "extend": "excelHtml5",
            "className": "btn-sm btn-primary",
            "text": "Export",
            "title": "Weekly Report",
            "exportOptions": {
                "columns": [0,2,3,4,5,6]
            }
        }
    ],
    .....


text:
Q: how to show inverse of M-by-N data matrix using singular value decomposition? The question is from the exercise questions from the EE4595 course being taught in TUDelft. The question is as follows...

So far my attempted solution is like the following.
The discretised data equation is given by $d=G_S\cdot q$ where $G_S$ is M-by-N data matrix and $q$ is N-by-1 source vector. To arrive at $q$ we need to invert $G_S$ and since $G_S$ is non-square it is non-invertible therefore, I thought the closest we get to the solution by using pseudo inverse resulting in $q=G_S^{\dagger}d$. However, the question apparently asks us to use singular value decomposition to show this process and this is where I got stuck. Any help to solve this question would be very much appreciated. Thanks in advance!


text:
Q: Get SOAP XML before __soapCall? Is it possible to get the XML generated by SOAP Client before sending it to webservice?
I need this because response from webservice if one of parameters is really wrong I get errors like
Server was unable to read request.
---> There is an error in XML document (2, 408).
---> Input string was not in a correct format.

This typically includes firing up tcpmon or some other tcp watcher utility, capturing the webservice call, copy and paste xml to text editor and go to column 408 to see what's the problem.
I'd really like to simplify this process by getting the XML before sending it.

A: It is very, very hard (nigh impossible) to do that.  What is much easier is using the SoapClient class' built-in debugging functionality to output the request after it has been sent.  You can do that like so:
First, when creating your SOAPClient, enable tracing, like so:
$client = new SoapClient($wsdl, array('trace' => true));

Then do whatever processing is necessary to get ready to make the SOAP call and make it.  Once it has been made, the following will give you the request you have just sent:
echo("<pre>"); //to format it legibly on your screen
var_dump($client->__getLastRequestHeaders()); //the headers of your last request
var_dump($client->__getLastRequest()); //your last request

And, if you want to see the response as well, the following should work:
var_dump($client->__getLastResponseHeaders()); //response headers
var_dump($client->__getLastResponse()); //the response


text:
Q: How can I check if the current string and previous string in Python code? In this code I want to compare the previous message with the current message. So I created a variable to save the previous message. I wanted to create it as a static variable then manipulate it inside the code. but the outside the x function if I declare the variable it shows an error.
flag = 1
        previousMessage = "abc"
        def x():
             do_something
             currentMessage = m #got a string from code
             if(currentMessage==previousMessage):
         #shows error in flag and previousMessgae
         #says create parameter of previousMessage and flag
                    flag=0
                    return
             else:
               do_something
               previousNews=currentNews
               flag=1
               return
        def call():
           while True:
             if(flag==1)
                x()
                time.sleep(60)
              elsif(flag==0)
                time.sleep(60)  **strong text**
        call()

A: Not sure if this is what you need. Try adding global before flag and previousMessage to make that variable a global variable.


text:
Q: How to change the text color of one cell based on text in another group of cells I am having difficulties being able to change the color of text in a particular cell based on what is written in a different group of cells. Ex. The text in E8 is to change to green if that exact text is found in any one of the cells in F3:F5.
I have been able to do this for individual cells =SEARCH("text"$F$3) but I am having trouble writing for a group of cells.
Do I need to have 3 separate rules for this one cell? or is there a way to only have one rule?
Thanks

A: You can use conditional formatting.  The rule you want to create is:
=COUNTIF($F$3:$F$5,"text")

(Note: This is not case sensitive)

A: Provided you really only want this for a single cell, a slightly shorter formula:
=COUNTIF(F3:F5,E8)

to be applied by selecting E8, clearing any exiting CF from it and and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true: as above, then Format..., select green fill, OK, OK.


text:
Q: How to replace placeholders for environment variables in static `index.html` to actual values with brunch? I use brunch for compilation of static assets. I've an index.html containing a <script> tag with environment variable placeholders. Based on the environment I want to change the placeholders to actual values. How can I do it the simplest way using brunch?
I tried several plugins, but although sounds to be a simple task, I fail to get anything replaced.

A: You can install handlebars-brunch plugin from master, add
handlebars: {
  locals: {
    env: process.env
  }
}

to plugins in brunch-config.js, rename index.html to index.html.hbs and use it like this:
<script>
    alert("{{env.key}}")
</script>


text:
Q: Trouble finding remainder for this problem expression? $$\left[\frac{2222^{5555}}{7} + \frac{5555^{2222}}{7}\right]$$
Please guide me through steps.
Thanx..

A: We need to evaluate $$2222^{5555}+5555^{2222}\equiv?\pmod{7}$$
We have,
$$2222\equiv3\pmod{7}$$
$$3^5\equiv5\pmod{7}$$
$$5555\equiv4\pmod{7}$$
$$4^2\equiv2\equiv-5\pmod{7}$$
Can you do it now?

A: $$a^{\varphi(n)} \equiv 1 \pmod n, \text{ when } (a,n)=1$$
$$\varphi(7)=6 \Rightarrow 2222^6\equiv 1 \pmod7$$
$$2222^{5555} \pmod7=2222^{925 \cdot 6 +5} \pmod7=(2222^6)^{925} \cdot 2222^5 \pmod7 = 2222^5 \pmod7 =3^5 \pmod7=243 \pmod7=5$$
Do the same for the other one..


text:
Q: Flask-socketio instance not Emitting from an External Process (Django) Hello am trying to emit to flask-socketIO from an external python application (django) but unfortunately it is not emitting.
I have defined my flask-socket app as follows:
app.register_blueprint(views)
socketio.init_app(app, message_queue='redis://127.0.0.1:6380')

My views are as follows:
from flask import render_template
from .. import socketio
from App import socketio
from App.views import views
from flask_socketio import join_room, leave_room, emit
import cgi

def ack():
    print("cron_failedMsg was delivered")

@socketio.on('connect', namespace='/node/cron')
def ws_conn():
    print("Connected")

@socketio.on('join', namespace='/node/cron')
def on_join(data):
    print("Joined room " + data['room'])
    join_room("room_" + data['room'])
    emit('msg', {'msg': "joined room room_" +
                 data['room']}, room="room_" + data['room'])

@socketio.on('leave', namespace='/node/cron')
def on_leave(data):
    print("leaved")
    leave_room("room_" + data['room'])

@socketio.on('cron_failed', namespace='/node/cron')
def ws_cron_failed(message):
    print("Failed")
    print("sending to room " + message['room'])
    """
    socketio.emit('cron_failed', {
                  'cron_failed': cgi.escape(message['cron_failed'])}, namespace='/node/cron')
    """
    emit('cron_failedMsg', {
        'cron_failed': cgi.escape(message['cron_failed'])}, room="room_" + cgi.escape(message['room']))

Am emitting to the message queue from an external python application (Django):
from flask_socketio import SocketIO

socketio = SocketIO(message_queue='redis://' +
                            redis6380_conf.redis6380['host'] + ":" + redis6380_conf.redis6380['port'])
        socketio.emit(
            'cron_' + status, {'cron' + status: redisConnection6381.get(str(userID) + '_' + status), 'room': str(userID)}, namespace='/node/cron')

Unfortunately its not emitting from the external python process.
I've tested emission from a webpage using javascript it works but not from the external python application(Django):
var url = "http://" + document.domain + ":" + location.port;
var socket = io.connect(url + "/node/cron");
socket.emit('join',{room:""+$rootScope.Data.ID});
 socket.emit('cron_failed',{cron_failed:"ddd",room:"3"})

How do I emit from the external python application(Django)? Is there any issue with the way am emitting from the external process?
For info I followed the instructions: https://flask-socketio.readthedocs.io/en/latest/#emitting-from-an-external-process

A: Do you want to emit from the Django process to the Flask-SocketIO server? If that's what you want to do, then on the Django side you need to use a Socket.IO client. For example, this one: https://pypi.python.org/pypi/socketIO-client.
The "emit from an external process" feature of Flask-SocketIO is different. The idea is that you want several server processes to emit to the client. This feature allows the Django server to emit to the client through the Flask-SocketIO server.
From your example, it seems you were expecting the 'cron_failed' event in your Flask-SocketIO server to run when you emit from Django, but really what you are doing is sending the event of that name to the clients. Maybe what you want is to change the event name to 'cron_failedMsg' on the Django emit? That's what the client expects, it seems.


text:
Q: What is a sepset in a probabilistic graphical model? The terminology sepset is used quite often in the Probabilistic graphical models and causality. What does it mean and what is its relevance ?

A: The term sepset is used in connection with cluster graphs. A cluster graph  is a graph with nodes $C$ including a subset of variables $\{X_1, \dots, X_n\}$.
A sepset $S_{ij}$ is the subset of variables between nodes $C_i$ and $C_j$ that are in the intersection of the scopes of both nodes (scope simply means the list of variables node $C$ depends on. I.e., $S_{ij} \subseteq (Scope(C_i) \bigcap Scope(C_j)).$
If $C_i = \phi(A, B, C)$ and $C_j = \phi(B, C, D)$, then possible sepsets are:

*

*$S_{ij}^1 = \{\}$ - this means there is no edge between $C_i, C_j$

*$S_{ij}^2 = \{B\}$

*$S_{ij}^3 = \{C\}$

*$S_{ij}^4 = \{B,C\}$
The relevance of sepsets is that they determine e.g. in belief propagation whether a node $C_i$ sends a message to $C_j$ about a given variable (they only send a message containing information about a variable if it is in $S_{ij}$).


text:
Q: Pyqtgraph ImageView problem: ImageItem gets displayed outside of visible space of ViewBox I am working on a GUI that at one point should display a long horizontal ROI of a camera feed. For that I am writing a widget consisting of an ImageView that is using a ViewBox and an ImageItem and then add that widget to a constrained space on a layout of the GUI. My problem is that the image from the camera is not visible upon opening the window but 'hidden' outside of the field of view of the widget (a little bit down). Upon resizing the window, it appears centered.
This is how it looks after resizing before that it is where the arrow indicates
This is a minimal version of the display widget in question:
class CameraViewerWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.viewport = GraphicsLayoutWidget()
        self.view = self.viewport.addViewBox(lockAspect=False, enableMenu=True)
        self.img = pg.ImageItem()
        self.view.addItem(self.img)
        self.imv = pg.ImageView(view=self.view, imageItem=self.img)
        layout = self.layout()
        layout.addWidget(self.imv)
    def update_image(self, image, auto_range=True, auto_histogram_range=False):
        self.imv.setImage(image, autoRange=auto_range, autoHistogramRange=auto_histogram_range)

It is then added to the GUI via addWidget() and update_image() is called repeatedly using a QTimer.
Obviously the auto_range argument does not help here. I also tried to use the setLimits() and setRange() methods of the ViewBox but that also did not change the situation. I am suspecting that as I add this Widget to a contrained size on the layout of the main GUI (maximumSize = 100) the ImageView does not know how much space it has but I am not sure how to test that and a bit confused by the different coordinate systems used here. Did anyone encounter similar issues or is able to see my error here?


text:
Q: R language, problems with SpatialPixelsDataFrame (This question comes from https://stackoverflow.com/questions/40698369/r-language-problems-with-spatialpixelsdataframe?noredirect=1#comment68629240_40698369)
The following two scripts will generate a "SpatialPixelDataFrame" object:
# FIRST
library(rgdal)
elev.grid <- readGDAL("whatever.asc")
elev.grid <- as(elev.grid, "SpatialPixelsDataFrame")

# SECOND
library(raster)
library(SDMTools)
library(adehabitat)
elev.grid <- raster("whatever.asc")
elev.grid.asc <- asc.from.raster(elev.grid)
elev.grid.SPDF <- asc2spixdf(elev.grid.asc)

However, the first one exceeds the capability of my computing resources when applying it to big (15000 x 16000) grids, and the second one generates an object which I can't use for some of my further analyses. For example, when I use it for krige purposes
x <- krige(V3~var, points, elev.grid)

I get the following:

Error in model.frame.default(terms(formula), as(data, "data.frame"), na.action = na.fail) : invalid type (closure) for variable 'var'

Whether providing me a trick to bypass the memory/capability issue in the first case (preferably), or fixing the error generated by the second case please recommend.

A: A different way to obtain a spatial object useful for gstatpackage (krige() for Krigging) avoiding as(object,"Class") function, is convert it to SpatialPointsDataFrame and grid data.
Try this:
library(raster)
r <- raster("whatever.asc")
xy <- data.frame(xyFromCell(r, 1:ncell(r)))
v <- getValues(r)
xy[,"z"] <- v
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE


text:
Q: Why does undefined get added to my string? I am very green when it comes to understanding the basics why things happen in native js. I am curious to know why I get undefined added to my results when I concatenate the following:
function myAdd(x, y) {
  return x + y;
}

myAdd('hello' + ' ' + 'world');

Gives me "hello worldundefined"
When the following will give me more of what I am looking for:
function myAddB(x, y, z) {
  return x + y + z;
}

myAddB('hello', ' ', 'world');

gives me " hello world"
or why
function myAddC(x, y, z) {
  return x + y + z;
}

myAddC('hello' + ' ' + 'world');

Gives me "hello worldundefinedundefined"

A: Because y and z are undefined...
You only pass one String. x will have something but y and z will be undefined:
myAdd('hello' + ' ' + 'world');

'hello' + ' ' + 'world' -> is all concatenated into 1 String...

A: In your first example, you are only passing one argument to myAdd -- 'hello' + ' ' + 'world'


text:
Q: Creating and modifying new netcdf based on initial netcdf using xarray I have an xarray dataset with foll. structure:
<xarray.Dataset>
Dimensions:           (N: 5, latitude: 360, longitude: 720, time: 27)
Coordinates:
  * latitude          (latitude) float64 89.75 89.25 88.75 88.25 87.75 87.25 ...
  * longitude         (longitude) float64 -179.8 -179.2 -178.8 -178.2 -177.8 ...
  * time              (time) float64 0.0 1.826e+03 3.652e+03 5.479e+03 ...
  * N                 (N) |S1 '1' '2' '3' '4' '5'

I want to copy a handle to this dataset and remove the coordinated named 'N'.
When I do this:
new_nc = hndl_nc.copy()
new_nc.drop('N')

Subsequently, when I try to assign data to new variable in new_nc, it does not work:
new_nc['new_var'] = ...

How do I fix this?

A: drop, like most xarray methods, returns a new xarray object rather than modifying the orginal object in-place. So instead you should write
new_nc = hdnl_nc.drop('N').
Alternatively, you could Python's del keyword: del new_nc['N']


text:
Q: Calculating elapsed time with time.time() resulted in negative value I have a python app that runs a loop continuously.
XUBUNTU 20.04.
Python 3.8
To calculate the elapsed time, I use the time module. End of the loop, app sleeps to ensure the loop interval is constant. Here is a sample:
import time

scan_time = 0.1
while True:
    tic = time.time()
    do_work1()
    toc = time.time()
    et = toc - tic
    print(f"Elapsed time for Work1 was {et}")

    do_work2()
    toc = time.time()
    et = toc - tic
    print(f"Overall elapsed time was {et}")

    if et < scan_time:
        time.sleep(scan_time - et)

I had complaints from users that the app hangs from time to time. Once I observed that the
 print(f"Overall elapsed time was {et}")
had printed a large negative number (equal -6124.428).
That means the sleep time was a large positive number and indeed the app had fallen to a deep sleep.
Why on earth would the et become negative?
Thanks


text:
Q: Question about inverse in a two-step estimator as a joint GMM-estimators approach I'm reading Newey & McFadden - Large sample estimation and hypothesis testing (in the Handbook of Econometrics, Volume 4, 1994, page 2178).
My model which I'm interested in has some former estimation done before the estimation of the primary model will take place. Hence the primary model (2nd-step) includes some estimated regressors from the former step (the 1st-step).
In order to account for the first-step variance I followed the approach from Newey & McFadden here the joint GMM-conditions are defined as $\widetilde{g}\left(z,\theta,\gamma\right) = \left[g\left(z,\theta,\gamma\right),m\left(z,\gamma\right)\right]$ where $g\left(z,\theta,\gamma\right)$ are the 2nd-step conditions and $m\left(z,\gamma\right)$ are the 1st-step ones.
The usual asymptotic GMM-variance of the GMM-estimator $\widehat{\theta}$ will look like
$Var\left(\widehat{\theta}\right)$ = $\left(G^TWG\right)^{-1}\mathbb{E}\left(g(z,\theta)g(z,\theta)^T\right)\left(G^TWG\right)^{-1}$
where $g(z,\theta)$ are some moment conditions, $G = \frac{\partial\mathbb{E}\left(g(z,\theta_0)\right)}{\partial \theta^T}$ and $W$ is some weight matrix.
In order to calculate the GMM-variance for the two-step approach I need to derive $G$, $W$ and the derivative of $\mathbb{E}$.
My Question: I struggle to understand why this is true.
Let $G_\theta = \frac{\partial\mathbb{E}\left(\widetilde{g}(z,\theta_0, \gamma_0)\right)}{\partial \theta^T}$, $G_\gamma = \frac{\partial\mathbb{E}\left(\widetilde{g}(z,\theta_0, \gamma_0)\right)}{\partial \gamma^T}$, $M = \frac{\partial\mathbb{E}\left(m(z, \gamma_0)\right)}{\partial \gamma^T}$
Then $\widetilde{G}  = \frac{\partial\mathbb{E}\left(\widetilde{g}(z,\theta_0, \gamma_0)\right)}{\partial \left(\theta^T, \gamma^T\right)^T} = \begin{Bmatrix} G_\theta & G_\gamma\\ 0 & M\end{Bmatrix}$
This is easy to see but why is the inverse of $G$ this
$\widetilde{G}^{-1}  = \begin{Bmatrix} G_\theta^{-1} & -G_\theta^{-1}G_\gamma M^{-1}\\ 0 & M^{-1}\end{Bmatrix}$
I know that the derivative of a 2x2-Jacobian-matrix is if $J = \begin{Bmatrix} x_u & x_v\\ y_u & y_v \end{Bmatrix}$ where $x_u,...$ are the partial derivatives then $J^{-1} = \frac{1}{det\left(J\right)}\begin{Bmatrix} y_v & -x_v\\ -y_u & x_u \end{Bmatrix}$
But then $\widetilde{G}^{-1} = M^{-1}G_\theta^{-1}\begin{Bmatrix} M & -G_\gamma\\ 0 & G_\theta \end{Bmatrix} = \begin{Bmatrix} M^{-1}G_\theta^{-1}M & -M^{-1}G_\theta^{-1}G_\gamma\\ 0 & M^{-1} \end{Bmatrix}$
But this is not the same. What have I done wrong?

A: First of all, the formula for the inverse of $J$ has nothing to do with Jacobians, it is just the general inverse of a $2 \times 2$ matrix.
Second, using the scalar expressions in the matrix context is extremely dangerous, as the matrix multiplication is not commutative, unlike the scalar multiplication (i.e., generally $AB \neq BA$). If you are not aware of this, you have very serious gaps in your math preparedness to tackle econometrics.
The inverse of a block matrix
$$
M = \left(\begin{array}{cc}A & B \\ C & D\end{array}\right)
$$
is
$$
M^{-1} = \left(\begin{array}{cc}
 A^{-1} + A^{-1} B P^{-1} C A^{-1}
 & - A^{-1} B P^{-1}
 \\ - P^{-1} C A^{-1}
 & P^{-1}
\end{array}\right), \quad P = D - CA^{-1} B
$$
or
$$
M^{-1} = \left(\begin{array}{cc}
 Q^{-1}
 & - Q^{-1} B D^{-1}
 \\ - D^{-1} C Q^{-1}
 & D^{-1} + D^{-1} C Q^{-1} B D^{-1}
\end{array}\right), \quad Q = A - BD^{-1} C
$$
depending on which is easier to tackle. See Section 1.11 of Magnus & Neudecker (1999) and/or Exercise 5.13 of Abadir & Magnus (2005). Once again, an econometrician must have at least one of these books within an arm's length.


text:
Q: static struct initialization in c99 I have encountered a strange behaviour when using compound literals for static struct initialization in GCC in c99/gnu99 modes.
Apparently this is fine:
struct Test
{
    int a;
};

static struct Test tt = {1}; /* 1 */

However, this is not:
static struct Test tt = (struct Test) {1}; /* 2 */

This triggers following error:

initializer element is not constant

Also this does not help either:
static struct Test tt = (const struct Test) {1}; /* 3 */

I do understand that initializer value for a static struct should be a compile-time constant. But I do not understand why this simplest initializer expression is not considered constant anymore? Is this defined by the standard?
The reason I'm asking is that I have encountered some legacy code written in GCC in gnu90 mode, that used such compound literal construct for static struct initialization (2). Apparently this was a GNU extension at the time, which was later adopted by C99.
And now it results in that the code that successfully compiled with GNU90 cannot be compiled with neither C99, nor even GNU99.
Why would they do this to me?

A: C language relies on an exact definition of what is constant expression. Just because something looks "known at compile time" does not mean that it satisfies the formal definition of constant expression.
C language does not define the constant expressions of non-scalar types. It allows implementations to introduce their own kinds of constant expressions, but the one defined by the standard are restricted to scalar types only.
In other words, C language does not define the concept of constant expression  for your type struct Test. Any value of struct Test is not a constant. Your compound literal (struct Test) {1} is not a constant (and is not a string literal) and, for this reason, it cannot be used as an initializer for objects with static storage duration. Adding a const qualifier to it will not change anything since in C const qualifier has no relation whatsoever to the concept of constant expression. It will never make any difference in such contexts.
Note that your first variant does not involve a compound literal at all. It uses a raw { ... } initializer syntax with constant expressions inside. This is explicitly allowed for objects with static storage duration.
So, in the most restrictive sense, the initialization with a compound literal is illegal, while the initialization with ordinary { ... } initializer is fine. Some compilers might accept compound literal initialization as an extension.  (By extending the concept of constant expression or by taking some other extension path. Consult compiler documentation to figure out why it compiles.)

A: Interestingly, the clang does not complain with this code, even with -pedantic-errors flag.
This is most certainly about C11 §6.7.9/p4 Initialization (emphasis mine going forward)

All the expressions in an initializer for an object that has static or
  thread storage duration shall be constant expressions or string
  literals.

Another subclause to look into is §6.5.2.5/p5 Compound literals:

The value of the compound literal is that of an unnamed object
  initialized by the initializer list. If the compound literal occurs
  outside the body of a function, the object has static storage
  duration; otherwise, it has automatic storage duration associated with
  the enclosing block.

and (for completeness) §6.5.2.5/p4:

In either case, the result is an lvalue.

but this does not mean, that such unnamed object can be treated as constant expression. The §6.6 Constant expressions says inter alia:

2) A constant expression can be evaluated during translation rather
  than runtime, and accordingly may be used in any place that a constant
  may be.
3) Constant expressions shall not contain assignment, increment,
  decrement, function-call, or comma operators, except when they are
  contained within a subexpression that is not evaluated.
10) An implementation may accept other forms of constant expressions.

There is no explicit mention about compound literals though, thus I would interpret this, they are invalid as constant expressions in strictly conforming program (thus I'd say, that clang has a bug).
Section J.2 Undefined behavior (informative) also clarifies that:

A constant expression in an initializer is not, or does not evaluate
  to, one of the following: an arithmetic constant expression, a null
  pointer constant, an address constant, or an address constant for a
  complete object type plus or minus an integer constant expression
  (6.6).

Again, no mention about compound literals.
Neverthless, there is a light in the tunnel. Another way, that is fully sanitized is to convey such unnamed object as address constant. The standard states in §6.6/p9 that:

An address constant is a null pointer, a pointer to an lvalue
  designating an object of static storage duration, or a pointer to a
  function designator; it shall be created explicitly using the unary &
  operator or an integer constant cast to pointer type, or implicitly by
  the use of an expression of array or function type. The
  array-subscript [] and member-access . and -> operators, the address &
  and indirection * unary operators, and pointer casts may be used in
  the creation of an address constant, but the value of an object shall
  not be accessed by use of these operators.

hence you can safely initialize it with constant expression in this form, because such compound literal indeed designates an lvalue of object, that has static storage duration:
#include <stdio.h>

struct Test
{
    int a;
};

static struct Test *tt = &((struct Test) {1}); /* 2 */

int main(void)
{
    printf("%d\n", tt->a);

    return 0;
}

As checked it compiles fine with -std=c99 -pedantic-errors flags on both gcc 5.2.0 and clang 3.6.
Note, that as opposite to C++, in C the const qualifier has no effect on constant expressions.

A: ISO C99 does support compound literals (according to this). However, currently only the GNU extension provides for initialization of objects with static storage duration by compound literals, but only for C90 and C++.
A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.
Usually, the specified type is a structure. Assume that struct foo and structure are declared as shown:
 struct foo {int a; char b[2];} structure;

Here is an example of constructing a struct foo with a compound literal:
 structure = ((struct foo) {x + y, 'a', 0});

This is equivalent to writing the following:
 {
   struct foo temp = {x + y, 'a', 0};
   structure = temp;
 }

GCC Extension:
As a GNU extension, GCC allows initialization of objects with static storage duration by compound literals ( which is not possible in ISO C99, because the initializer is not a constant ). It is handled as if the object is initialized only with the bracket enclosed list if the types of the compound literal and the object match. The initializer list of the compound literal must be constant. If the object being initialized has array type of unknown size, the size is determined by compound literal size.
 static struct foo x = (struct foo) {1, 'a', 'b'};
 static int y[] = (int []) {1, 2, 3};
 static int z[] = (int [3]) {1};

Note:
The compiler tags on your post include only GCC; however, you make comparisons to C99, (and multiple GCC versions).  It is important to note that GCC is quicker to add extended capabilities to its compilers than the larger C standard groups are.  This has sometimes lead to buggy behavior and inconsistencies between versions.  Also important to note, extensions to a well known and popular compiler, but that do not comply with an accepted C standard, lead to potentially non-portable code.  It is always worth considering target customers when deciding to use an extension that has not yet been accepted by the larger C working groups/standards organizations. (See ISO (Wikipedia) and ANSI (Wikipedia).)
There are several examples where the smaller more nimble Open Source C working groups or committees have responded to user base expressed interest by adding extensions.  For example, the switch case range extension.

A: This is/was a gcc bug (HT to cremno), the bug report says:

I believe we should just allow initializing objects with static
  storage duration with compound literals even in gnu99/gnu11. [...]
  (But warn with -pedantic.)

We can see from the gcc document on compound literals that initialization of objects with static storage duration should be supported as an extension:

As a GNU extension, GCC allows initialization of objects with static
  storage duration by compound literals (which is not possible in ISO
  C99, because the initializer is not a constant).

This is fixed in gcc 5.2. So, in gcc 5.2 you will only get this warning when using the -pedantic flag see it live, which does not complain without -pedantic.
Using -pedantic means that gcc should provide diagnostics as the standard requires:

to obtain all the diagnostics required by the standard, you should
  also specify -pedantic (or -pedantic-errors if you want them to be
  errors rather than warnings)

A compound literal is not a constant expression as covered by the C99 draft standard section 6.6 Constant expressions, we see from section 6.7.8 Initialization that:

All the expressions in an initializer for an object that has static storage duration shall be
  constant expressions or string literals.

gcc is allowed to accept other forms of constant expressions as an extension, from section 6.6:

An implementation may accept other forms of constant expressions.

interesting to note that clang does not complain about this using -pedantic

A: Quoting the C11 standard, chapter §6.5.2.5, Compound literals, paragraph 3, (emphasis mine)

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

So, a compound literal is tread as an unnamed object, which is not considered a compile time constant.
Just like you cannot use another variable to initialize a static variable, onward C99, you cannot use this compound literal either to initialize a static variable anymore.


text:
Q: Keys with different hash code present in same bucket. C++ I created an ordered_map and inserted the following elements
  typedef std::unordered_multimap<std::string,std::string> stringMap;
  stringMap mymap;
  mymap.insert( {
            {"house","maison"},
            {"apple","pomme"},
            {"tree","arbre"},
            {"book","livre"},
            {"door","porte"},
            {"grapefruit","pamplemousse"}
            } );

When I checked the buckets, I found that there were 7 buckets.
This is what I read:
    The elements of an un_ordered associative container are organized into  buckets. Keys with the same hash code appear in the same bucket
But when I printed the hash code of the keys, I found that there are elements present in a bucket with different hash codes.
#include <iostream>
#include <string>
#include <unordered_map>
int main ()
{
  typedef std::unordered_multimap<std::string,std::string> stringMap;
  stringMap mymap;
  mymap.insert( {
            {"house","maison"},
            {"apple","pomme"},
            {"tree","arbre"},
            {"book","livre"},
            {"door","porte"},
            {"grapefruit","pamplemousse"},
            } );

  unsigned n = mymap.bucket_count();
  unsigned s = mymap.size();

  std::cout << "mymap has " << n << " buckets.\n";
  std::cout << "mymap size " << s << " keys.\n";

  stringMap::hasher fn = mymap.hash_function();

  for (unsigned i=0; i<n; ++i)
  {
    std::cout << "bucket #" << i << " contains: " << std::endl;;
    for (auto it = mymap.begin(i); it!=mymap.end(i); ++it)
    {
      std::cout << "[" << it->first << ":" << it->second << "] ";
      std::cout << "KEY HASH VALUE: " << fn (it->first) << std::endl;
    }

    std::cout << "\n";
  }

  return 0;
}

Could anyone please tell, if I'm missing anything and why Elements with different hash codes and present in same bucket.
Results:
mymap has 7 buckets.
mymap size 6 keys.
bucket #0 contains:
[book:livre] KEY HASH VALUE: 4190142187
[house:maison] KEY HASH VALUE: 4227651036

bucket #1 contains:

bucket #2 contains:

bucket #3 contains:
[grapefruit:pamplemousse] KEY HASH VALUE: 3375607049
[tree:arbre] KEY HASH VALUE: 335777326

bucket #4 contains:

bucket #5 contains:
[apple:pomme] KEY HASH VALUE: 2758877147

bucket #6 contains:
[door:porte] KEY HASH VALUE: 3658195372

Thanks

A: That's normal. If you have a 32 bit hash code, you don't want 2^32 buckets. Instead, the hash code is mapped to the index of a bucket. For example if you have 7 buckets, an item might use bucket #(hash % 7). So the items with hash codes 0, 7, 14, 21, ... and so on all appear in the same bucket.


text:
Q: Discord.py | Trying to dm user and getting AttributeError: 'NoneType' object has no attribute 'send' I'm trying to dm user when bot just started, and it gets error. When I print user variable it shows me None, but why it is None if id is right? Code is taken from discord.py documentation, so I feel kinda stupid :'d
@bot.event
async def on_ready():
    user = bot.get_user(427406422733619200)
    await user.send('Oh no.. I\'m alive..')

A: Replace user = bot.get_user(427406422733619200) with user = await bot.fetch_user(427406422733619200)
This works because bot.get_user fetches the user object from a cache which may have not been populated right when the bot starts.
However, bot.fetch_user fetches the User object from the discord servers, which is also why you need to use the await keyword.


text:
Q: Changing visual studio compiler version Visual Studio is compiling Asp.Net to 4.0, but I need it to compile to 3.5.  Where do I change this?
According to this (right click project, property pages, build) it is targeting 3.5, but I'm fairly certain based on the errors I'm getting with install that it's requiring 4.0 components.

A: Have you checked the <compilation> section of the Web.config file? If it still reads targetFramework="4.0" try removing/changing this value. This has worked for me in the past.

A: Don't forget, it doesn't matter what you version you compile too, if the web server is configured to run your app under a particular version, it will do. Some ways will work, ie compiled to 3.5 will work in 4.0 app pool. other way round won't.
On IIS7 the version is defined in the app pool associated with your app. IIS6 it's in the ASP.Net tab.

A: manually in the  web.config  file
And Automatically in visual studio, in the solution explorer, right click (in the web icon not in the solution icon) -> property pages -> build -> target framework -> change value.
You can check it, viewing the web.config.

name="system.web.extensions"
  type="System.Web.Configuration.SystemWebExtensionsSectionGroup,
  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,

it indicate that the web is using net framework 3.5


text:
Q: Proof about cubic $t$-transitive graphs I am reading "Algebraic Graph Theory" by Norman Biggs (1974). On page 119, there is a proposition which says the following:

Proposition 18.1: Let $[\alpha]$ be a $t$-arc in a cubic $t$-transitive graph $X$. Then
  an automorphism of $X$ which fixes $[\alpha]$ must be the identity
  automorphism.

To understand the Proposition, and the proof, some definitions and lemmas are needed. A $t$-arc is defined as follows:

A $t$-arc in a graph $X$ is an ordered set $[\alpha] =
 (\alpha_0,\ldots, \alpha_t)$ of $t+1$ vertices in $V(X)$, such that
   $\alpha_i \alpha_{i+1} \in E(X)$ and $\alpha_{i-1} \neq \alpha_{i+1}$
   for $1 \leq i \leq t-1$.

We can concatenate such arcs by the following definition

If $[\alpha]$ is a $t$-arc in a graph $X$ and $[\beta]$ is a $s$-arc in $X$, then we use $[\alpha . \beta]$ to denote the $(t+s+1)$-arc  $(\alpha_0,\ldots,\alpha_t,\beta_0,\ldots,\beta_s)$, provided that $\alpha_t \beta_0 \in E(X)$, $\alpha_{t-1} \neq \beta_0$ and $\alpha_{t} \neq \beta_1$.

We also need the term succesive arcs

Let $[\alpha]$ and $[\beta]$ be any two $s$-arcs in a graph $X$. We say that $[\beta]$ is a successor of $[\alpha]$ if $\beta_i = \alpha_{i+1}$ $(0 \leq i \leq s-1)$.

We also need a Lemma which states

Lemma 17.4: Let $X$ be a connected graph in which the degree of each vertex is at least three. If $s \geq 1$ and $[\alpha],[\beta]$ are any two $s$-arcs in $X$, then there is a finite sequence $[\alpha^{(i)}]$ $(1  \leq i \leq l)$ of $s$-arcs in $X$ such that $[\alpha^{(1)}] = [\alpha]$, and $[\alpha^{(l)}] = [\beta]$, and $[\alpha^{(i+1)}]$ is a successor of $[\alpha^{(i)}]$ for $1 \leq i \leq s-1$.

and at last a Theorem which says

Theorem 17.5: Let $X$ be a connected graph, where all vertices in $V(X)$ are at least 3 and let $[\alpha]$ be a $t$-arc in $X$. Suppose the vertices adjacent to $\alpha_t$ are $\alpha_{t-1}$ and $v_1,v_2,\ldots,v_l$, and let $[\beta^{(i)}]$ denote the $t$-arc $(\alpha_1,\alpha_2,\ldots,\alpha_t,v_i)$ for $1 \leq i \leq l$, so that each $[\beta^{(i)}]$ is a successor of $[\alpha]$. Now $Aut(X)$ is transitive on $t$-arcs if and only if there are automorphisms $g_1,g_2,\ldots,g_l$ in $Aut(X)$ such that $g_i[\alpha] = [\beta^{(i)}] (1 \leq i \leq l)$.

The proof of the proposition goes as follows:

Proof of Proposition 18.1: Suppose $f$ is an automorphism fixing $\alpha_0,\alpha_1,\ldots,\alpha_t$; if $f$is not the identity, then $f$ does not fix all $t$-arcs in $X$. Thus, it follows from Lemma 17.4 that there is some $t$-arc $[\beta]$ such that $f$ fixes $[\beta]$, but $f$ does not fix both successors of $[\beta]$. In fact, if $\beta_{t-1},u_1,u_2$ are the vertices adjacent to $\beta_t$, then $f$ must interchange $u_1$ and $u_2$. Let $w \neq \beta_1$ be a vertex adjacent to $\beta_0$. Since $X$ is $t$-transitive there is an automorphism $h \in Aut(X)$ taking the $t$-arc $(w,\beta_0,\ldots,\beta_{t-1})$ to $[\beta]$, and we may suppose the notation chosen so that $h(\beta_t) = u_1$. Then $h$ and $fh$ are automorphisms of $X$ taking the $(t+1)$-arc $[w.\beta]$ to its two successors, and by Theorem 17.5, $Aut(X)$ is transitive on $(t+1)$-arcs. This contradicts our hypothesis, and so we must have $f = 1$.

I have some problem understanding parts of the proof. The first thing, which is not really essential for proving the proposition, is the part:

In fact, if $\beta_{t-1},u_1,u_2$ are the vertices adjacent to $\beta_t$, then $f$ must interchange $u_1$ and $u_2$

The other problem, which is quite essential to the proof, is the part:

Since $X$ is $t$-transitive there is an automorphism $h \in Aut(X)$ taking the $t$-arc $(w,\beta_0,\ldots,\beta_{t-1})$ to $[\beta]$, and we may suppose the notation chosen so that $h(\beta_t) = u_1$. Then $h$ and $fh$ are automorphisms of $X$ taking the $(t+1)$-arc $[w.\beta]$ to its two successors

I get why there must be such a $h$, taking $(w,\beta_0,\ldots,\beta_{t-1})$ to $[\beta]$. But I do not get, why we can (without loss of generality) assume that $h(\beta_t)$ is a neighbor of $\beta_t$. Thus, I do not see how the other part; that

$h$ and $fh$ are automorphisms of $X$ taking the $(t+1)$-arc $[w.\beta]$ to its two successors

is true.
This question has become rather long, and I have surely missed a definition of something. Everything in gray, can be found in Biggs 1974, on pages 112-115. I have understood the proof of Theorem 17.5, but the proof of Proposition 18.1 uses some arguments, which are non-obvious to me.

A: In the end, I found the missing argument. It is a rather simple one, but I did not see it at first. In fact, both of the questions I raised about the proof, needed the same argument, and I found out, that the statement:

In fact, if $\beta_{t-1},u_1,u_2$ are the vertices adjacent to $\beta_t$, then $f$ must interchange $u_1$ and $u_2$

is essential to the proof. The reason that the above statement is correct, is that an automorphism on a graph, preserves neighbors. That is, for a graph $X$; then if $v,u \in V(X)$ are neighbors, and $\pi$ is an automorphism on $X$, then $\pi(v),\pi(u)$ are also neighbors.
Using this knowledge of automorphisms on graphs, we can see, that if $f$ fixes $\beta_t$, but does not fix both of the successors of $[\beta]$ $u_1$ and $u_2$, then $f$ has to interchange $u_1$ and $u_2$ to preserve the neighborhood of $\beta_t$.
The same argument applies for the part:

Since $X$ is $t$-transitive there is an automorphism $h \in Aut(X)$ taking the $t$-arc $(w,\beta_0,\ldots,\beta_{t-1})$ to $[\beta]$, and we may suppose the notation chosen so that $h(\beta_t) = u_1$. Then $h$ and $fh$ are automorphisms of $X$ taking the $(t+1)$-arc $[w.\beta]$ to its two successors

since we now know that $u_1$ is a neighbor of $\beta_t$, even after applying $h$.


text:
Q: PHP array_push causes the script to stop I have two arrays, one containing user information and another one containing ids about user from the first array that I don't want to be selected.
I want to insert into a new array data from the first one that are not in the second array.
while ( count( $new_array) < 50 )
    {
        $index = array_rand($array_1);

        if ( ! in_array( $array_1[$index]['id'], $array_2) )
        {
            array_push( $new_array, $array_1[$index] );
            array_push( $array_2, $array_1[$index]['id'] );
        }
    }

When data are selected from the $array_1 I insert them in $array_2 in order for it not to be selected again. This works if the while loop does not run more than 12 times, but more than that it runs for more than 30 seconds causing the script to stop.
What can be the problem?

A: Instead of attempting to keep track of which index has already been randomly selected from array1, just remove that item from the array after it's been selected. If you need to keep the original array unchanged, start by duplicating it.


text:
Q: How to find Laurent expansion of $f(z)$ I want to know the Laurent expansion of $f(z)=\frac{z^2}{1-e^z}$ centered at $z=2k\pi i $ with $k\in \mathbb{Z}$ and $k\neq 0$.
I tried using the expansion of $e^z$ or the geometric series but with no sucess.


text:
Q: accessing web.xml params inside a contextInitializer class so several articles describe how to configure spring.profiles.active inside a contextInitializerClass. You'd add something like the below to web.xml:
<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.mycompany.SpringProfileInitializer</param-value>
</context-param>

And the corresponding class:
public class SpringProfileInitializer implements       ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {

        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        environment.setActiveProfiles( getActiveProfiles(NEED_PARAM_HERE) );
    }

}

But i need to get an argument into the call to getActiveProfiles() above; just a string will do, as long as it's "somewhere" in the web.xml file.
How can i do this?
Thx.
EDIT: Just to back up a step, the problem i'm really trying to solve is the notion of multiple wars running in one JVM, each wanting a different spring.profiles.active property, AND, the value of spring.profiles.active is going to be env-specific, sitting inside some property file.
Clearly, i can't use -Dspring.active.profiles, since this is global to the JVM. We already have a per-war properties file that is env-specific, each war knows how to pull this prop file in by using a PropertyPlaceholderConfigurer. Adding the spring.profiles.active property to this prop file doesn't work (presumably it's too late in the process). Note that these war-specific prop files are all installed in some known location on disk, with some war-specific name.
Now, i can solve my problem in 2 ways using ApplicationContextInitializer as described above.
1) I can simply have a new class per war that implements ApplicationContextInitializer, likely extending some "base" class that does the real work. The class-per-war will simply hardcode the name of the prop file, read it in, and pull out the spring.profiles.active property.
2) I can create a war-specific prop file with the same name across wars, call it spring-profile-loc.properties. This file will contain just one property, the name of the aforementioned war-specific prop file. In this scenario, there is just the SpringProfileInitializer class i have above, and it just reads in this spring-profile-loc.properties file, pulls out the single prop, and then reads in the real prop file to access the spring.profiles.active prop (there are other variants of this idea as well).
I'm not fond of either approach, they seem clunky and roundabout. It would be simpler if i can just "configure" something in the web.xml and access it directly in my impl of ApplicationContextInitializer.
But if there's some completely different approach to solving this, i'm all ears.
Thx.

A: you can try to implement ServletContextAware and then use servletContext.getInitParameter() (or getAttribute() ?)
but i don't know if getting servletContext injected at this point works

A: You can activate profiles by this in the web.xml file:
In your Dispatcher Servlet's init-param:
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>myenv</param-value>
    </init-param>
</servlet>

Or per this
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>profileName</param-value>
</context-param>


text:
Q: Collect terms in inverse powers of three variables I have the following expression

-(((-(L/r1) + L/r2)^2*(L/r1 - L/r3)^2*(-(L/r2) + L/r3)^2)/(1 + 1/r1 + 1/r2 + 1/r3)^2) + (1 + L^2/r1 + ((-(L/r1) + L/r2)*(L/r1 - L/r3))/(1 + 1/r1 + 1/r2 + 1/r3))*
   (1 + L^2/r2 + ((-(L/r1) + L/r2)*(-(L/r2) + L/r3))/(1 + 1/r1 + 1/r2 + 1/r3))*(1 + 1/r1 + 1/r2 + 1/r3)*(1 + ((L/r1 - L/r3)*(-(L/r2) + L/r3))/(1 + 1/r1 + 1/r2 + 1/r3) +
    L^2/r3)

Which I want to rewrite by collecting according to the inverse powers of r1, r2 and r3. That is, I want to get

1 + (1 + L^2)/r1 + (1 + L^2)/r2 + (1 + L^2)/r3 + (3*L^2 + L^4)/(r1*r2) + (3*L^2 + L^4)/(r1*r3) + (3*L^2 + L^4)/(r2*r3) + (9*L^4 + L^6)/(r1*r2*r3) -
   L^6/(r1^2*r2^2) - L^6/(r1^2*r3^2) - L^6/(r2^2*r3^2) + (2*L^6)/(r1*r2*r3^2) + (2*L^6)/(r1*r2^2*r3) + (2*L^6)/(r1^2*r2*r3)

I have done this by hand, but for more complciated expressions I want to use Mathematica. I tried Collect[expression,{r1,r2,r3},Simplify] but it did nothing for me. Also, I do not want to collect in powers of L.

A: Here is a pretty manual approach:
Total[
  Simplify@*Total /@
    GatherBy[
      List @@ Expand[FullSimplify@expr],
      Denominator
    ]
]

A: Total @ Factor @ MonomialList[Simplify @ expr, 1/{r1, r2, r3}]

To have the terms in a specific order, sort the monomials as you like and wrap the resulting list with Apply[Defer @* Plus]:
Apply[Defer @* Plus] @
  SortBy[Through @ {Total, Sort} @ Exponent[#, 1/{r1, r2, r3}] &] @
    Factor @ MonomialList[Simplify @ expr, 1/{r1, r2, r3}]

Using an alternative ordering of terms:
Apply[Defer @* Plus] @ Factor @
   MonomialList[Simplify @ expr, 1/{r1, r2, r3}, "NegativeDegreeReverseLexicographic"]


text:
Q: Angular - How to remove padding-right from mat-list-text? I am trying to add a button to a mat-list-item. This is my current HTML template code:
<mat-selection-list
  [multiple]="false"
  [class.selected]="currentItem"
  formControlName="itemListControl"
>
  <mat-list-option
    *ngFor="let item of items"
    [value]="item.id"
  >

        {{ item.name }}

      <button mat-icon-button>
        <mat-icon>edit</mat-icon>
      </button>

  </mat-list-option>
</mat-selection-list>

When I inspect the site in my browser, I can see that there is a 16px padding which moves the button to the left inside the list item:

I already tried removing it by adding this to my scss file for the component:
.mat-list-item {
  padding-right: 0 !important;
}

For some reason, this does not have any effect. It seems like this is not even applied at all to the element. What am I doing wrong and how can I get rid of this padding (without causing any potentially bad side effects)?

A: Please use like below. It would work.
.mat-list-text {
  padding-right: 0 !important;
}

Thanks!

A:
Use the whole selector(instead of just .mat-list-text, copy all the selector part of the css highlighted in the image above) to remove the the padding, angular material is very hard to modify. Dont forget to add the !important aswell. I had to do this previously. I hope it will work for you aswell.


text:
Q: How do you get the default compatibility level in Azure SQL Database from T-SQL? In on-prem SQL Server you can check the server version and multiply by 10 to get the maximum compatibility level supported by the server, or check the compatibility level of the model database to get the default compatibility level new databases will be created with.
In Azure SQL Database, neither of these work; the server version stays at 12 even though the maximum compatibility level is 140, and there isn't a model database to check against.
How do you find out what the current default compatibility level is in Azure SQL Database, from T-SQL? In other words, I want a T-SQL query that would have returned 130 if run before 18th Jan 2018, returns 140 if run today, and will return 150 whenever Azure updates to a default compatibility level of 150.

A: I couldn't find anything specifically documented for this, but:
SELECT SERVERPROPERTY('ResourceVersion');

...currently returns "15.00.2000" for Azure SQL Database, which may be useful to you.
I had thought you might be able to query:
SELECT H.[name]
FROM sys.dm_exec_valid_use_hints AS H
WHERE H.name LIKE N'QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_%';

...but that returns:

name

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_100

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_110

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_120

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_130

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_140

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_150

QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_160

...which are all valid hints, but 150 is the maximum you can set database compatibility to at the time of writing.

A: There isn't a clean way that I know of. You could try set them all incrementally then see what the final value is. That will return the current maximum:
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'ALTER DATABASE '+DB_NAME()+' SET COMPATIBILITY_LEVEL = 130'; EXEC (@SQL)
SET @SQL = 'ALTER DATABASE '+DB_NAME()+' SET COMPATIBILITY_LEVEL = 140'; EXEC (@SQL)
SET @SQL = 'ALTER DATABASE '+DB_NAME()+' SET COMPATIBILITY_LEVEL = 150'; EXEC (@SQL)
SET @SQL = 'ALTER DATABASE '+DB_NAME()+' SET COMPATIBILITY_LEVEL = 160'; EXEC (@SQL)
SET @SQL = 'ALTER DATABASE '+DB_NAME()+' SET COMPATIBILITY_LEVEL = 170'; EXEC (@SQL)
SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()
-- currently returns compatibility_level=150

Obviously you don't want to do this on an active application database as changing the levels could have consequences for the application users.
The test above uses ad-hoc SQL because otherwise the later versions fail syntax check without it even trying the rest, and you have to hard-code the database name. In SSMS or similar you could get around the first issue by breaking the batch into multiple:
ALTER DATABASE test_clvl SET COMPATIBILITY_LEVEL = 130
GO
ALTER DATABASE test_clvl SET COMPATIBILITY_LEVEL = 140
GO
ALTER DATABASE test_clvl SET COMPATIBILITY_LEVEL = 150
GO
ALTER DATABASE test_clvl SET COMPATIBILITY_LEVEL = 160
GO
ALTER DATABASE test_clvl SET COMPATIBILITY_LEVEL = 170
GO
SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()

If you can use outside tools, then script up a database create, then find the level from master.sys.databases, then drop the test DB, using powershell or similar.
In any case you'll need to ignore the error responses to the later versions. Perhaps TRY/CATCH can make this cleaner, but I'll leave you to play with that.

A: Azure SQL Database runs the latest version of SQL Server under the hood. Do not get confused with the Azure Sql version which would be 'Microsoft SQL Azure (RTM) - 12.0.2000.8 '
So if you see we have SQL Server 2019 with compatibility 150 and should be available on your Azure database.


text:
Q: Access. Alternative for left function i am trying to write a query using left function in access to take only the first 3 characters of a field.
Is there any alternative method for performing the same process without using left
Usage of left function shows a compile. error all of a sudden without any reason. If i copy the table and query to a new database it works fine for a while before the error comes again. This happens only on the usage of Left function.

A: The compile error is showing up because you have a missing reference.  Open any module and check the References.

A: you can use mid function:
Mid (Field, 1, 3)

A: You can always try Mid
Mid([field1],1,3)

A: It sounds very like you have a problem with your references. Look for any references marked "MISSING". Also try to delete Visual Basic for Applications, it won't allow this, but it sometimes corrects the problem. Finally, check the details of Visual Basic for Applications and make sure that is available in the stated location. Any alternative to Left will be affected by this problem.
This problem is frequently associated with a missing reference that you would not think had anything to do with Left.

A: Run the following code and report back as to the results.   Also tell us what version of Access you are running.
Sub ViewReferenceDetails()

Dim ref As Reference

    For Each ref In Access.References
        Debug.Print ref.Name & " - " & ref.Major & "." & ref.Minor & " - " & ref.FullPath
    Next ref

End Sub


text:
Q: Realizability of extensions of a free oriented matroid by an independent set Question:
I am searching for a non-realizable matroid with few dependencies relative to the number of points. Precisely, I would like to find a non-realizable (over $\mathbb{R}$) oriented matroid $M$ on a set $A\cup B$ such that $A$ is a basis of $M$, and $B$ is independent in $M$. Can there be such an example? I would also be very interested to hear about any known results concerning the spaces of realizations of such oriented matroids.
Motivation and background:
There are many known explicit non-realizable oriented matroids. However, all the examples I have found in the literature seem to rely on having a low rank relative to the number of points. For instance, here are depictions of two well-known (minimal) examples of non-realizable oriented matroids, both of rank three on nine points: the non-Pappus pseudo-line arrangement, and its perturbation given by Ringel's uniform oriented matroid. In both cases, the non-realizability amounts to the impossibility of straightening the curved lines.

A: I believe you can take one of the low rank examples, such as Ringel's, and simply take the dual. Since Ringel's is on 9 points, with rank 3, the dual is on 9 points with rank 6.
@RicardoAndrade, I wrote some code to test this on a range of oriented matroids. My results are as follows:
ceva:            good =  31; not basis =  4; bad = 0
πάππος:          good =  75; not basis =  9; bad = 0
ringel:          good =  84; not basis =  0; bad = 0
tsukamoto13[+1]: good = 267; not basis = 19; bad = 0
tsukamoto13[0]:  good = 266; not basis = 20; bad = 0
tsukamoto13[-1]: good = 267; not basis = 19; bad = 0
circularsaw3:    good =  35; not basis =  0; bad = 0
Ω14[+1]:         good = 334; not basis = 30; bad = 0
Ω14[0]:          good = 333; not basis = 31; bad = 0
Ω14[-1]:         good = 334; not basis = 30; bad = 0
suvorov14:       good = 331; not basis = 33; bad = 0

For each of the dual oriented matroids, I took each r element subset of the n elements. If they were independent forming your A and the remaining set, your B, was also independent, I counted this as good; if the r element subset were dependent I added to the not basis count. The bad count, always 0, is when the A set was a basis, and the remainder was not independent.
So I conclude that while your observation that while every r element subset for a uniform oriented matroid will satisfy your conditions, the restriction to uniformity is pretty strong and unnecessary.
@Ricardo I am sorry to keep posting up here, but I want an image this time:

This one is all bad ... i.e. wheel12: good = 0; not basis = 165; bad = 55
I think my main observation is that my interest is pseudoline stretching, i.e. rank 3 oriented matroids, typically 'interesting' ones. This wheel is not very interesting for me. Whenever a lot of pseudolines meet at a single point, then the dual of the rank 3 oriented matroid will tend to have small dependent sets, and so not have the property you are interested in. But the oriented matroids of interest to me, are rank 3, and typically at each vertex have only two or three lines, maybe four meeting, so that every convector has at least n-4 elements, and all sets of size 3 are independent (in the dual), so that your property is trivial for any basis of the dual. In summary I think the fact that the bad column is always 0 is just an artifact of my interest versus yours.


text:
Q: Cannot serializing sorted dictionary to JSON - Swift 3 Cannot serialize my sorted dictionary into JSON via JSONSerialization.data(withJSONObject:options:)
Serialization works with unsorted dictionary, but with sorted app throws error with description:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

Here is how my method looks like:
func createJSONFile(){
    // create path to json file
    let fileManager = FileManager.default
    let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectory = urls[0] as NSURL
    guard let jsonURL = documentDirectory.appendingPathComponent("graphData") else {
        print("Failed to create path to json file.")
        return
    }

    print(jsonURL.absoluteString)
    // creating a .json file in the Documents folder
    if !fileManager.fileExists(atPath: jsonURL.absoluteString){
      fileManager.createFile(atPath: jsonURL.absoluteString, contents: nil, attributes: nil)
        print("file created")
    }

    do {
        let unsortedDic = self.tempDictionaryForJsonFile
        let sortedDic = unsortedDic.sorted(by: <)
        let jsonData = try JSONSerialization.data(withJSONObject: sortedDic, options: .prettyPrinted)
        print(jsonData)
        try jsonData.write(to: jsonURL)

        print(fileManager.fileExists(atPath: jsonURL.absoluteString))

        let content = try String.init(contentsOf: jsonURL, encoding: .utf8)
        print(content)

    } catch {
        print(error.localizedDescription)
    }
}

It is interesting that in inspector while debugging unsorted dictionary looks like this: unsorted dictionary and sorted looks like this sorted dictionary
Please help in solving this issue.

A: First, there are no sorted directories in Swift stdlib (or in JSON for that matter; JSON objects are unordered). When you call .sorted() on a dictionary, it returns an array of key/value pairs [(Key, Value)].
JSONSerialization has rules about what it can serialize:

*

*The top level object is an NSArray or NSDictionary.

*All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

*All dictionary keys are instances of NSString.

*Numbers are not NaN or infinity.
There are implicit bridges from NS-compatible collections to their NS equivalent, but you only get this if the contents can be expressed in ObjC (and (Key, Value) can't be).
How to implement this correctly depends heavily on the type and contents of tempDictionaryForJsonFile which aren't given here. It also depends on what you're trying to achieve with a "sorted dictionary" (which doesn't exist in JSON, so there's no way to get to it from Swift). If you mean "an ordered array of JSON objects, each with one key/value," that can be built (but you'll need to support it in whatever is consuming this data).


text:
Q: Simple .NET file system persistence? I need to store some simple data (just some POCO objects with a few attributes, nothing fancy).
public class MyPOCO
{
    public int Id {get; set;}
    public string Title {get; set;}
    public string Email {get; set;}
    // ...
}

Basically, at some point of my web application I need to check if the MyPOCO object is already persisted (matching by Id), and if it's not, persist it. That's all I need.
It can't be any database, so probably XML or JSON. What's an easy way (or Nuget package) to store it?

A: I suggest to use a in-process database like SQL Server CE or SQLite together with an O/R mapper. This is easier and more maintainable than reinventing a small database.


text:
Q: How to make a formula-based cell read-only in MS Excel? I'm trying to create a unique ID for each row in Excel, based on the formula [RowNum + X] (X is given).
The formula autocompletes on each new row, based on Excel Tables.
After creating the new row, I wish to make the ID cell Read-Only, thus not changeable afterwards.
Is this possible?

A: You can lock cells in a sheet.
First, you can just turn off the protection settings on all the cells of your sheet by selecting all of them (Ctrl+A) go to their properties (Ctrl+1) and in the protection tab uncheck Locked.
Then, turn it on only for the cells you want to protect. By selecting them and checking the Locked property the same way you unchecked it before.
To conclude, in the review tab click the Protect Sheet button to enforce the settings.
This should make people unable to change the formula in your ID column.


text:
Q: What is Activity Score in MIKROS? I'm currently checking out the MIKROS documentation and have trouble understanding what the Activity Score is. I understand that people who spend more time on your games are ranked higher, but what do the associated categories mean?

A: Players are ranked into three categories based on the Activity Score they have.
Players with an Activity Score of 8-10 are classified as "Legendary" players. They spend a great majority of their free time playing games, and thus, are a highly sought-after type of player.
Players with an Activity Score of 5-7 are classified as "Core" players. While not as dedicated as the "Legendary" players, these players still enjoy playing games. They just prefer to play games from varying genres.
Players with an Activity Score less than 5 are classified as "Casual" players. These players don't invest significant time into a certain game, and just play whenever they feel like it.


text:
Q: How can I assign a boolean condition result to a scalar variable in perl? I am doing the following, but it is not working properly:
    my $enabled = $hash &&
                  $hash->{'key'} &&
                  $hash->{'key'}->{'enabled'} &&
                  $hash->{'key'}->{'active'};

Is this an acceptable way to assign a boolean value to a scalar variable?
My code is misbehaving in strange ways, as it is, and I believe it is because of this assignment. I have validated that the individual values exist for all of these keys and are set to a value.
P.S. Sorry for being a noob! I googled for ~10 minutes and couldn't find the answer anywhere.

A: The Perl boolean operators like &&, ||, and, or don't return a boolean value, they return the value of one of their arguments:
say 2 && 3;

outputs 3.
You can force it to a boolean with the double negation trick:
say !!(2 && 3);
# or
say not not 2 && 3;

outputs 1.


text:
Q: Change icon of moving marker of Google Map I have a code which moves between lattitude and longitude on google map. I want to change the icon of the marker and also align the map in between of start points of lattitude, longitude and end points of lattitude, longitude. Please can you guys help me? Thanks in advance
Here's my code:
<script>
var markers = [];
function initialize() {

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: new google.maps.LatLng(<?php echo $mapdata->deplat?>,<?php echo $mapdata->deplng;?>),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var startPos = new google.maps.LatLng(<?php echo $mapdata->deplat?>,<?php echo $mapdata->deplng;?>);
var endPos = new google.maps.LatLng(<?php echo $mapdata->arrlat?>,<?php echo $mapdata->arrlng;?>);

// generate fake points for route
var pointsNo = 80;
var latDelta = (endPos.lat() - startPos.lat()) / pointsNo;
var lngDelta = (endPos.lng() - startPos.lng()) / pointsNo;
var positions = [];
for (var i = 0; i < pointsNo; i++) {
    var curLat = startPos.lat() + i * latDelta;
    var curLng = startPos.lng() + i * lngDelta;
    positions.push(new google.maps.LatLng(curLat, curLng));

    var curMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(curLat, curLng),
        visible: false
    });
    markers.push(curMarker);
}
}

function displayMarker(markers, index, delay) {
if (index > 0)
    markers[index - 1].setVisible(false);
else {
    markers[markers.length - 1].setVisible(false);
}

markers[index].setVisible(true);
if (index < markers.length - 1) {
    setTimeout(function () {
        displayMarker(markers, index + 1, delay);
    }, delay);
} else {
    displayMarker(markers, 0, delay);
}
}

//google.maps.event.addDomListener(window, 'load', function() {
initialize();
//});

$('input[type=button]').click( function() {
var delay = 40;
displayMarker(markers, 0, delay);
});
</script>


text:
Q: CrashPlan requests network connection on startup Since upgrading to Mavericks, CrashPlan requests incoming network connections each time my MBP is restarted. I always click "Allow" and I've ensured that my firewall settings allow it, but I still get the alert.
I've followed the instructions from Code42 support, but the issue persists.

A: My previous response confirmed that the status had not changed since June (4 months ago). I also confirmed that the problem still exists in Yosemite. ie this is still an open issue without a known resolution.
I've looked a bit further into this issue.  The current version of CrashPlan is 3.6.4.
To resolve this issue:
 - Download the current version
 - Use the 'uninstall' script on the disk image to remove your current installation.
 - Reboot.
 - Install the new version
This also resolves some issues with display and Wireless network detection under Yosemite.
I've not tested to see if just upgrading over the top of the old installation also fixes the issue.


text:
Q: Can I add a few completely new tags to the YouTrack issue using single command window? Like the title says, is it possible to add a few completely new tags to the issue using single command window?
I tried e.g. tag test1 tag test2 but command preview sees this as one command 1. Add new tag test1 tag test2. It looks like I need some kind of text separator, but I cannot find it in documentation.
Thanks

A: No it's not possible.
In case of 'tag' command it will try first to find existing tag and in if there is no such tag it will create one from entire string.


text:
Q: Can I download free games with an expired PlayStation Plus subscription? I had a PlayStation Plus subscription but it expired. Can you not still download the free games you have if you do it on a console that you had your account set to primary?

A: When your subscription lapses so does your access to the games (except those actually bought for at least some money). You get access back by subscribing again.


text:
Q: How to pass structure as pointer in C dll from C# I am working on simple telephony application where I am changing the class of service of panasonic pbx extension. For that I am using "Tapi32.dll" which has methods in c++. Now as per my need I have to pass two argument both integer pointer type. One Argument is getting passed correctly but I am not able to pass second argumnet which is structure type.
Here is my code...
[DllImport("Tapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
unsafe private static extern int lineDevSpecific(int* hLine, int* lpParams);

[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
    [MarshalAs(UnmanagedType.I4)]
    public int dwMode=4;
    public int dwParam1=8;
}

unsafe static void Main(string[] args) {
    int vline=int.Parse("Ext101");
    int* hline = &vline;
    lineDevSpecific(hline, ref UserRec userrec);
}

A: [DllImport("Tapi32.dll", SetLastError=true)]
unsafe private static extern int lineDevSpecific(int* hLine, IntPtr lpParams);

unsafe static void Main(string[] args) {
    int vline=int.Parse("Ext101");
    int* hline=&vline;

    var sizeUserRec=Marshal.SizeOf(typeof(UserRec));
    var userRec=Marshal.AllocHGlobal(sizeUserRec);
    lineDevSpecific(hline, userRec);
    var x=(UserRec)Marshal.PtrToStructure(userRec, typeof(UserRec));
    Marshal.FreeHGlobal(userRec);
}

Take a look of this answer of question

*

*Physical disk size not correct (IoCtlDiskGetDriveGeometry)
You can find some more to make marshalling easier and more reusable.


text:
Q: Access protected member through friend Say class B inherits class A, and B friends C. Class A has a protected member foo.
May class C access foo? Are there any differences between C++ standard revisions?
Example:
class A {
protected:
    void foo() {}
};

class B : public A {
    friend class C;
};

class C {
    void func() {
        B b;
        b.foo();
    }
};

A: Yes, C has access to B::foo. Friends have access to anything you have access to. Since B can access foo, so can C access B::foo. friends don't, however, have access to friends of friends.
No, there is no difference between compilers on this matter that I'm aware of.